Repository navigation
feat(minvmd): scaffold crate with libkrun FFI wrappers and smoke test #237
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
d63d1ae
feat(minvmd): scaffold crate with libkrun FFI wrappers and smoke test
norrietaylor 7c8a96c
refactor(minvmd): make krun submodules private, curate via re-export
norrietaylor 4d023d4
fix(minvmd): gate check_backend on macOS to fix Linux dead-code lint
norrietaylor c0aed34
refactor(minvmd): address review feedback on error handling
norrietaylor File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| [package] | ||
| name = "minvmd" | ||
| version = "0.0.1" | ||
| edition.workspace = true | ||
| publish.workspace = true | ||
|
|
||
| [dependencies] | ||
| anyhow.workspace = true | ||
| clap.workspace = true | ||
| clap_complete.workspace = true | ||
| libc.workspace = true | ||
| tracing.workspace = true | ||
| tracing-subscriber.workspace = true |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| //! Build script for `minvmd`. | ||
| //! | ||
| //! On macOS, wires up the link search path and rpath for libkrun. The libkrun | ||
| //! prefix defaults to `/opt/homebrew/lib` (the Homebrew tap install location | ||
| //! used by `~/code/min-ctl`); override with the `LIBKRUN_PREFIX` env var. | ||
| //! | ||
| //! On Linux this is a no-op — the crate compiles to a runtime-bailing stub | ||
| //! and never links libkrun. | ||
|
|
||
| fn main() { | ||
| println!("cargo:rerun-if-env-changed=LIBKRUN_PREFIX"); | ||
|
|
||
| if std::env::var_os("CARGO_CFG_TARGET_OS").as_deref() != Some("macos".as_ref()) { | ||
| return; | ||
| } | ||
|
|
||
| let prefix = | ||
| std::env::var("LIBKRUN_PREFIX").unwrap_or_else(|_| "/opt/homebrew/lib".to_string()); | ||
| println!("cargo:rustc-link-search=native={prefix}"); | ||
| println!("cargo:rustc-link-arg=-Wl,-rpath,{prefix}"); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| <?xml version="1.0" encoding="UTF-8"?> | ||
| <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> | ||
| <plist version="1.0"> | ||
| <dict> | ||
| <key>com.apple.security.hypervisor</key> | ||
| <true/> | ||
| </dict> | ||
| </plist> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| //! Test helper binary for `tests/krun_smoke.rs`. | ||
| //! | ||
| //! Exists as a separate process because `krun_start_enter`, on success, calls | ||
| //! `exit()` with the guest workload's exit code and never returns. Driving it | ||
| //! from inside the test process would tear down the test harness; running it | ||
| //! in a child lets the parent test observe the outcome via the child's exit | ||
| //! status. | ||
| //! | ||
| //! Behaviour: | ||
| //! 1. Always drive the FFI bring-up surface: create_ctx → set_vm_config(1, 512) | ||
| //! → set_exec("/bin/true"). Print stage markers. | ||
| //! 2. If `MINVMD_KERNEL_PATH` and `MINVMD_ROOTFS_PATH` are both set, also | ||
| //! configure them and call `krun_start_enter`. Without either, skip | ||
| //! start_enter — libkrun aborts internally on an incomplete config, so | ||
| //! calling it would be a false-negative for the FFI surface itself. | ||
| //! | ||
| //! Exit codes: | ||
| //! 0 — bring-up surface drove cleanly; or guest workload (/bin/true) ran. | ||
| //! 2 — start_enter returned an error (libkrun-side failure before boot). | ||
| //! 125/126/127 — libkrun init-time error codes per `krun_start_enter` docs. | ||
| //! | ||
| //! Linux is a no-op stub (exit 0); the integration test is `target_os = macos`. | ||
|
|
||
| fn main() -> Result<(), minvmd::VmError> { | ||
| #[cfg(target_os = "macos")] | ||
| return run_macos(); | ||
|
|
||
| #[cfg(not(target_os = "macos"))] | ||
| { | ||
| eprintln!("krun_smoke_child: macOS-only; nothing to do on this platform"); | ||
| Ok(()) | ||
| } | ||
| } | ||
|
|
||
| #[cfg(target_os = "macos")] | ||
| fn run_macos() -> Result<(), minvmd::VmError> { | ||
| use minvmd::krun::{Context, KRUN_KERNEL_FORMAT_IMAGE_BZ2, KRUN_KERNEL_FORMAT_IMAGE_GZ}; | ||
|
|
||
| eprintln!("STAGE: create_ctx"); | ||
| let mut ctx = Context::create()?; | ||
| eprintln!("STAGE: create_ctx ok ctx_id={}", ctx.id()); | ||
|
|
||
| eprintln!("STAGE: set_vm_config"); | ||
| ctx.set_vm_config(1, 512)?; | ||
| eprintln!("STAGE: set_vm_config ok"); | ||
|
|
||
| eprintln!("STAGE: set_exec"); | ||
| ctx.set_exec("/bin/true", &[] as &[&str], None::<&[&str]>)?; | ||
| eprintln!("STAGE: set_exec ok"); | ||
|
|
||
| let kernel = std::env::var("MINVMD_KERNEL_PATH").ok(); | ||
| let rootfs = std::env::var("MINVMD_ROOTFS_PATH").ok(); | ||
| let Some((kernel, rootfs)) = kernel.zip(rootfs) else { | ||
| eprintln!( | ||
| "STAGE: skip_start_enter \ | ||
| (MINVMD_KERNEL_PATH or MINVMD_ROOTFS_PATH unset; FFI bring-up verified, \ | ||
| start_enter requires a configured kernel + rootfs)" | ||
| ); | ||
| drop(ctx); // RAII free_ctx | ||
| return Ok(()); | ||
| }; | ||
|
|
||
| eprintln!("STAGE: set_root path={rootfs}"); | ||
| ctx.set_root(&rootfs)?; | ||
| eprintln!("STAGE: set_root ok"); | ||
|
|
||
| // Per-arch kernel format: the virtio-linux package ships `Image.gz` on | ||
| // aarch64 and `bzImage` on x86_64. | ||
| let format = if cfg!(target_arch = "aarch64") { | ||
| KRUN_KERNEL_FORMAT_IMAGE_GZ | ||
| } else { | ||
| KRUN_KERNEL_FORMAT_IMAGE_BZ2 | ||
| }; | ||
| eprintln!("STAGE: set_kernel path={kernel} format={format}"); | ||
| ctx.set_kernel(&kernel, format, None::<&std::path::Path>, None)?; | ||
| eprintln!("STAGE: set_kernel ok"); | ||
|
|
||
| eprintln!("STAGE: start_enter"); | ||
| let err = ctx.start_enter(); | ||
| // Reaching this point means start_enter returned an error (libkrun | ||
| // `exit()`s on success and never comes back). Surface the typed error | ||
| // and report exit 2 so the parent test can distinguish from a clean | ||
| // workload run (exit 0) or libkrun init errors (125/126/127). | ||
| eprintln!("STAGE: start_enter returned: {err}"); | ||
| std::process::exit(2); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,126 @@ | ||
| //! Typed errors for `minvmd`. | ||
| //! | ||
| //! Library code returns `VmError`; CLI / boundary code wraps in | ||
| //! `anyhow::Result`. `Backend` preserves the original libkrun errno so the | ||
| //! source magnitude survives any wrap-and-rethrow. | ||
|
|
||
| use std::fmt; | ||
| use std::io; | ||
| use std::path::PathBuf; | ||
|
|
||
| /// Errors produced by `minvmd`'s VM layer. | ||
| #[derive(Debug)] | ||
| #[non_exhaustive] | ||
| pub enum VmError { | ||
| /// A libkrun FFI call returned a negative errno. `op` names the libkrun | ||
| /// function so the caller can attribute the failure without parsing | ||
| /// strings; `source` carries the errno as an [`io::Error`] (libkrun | ||
| /// returns negative errnos; the sign is stripped when constructing it). | ||
| Backend { op: &'static str, source: io::Error }, | ||
|
|
||
| /// A caller-supplied path contained a NUL byte and cannot be passed across | ||
| /// the C FFI boundary. `what` identifies the parameter for diagnostics. | ||
| NulInPath { what: &'static str, path: PathBuf }, | ||
|
|
||
| /// A caller-supplied string (e.g. an env var or argv entry) contained a | ||
| /// NUL byte and cannot be passed across the C FFI boundary. | ||
| NulInString { what: &'static str, value: String }, | ||
|
|
||
| /// `krun_start_enter` returned a non-negative value. libkrun's docs state | ||
| /// the function only returns on error (on success it `exit()`s the host | ||
| /// process with the guest workload's exit code), so a non-negative | ||
| /// return is a protocol violation. `ret` is the raw libkrun return. | ||
| StartEnterReturnedUnexpectedly { ret: i32 }, | ||
| } | ||
|
|
||
| impl fmt::Display for VmError { | ||
| fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| match self { | ||
| Self::Backend { op, source } => { | ||
| write!(f, "libkrun {op} failed: {source}") | ||
| } | ||
| Self::NulInPath { what, path } => { | ||
| write!( | ||
| f, | ||
| "{what} path contains a NUL byte and cannot cross the FFI boundary: {}", | ||
| path.display() | ||
| ) | ||
| } | ||
| Self::NulInString { what, value } => { | ||
| write!( | ||
| f, | ||
| "{what} contains a NUL byte and cannot cross the FFI boundary: {value:?}" | ||
| ) | ||
| } | ||
| Self::StartEnterReturnedUnexpectedly { ret } => { | ||
| write!( | ||
| f, | ||
| "krun_start_enter returned {ret} but libkrun's docs say it only returns on error" | ||
| ) | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl std::error::Error for VmError { | ||
| fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { | ||
| match self { | ||
| Self::Backend { source, .. } => Some(source), | ||
| Self::NulInPath { .. } | ||
| | Self::NulInString { .. } | ||
| | Self::StartEnterReturnedUnexpectedly { .. } => None, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
|
|
||
| #[test] | ||
| fn backend_preserves_errno_in_source() { | ||
| let err = VmError::Backend { | ||
| op: "krun_create_ctx", | ||
| source: io::Error::from_raw_os_error(22), | ||
| }; | ||
| let VmError::Backend { source, .. } = &err else { | ||
| panic!("expected Backend, got {err:?}"); | ||
| }; | ||
| assert_eq!( | ||
| source.raw_os_error(), | ||
| Some(22), | ||
| "errno magnitude must be preserved" | ||
| ); | ||
| // `source()` exposes the io::Error so the chain is traversable. | ||
| assert!(std::error::Error::source(&err).is_some()); | ||
| } | ||
|
|
||
| #[test] | ||
| fn display_includes_op_and_errno() { | ||
| let err = VmError::Backend { | ||
| op: "krun_set_vm_config", | ||
| source: io::Error::from_raw_os_error(12), | ||
| }; | ||
| let s = format!("{err}"); | ||
| assert!(s.contains("krun_set_vm_config"), "display: {s}"); | ||
| } | ||
|
|
||
| #[test] | ||
| fn display_start_enter_returned_unexpectedly() { | ||
| let err = VmError::StartEnterReturnedUnexpectedly { ret: 0 }; | ||
| let s = format!("{err}"); | ||
| assert!(s.contains("krun_start_enter"), "display: {s}"); | ||
| assert!(s.contains("only returns on error"), "display: {s}"); | ||
| } | ||
|
|
||
| #[test] | ||
| fn display_nul_in_path() { | ||
| let err = VmError::NulInPath { | ||
| what: "rootfs", | ||
| path: PathBuf::from("/tmp/bad"), | ||
| }; | ||
| let s = format!("{err}"); | ||
| assert!(s.contains("rootfs")); | ||
| assert!(s.contains("/tmp/bad")); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.