The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
use std::collections::HashMap;
use std::env;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
// ── Constants ────────────────────────────────────────────────────────────────
// libkrunfw release configuration
// Source: https://github.com/boxlite-ai/libkrunfw (fork with prebuilt releases)
const LIBKRUNFW_VERSION: &str = "v5.4.0";
// macOS: Download prebuilt kernel.c, compile locally to .dylib
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
const LIBKRUNFW_PREBUILT_URL: &str =
"https://github.com/boxlite-ai/libkrunfw/releases/download/v5.4.0/libkrunfw-prebuilt-aarch64.tgz";
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
const LIBKRUNFW_SHA256: &str = "1d1b848cee7053c3d26915f30312560343a4e382b5b4e83be1d6755939582de6";
// Linux: Download pre-compiled .so directly (no build needed)
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
const LIBKRUNFW_SO_URL: &str =
"https://github.com/boxlite-ai/libkrunfw/releases/download/v5.4.0/libkrunfw-x86_64.tgz";
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
const LIBKRUNFW_SHA256: &str = "63df4e4cc99d6c876757fb2f374ce2fee00f3408a1133b2c44600ce0195286b5";
#[cfg(all(target_os = "linux", target_arch = "aarch64"))]
const LIBKRUNFW_SO_URL: &str =
"https://github.com/boxlite-ai/libkrunfw/releases/download/v5.4.0/libkrunfw-aarch64.tgz";
#[cfg(all(target_os = "linux", target_arch = "aarch64"))]
const LIBKRUNFW_SHA256: &str = "e52a05f83baf1e0f6d3e58b96837bcd8729820ecea74a55a1903bd47e0505c57";
// Library directory name differs by platform
#[cfg(target_os = "macos")]
const LIB_DIR: &str = "lib";
#[cfg(target_os = "linux")]
const LIB_DIR: &str = "lib64";
// ── Core utilities ───────────────────────────────────────────────────────────
/// Runs a command and panics with a helpful message if it fails.
fn run_command(cmd: &mut Command, description: &str) {
let status = cmd
.status()
.unwrap_or_else(|e| panic!("Failed to execute {}: {}", description, e));
if !status.success() {
panic!("{} failed with exit code: {:?}", description, status.code());
}
}
/// Verifies vendored sources exist.
fn verify_vendored_sources(manifest_dir: &Path, require_libkrunfw: bool) {
let libkrun_src = manifest_dir.join("vendor/libkrun");
let libkrunfw_src = manifest_dir.join("vendor/libkrunfw");
// Submodule directories can exist but be empty if `git submodule update` wasn't run.
// Check for a marker file (Makefile) instead of just the directory.
let missing_libkrun = !libkrun_src.join("Makefile").exists();
let missing_libkrunfw = require_libkrunfw && !libkrunfw_src.join("Makefile").exists();
if missing_libkrun || missing_libkrunfw {
eprintln!("ERROR: Vendored sources not found");
eprintln!();
eprintln!("Initialize git submodules:");
eprintln!(" git submodule update --init --recursive");
std::process::exit(1);
}
}
// ── Fetcher: download, verify, extract ───────────────────────────────────────
struct Fetcher;
impl Fetcher {
/// Downloads, verifies, and extracts a tarball.
/// Reuses an existing tarball only after verifying its checksum.
pub fn fetch(
url: &str,
sha256: &str,
tarball_path: &Path,
extract_dir: &Path,
) -> io::Result<()> {
let shared = env::var_os("BOXLITE_CACHE")
.filter(|root| !root.is_empty())
.map(|root| PathBuf::from(root).join("firmware").join(sha256));
let archive = shared.as_deref().unwrap_or(tarball_path);
if archive.try_exists()? {
if let Err(error) = Self::verify_sha256(archive, sha256) {
if error.kind() == io::ErrorKind::InvalidData {
fs::remove_file(archive)?;
}
return Err(error);
}
} else {
if let Some(parent) = archive.parent() {
fs::create_dir_all(parent)?;
}
let partial = Self::reserve_partial(archive)?;
let result = Self::download(url, &partial)
.and_then(|()| Self::verify_sha256(&partial, sha256))
.and_then(|()| fs::rename(&partial, archive));
if result.is_err() {
let _ = fs::remove_file(&partial);
}
result?;
}
Self::extract_tarball(archive, extract_dir)
}
fn reserve_partial(archive: &Path) -> io::Result<PathBuf> {
// PID namespaces can assign the same PID to writers sharing a cache.
let mut attempt = 0_u64;
loop {
let path = archive.with_extension(format!("part.{}.{attempt}", std::process::id()));
match fs::File::create_new(&path) {
Ok(_) => return Ok(path),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => attempt += 1,
Err(error) => return Err(error),
}
}
}
/// Downloads a file from URL to the specified path.
fn download(url: &str, dest: &Path) -> io::Result<()> {
println!("cargo:warning=Downloading {}...", url);
let output = Command::new("sh")
.args([
"-c",
include_str!("download-archive.sh"),
"download-archive",
url,
])
.arg(dest)
.arg("curl")
.output()?;
if !output.status.success() {
return Err(io::Error::other(format!(
"curl failed: {}",
String::from_utf8_lossy(&output.stderr)
)));
}
Ok(())
}
/// Verifies SHA256 checksum of a file.
fn verify_sha256(file: &Path, expected: &str) -> io::Result<()> {
let (cmd, args): (&str, &[&str]) = if cfg!(target_os = "linux") {
("sha256sum", &[])
} else {
("shasum", &["-a", "256"])
};
let output = Command::new(cmd)
.args(args)
.stdin(fs::File::open(file)?)
.output()?;
if !output.status.success() {
return Err(io::Error::other(format!("{} failed", cmd)));
}
let actual = String::from_utf8_lossy(&output.stdout)
.split_whitespace()
.next()
.unwrap_or("")
.to_string();
if actual != expected {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("SHA256 mismatch: expected {}, got {}", expected, actual),
));
}
println!("cargo:warning=SHA256 verified: {}", expected);
Ok(())
}
/// Extracts a tarball to the specified directory.
fn extract_tarball(tarball: &Path, dest: &Path) -> io::Result<()> {
fs::create_dir_all(dest)?;
let status = Command::new("tar")
.arg("-xzf")
.arg(tarball)
.arg("-C")
.arg(dest)
.status()?;
if !status.success() {
return Err(io::Error::other("tar extraction failed"));
}
Ok(())
}
}
fn libkrunfw_cache_key() -> String {
format!("{LIBKRUNFW_VERSION}-{}", &LIBKRUNFW_SHA256[..12])
}
/// Downloads and extracts the prebuilt libkrunfw tarball (macOS).
/// Returns the path to the extracted source directory containing kernel.c.
#[cfg(target_os = "macos")]
fn download_libkrunfw_prebuilt(out_dir: &Path) -> PathBuf {
println!("cargo:rerun-if-env-changed=BOXLITE_LIBKRUNFW_SOURCE");
if let Some(source) = env::var_os("BOXLITE_LIBKRUNFW_SOURCE") {
let source = fs::canonicalize(source).expect("resolve firmware source directory");
for file in ["kernel.c", "kernel.config", "Makefile"] {
let path = source.join(file);
assert!(
path.is_file(),
"Missing firmware source: {}",
path.display()
);
println!("cargo:rerun-if-changed={}", path.display());
}
println!(
"cargo:warning=Using explicit firmware source: {}",
source.display()
);
return source;
}
let cache_key = libkrunfw_cache_key();
let versioned_dir = format!("libkrunfw-src-{cache_key}");
let tarball_path = out_dir.join(format!("libkrunfw-prebuilt-{cache_key}.tar.gz"));
let extract_dir = out_dir.join(&versioned_dir);
let src_dir = extract_dir.join("libkrunfw");
if src_dir.join("kernel.c").exists() {
println!("cargo:warning=Using cached libkrunfw source ({cache_key})");
return src_dir;
}
// Clean stale extraction before re-extracting
if extract_dir.exists() {
fs::remove_dir_all(&extract_dir).ok();
}
Fetcher::fetch(
LIBKRUNFW_PREBUILT_URL,
LIBKRUNFW_SHA256,
&tarball_path,
&extract_dir,
)
.unwrap_or_else(|e| panic!("Failed to fetch libkrunfw: {}", e));
println!("cargo:warning=Extracted libkrunfw to {}", src_dir.display());
src_dir
}
/// Downloads pre-compiled libkrunfw .so files (Linux).
/// Extracts directly to the install directory - no build step needed.
#[cfg(target_os = "linux")]
fn download_libkrunfw_so(install_dir: &Path) {
let lib_dir = install_dir.join(LIB_DIR);
let cache_key = libkrunfw_cache_key();
let version_marker = install_dir.join(format!(".version-{cache_key}"));
if version_marker.exists() {
println!("cargo:warning=Using cached libkrunfw.so ({cache_key})");
return;
}
// Remove stale artifacts from a previous version
if install_dir.exists() {
fs::remove_dir_all(install_dir).ok();
}
fs::create_dir_all(install_dir)
.unwrap_or_else(|e| panic!("Failed to create install dir: {}", e));
let tarball_path = install_dir.join(format!("libkrunfw-{cache_key}.tgz"));
Fetcher::fetch(
LIBKRUNFW_SO_URL,
LIBKRUNFW_SHA256,
&tarball_path,
install_dir,
)
.unwrap_or_else(|e| panic!("Failed to fetch libkrunfw: {}", e));
fs::write(&version_marker, &cache_key)
.unwrap_or_else(|e| panic!("Failed to write version marker: {}", e));
println!(
"cargo:warning=Extracted libkrunfw.so to {}",
lib_dir.display()
);
}
// ── Make utilities ───────────────────────────────────────────────────────────
/// Creates a make command with common configuration.
fn make_command(source_dir: &Path, extra_env: &HashMap<String, String>) -> Command {
let mut cmd = Command::new("make");
cmd.stdout(Stdio::inherit());
cmd.stderr(Stdio::inherit());
cmd.args(["-j", &num_cpus::get().to_string()])
.arg("MAKEFLAGS=") // Clear MAKEFLAGS to prevent -w flag issues in submakes
.current_dir(source_dir);
// Apply extra environment variables
for (key, value) in extra_env {
cmd.env(key, value);
}
cmd
}
/// Builds a library using Make with the specified parameters.
fn build_with_make(
source_dir: &Path,
install_dir: &Path,
lib_name: &str,
extra_env: &HashMap<String, String>,
extra_make_args: &[String],
) {
println!("cargo:warning=Building {} from source...", lib_name);
fs::create_dir_all(install_dir)
.unwrap_or_else(|e| panic!("Failed to create install directory: {}", e));
// Build
let mut make_cmd = make_command(source_dir, extra_env);
make_cmd.env("PREFIX", install_dir);
make_cmd.args(extra_make_args);
run_command(&mut make_cmd, &format!("make {}", lib_name));
// Install
let mut install_cmd = make_command(source_dir, extra_env);
install_cmd.env("PREFIX", install_dir);
install_cmd.args(extra_make_args);
install_cmd.arg("install");
run_command(&mut install_cmd, &format!("make install {}", lib_name));
}
// ── LibBuilder: libkrun build operations ─────────────────────────────────────
struct LibBuilder;
impl LibBuilder {
/// Builds libkrun as a static library.
///
/// The init binary is built automatically by the `devices` crate's build.rs
/// using the `CC_LINUX` environment variable.
///
/// Link directives and DEP var metadata are emitted by the caller
/// (platform `build()` functions) so they can be gated on features.
pub fn build(
libkrun_src: &Path,
libkrun_install: &Path,
libkrunfw_install: &Path,
env_overrides: &HashMap<String, String>,
cc_linux: Option<&str>,
) {
Self::build_libkrun_static(
libkrun_src,
libkrun_install,
libkrunfw_install,
env_overrides,
cc_linux,
);
}
/// Builds libkrun as a static library using `cargo rustc --crate-type staticlib`.
///
/// This overrides libkrun's Cargo.toml crate-type (cdylib) at the command line,
/// producing libkrun.a without modifying the vendored source code.
fn build_libkrun_static(
libkrun_src: &Path,
install_dir: &Path,
libkrunfw_install: &Path,
env_overrides: &HashMap<String, String>,
cc_linux: Option<&str>,
) {
println!("cargo:warning=Building libkrun as static library...");
let lib_dir = install_dir.join(LIB_DIR);
fs::create_dir_all(&lib_dir)
.unwrap_or_else(|e| panic!("Failed to create lib directory: {}", e));
// Read the outer build's TARGET to propagate cross-compilation (e.g., musl)
let target = env::var("TARGET").ok();
let mut cmd = Command::new("cargo");
cmd.args([
"rustc",
"-p",
"libkrun",
"--release",
"--crate-type",
"staticlib",
]);
// Features must be forwarded to internal dependency crates explicitly when
// using -p, since libkrun's Cargo.toml doesn't propagate them (net = [], blk = []).
// Without -p, workspace-level feature unification handles this automatically,
// but cargo rustc -p requires explicit dep/feature syntax.
cmd.args([
"--features",
"net,blk,vmm/net,vmm/blk,devices/net,devices/blk",
]);
// Propagate target for cross-compilation (e.g., x86_64-unknown-linux-musl)
if let Some(ref target) = target {
cmd.args(["--target", target]);
}
cmd.current_dir(libkrun_src);
cmd.env(
"PKG_CONFIG_PATH",
format!("{}/{}/pkgconfig", libkrunfw_install.display(), LIB_DIR),
);
cmd.stdout(Stdio::inherit());
cmd.stderr(Stdio::inherit());
// Pass CC_LINUX for init binary cross-compilation (used by devices/build.rs)
if let Some(cc_linux) = cc_linux {
cmd.env("CC_LINUX", cc_linux);
}
// Compile the guest init's clock_worker into init.c (`-D__TIMESYNC__`).
// It binds vsock port 123 and applies host timestamps via clock_settime,
// so the guest clock tracks the host across host sleep and vCPU pause.
//
// macOS targets only: the VMM-side sender (the vsock muxer's
// TimesyncThread) is itself macOS-gated, so enabling this elsewhere would
// fork a guest child that blocks in recvfrom on port 123 forever with
// nothing ever sending. Keyed off the target rather than the build host
// because this function cross-compiles.
if env::var("CARGO_CFG_TARGET_OS").unwrap_or_default() == "macos" {
cmd.env("TIMESYNC", "1");
}
// Apply environment overrides (e.g., PATH with llvm/lld directories)
for (key, value) in env_overrides {
cmd.env(key, value);
}
// Prevent outer RUSTFLAGS from leaking into vendored libkrun build.
// CI tools (e.g., actions-rust-lang/setup-rust-toolchain) set RUSTFLAGS=-D warnings,
// which would promote warnings in vendored code to errors.
cmd.env_remove("RUSTFLAGS");
cmd.env_remove("CARGO_ENCODED_RUSTFLAGS");
run_command(&mut cmd, "cargo rustc (libkrun staticlib)");
// Determine output path (differs when --target is specified)
let output_dir = if let Some(ref target) = target {
libkrun_src.join(format!("target/{}/release", target))
} else {
libkrun_src.join("target/release")
};
let src = output_dir.join("libkrun.a");
let dst = lib_dir.join("libkrun.a");
fs::copy(&src, &dst).unwrap_or_else(|e| {
panic!(
"Failed to copy libkrun.a from {} to {}: {}",
src.display(),
dst.display(),
e
)
});
println!("cargo:warning=Built static libkrun at {}", dst.display());
}
}
// ── LibFixup: post-build library fixup ───────────────────────────────────────
struct LibFixup;
impl LibFixup {
/// Fixes the shared library name (install_name on macOS, SONAME on Linux).
fn fix_install_name(lib_name: &str, lib_path: &Path) {
let lib_path_str = lib_path.to_str().expect("Invalid library path");
#[cfg(target_os = "macos")]
let mut cmd = {
let mut c = Command::new("install_name_tool");
c.args(["-id", &format!("@rpath/{}", lib_name), lib_path_str]);
c
};
#[cfg(target_os = "linux")]
let mut cmd = {
println!("cargo:warning=Fixing {} in {}", lib_name, lib_path_str);
let mut c = Command::new("patchelf");
c.args(["--set-soname", lib_name, lib_path_str]);
c
};
run_command(&mut cmd, &format!("fix install name for {}", lib_name));
}
/// Holds a library's libc `DT_NEEDED` entry to what the target
/// architecture requires: present on aarch64, absent everywhere else.
///
/// libkrunfw is a kernel blob linked `-nostdlib`, so it declares no
/// dependencies at all. A `+crt-static` shim cannot dlopen such a library
/// on aarch64: glibc's static-dlopen path resolves `_dl_var_init` through
/// the loaded object's own scope, and with no dependency chain `ld.so` —
/// the only place that symbol exists — is never reached. The load then
/// fails as `undefined symbol: _dl_var_init`, naming the library, which
/// does not reference it. Depending on libc pulls `ld.so` into scope.
///
/// This is deliberately aarch64-only, and enforced in both directions:
/// added where it is required, removed where it is not. Elsewhere the entry
/// makes a portable static shim load the deployment host's libc as a second
/// libc, and the dlopen fails as `Couldn't find or load libkrunfw.so.5` — on
/// the target machine, long after the build looked green. Enforcing it here,
/// where the dependency is decided, is what keeps the two from drifting.
///
/// The architecture that decides is the *target* (`CARGO_CFG_TARGET_ARCH`),
/// since the artifact is loaded wherever it is deployed, not where it is
/// built. The enclosing `cfg` is about the host instead: `libc.so.6` is
/// glibc's soname and build scripts compile for the host, so a musl host
/// would otherwise be stamped with a dependency it cannot resolve.
#[cfg(all(target_os = "linux", target_env = "gnu"))]
fn enforce_libc_dependency(lib_path: &Path) {
const LIBC: &str = "libc.so.6";
let lib_path_str = lib_path.to_str().expect("Invalid library path");
let needed = Command::new("patchelf")
.args(["--print-needed", lib_path_str])
.output()
.unwrap_or_else(|e| panic!("Failed to read DT_NEEDED of {}: {}", lib_path_str, e));
let has_libc = String::from_utf8_lossy(&needed.stdout)
.lines()
.any(|entry| entry.trim() == LIBC);
if env::var("CARGO_CFG_TARGET_ARCH").as_deref() != Ok("aarch64") {
if !has_libc {
return;
}
// Strip rather than fail: this also runs over a cached OUT_DIR, so an
// artifact stamped by an earlier build heals on the next one instead of
// wedging it. libkrunfw is `-nostdlib`, so no dependency is its own
// natural state.
let mut cmd = Command::new("patchelf");
cmd.args(["--remove-needed", LIBC, lib_path_str]);
run_command(&mut cmd, &format!("remove {} dependency", LIBC));
println!(
"cargo:warning=Removed {} dependency from {} (only aarch64 needs it)",
LIBC, lib_path_str
);
return;
}
if has_libc {
return;
}
let mut cmd = Command::new("patchelf");
cmd.args(["--add-needed", LIBC, lib_path_str]);
run_command(&mut cmd, &format!("add {} dependency", LIBC));
println!(
"cargo:warning=Added {} dependency to {}",
LIBC, lib_path_str
);
}
/// Extract SONAME from versioned library filename.
/// e.g., libkrunfw.so.4.9.0 -> Some("libkrunfw.so.4")
#[cfg(target_os = "linux")]
fn extract_major_soname(filename: &str) -> Option<String> {
if let Some(so_pos) = filename.find(".so.") {
let base = &filename[..so_pos + 3];
let versions = &filename[so_pos + 4..];
if let Some(major) = versions.split('.').next() {
return Some(format!("{}.{}", base, major));
}
}
None
}
/// Fixes install names and re-signs libraries in a directory.
pub fn fix(lib_dir: &Path, lib_prefix: &str) -> Result<(), String> {
let ext = if cfg!(target_os = "macos") {
".dylib"
} else {
".so"
};
for entry in
fs::read_dir(lib_dir).map_err(|e| format!("Failed to read directory: {}", e))?
{
let entry = entry.map_err(|e| format!("Failed to read entry: {}", e))?;
let path = entry.path();
let filename = path.file_name().unwrap().to_string_lossy().to_string();
if filename.starts_with(lib_prefix) && filename.contains(ext) {
let metadata = fs::symlink_metadata(&path)
.map_err(|e| format!("Failed to get metadata: {}", e))?;
if metadata.file_type().is_symlink() {
continue;
}
// Linux: rename libkrunfw to major-version soname
#[cfg(target_os = "linux")]
if lib_prefix == "libkrunfw" {
if let Some(soname) = Self::extract_major_soname(&filename) {
if soname != filename {
let new_path = lib_dir.join(&soname);
fs::rename(&path, &new_path)
.map_err(|e| format!("Failed to rename file: {}", e))?;
println!("cargo:warning=Renamed {} to {}", filename, soname);
Self::fix_install_name(&soname, &new_path);
#[cfg(target_env = "gnu")]
Self::enforce_libc_dependency(&new_path);
continue;
}
}
}
Self::fix_install_name(&filename, &path);
#[cfg(all(target_os = "linux", target_env = "gnu"))]
Self::enforce_libc_dependency(&path);
// macOS: re-sign after modifying
#[cfg(target_os = "macos")]
{
let sign_status = Command::new("codesign")
.args(["-s", "-", "--force"])
.arg(&path)
.status()
.map_err(|e| format!("Failed to run codesign: {}", e))?;
if !sign_status.success() {
return Err(format!("codesign failed for {}", filename));
}
println!("cargo:warning=Fixed and signed {}", filename);
}
}
}
Ok(())
}
}
// ── MacToolchain: macOS toolchain discovery ──────────────────────────────────
#[cfg(target_os = "macos")]
struct MacToolchain {
clang: PathBuf,
path_dirs: Vec<PathBuf>,
}
#[cfg(target_os = "macos")]
impl MacToolchain {
/// Sets LIBCLANG_PATH for bindgen if not already set.
/// This is needed when llvm is installed via brew but not linked (keg-only).
fn setup_libclang_path() {
// Skip if LIBCLANG_PATH already set or llvm-config is in PATH
if env::var("LIBCLANG_PATH").is_ok() {
return;
}
if Command::new("llvm-config")
.arg("--version")
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.is_ok_and(|s| s.success())
{
return;
}
// Try common Homebrew locations (useful when `brew` itself can't be executed).
for prefix in ["/opt/homebrew/opt/llvm", "/usr/local/opt/llvm"] {
let lib_path = Path::new(prefix).join("lib");
if lib_path.join("libclang.dylib").exists() {
env::set_var("LIBCLANG_PATH", &lib_path);
return;
}
}
// Try to find brew's llvm
if let Ok(output) = Command::new("brew").args(["--prefix", "llvm"]).output() {
if output.status.success() {
let prefix = String::from_utf8_lossy(&output.stdout).trim().to_string();
let lib_path = format!("{}/lib", prefix);
if Path::new(&lib_path).join("libclang.dylib").exists() {
env::set_var("LIBCLANG_PATH", &lib_path);
}
}
}
}
fn brew_prefix(formula: &str) -> Option<PathBuf> {
let output = Command::new("brew")
.args(["--prefix", formula])
.output()
.ok()?;
if !output.status.success() {
return None;
}
let prefix = String::from_utf8_lossy(&output.stdout).trim().to_string();
if prefix.is_empty() {
return None;
}
Some(PathBuf::from(prefix))
}
fn find_non_apple_clang_in_path() -> Option<PathBuf> {
let version = Command::new("clang").arg("--version").output().ok()?;
if !version.status.success() {
return None;
}
let version_stdout = String::from_utf8_lossy(&version.stdout);
if version_stdout.starts_with("Apple clang") {
return None;
}
let output = Command::new("which").arg("clang").output().ok()?;
if !output.status.success() {
return None;
}
let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
if path.is_empty() {
return None;
}
let path = PathBuf::from(path);
path.exists().then_some(path)
}
fn find_llvm_clang() -> Option<PathBuf> {
// If the user has already put a non-Apple clang first in PATH, prefer that.
if let Some(clang) = Self::find_non_apple_clang_in_path() {
return Some(clang);
}
// If llvm-config is available, use it.
if let Ok(output) = Command::new("llvm-config").arg("--bindir").output() {
if output.status.success() {
let bindir = String::from_utf8_lossy(&output.stdout).trim().to_string();
if !bindir.is_empty() {
let clang = PathBuf::from(bindir).join("clang");
if clang.exists() {
return Some(clang);
}
}
}
}
// Common Homebrew locations (useful when `brew` itself can't be executed).
for prefix in ["/opt/homebrew/opt/llvm", "/usr/local/opt/llvm"] {
let clang = Path::new(prefix).join("bin/clang");
if clang.exists() {
return Some(clang);
}
}
// Homebrew llvm is keg-only; locate it via brew.
Self::brew_prefix("llvm")
.map(|prefix| prefix.join("bin/clang"))
.filter(|clang| clang.exists())
}
fn find_lld_bin_dir() -> Option<PathBuf> {
// If ld.lld is already in PATH, we're good.
if Command::new("ld.lld")
.arg("--version")
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.is_ok_and(|s| s.success())
{
return None;
}
// Common Homebrew locations (useful when `brew` itself can't be executed).
for prefix in ["/opt/homebrew/opt/lld", "/usr/local/opt/lld"] {
let ld_lld = Path::new(prefix).join("bin/ld.lld");
if ld_lld.exists() {
return ld_lld.parent().map(Path::to_path_buf);
}
}
// Otherwise, try locating via Homebrew.
let ld_lld = Self::brew_prefix("lld")
.map(|prefix| prefix.join("bin/ld.lld"))
.filter(|path| path.exists())?;
ld_lld.parent().map(Path::to_path_buf)
}
fn prepend_path_dirs(path_dirs: &[PathBuf]) -> Option<String> {
if path_dirs.is_empty() {
return None;
}
let existing = env::var("PATH").unwrap_or_default();
let mut merged = String::new();
for dir in path_dirs {
if merged.is_empty() {
merged.push_str(&dir.to_string_lossy());
} else {
merged.push(':');
merged.push_str(&dir.to_string_lossy());
}
}
if existing.is_empty() {
return Some(merged);
}
merged.push(':');
merged.push_str(&existing);
Some(merged)
}
/// Discovers the LLVM clang and lld paths, storing them as intermediate state.
fn discover() -> Result<Self, String> {
if let Ok(cc_linux) = env::var("BOXLITE_LIBKRUN_CC_LINUX") {
let cc_linux = cc_linux.trim().to_string();
if cc_linux.is_empty() {
return Err("BOXLITE_LIBKRUN_CC_LINUX is set but empty".to_string());
}
// User-provided override — no clang discovery needed, but we still
// need a valid PathBuf. Store the raw string as the clang path.
return Ok(Self {
clang: PathBuf::from(cc_linux),
path_dirs: Vec::new(),
});
}
let clang = Self::find_llvm_clang().ok_or_else(|| {
"libkrun cross-compilation on macOS requires LLVM clang + lld. Run `make setup` (or `brew install llvm lld`) and retry."
.to_string()
})?;
let mut path_dirs = Vec::new();
if let Some(dir) = clang.parent() {
path_dirs.push(dir.to_path_buf());
}
if let Some(lld_dir) = Self::find_lld_bin_dir() {
path_dirs.push(lld_dir);
}
Ok(Self { clang, path_dirs })
}
/// Converts the discovered toolchain into make arguments and env overrides.
fn into_cc_linux(
self,
libkrun_src: &Path,
) -> Result<(String, HashMap<String, String>), String> {
// If the user provided BOXLITE_LIBKRUN_CC_LINUX, return it directly
if env::var("BOXLITE_LIBKRUN_CC_LINUX").is_ok() {
let cc_linux = self.clang.to_string_lossy().to_string();
return Ok((cc_linux, HashMap::new()));
}
let path_override = Self::prepend_path_dirs(&self.path_dirs);
// Ensure ld.lld is available (either already in PATH or via brew lld).
let mut ld_lld_cmd = Command::new("ld.lld");
ld_lld_cmd
.arg("--version")
.stdout(Stdio::null())
.stderr(Stdio::null());
if let Some(ref path) = path_override {
ld_lld_cmd.env("PATH", path);
}
if !ld_lld_cmd.status().is_ok_and(|s| s.success()) {
return Err(
"Missing `ld.lld` (LLVM linker). Install it with `make setup` (or `brew install lld`)."
.to_string(),
);
}
println!(
"cargo:warning=Using LLVM clang for libkrun init cross-compile: {}",
self.clang.display()
);
let linux_target_triple = match env::var("CARGO_CFG_TARGET_ARCH")
.unwrap_or_else(|_| "aarch64".to_string())
.as_str()
{
"arm64" | "aarch64" => "aarch64-linux-gnu".to_string(),
"x86_64" => "x86_64-linux-gnu".to_string(),
arch => format!("{arch}-linux-gnu"),
};
// Prepare sysroot via the Makefile's auto-download mechanism
let sysroot_dir = libkrun_src.join("linux-sysroot");
if !sysroot_dir.join(".sysroot_ready").exists() {
println!("cargo:warning=Preparing Linux sysroot for cross-compilation...");
let mut env_for_make = HashMap::new();
if let Some(ref path) = path_override {
env_for_make.insert("PATH".to_string(), path.clone());
}
let mut cmd = make_command(libkrun_src, &env_for_make);
cmd.arg("linux-sysroot/.sysroot_ready");
run_command(&mut cmd, "make linux-sysroot/.sysroot_ready");
}
let sysroot_abs = fs::canonicalize(&sysroot_dir)
.unwrap_or_else(|e| panic!("Failed to resolve sysroot path: {}", e));
let clang_str = self.clang.to_string_lossy();
let cc_linux = format!(
"{} -target {} -fuse-ld=lld -Wl,-strip-debug --sysroot {} -Wno-c23-extensions",
clang_str,
linux_target_triple,
sysroot_abs.display()
);
let mut env_overrides = HashMap::new();
if let Some(path) = path_override {
env_overrides.insert("PATH".to_string(), path);
}
Ok((cc_linux, env_overrides))
}
/// Entry point: discovers the toolchain and produces CC_LINUX value + env overrides.
pub fn resolve(libkrun_src: &Path) -> Result<(String, HashMap<String, String>), String> {
Self::setup_libclang_path();
Self::discover()?.into_cc_linux(libkrun_src)
}
}
// ── Platform build orchestration ─────────────────────────────────────────────
/// macOS: Build libkrunfw and/or libkrun based on enabled features.
///
/// - `krunfw`: Download prebuilt kernel.c, compile to .dylib (fast)
/// - `krun`: Build init binary + libkrun.a static library (expensive)
///
/// `krun` implies libkrunfw download (needed for pkgconfig during build).
#[cfg(target_os = "macos")]
fn build() {
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
let libkrunfw_install = out_dir.join("libkrunfw");
let libkrun_install = out_dir.join("libkrun");
let libkrunfw_lib = libkrunfw_install.join(LIB_DIR);
// Step 1: Download and build libkrunfw dylib.
// Needed for both features: krunfw bundles the dylib,
// krun needs libkrunfw's pkgconfig for compilation.
println!("cargo:warning=Building libkrunfw for macOS...");
let libkrunfw_src = download_libkrunfw_prebuilt(&out_dir);
build_with_make(
&libkrunfw_src,
&libkrunfw_install,
"libkrunfw",
&HashMap::new(),
&[],
);
LibFixup::fix(&libkrunfw_lib, "libkrunfw")
.unwrap_or_else(|e| panic!("Failed to fix libkrunfw: {}", e));
// Expose libkrunfw library directory for downstream bundling
println!("cargo:LIBKRUNFW_BOXLITE_DEP={}", libkrunfw_lib.display());
// Step 2: Build libkrun.a (expensive — only when krun feature is enabled)
if cfg!(feature = "krun") {
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
println!("cargo:warning=Building libkrun for macOS (static)...");
verify_vendored_sources(&manifest_dir, false);
let libkrun_src = manifest_dir.join("vendor/libkrun");
let (cc_linux_value, env_overrides) =
MacToolchain::resolve(&libkrun_src).unwrap_or_else(|e| panic!("{}", e));
LibBuilder::build(
&libkrun_src,
&libkrun_install,
&libkrunfw_install,
&env_overrides,
Some(&cc_linux_value),
);
let libkrun_lib = libkrun_install.join(LIB_DIR);
println!("cargo:LIBKRUN_BOXLITE_DEP={}", libkrun_lib.display());
println!("cargo:rustc-link-search=native={}", libkrun_lib.display());
println!("cargo:rustc-link-lib=static=krun");
println!("cargo:rustc-link-lib=framework=Hypervisor");
}
}
/// Linux: Build libkrunfw and/or libkrun based on enabled features.
///
/// - `krunfw`: Download pre-compiled .so (fast) or build from source
/// - `krun`: Build init binary + libkrun.a static library (expensive)
///
/// `krun` implies libkrunfw download (needed for pkgconfig during build).
#[cfg(target_os = "linux")]
fn build() {
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
let libkrunfw_install = out_dir.join("libkrunfw");
let libkrun_install = out_dir.join("libkrun");
let libkrunfw_lib_dir = libkrunfw_install.join(LIB_DIR);
// Step 1: Download/build libkrunfw.
// Needed for both features: krunfw bundles the .so,
// krun needs libkrunfw's pkgconfig for compilation.
let build_from_source = env::var("BOXLITE_BUILD_LIBKRUNFW").is_ok();
println!("cargo:rerun-if-env-changed=BOXLITE_LIBKRUNFW_SOURCE");
if let Some(source) = env::var_os("BOXLITE_LIBKRUNFW_SOURCE") {
let source = fs::canonicalize(source).expect("BOXLITE_LIBKRUNFW_SOURCE must exist");
for file in ["kernel.c", "Makefile"] {
let path = source.join(file);
assert!(path.is_file(), "missing firmware input: {}", path.display());
println!("cargo:rerun-if-changed={}", path.display());
}
// An override must not leave the ordinary firmware's cache marker behind:
// unsetting it on the next build must restore the ordinary firmware.
if libkrunfw_install.exists() {
fs::remove_dir_all(&libkrunfw_install).expect("remove previous firmware install");
}
build_with_make(
&source,
&libkrunfw_install,
"libkrunfw",
&HashMap::new(),
&[],
);
} else if build_from_source {
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
println!("cargo:warning=Building libkrunfw from source (BOXLITE_BUILD_LIBKRUNFW=1)");
verify_vendored_sources(&manifest_dir, true);
let libkrunfw_src = manifest_dir.join("vendor/libkrunfw");
build_with_make(
&libkrunfw_src,
&libkrunfw_install,
"libkrunfw",
&HashMap::new(),
&[],
);
} else {
println!("cargo:warning=Downloading pre-compiled libkrunfw...");
download_libkrunfw_so(&libkrunfw_install);
}
LibFixup::fix(&libkrunfw_lib_dir, "libkrunfw")
.unwrap_or_else(|e| panic!("Failed to fix libkrunfw: {}", e));
// Expose libkrunfw library directory for downstream bundling
println!(
"cargo:LIBKRUNFW_BOXLITE_DEP={}",
libkrunfw_lib_dir.display()
);
// Step 2: Build libkrun.a (expensive — only when krun feature is enabled)
if cfg!(feature = "krun") {
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
println!("cargo:warning=Building libkrun for Linux (static)...");
verify_vendored_sources(&manifest_dir, false);
let libkrun_src = manifest_dir.join("vendor/libkrun");
LibBuilder::build(
&libkrun_src,
&libkrun_install,
&libkrunfw_install,
&HashMap::new(),
None,
);
let libkrun_lib = libkrun_install.join(LIB_DIR);
println!("cargo:LIBKRUN_BOXLITE_DEP={}", libkrun_lib.display());
println!("cargo:rustc-link-search=native={}", libkrun_lib.display());
println!("cargo:rustc-link-lib=static=krun");
}
}
// ── Entry point ──────────────────────────────────────────────────────────────
fn main() {
// Rebuild if vendored sources change
println!("cargo:rerun-if-changed=vendor/libkrun");
println!("cargo:rerun-if-changed=vendor/libkrunfw");
println!("cargo:rerun-if-env-changed=BOXLITE_DEPS_STUB");
#[cfg(target_os = "macos")]
println!("cargo:rerun-if-env-changed=BOXLITE_LIBKRUN_CC_LINUX");
// Auto-detect crates.io download: Cargo injects .cargo_vcs_info.json into
// published packages. When present, enter stub mode since vendor sources are
// excluded from the package and building from source is not possible.
if env::var("BOXLITE_DEPS_STUB").is_err() {
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
if manifest_dir.join(".cargo_vcs_info.json").exists() {
// SAFETY: build.rs is single-threaded; no concurrent env var access.
unsafe { env::set_var("BOXLITE_DEPS_STUB", "1") };
}
}
// Check for stub mode (for CI linting or crates.io install)
if env::var("BOXLITE_DEPS_STUB").is_ok() {
println!("cargo:warning=BOXLITE_DEPS_STUB mode: skipping libkrun build");
println!("cargo:LIBKRUN_BOXLITE_DEP=/nonexistent");
println!("cargo:LIBKRUNFW_BOXLITE_DEP=/nonexistent");
return;
}
// Skip native builds when no build features are enabled.
// FFI declarations in src/lib.rs remain available but nothing gets built/linked.
let need_build = cfg!(feature = "krunfw") || cfg!(feature = "krun");
if !need_build {
println!("cargo:warning=libkrun-sys: no build features enabled, skipping native builds");
return;
}
build();
}