Skip to content
Closed
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
5 changes: 5 additions & 0 deletions .claude/settings.local.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"env": {
"CLAUDE_CODE_TASK_LIST_ID": "feature-minvmd-host-daemon"
}
}
11 changes: 11 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 @@ -17,6 +17,7 @@ members = [
"crates/minimal",
"crates/minimal2",
"crates/minimald",
"crates/minvmd",
"crates/remote-client",
"crates/remote-proto",
"crates/sandbox2",
Expand Down
12 changes: 12 additions & 0 deletions crates/minvmd/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]
name = "minvmd"
version = "0.0.1"
edition.workspace = true
publish.workspace = true

[dependencies]
anyhow.workspace = true
clap.workspace = true
clap_complete.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
//! per R1.1 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>
97 changes: 97 additions & 0 deletions crates/minvmd/src/bin/krun_smoke_child.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
//! 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() {
#[cfg(not(target_os = "macos"))]
{
eprintln!("krun_smoke_child: macOS-only; nothing to do on this platform");
std::process::exit(0);
}

#[cfg(target_os = "macos")]
{
run_macos();
}
}

#[cfg(target_os = "macos")]
fn run_macos() {
use minvmd::krun::Context;
use minvmd::krun::raw::{KRUN_KERNEL_FORMAT_IMAGE_BZ2, KRUN_KERNEL_FORMAT_IMAGE_GZ};

eprintln!("STAGE: create_ctx");
let mut ctx = Context::create().expect("krun_create_ctx must succeed");
eprintln!("STAGE: create_ctx ok ctx_id={}", ctx.id());

eprintln!("STAGE: set_vm_config");
ctx.set_vm_config(1, 512)
.expect("krun_set_vm_config 1 vcpu / 512 MiB must succeed");
eprintln!("STAGE: set_vm_config ok");

eprintln!("STAGE: set_exec");
ctx.set_exec("/bin/true", &[] as &[&str], None::<&[&str]>)
.expect("krun_set_exec /bin/true must succeed");
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 kernel + rootfs configured per R2.1 / R2.2)"
);
drop(ctx); // RAII free_ctx
std::process::exit(0);
};

eprintln!("STAGE: set_root path={rootfs}");
ctx.set_root(&rootfs).expect("krun_set_root must succeed");
eprintln!("STAGE: set_root ok");

// Per-arch kernel format: virtio-linux (pkgs#154) ships `Image.gz` on
// aarch64 and `bzImage` on x86_64 (R2.1).
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, // cmdline
)
.expect("krun_set_kernel must succeed");
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);
}
135 changes: 135 additions & 0 deletions crates/minvmd/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
//! Typed errors for `minvmd`.
//!
//! Library code returns `VmError`; CLI / boundary code wraps in
//! `anyhow::Result`. Per spec lesson "error fidelity": `Backend` preserves the
//! original libkrun errno so the source magnitude survives any wrap-and-rethrow.

use std::fmt;
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; `code` is the absolute errno magnitude (libkrun returns
/// negative errnos; we strip the sign before surfacing).
Backend { op: &'static str, code: i32 },

/// 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, code } => {
write!(f, "libkrun {op} returned errno {code}")
}
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 {}

impl VmError {
/// Translate a libkrun return code into a `Result`. libkrun returns zero
/// (or a positive id) on success and a negative errno on failure; we
/// preserve the magnitude as a positive `code` per spec lesson "error
/// fidelity".
#[inline]
pub(crate) fn check_backend(op: &'static str, ret: i32) -> Result<i32, VmError> {
if ret < 0 {
Err(VmError::Backend {
op,
code: ret.unsigned_abs() as i32,
})
} else {
Ok(ret)
}
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn backend_check_passes_through_success() {
assert_eq!(VmError::check_backend("op", 0).unwrap(), 0);
assert_eq!(VmError::check_backend("op", 7).unwrap(), 7);
}

#[test]
fn backend_check_translates_negative_to_typed_error() {
let err = VmError::check_backend("krun_create_ctx", -22).unwrap_err();
match err {
VmError::Backend { op, code } => {
assert_eq!(op, "krun_create_ctx");
assert_eq!(code, 22, "errno magnitude must be preserved");
}
other => panic!("expected Backend, got {other:?}"),
}
}

#[test]
fn display_includes_op_and_code() {
let err = VmError::Backend {
op: "krun_set_vm_config",
code: 12,
};
let s = format!("{err}");
assert!(s.contains("krun_set_vm_config"), "display: {s}");
assert!(s.contains("12"), "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