Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

perf(jailer,vmm): trim bwrap mounts, bump libkrun, forward KRUN_USE_THP (#3159)

lfld287301fd73553e0
diff --git a/docs/contributing/architecture/vmm/README.md b/docs/contributing/architecture/vmm/README.md
index a6712bad6..233a93075 100644
--- a/docs/contributing/architecture/vmm/README.md
+++ b/docs/contributing/architecture/vmm/README.md
@@ -10,8 +10,8 @@ BoxLite is replacing libkrun and libkrunfw with a virtualization stack it owns:
This document is the design the VMM milestones build on
([#1512](https://github.com/boxlite-ai/boxlite/issues/1512)). It covers the
hypervisor backend interface, the device model, the VM lifecycle and its
-errors, and the guest boot contract. libkrun ships unchanged until the new VMM
-becomes the default in M5.
+errors, and the guest boot contract. The libkrun backend remains in use until
+the new VMM becomes the default in M5.
Diagrams of this design:
@@ -24,7 +24,21 @@ Diagrams of this design:
BoxLite line references are to commit `42ec1a2a6`. External citations name
their project; their revisions are pinned under [References](#references).
`libkrun/` is the vendored copy at `src/deps/libkrun-sys/vendor/libkrun/`
-(upstream `e12b9b3`).
+(revision `a66775c`).
+
+This revision includes opt-in Transparent Huge Pages (THP) for Linux guest boot RAM
+([boxlite-ai/libkrun#17](https://github.com/boxlite-ai/libkrun/pull/17)),
+checkpoint vsock and musl fixes
+([boxlite-ai/libkrun#18](https://github.com/boxlite-ai/libkrun/pull/18)), and
+virtio-net unixgram TX handling that keeps the backend open on single-frame
+internal errors such as macOS `EMSGSIZE` so subsequent frames continue to be
+delivered ([boxlite-ai/libkrun#19](https://github.com/boxlite-ai/libkrun/pull/19)).
+With bubblewrap enabled, `BwrapSandbox` passes `KRUN_USE_THP=1` to
+`boxlite-shim` after clearing the inherited environment. Only the exact value
+`1` in the host launcher environment is forwarded; unset or other values are
+omitted. `KRUN_USE_THP=1` only takes effect on **Linux x86_64 (non-TEE)** hosts,
+and THP backing depends on the host kernel (on managed hosts, pairing it with
+`transparent_hugepage/defrag=defer` or `never` is recommended).
## Scope
@@ -871,7 +885,7 @@ the M10 notes used these pinned sources:
| [crosvm](https://github.com/google/crosvm/tree/4c88690f44c382e34bdff7ad18ca10f8f9de6aa2) | `4c88690` | `hypervisor/src/lib.rs`, `devices/src/bus.rs`, `aarch64/src/lib.rs` |
| [OpenVMM](https://github.com/microsoft/openvmm/tree/998904f2debee98416c5d007a17f05be1b7dad34) | `998904f` | `vmm_core/virt_whp/src/`, `vmm_core/virt/src/irqcon.rs`, `vm/x86/x86emu/` |
| [cloud-hypervisor](https://github.com/cloud-hypervisor/cloud-hypervisor/tree/c24527002473dec810ef98fe3befb558ff2d5ede) | `c245270` | `hypervisor/src/`, `vm-device/src/bus.rs`, `arch/src/*/layout.rs`, `README.md` |
-| [libkrun](https://github.com/libkrun/libkrun/tree/e12b9b3780ffa8df9f3e1797b217d13453479167) | `e12b9b3` | `src/hvf/src/lib.rs`, `src/vmm/src/builder.rs`, `init/init.c`, `src/devices/src/legacy/vcpu.rs`, `src/arch/src/x86_64/mod.rs`, `src/devices/src/fdt/aarch64.rs` |
+| [libkrun](https://github.com/boxlite-ai/libkrun/tree/a66775ca9f93a2662031c366a6c5d7b9da0e3bc3) | `a66775c` | `src/hvf/src/lib.rs`, `src/vmm/src/builder.rs`, `init/init.c`, `src/devices/src/legacy/vcpu.rs`, `src/arch/src/x86_64/mod.rs`, `src/devices/src/fdt/aarch64.rs` |
| [alioth](https://github.com/google/alioth/tree/9d39a5d288fcd8630a24c5e762e4c31e97f1840f) | `9d39a5d` | `alioth/src/hv/hv.rs`, `alioth/src/arch/*/layout.rs` |
| [hyperlight](https://github.com/hyperlight-dev/hyperlight/tree/398e7957c194ef6227d79fa729fd8dd43e5dc117) | `398e795` | `src/hyperlight_host/src/hypervisor/virtual_machine/mod.rs` |
| [kvm-ioctls](https://github.com/rust-vmm/kvm-ioctls/tree/668b30b650c7032efcd1c3c82c065bd44036bea9) | `668b30b` | `kvm-ioctls/src/ioctls/vcpu.rs`, `kvm-ioctls/src/ioctls/vm.rs` |
diff --git a/src/boxlite/src/jailer/bwrap.rs b/src/boxlite/src/jailer/bwrap.rs
index e143d5dcb..beacb2083 100644
--- a/src/boxlite/src/jailer/bwrap.rs
+++ b/src/boxlite/src/jailer/bwrap.rs
@@ -31,9 +31,10 @@
use crate::runtime::advanced_options::SecurityOptions;
use crate::runtime::layout::FilesystemLayout;
use crate::util::{HostDiagnostic, find_binary};
-use std::path::{Path, PathBuf};
+use std::path::{Component, Path, PathBuf};
use std::process::Command;
use std::sync::OnceLock;
+use std::sync::atomic::{AtomicBool, Ordering};
/// Cached path to the bwrap binary (system or bundled).
///
@@ -91,7 +92,9 @@ pub fn is_available() -> bool {
get_bwrap_path().is_some()
}
-/// Probe whether bwrap can create user namespaces.
+static USERNS_VERIFIED: AtomicBool = AtomicBool::new(false);
+
+/// Probe whether bwrap can create user namespaces, caching only success.
///
/// Performs two checks:
/// 1. **Chrome-style raw probe** — `clone(CLONE_NEWUSER)` for kernel-level
@@ -105,6 +108,23 @@ pub fn is_available() -> bool {
///
/// Returns `Ok(())` if working, `Err` with diagnostic guidance.
pub(crate) fn can_create_user_namespace() -> Result<(), HostDiagnostic> {
+ verify_user_namespace(&USERNS_VERIFIED, probe_user_namespace)
+}
+
+fn verify_user_namespace(
+ verified: &AtomicBool,
+ probe: impl FnOnce() -> Result<(), HostDiagnostic>,
+) -> Result<(), HostDiagnostic> {
+ if verified.load(Ordering::Acquire) {
+ return Ok(());
+ }
+
+ probe()?;
+ verified.store(true, Ordering::Release);
+ Ok(())
+}
+
+fn probe_user_namespace() -> Result<(), HostDiagnostic> {
let bwrap_path = match get_bwrap_path() {
Some(p) => p,
None => {
@@ -293,6 +313,67 @@ pub fn version() -> Option<String> {
.map(|s| s.trim().to_string())
}
+/// Read-only system directories or their usrmerge aliases.
+#[derive(Debug)]
+enum SystemDir {
+ Bind(PathBuf),
+ UsrAlias { path: PathBuf, target: PathBuf },
+}
+
+static SYSTEM_DIRS: OnceLock<Vec<SystemDir>> = OnceLock::new();
+
+fn inspect_system_dirs(root: &Path) -> Vec<SystemDir> {
+ let usr = root.join("usr");
+ let usr_is_dir = std::fs::symlink_metadata(&usr).is_ok_and(|m| m.is_dir());
+ ["usr", "lib", "lib64", "bin", "sbin"]
+ .into_iter()
+ .filter_map(|name| {
+ let host_path = root.join(name);
+ let path = Path::new("/").join(name);
+ if name != "usr"
+ && usr_is_dir
+ && std::fs::symlink_metadata(&host_path).is_ok_and(|m| m.is_symlink())
+ && let Ok(target) = std::fs::read_link(&host_path)
+ && target.to_str().is_some()
+ && let relative = target.strip_prefix("/").unwrap_or(&target)
+ && relative.starts_with("usr")
+ && relative
+ .components()
+ .all(|part| matches!(part, Component::Normal(_)))
+ && let Ok(resolved) = root.join(relative).canonicalize()
+ && resolved == root.join(relative)
+ && resolved.is_dir()
+ {
+ return Some(SystemDir::UsrAlias { path, target });
+ }
+ host_path.exists().then_some(SystemDir::Bind(path))
+ })
+ .collect()
+}
+
+/// Resolve the deepest existing ancestor of `dest` through symlinks and
+/// re-append any non-existent suffix, returning `None` on dangling symlinks or
+/// non-`NotFound` metadata errors.
+fn resolve_destination(dest: &Path) -> Option<PathBuf> {
+ let dest: PathBuf = dest.components().collect();
+ for ancestor in dest.ancestors() {
+ match std::fs::symlink_metadata(ancestor) {
+ Ok(_) => {
+ let canonical = ancestor.canonicalize().ok()?;
+ let suffix = dest.strip_prefix(ancestor).ok()?;
+ return Some(if suffix.as_os_str().is_empty() {
+ canonical
+ } else {
+ canonical.join(suffix)
+ });
+ }
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
+ Err(_) => return None,
+ }
+ }
+ None
+}
+
/// Builder for constructing bwrap command arguments.
#[derive(Debug, Clone)]
#[allow(dead_code)]
@@ -348,6 +429,60 @@ impl BwrapCommand {
// Bind mounts
// ─────────────────────────────────────────────────────────────────────
+ /// Recreate an alias within the sandbox without adding a mount.
+ pub fn symlink(&mut self, target: &Path, path: &Path) -> &mut Self {
+ self.args.push("--symlink".into());
+ self.args.push(target.to_string_lossy().into_owned());
+ self.args.push(path.to_string_lossy().into_owned());
+ self
+ }
+
+ pub(crate) fn with_system_dirs(&mut self, extra_destinations: &[&Path]) -> &mut Self {
+ let dirs = SYSTEM_DIRS.get_or_init(|| inspect_system_dirs(Path::new("/")));
+ self.add_system_dirs(dirs, extra_destinations)
+ }
+
+ fn add_system_dirs(&mut self, dirs: &[SystemDir], extra_destinations: &[&Path]) -> &mut Self {
+ let resolved_destinations: Vec<_> = extra_destinations
+ .iter()
+ .map(|dest| {
+ let resolved = (dest.is_absolute()
+ && !dest.components().any(|part| part == Component::ParentDir))
+ .then(|| resolve_destination(dest))
+ .flatten();
+ (*dest, resolved)
+ })
+ .collect();
+
+ for dir in dirs {
+ match dir {
+ SystemDir::Bind(path) => self.ro_bind(path, path),
+ SystemDir::UsrAlias { path, target } => {
+ let absolute_target = Path::new("/").join(target);
+ // An explicit mount on either side can change one view but not
+ // the other. Keep independent binds when that is possible.
+ let conflicts = resolved_destinations.iter().any(|(dest, resolved)| {
+ let Some(resolved) = resolved else {
+ return true;
+ };
+ [path.as_path(), &absolute_target].iter().any(|alias| {
+ dest.starts_with(alias)
+ || alias.starts_with(dest)
+ || resolved.starts_with(alias)
+ || alias.starts_with(resolved)
+ })
+ });
+ if conflicts {
+ self.ro_bind(path, path)
+ } else {
+ self.symlink(target, path)
+ }
+ }
+ };
+ }
+ self
+ }
+
/// Add read-only bind mount.
pub fn ro_bind(&mut self, src: impl AsRef<Path>, dest: impl AsRef<Path>) -> &mut Self {
self.args.push("--ro-bind".to_string());
@@ -545,12 +680,10 @@ pub fn build_shim_command(
// =========================================================================
// Mount system directories (read-only)
// =========================================================================
- bwrap
- .ro_bind_if_exists("/usr", "/usr")
- .ro_bind_if_exists("/lib", "/lib")
- .ro_bind_if_exists("/lib64", "/lib64")
- .ro_bind_if_exists("/bin", "/bin")
- .ro_bind_if_exists("/sbin", "/sbin");
+ let extra_destinations: Vec<_> = std::iter::once(layout.home_dir())
+ .chain(shim_path.parent())
+ .collect();
+ bwrap.with_system_dirs(&extra_destinations);
// =========================================================================
// Mount devices
@@ -653,6 +786,20 @@ pub fn build_shim_command(
mod tests {
use super::*;
+ #[test]
+ fn user_namespace_probe_retries_failures_and_caches_success() {
+ let verified = AtomicBool::new(false);
+ let result = verify_user_namespace(&verified, || {
+ Err(HostDiagnostic::new("unavailable", "probe failed"))
+ });
+ assert!(result.is_err());
+ assert!(!verified.load(Ordering::Acquire));
+
+ verify_user_namespace(&verified, || Ok(())).unwrap();
+ assert!(verified.load(Ordering::Acquire));
+ verify_user_namespace(&verified, || panic!("successful probe must be cached")).unwrap();
+ }
+
#[test]
fn test_bwrap_available() {
// This test will pass if bwrap is installed
@@ -767,3 +914,7 @@ mod tests {
}
}
}
+
+#[cfg(test)]
+#[path = "tests/bwrap_system_dirs.rs"]
+mod system_dir_tests;
diff --git a/src/boxlite/src/jailer/sandbox/bwrap.rs b/src/boxlite/src/jailer/sandbox/bwrap.rs
index b96d7066d..1e71baa37 100644
--- a/src/boxlite/src/jailer/sandbox/bwrap.rs
+++ b/src/boxlite/src/jailer/sandbox/bwrap.rs
@@ -3,9 +3,10 @@
//! Implements the [`Sandbox`] trait using bubblewrap (bwrap) for
//! namespace isolation, bind mounts, and environment sanitization.
-use super::{Sandbox, SandboxContext};
+use super::{PathAccess, Sandbox, SandboxContext};
use crate::jailer::{bwrap, cgroup};
use boxlite_shared::errors::{BoxliteError, BoxliteResult};
+use std::path::Path;
use std::process::Command;
/// Linux sandbox using bubblewrap for namespace isolation.
@@ -65,8 +66,7 @@ impl Sandbox for BwrapSandbox {
.get_args()
.map(|a| a.to_string_lossy().into_owned())
.collect();
- let shim_plan =
- crate::jailer::shim_cache::plan_bwrap_shim_mounts(std::path::Path::new(&binary));
+ let shim_plan = crate::jailer::shim_cache::plan_bwrap_shim_mounts(Path::new(&binary));
let mut bwrap_cmd = bwrap::BwrapCommand::new();
@@ -86,12 +86,14 @@ impl Sandbox for BwrapSandbox {
// =====================================================================
// System directories (read-only)
// =====================================================================
+ let extra_destinations: Vec<_> = ctx
+ .paths
+ .iter()
+ .map(|pa| pa.path.as_path())
+ .chain(shim_plan.ro_binds.iter().map(|(_, dest)| dest.as_path()))
+ .collect();
bwrap_cmd
- .ro_bind_if_exists("/usr", "/usr")
- .ro_bind_if_exists("/lib", "/lib")
- .ro_bind_if_exists("/lib64", "/lib64")
- .ro_bind_if_exists("/bin", "/bin")
- .ro_bind_if_exists("/sbin", "/sbin")
+ .with_system_dirs(&extra_destinations)
// DNS resolver config: gvproxy runs in this shim. It forwards the
// guest's DNS queries to the host resolver, and it re-resolves
// every `allow_net` hostname at connect time to decide where to
@@ -117,13 +119,14 @@ impl Sandbox for BwrapSandbox {
// =====================================================================
// Bind all pre-computed paths (system dirs + user volumes)
// =====================================================================
- for pa in ctx.writable_paths() {
- bwrap_cmd.bind(&pa.path, &pa.path);
- tracing::debug!(path = %pa.path.display(), "bwrap: bind (rw)");
- }
- for pa in ctx.readonly_paths() {
- bwrap_cmd.ro_bind(&pa.path, &pa.path);
- tracing::debug!(path = %pa.path.display(), "bwrap: ro-bind");
+ for pa in bind_mounts(ctx) {
+ if pa.writable {
+ bwrap_cmd.bind(&pa.path, &pa.path);
+ tracing::debug!(path = %pa.path.display(), "bwrap: bind (rw)");
+ } else {
+ bwrap_cmd.ro_bind(&pa.path, &pa.path);
+ tracing::debug!(path = %pa.path.display(), "bwrap: ro-bind");
+ }
}
for (src, dest) in &shim_plan.ro_binds {
bwrap_cmd.ro_bind(src, dest);
@@ -157,6 +160,7 @@ impl Sandbox for BwrapSandbox {
if let Ok(rust_backtrace) = std::env::var("RUST_BACKTRACE") {
bwrap_cmd.setenv("RUST_BACKTRACE", rust_backtrace);
}
+ apply_thp_env(&mut bwrap_cmd, std::env::var_os("KRUN_USE_THP").as_deref());
bwrap_cmd.chdir("/");
@@ -180,6 +184,93 @@ impl Sandbox for BwrapSandbox {
}
}
+fn paths_overlap(a: &Path, b: &Path) -> bool {
+ a.starts_with(b) || b.starts_with(a)
+}
+
+/// Collapse redundant plain mounts per mode, emitting all writable mounts before
+/// all read-only mounts so read-only mounts always take precedence.
+fn bind_mounts<'a>(ctx: &'a SandboxContext<'_>) -> Vec<&'a PathAccess> {
+ let paths: Vec<_> = ctx.writable_paths().chain(ctx.readonly_paths()).collect();
+ let resolved: Vec<_> = paths.iter().map(|pa| pa.path.canonicalize().ok()).collect();
+ let plain = |i: usize| resolved[i].as_deref() == Some(paths[i].path.as_path());
+
+ // Keep alias-dependent mounts and any transitively overlapping mounts in
+ // their existing order so a sorted child cannot precede an opaque parent.
+ let mut opaque: Vec<_> = (0..paths.len()).map(|i| !plain(i)).collect();
+ while (0..paths.len()).fold(false, |changed, i| {
+ let overlaps = |j: usize| {
+ paths_overlap(&paths[i].path, &paths[j].path)
+ || resolved[j]
+ .as_deref()
+ .is_some_and(|t| paths_overlap(&paths[i].path, t))
+ };
+ if !opaque[i] && (0..paths.len()).any(|j| opaque[j] && overlaps(j)) {
+ opaque[i] = true;
+ true
+ } else {
+ changed
+ }
+ }) {}
+
+ let mut plain_ro: Vec<_> = (0..paths.len())
+ .filter(|&i| !opaque[i] && !paths[i].writable)
+ .map(|i| paths[i])
+ .collect();
+ plain_ro.sort_by_key(|pa| (pa.path.components().count(), &pa.path));
+
+ let mut kept_plain_ro: Vec<&PathAccess> = Vec::new();
+ for pa in plain_ro {
+ if !kept_plain_ro
+ .iter()
+ .any(|parent| pa.path.starts_with(&parent.path))
+ {
+ kept_plain_ro.push(pa);
+ }
+ }
+
+ let mut plain_rw: Vec<_> = (0..paths.len())
+ .filter(|&i| !opaque[i] && paths[i].writable)
+ .map(|i| paths[i])
+ .collect();
+ plain_rw.sort_by_key(|pa| (pa.path.components().count(), &pa.path));
+
+ let mut kept_plain_rw: Vec<&PathAccess> = Vec::new();
+ for pa in plain_rw {
+ if !kept_plain_rw
+ .iter()
+ .chain(kept_plain_ro.iter())
+ .any(|parent| pa.path.starts_with(&parent.path))
+ {
+ kept_plain_rw.push(pa);
+ }
+ }
+
+ let mut ordered = Vec::with_capacity(paths.len());
+ ordered.extend(
+ opaque
+ .iter()
+ .zip(&paths)
+ .filter_map(|(&is_opaque, &pa)| (is_opaque && pa.writable).then_some(pa)),
+ );
+ ordered.extend(kept_plain_rw);
+ ordered.extend(
+ opaque
+ .iter()
+ .zip(&paths)
+ .filter_map(|(&is_opaque, &pa)| (is_opaque && !pa.writable).then_some(pa)),
+ );
+ ordered.extend(kept_plain_ro);
+ ordered
+}
+
+/// Forward `KRUN_USE_THP=1` only when explicitly enabled on the host.
+fn apply_thp_env(bwrap_cmd: &mut bwrap::BwrapCommand, krun_use_thp: Option<&std::ffi::OsStr>) {
+ if krun_use_thp == Some(std::ffi::OsStr::new("1")) {
+ bwrap_cmd.setenv("KRUN_USE_THP", "1");
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -273,7 +364,6 @@ mod tests {
#[test]
fn apply_mounts_symlinked_runtime_into_synthetic_shim_dir() {
- use crate::jailer::sandbox::PathAccess;
use crate::jailer::shim_cache::BWRAP_SANDBOX_SHIM_DIR;
use std::os::unix::fs::{PermissionsExt, symlink};
@@ -389,4 +479,41 @@ mod tests {
assert!(sibling_out.stdout.is_empty());
}
}
+
+ #[test]
+ fn apply_thp_env_forwards_only_explicit_one() {
+ use std::ffi::OsStr;
+
+ let build_args = |val: Option<&OsStr>| -> Vec<String> {
+ let mut bwrap_cmd = bwrap::BwrapCommand::new();
+ apply_thp_env(&mut bwrap_cmd, val);
+ bwrap_cmd.get_args().to_vec()
+ };
+
+ let enabled_args = build_args(Some(OsStr::new("1")));
+ assert!(
+ enabled_args
+ .windows(3)
+ .any(|w| w[0] == "--setenv" && w[1] == "KRUN_USE_THP" && w[2] == "1")
+ );
+
+ for disabled in [
+ None,
+ Some(OsStr::new("")),
+ Some(OsStr::new("0")),
+ Some(OsStr::new("true")),
+ ] {
+ let args = build_args(disabled);
+ assert!(
+ !args
+ .windows(2)
+ .any(|w| w[0] == "--setenv" && w[1] == "KRUN_USE_THP"),
+ "unexpected KRUN_USE_THP for {disabled:?}"
+ );
+ }
+ }
}
+
+#[cfg(test)]
+#[path = "tests/bwrap_mounts.rs"]
+mod bind_mounts_tests;
diff --git a/src/boxlite/src/jailer/sandbox/tests/bwrap_mounts.rs b/src/boxlite/src/jailer/sandbox/tests/bwrap_mounts.rs
new file mode 100644
index 000000000..cb8b08626
--- /dev/null
+++ b/src/boxlite/src/jailer/sandbox/tests/bwrap_mounts.rs
@@ -0,0 +1,219 @@
+use super::*;
+use crate::runtime::advanced_options::ResourceLimits;
+
+fn tempdir_with(dirs: &[&str]) -> (tempfile::TempDir, std::path::PathBuf) {
+ let dir = tempfile::tempdir().unwrap();
+ let root = dir.path().canonicalize().unwrap();
+ for d in dirs {
+ std::fs::create_dir_all(root.join(d)).unwrap();
+ }
+ (dir, root)
+}
+
+fn mount_plan(root: &Path, paths: &[(&str, bool)]) -> Vec<(std::path::PathBuf, bool)> {
+ let limits = ResourceLimits::default();
+ bind_mounts(&SandboxContext {
+ id: "test-mounts",
+ paths: paths
+ .iter()
+ .map(|&(p, writable)| PathAccess {
+ path: root.join(p),
+ writable,
+ })
+ .collect(),
+ unix_sockets: Default::default(),
+ resource_limits: &limits,
+ network_enabled: false,
+ sandbox_profile: None,
+ shim_cache_dir: None,
+ detached: false,
+ })
+ .into_iter()
+ .map(|pa| (pa.path.strip_prefix(root).unwrap().to_owned(), pa.writable))
+ .collect()
+}
+
+#[test]
+fn bind_mounts_readonly_parent_suppresses_writable_descendants() {
+ let (_dir, root) = tempdir_with(&[
+ "bases/writable/protected/redundant",
+ "bases/writable/redundant",
+ "bases-sibling",
+ ]);
+ std::fs::write(root.join("bases/image.ext4"), []).unwrap();
+ let mounts = mount_plan(
+ &root,
+ &[
+ ("bases/writable/protected", false),
+ ("bases/writable/protected", true),
+ ("bases/writable/redundant", true),
+ ("bases/writable", true),
+ ("bases/image.ext4", false),
+ ("bases", false),
+ ("bases/writable/protected/redundant", false),
+ ("bases-sibling", false),
+ ],
+ );
+ assert_eq!(
+ mounts,
+ [("bases".into(), false), ("bases-sibling".into(), false)]
+ );
+}
+
+#[test]
+fn bind_mounts_writable_parent_preserves_readonly_override_after_rw() {
+ let (_dir, root) = tempdir_with(&["work/sub", "work/locked/rw-child", "other"]);
+ let mounts = mount_plan(
+ &root,
+ &[
+ ("work/sub", true),
+ ("work/locked/rw-child", true),
+ ("work/locked", false),
+ ("work", true),
+ ("other", false),
+ ],
+ );
+ assert_eq!(
+ mounts,
+ [
+ ("work".into(), true),
+ ("other".into(), false),
+ ("work/locked".into(), false),
+ ]
+ );
+}
+
+#[test]
+fn bind_mounts_exact_path_conflict_keeps_readonly() {
+ let (_dir, root) = tempdir_with(&["shared"]);
+ let mounts = mount_plan(&root, &[("shared", true), ("shared", false)]);
+ assert_eq!(mounts, [("shared".into(), false)]);
+}
+
+#[test]
+fn bind_mounts_preserve_mounts_overlapping_symlink_names_and_targets() {
+ let (_dir, root) = tempdir_with(&["aliases", "real/target/nested", "unrelated/nested"]);
+ std::os::unix::fs::symlink("../real/target", root.join("aliases/link")).unwrap();
+ let mounts = mount_plan(
+ &root,
+ &[
+ ("aliases/link", false),
+ ("real/target/nested", true),
+ ("unrelated/nested", false),
+ ("aliases", false),
+ ("real", true),
+ ("unrelated", false),
+ ],
+ );
+ assert_eq!(
+ mounts,
+ [
+ ("real/target/nested".into(), true),
+ ("real".into(), true),
+ ("aliases/link".into(), false),
+ ("aliases".into(), false),
+ ("unrelated".into(), false),
+ ]
+ );
+ let (_dir2, root2) = tempdir_with(&["z/deep/path", "a/b", "a/c"]);
+ std::os::unix::fs::symlink("a/b", root2.join("link")).unwrap();
+ let mounts = mount_plan(
+ &root2,
+ &[
+ ("z/deep/path", true),
+ ("a", true),
+ ("a/c", false),
+ ("link", false),
+ ],
+ );
+ let pos = |p: &str| mounts.iter().position(|(m, _)| m == Path::new(p)).unwrap();
+ assert!(
+ pos("a") < pos("a/c")
+ && pos("a/c") < pos("link")
+ && mounts.contains(&("z/deep/path".into(), true))
+ );
+}
+
+#[test]
+fn bind_mounts_nonexistent_path_preserves_rw_before_ro_order() {
+ let (_dir, root) = tempdir_with(&["existing", "plain"]);
+ let mounts = mount_plan(
+ &root,
+ &[
+ ("existing/missing", true),
+ ("existing", false),
+ ("plain", false),
+ ],
+ );
+ assert_eq!(
+ mounts,
+ [
+ ("existing/missing".into(), true),
+ ("existing".into(), false),
+ ("plain".into(), false),
+ ]
+ );
+}
+
+#[test]
+fn apply_readonly_parent_suppresses_writable_child_in_bwrap() {
+ if !bwrap::is_available() || bwrap::can_create_user_namespace().is_err() {
+ eprintln!(
+ "skipping apply_readonly_parent_suppresses_writable_child_in_bwrap: bwrap or userns not available"
+ );
+ return;
+ }
+
+ let (_dir, root) = tempdir_with(&["ro_parent/rw_child", "rw_control"]);
+ let ro_child = root.join("ro_parent/rw_child");
+ let rw_control = root.join("rw_control");
+
+ let limits = Box::leak(Box::new(ResourceLimits::default()));
+ let ctx = SandboxContext {
+ id: "test-ro-suppresses-rw",
+ paths: vec![
+ PathAccess {
+ path: root.join("ro_parent"),
+ writable: false,
+ },
+ PathAccess {
+ path: ro_child.clone(),
+ writable: true,
+ },
+ PathAccess {
+ path: rw_control.clone(),
+ writable: true,
+ },
+ ],
+ unix_sockets: Default::default(),
+ resource_limits: limits,
+ network_enabled: false,
+ sandbox_profile: None,
+ shim_cache_dir: None,
+ detached: true,
+ };
+
+ let mut cmd = Command::new("/bin/sh");
+ cmd.arg("-c")
+ .arg("test -d \"$1\" || exit 11; if touch \"$1/probe.txt\" 2>/dev/null; then exit 10; fi; touch \"$2/probe.txt\"")
+ .arg("sh")
+ .arg(&ro_child)
+ .arg(&rw_control);
+ BwrapSandbox::new().apply(&ctx, &mut cmd);
+
+ let output = cmd.output().expect("execute bwrap ro-parent test");
+ assert!(
+ output.status.success(),
+ "bwrap execution failed (status={:?}): {}",
+ output.status.code(),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert!(
+ !ro_child.join("probe.txt").exists(),
+ "writable child under readonly parent must remain read-only"
+ );
+ assert!(
+ rw_control.join("probe.txt").exists(),
+ "independent writable control directory must be writable"
+ );
+}
diff --git a/src/boxlite/src/jailer/tests/bwrap_system_dirs.rs b/src/boxlite/src/jailer/tests/bwrap_system_dirs.rs
new file mode 100644
index 000000000..b3beb456b
--- /dev/null
+++ b/src/boxlite/src/jailer/tests/bwrap_system_dirs.rs
@@ -0,0 +1,147 @@
+use super::*;
+
+#[test]
+fn inspect_system_dirs_distinguishes_usrmerge_aliases_from_binds() {
+ use std::fs;
+ use std::os::unix::fs::symlink;
+
+ let dir = tempfile::tempdir().unwrap();
+ let root = dir.path().canonicalize().unwrap();
+ for name in ["usr/lib", "usr/bin", "opt/tools"] {
+ fs::create_dir_all(root.join(name)).unwrap();
+ }
+ symlink("usr/lib", root.join("lib")).unwrap();
+ symlink("/usr/bin", root.join("bin")).unwrap();
+ symlink("opt/tools", root.join("sbin")).unwrap();
+ symlink("usr/lib64", root.join("lib64")).unwrap();
+
+ let dirs = inspect_system_dirs(&root);
+ assert!(
+ matches!(
+ dirs.as_slice(),
+ [SystemDir::Bind(usr), SystemDir::UsrAlias { path: lib, target: lib_target },
+ SystemDir::UsrAlias { path: bin, target: bin_target }, SystemDir::Bind(sbin)]
+ if usr == Path::new("/usr")
+ && lib == Path::new("/lib") && lib_target == Path::new("usr/lib")
+ && bin == Path::new("/bin") && bin_target == Path::new("/usr/bin")
+ && sbin == Path::new("/sbin")
+ ),
+ "unexpected system directories: {dirs:?}"
+ );
+}
+
+#[test]
+fn add_system_dirs_uses_binds_when_mount_destinations_overlap_aliases() {
+ let dirs = [
+ SystemDir::Bind("/usr".into()),
+ SystemDir::UsrAlias {
+ path: "/lib".into(),
+ target: "usr/lib".into(),
+ },
+ ];
+
+ let mut bwrap = BwrapCommand::new();
+ bwrap.add_system_dirs(
+ &dirs,
+ &[
+ Path::new("/opt/nonexistent-boxlite-test"),
+ Path::new("/lib-other"),
+ ],
+ );
+ assert_eq!(
+ bwrap.get_args(),
+ ["--ro-bind", "/usr", "/usr", "--symlink", "usr/lib", "/lib"]
+ );
+
+ for destination in [
+ "/lib/extra",
+ "/usr/lib/extra",
+ "/usr",
+ "relative",
+ "/tmp/../lib",
+ ] {
+ let mut bwrap = BwrapCommand::new();
+ bwrap.add_system_dirs(&dirs, &[Path::new(destination)]);
+ assert_eq!(
+ bwrap.get_args(),
+ ["--ro-bind", "/usr", "/usr", "--ro-bind", "/lib", "/lib"],
+ "destination: {destination}"
+ );
+ }
+}
+
+#[test]
+fn add_system_dirs_resolves_symlinked_mount_destinations() {
+ use std::fs;
+ use std::os::unix::fs::symlink;
+
+ let dir = tempfile::tempdir().unwrap();
+ let root = dir.path().canonicalize().unwrap();
+ let usr = root.join("usr");
+ let usr_lib = usr.join("lib");
+ let lib = root.join("lib");
+ let other = root.join("other");
+ fs::create_dir_all(&usr_lib).unwrap();
+ fs::create_dir_all(&other).unwrap();
+
+ let dirs = [
+ SystemDir::Bind(usr.clone()),
+ SystemDir::UsrAlias {
+ path: lib.clone(),
+ target: usr_lib.clone(),
+ },
+ ];
+
+ let to_usr_lib = root.join("to_usr_lib");
+ let broken = root.join("broken");
+ let to_other = root.join("to_other");
+ symlink(&usr_lib, &to_usr_lib).unwrap();
+ symlink(root.join("nonexistent-target"), &broken).unwrap();
+ symlink(&other, &to_other).unwrap();
+
+ let usr_str = usr.to_string_lossy().into_owned();
+ let usr_lib_str = usr_lib.to_string_lossy().into_owned();
+ let lib_str = lib.to_string_lossy().into_owned();
+
+ let broken_trailing = PathBuf::from(format!("{}/", broken.display()));
+ for destination in [
+ to_usr_lib.as_path(),
+ &to_usr_lib.join("missing"),
+ &broken,
+ &broken_trailing,
+ ] {
+ let mut bwrap = BwrapCommand::new();
+ bwrap.add_system_dirs(&dirs, &[destination]);
+ assert_eq!(
+ bwrap.get_args(),
+ [
+ "--ro-bind",
+ &usr_str,
+ &usr_str,
+ "--ro-bind",
+ &lib_str,
+ &lib_str
+ ],
+ "destination: {}",
+ destination.display()
+ );
+ }
+
+ for destination in [to_other.as_path(), &to_other.join("missing")] {
+ let mut bwrap = BwrapCommand::new();
+ bwrap.add_system_dirs(&dirs, &[destination]);
+ assert_eq!(
+ bwrap.get_args(),
+ [
+ "--ro-bind",
+ &usr_str,
+ &usr_str,
+ "--symlink",
+ &usr_lib_str,
+ &lib_str
+ ],
+ "destination: {}",
+ destination.display()
+ );
+ }
+}
diff --git a/src/deps/libkrun-sys/vendor/libkrun b/src/deps/libkrun-sys/vendor/libkrun
index e12b9b378..a66775ca9 160000
--- a/src/deps/libkrun-sys/vendor/libkrun
+++ b/src/deps/libkrun-sys/vendor/libkrun
@@ -1 +1 @@
-Subproject commit e12b9b3780ffa8df9f3e1797b217d13453479167
+Subproject commit a66775ca9f93a2662031c366a6c5d7b9da0e3bc3