8000 feat(minvmd): scaffold crate with libkrun FFI wrappers and smoke test by norrietaylor · Pull Request #237 · gominimal/minimal · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ members = [
"crates/minimal",
"crates/minimal2",
"crates/minimald",
"crates/minvmd",
"crates/remote-client",
"crates/remote-proto",
"crates/sandbox2",
Expand Down
13 changes: 13 additions & 0 deletions crates/minvmd/Cargo.toml
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
21 changes: 21 additions & 0 deletions crates/minvmd/build.rs
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}");
}
8 changes: 8 additions & 0 deletions crates/minvmd/minvmd.entitlements
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>
86 changes: 86 additions & 0 deletions crates/minvmd/src/bin/krun_smoke_child.rs
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);
}
126 changes: 126 additions & 0 deletions crates/minvmd/src/error.rs
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,
}
}
}

Comment thread
norrietaylor marked this conversation as resolved.
Resolved
#[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"));
}
}
Loading
Loading
0