The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
perf(jailer): add shim_cache single-flight and 60s stamp throttle (#3165)
lfld287babf6b0afd3b
diff --git a/docs/concepts/security.md b/docs/concepts/security.mdindex 861f7b217..7e9bf7344 100644--- a/docs/concepts/security.md+++ b/docs/concepts/security.md@@ -62,3 +62,30 @@ let opts = BoxOptions {See the [jailer threat model](../../src/boxlite/src/jailer/README.md) for isolation boundaries,and [jailer network permissions](../contributing/architecture/jailer-network-permissions.md)for guest networking and host access.++## Shim binary cache++Jailed boxes in the same runtime home share a content-addressed cache of the shim+binary and its firmware. On a cache miss, singleflight staging lets concurrent+requests for the same shim source and cache reuse one build. Per-source file+locks and stable digest memos live in `<runtime home>/shims.sources`, next to+`<runtime home>/shims`, so lock state never appears among the 16-digit hex+generation directories. The builder copies the files into a unique staging+directory, writes the `.complete` marker, and atomically renames the directory+into place so readers never see a partially staged generation.++In-process `RwLock`s let cache hits read the digest memo and validate staged+entries concurrently. Memo updates, publication, and marker refreshes use+exclusive access to their respective state. During `cleanup_stale`, the+in-process `LIFECYCLE_LOCK` write lock is acquired only in `retire_if_stale` to+re-check expiration and atomically rename a stale directory out of the cache+namespace; directory scanning, initial metadata checks, and deleting moved-out+directories or expired `.staging.*` orphan directories run outside the lock, and+the lock applies only within a single process. Staging also bounds how long it+waits on the in-process singleflight and per-source file locks, falling back to+the original shim if the timeout expires.++On a cache hit, the `.complete` marker (`STAMP`) is refreshed only when its+modification time is at least 60 seconds old. The cache uses metadata already+read during validation, avoiding a separate stat for the refresh decision and+skipping most mtime update syscalls. Cache hits still validate the staged files.diff --git a/src/boxlite/src/jailer/builder.rs b/src/boxlite/src/jailer/builder.rsindex c9a00569e..ed7228f61 100644--- a/src/boxlite/src/jailer/builder.rs+++ b/src/boxlite/src/jailer/builder.rs@@ -2,6 +2,7 @@use super::Jailer;use super::PathAccess;+use super::StagedShim;use super::sandbox::{PlatformSandbox, Sandbox};use crate::runtime::advanced_options::{ResourceLimits, SecurityOptions};use crate::runtime::layout::BoxFilesystemLayout;@@ -31,6 +32,7 @@ pub struct JailerBuilder {box_id: Option<String>,layout: Option<BoxFilesystemLayout>,shim_cache_dir: Option<PathBuf>,+ staged_shim: StagedShim,preserved_fds: Vec<(RawFd, i32)>,detach: bool,additional_path_access: Vec<PathAccess>,@@ -53,6 +55,7 @@ impl JailerBuilder {box_id: None,layout: None,shim_cache_dir: None,+ staged_shim: StagedShim::Unstaged,preserved_fds: Vec::new(),detach: false,additional_path_access: Vec::new(),@@ -77,6 +80,11 @@ impl JailerBuilder {self}+ pub(crate) fn with_staged_shim(mut self, staged_shim: StagedShim) -> Self {+ self.staged_shim = staged_shim;+ self+ }+/// Set security options.pub fn with_security(mut self, security: SecurityOptions) -> Self {self.security = security;@@ -363,6 +371,7 @@ impl JailerBuilder {box_id,layout,shim_cache_dir: self.shim_cache_dir,+ staged_shim: self.staged_shim,preserved_fds: self.preserved_fds,detach: self.detach,additional_path_access: self.additional_path_access,diff --git a/src/boxlite/src/jailer/command.rs b/src/boxlite/src/jailer/command.rsindex 27756412b..dd164151e 100644--- a/src/boxlite/src/jailer/command.rs+++ b/src/boxlite/src/jailer/command.rs@@ -5,9 +5,9 @@#[cfg(test)]mod tests {- use crate::jailer::Jail;use crate::jailer::builder::JailerBuilder;use crate::jailer::sandbox::{PathAccess, Sandbox, SandboxContext};+ use crate::jailer::{Jail, StagedShim, shim_cache};use crate::runtime::advanced_options::SecurityOptions;use crate::runtime::layout::{BoxFilesystemLayout, FsLayoutConfig};use std::fs;@@ -193,6 +193,107 @@ mod tests {}}+ #[test]+ fn command_uses_prestaged_shim_without_restaging() {+ let (home, binary, _layout, builder) = staging_fixture();+ let cache = home.path().join("shims");+ let prestaged_dir = cache.join("0000000000000001");+ fs::create_dir_all(&prestaged_dir).unwrap();+ let prestaged = prestaged_dir.join("boxlite-shim");+ fs::write(&prestaged, b"prestaged-shim").unwrap();++ let canonical_cache = cache.canonicalize().unwrap();+ let source_key = binary+ .parent()+ .unwrap()+ .canonicalize()+ .unwrap()+ .join(binary.file_name().unwrap());+ let _lock = shim_cache::lock_source(&canonical_cache, &source_key).unwrap();++ let jail = builder+ .with_shim_cache_dir(&cache)+ .with_staged_shim(StagedShim::Staged(prestaged.clone()))+ .build_with(RecordingSandbox::default())+ .unwrap();++ let cmd = jail.command(&binary, &[]);+ assert_eq!(cmd.get_program(), prestaged);++ let entries: Vec<_> = fs::read_dir(&cache)+ .unwrap()+ .map(|e| e.unwrap().file_name())+ .collect();+ assert_eq!(entries, vec![std::ffi::OsString::from("0000000000000001")]);++ let grants = jail.sandbox.0.lock().unwrap();+ let canonical_prestaged_dir = prestaged_dir.canonicalize().unwrap();+ for dir in [binary.parent().unwrap(), canonical_prestaged_dir.as_path()] {+ let matching: Vec<_> = grants.iter().filter(|grant| grant.path == dir).collect();+ assert_eq!(matching.len(), 1);+ assert!(!matching[0].writable);+ }+ }++ #[cfg(unix)]+ #[test]+ fn command_fallback_skips_restaging_and_grants_symlink_targets() {+ use std::os::unix::fs::symlink;++ let home = tempfile::tempdir().unwrap();+ let target_root = home.path().join("target-debug");+ let build_out = target_root.join("build/boxlite-hash/out/runtime");+ let runtime_dir = target_root.join("runtime");+ let cache = home.path().join("shims");+ fs::create_dir_all(&build_out).unwrap();+ fs::create_dir_all(&runtime_dir).unwrap();+ fs::create_dir_all(&cache).unwrap();++ let real_shim = target_root.join("boxlite-shim");+ let real_fw = build_out.join("libkrunfw.5.dylib");+ let sibling_top = target_root.join("sibling.txt");+ fs::write(&real_shim, b"shim").unwrap();+ fs::write(&real_fw, b"fw").unwrap();+ fs::write(&sibling_top, b"secret").unwrap();++ let runtime_shim = runtime_dir.join("boxlite-shim");+ let runtime_fw = runtime_dir.join("libkrunfw.5.dylib");+ symlink("../boxlite-shim", &runtime_shim).unwrap();+ symlink(+ "../build/boxlite-hash/out/runtime/libkrunfw.5.dylib",+ &runtime_fw,+ )+ .unwrap();++ let canonical_cache = cache.canonicalize().unwrap();+ let source_key = runtime_dir.canonicalize().unwrap().join("boxlite-shim");+ let _lock = shim_cache::lock_source(&canonical_cache, &source_key).unwrap();++ let layout = test_layout(home.path().join("boxes/test-box"));+ let jail = JailerBuilder::new()+ .with_box_id("test-box")+ .with_layout(layout)+ .with_shim_cache_dir(&cache)+ .with_staged_shim(StagedShim::Fallback)+ .with_jailer_enabled(true)+ .build_with(RecordingSandbox::default())+ .unwrap();++ let cmd = jail.command(&runtime_shim, &[]);+ assert_eq!(cmd.get_program(), runtime_shim);+ assert_eq!(fs::read_dir(&cache).unwrap().count(), 0);++ let canonical_shim = real_shim.canonicalize().unwrap();+ let canonical_fw = real_fw.canonicalize().unwrap();+ let grants = jail.sandbox.0.lock().unwrap();+ for resolved in [&canonical_shim, &canonical_fw] {+ let matches: Vec<_> = grants.iter().filter(|g| &g.path == resolved).collect();+ assert_eq!(matches.len(), 1);+ assert!(!matches[0].writable);+ }+ assert!(grants.iter().all(|g| g.path != sibling_top));+ }+#[test]fn command_jailer_disabled_skips_staging_and_leaves_legacy_untouched() {let (home, binary, layout, builder) = staging_fixture();diff --git a/src/boxlite/src/jailer/mod.rs b/src/boxlite/src/jailer/mod.rsindex 4bd9757ff..13acc15cc 100644--- a/src/boxlite/src/jailer/mod.rs+++ b/src/boxlite/src/jailer/mod.rs@@ -387,6 +387,18 @@ fn system_ca_paths() -> [PathBuf; 5] {]}+/// Pre-staged shim outcome passed into [`Jailer`] when staging ran off-thread.+#[derive(Debug, Clone, Default)]+pub(crate) enum StagedShim {+ /// Staging has not been attempted yet; [`Jailer::command`] stages lazily.+ #[default]+ Unstaged,+ /// Shim was already staged at this path.+ Staged(PathBuf),+ /// Staging failed and was already logged; fall back to the original shim.+ Fallback,+}+/// Jailer provides process isolation for boxlite-shim.////// Encapsulates security configuration and delegates to a [`Sandbox`]@@ -423,6 +435,7 @@ pub struct Jailer<S: Sandbox> {/// Box filesystem layout (provides typed path accessors).pub(crate) layout: BoxFilesystemLayout,pub(crate) shim_cache_dir: Option<PathBuf>,+ pub(crate) staged_shim: StagedShim,/// FDs to preserve through pre_exec: each (source_fd, target_fd) is dup2'd/// before FD cleanup. Used for watchdog pipe inheritance across fork.pub(crate) preserved_fds: Vec<(std::os::fd::RawFd, i32)>,@@ -481,14 +494,21 @@ impl<S: Sandbox> Jail for Jailer<S> {}let mut staged_ok = false;if let Some(cache_dir) = self.resolve_shim_cache_dir() {- match shim_cache::stage_shim(binary, &cache_dir) {- Ok(staged) => {- effective_binary = staged;+ match &self.staged_shim {+ StagedShim::Staged(staged) => {+ effective_binary = staged.clone();staged_ok = true;}- Err(err) => {- tracing::warn!(error = %err, "Failed to stage shim, using original")- }+ StagedShim::Fallback => {}+ StagedShim::Unstaged => match shim_cache::stage_shim(binary, &cache_dir) {+ Ok(staged) => {+ effective_binary = staged;+ staged_ok = true;+ }+ Err(err) => {+ tracing::warn!(error = %err, "Failed to stage shim, using original")+ }+ },}ctx.shim_cache_dir = Some(cache_dir);} else {diff --git a/src/boxlite/src/jailer/shim_cache.rs b/src/boxlite/src/jailer/shim_cache.rsindex ebfe54ee0..7897ab0f2 100644--- a/src/boxlite/src/jailer/shim_cache.rs+++ b/src/boxlite/src/jailer/shim_cache.rs@@ -2,21 +2,24 @@use boxlite_shared::errors::{BoxliteError, BoxliteResult};use filetime::FileTime;-use parking_lot::Mutex;+use parking_lot::{Mutex, RwLock};use sha2::{Digest, Sha256};use std::collections::HashMap;use std::ffi::{OsStr, OsString};use std::fs::{self, Metadata};-use std::io::{self, Read};-#[cfg(unix)]-use std::os::unix::fs::{MetadataExt, PermissionsExt};+use std::io::{self, Read, Seek, Write};+use std::os::fd::AsRawFd;+use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt};use std::path::{Path, PathBuf};use std::sync::atomic::{AtomicU64, Ordering};-use std::sync::{Arc, OnceLock};-use std::time::{Duration, SystemTime};+use std::sync::{Arc, LazyLock, Weak};+use std::time::{Duration, Instant, SystemTime};+/// Bound how long staging waits on singleflight or source locks before falling back.+const SOURCE_LOCK_TIMEOUT: Duration = Duration::from_secs(30);/// Hidden completion marker written after all generation files are copied.const STAMP: &str = ".complete";+const STAMP_REFRESH_INTERVAL: Duration = Duration::from_secs(60);/// Hidden namespace for temporary directories outside the published digest names.const STAGING_PREFIX: &str = ".staging.";/// Give in-progress staging an hour before treating its directory as abandoned.@@ -50,8 +53,11 @@ const FIRMWARE_MODE: u32 = 0o644;pub(crate) const BWRAP_SANDBOX_SHIM_DIR: &str = "/run/boxlite-shim";static SEQUENCE: AtomicU64 = AtomicU64::new(0);-static MEMO: OnceLock<Mutex<HashMap<PathBuf, Arc<MemoEntry>>>> = OnceLock::new();-static LIFECYCLE_LOCK: Mutex<()> = Mutex::new(());+static MEMO: LazyLock<RwLock<HashMap<PathBuf, Arc<MemoEntry>>>> = LazyLock::new(RwLock::default);+static LIFECYCLE_LOCK: RwLock<()> = RwLock::new(());+type StageFlight = Mutex<Option<Arc<MemoEntry>>>;+type StageFlights = HashMap<(PathBuf, PathBuf), Weak<StageFlight>>;+static STAGE_FLIGHTS: LazyLock<Mutex<StageFlights>> = LazyLock::new(Mutex::default);#[derive(Debug, Clone, PartialEq, Eq)]pub(crate) struct ResolvedRuntimeFile {@@ -257,21 +263,31 @@ fn collect_sources(shim: &Path, dir: &Path, name: &OsStr) -> io::Result<Vec<FileOk(files)}+fn memoized_digest(key: &Path, files: &[FileFingerprint]) -> Option<Arc<MemoEntry>> {+ MEMO.read()+ .get(key)+ .filter(|entry| entry.fingerprints == files)+ .cloned()+}++fn remember_digest(key: &Path, entry: &Arc<MemoEntry>) {+ MEMO.write().insert(key.to_path_buf(), Arc::clone(entry));+}++fn stable_sources(files: &[FileFingerprint], now: SystemTime) -> bool {+ let cutoff = FileTime::from_system_time(now - RACY_STAT_WINDOW);+ files.iter().all(|f| f.older_than(cutoff))+}+fn digest_at(- shim: &Path,+ key: &Path,dir: &Path,files: &[FileFingerprint],now: SystemTime,-) -> io::Result<String> {- let key = shim.canonicalize().unwrap_or_else(|_| shim.to_path_buf());- let memo = MEMO.get_or_init(|| Mutex::new(HashMap::new()));- let cached = memo.lock().get(&key).cloned();- if let Some(entry) = cached- && entry.fingerprints == files- {- return Ok(entry.digest.clone());+) -> io::Result<Arc<MemoEntry>> {+ if let Some(entry) = memoized_digest(key, files) {+ return Ok(entry);}-let mut hash = Sha256::new();let mut buffer = [0; HASH_BUFFER_BYTES];for source in files {@@ -290,25 +306,146 @@ fn digest_at(}source.check_metadata(&path, &file.metadata()?)?;}- let digest = hex::encode(&hash.finalize()[..DIGEST_BYTES]);- // Coarse file timestamps can alias writes made close to the hash read.- let cutoff = FileTime::from_system_time(now - RACY_STAT_WINDOW);- if files.iter().all(|f| f.older_than(cutoff)) {- let entry = Arc::new(MemoEntry {- fingerprints: files.to_vec(),- digest: digest.clone(),- });- let _previous = memo.lock().insert(key, entry);+ let entry = Arc::new(MemoEntry {+ fingerprints: files.to_vec(),+ digest: hex::encode(&hash.finalize()[..DIGEST_BYTES]),+ });+ if stable_sources(files, now) {+ remember_digest(key, &entry);}- Ok(digest)+ Ok(entry)+}++fn digest_name(bytes: &[u8]) -> bool {+ bytes.len() == DIGEST_HEX_LEN+ && bytes+ .iter()+ .all(|&b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))+}++#[cfg(test)]+pub(crate) fn lock_source(cache_dir: &Path, source_key: &Path) -> io::Result<fs::File> {+ lock_source_until(cache_dir, source_key, Instant::now() + SOURCE_LOCK_TIMEOUT)}-fn is_complete(target: &Path, files: &[FileFingerprint]) -> bool {- target.join(STAMP).is_file()+fn lock_source_until(+ cache_dir: &Path,+ source_key: &Path,+ deadline: Instant,+) -> io::Result<fs::File> {+ let name = cache_dir.file_name().ok_or(io::ErrorKind::InvalidInput)?;+ let mut dir = name.to_os_string();+ dir.push(".sources");+ let locks = cache_dir.with_file_name(dir);+ let mut builder = fs::DirBuilder::new();+ builder.recursive(true).mode(0o700).create(&locks)?;+ let name = hex::encode(Sha256::digest(source_key.as_os_str().as_encoded_bytes()));+ // Never unlink lock files: waiters may still have the original inode open.+ let file = fs::File::options()+ .read(true)+ .write(true)+ .create(true)+ .truncate(false)+ .mode(0o600)+ .custom_flags(libc::O_NOFOLLOW)+ .open(locks.join(name))?;+ let mut backoff = Duration::from_millis(1);+ const MAX_BACKOFF: Duration = Duration::from_millis(25);+ loop {+ // SAFETY: `file` owns the open descriptor and closing it releases the lock.+ if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 {+ return Ok(file);+ }+ let err = io::Error::last_os_error();+ match err.kind() {+ io::ErrorKind::Interrupted => continue,+ io::ErrorKind::WouldBlock => {+ let now = Instant::now();+ if now >= deadline {+ return Err(io::Error::new(+ io::ErrorKind::TimedOut,+ "timed out waiting for shim source lock",+ ));+ }+ std::thread::sleep(backoff.min(deadline - now));+ backoff = (backoff * 2).min(MAX_BACKOFF);+ }+ _ => return Err(err),+ }+ }+}++fn fingerprint_key(files: &[FileFingerprint]) -> [u8; 32] {+ let mut hash = Sha256::new();+ for f in files {+ let name = f.name.as_encoded_bytes();+ hash.update((name.len() as u64).to_le_bytes());+ hash.update(name);+ hash.update(f.len.to_le_bytes());+ for t in [f.mtime, f.ctime] {+ hash.update(t.unix_seconds().to_le_bytes());+ hash.update(t.nanoseconds().to_le_bytes());+ }+ hash.update(f.inode.0.to_le_bytes());+ hash.update(f.inode.1.to_le_bytes());+ }+ hash.finalize().into()+}++fn read_digest(mut lock: &fs::File, key: &[u8; 32]) -> Option<String> {+ let mut record = [0; 32 + DIGEST_HEX_LEN];+ lock.read_exact(&mut record).ok()?;+ let (stored_key, digest) = record.split_at(32);+ (stored_key == key && digest_name(digest)).then(|| String::from_utf8_lossy(digest).into_owned())+}++fn write_digest(mut lock: &fs::File, key: &[u8; 32], digest: &str) -> io::Result<()> {+ lock.rewind()?;+ lock.set_len(0)?;+ lock.write_all(key)?;+ lock.write_all(digest.as_bytes())+}++fn complete_stamp(target: &Path, files: &[FileFingerprint]) -> Option<Metadata> {+ let stamp = fs::metadata(target.join(STAMP)).ok()?;+ (stamp.is_file()&& files.iter().all(|file| {fs::metadata(target.join(&file.name)).is_ok_and(|metadata| metadata.is_file() && metadata.len() == file.len)- })+ }))+ .then_some(stamp)+}++fn refresh_stamp(path: &Path, stamp: &Metadata, now: SystemTime) {+ if refresh_due(stamp, now) {+ let _ = filetime::set_file_mtime(path.join(STAMP), FileTime::from_system_time(now));+ }+}++fn refresh_due(stamp: &Metadata, now: SystemTime) -> bool {+ stamp.modified().is_ok_and(|time| {+ now.duration_since(time)+ .is_ok_and(|age| age >= STAMP_REFRESH_INTERVAL)+ })+}++fn cache_hit(target: &Path, files: &[FileFingerprint]) -> bool {+ {+ let _lock = LIFECYCLE_LOCK.read();+ let Some(stamp) = complete_stamp(target, files) else {+ return false;+ };+ if !refresh_due(&stamp, SystemTime::now()) {+ return true;+ }+ }+ // Recheck in case another hit refreshed the stamp or GC retired it.+ let _lock = LIFECYCLE_LOCK.write();+ let Some(stamp) = complete_stamp(target, files) else {+ return false;+ };+ refresh_stamp(target, &stamp, SystemTime::now());+ true}struct StagingGuard {@@ -318,14 +455,14 @@ struct StagingGuard {impl StagingGuard {fn publish(mut self, target: &Path, files: &[FileFingerprint]) -> io::Result<bool> {- let result = fs::rename(&self.path, target);- let _lock = LIFECYCLE_LOCK.lock();- match result {+ let _lock = LIFECYCLE_LOCK.write();+ match fs::rename(&self.path, target) {Ok(()) => self.published = true,- Err(_) if is_complete(target, files) => {}- Err(err) => return Err(err),+ Err(err) => {+ let stamp = complete_stamp(target, files).ok_or(err)?;+ refresh_stamp(target, &stamp, SystemTime::now());+ }}- let _ = filetime::set_file_mtime(target.join(STAMP), FileTime::now());Ok(self.published)}}@@ -349,64 +486,155 @@ pub(crate) fn stage_shim(shim_path: &Path, cache_dir: &Path) -> BoxliteResult<Pa}fn stage(shim_path: &Path, cache_dir: &Path) -> io::Result<PathBuf> {+ stage_with_timeout(+ shim_path,+ cache_dir,+ SystemTime::now(),+ SOURCE_LOCK_TIMEOUT,+ digest_at,+ )+}++#[cfg(test)]+fn stage_with(+ shim_path: &Path,+ cache_dir: &Path,+ now: SystemTime,+ digest: impl FnOnce(&Path, &Path, &[FileFingerprint], SystemTime) -> io::Result<Arc<MemoEntry>>,+) -> io::Result<PathBuf> {+ stage_with_timeout(shim_path, cache_dir, now, SOURCE_LOCK_TIMEOUT, digest)+}++fn stage_with_timeout(+ shim_path: &Path,+ cache_dir: &Path,+ now: SystemTime,+ timeout: Duration,+ digest: impl FnOnce(&Path, &Path, &[FileFingerprint], SystemTime) -> io::Result<Arc<MemoEntry>>,+) -> io::Result<PathBuf> {+ let deadline = Instant::now() + timeout;let name = shim_path.file_name().filter(|name| !name.is_empty() && *name != STAMP).ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "invalid shim filename"))?;let dir = shim_parent_dir(shim_path);+ // Key by the logical shim path so adjacent firmware stays part of its identity.+ let source_key = dir.canonicalize()?.join(name);let files = collect_sources(shim_path, dir, name)?;- let digest = digest_at(shim_path, dir, &files, SystemTime::now())?;- let target = cache_dir.join(&digest);-- let hit = {- let _lock = LIFECYCLE_LOCK.lock();- let complete = is_complete(&target, &files);- if complete {- let _ = filetime::set_file_mtime(target.join(STAMP), FileTime::now());+ if let Some(entry) = memoized_digest(&source_key, &files)+ && let Some(path) = cached_path(cache_dir, name, &entry)+ {+ return Ok(path);+ }++ fs::create_dir_all(cache_dir)?;+ let cache_dir = cache_dir.canonicalize()?;+ let flight = {+ let mut flights = STAGE_FLIGHTS.lock();+ flights.retain(|_, flight| flight.strong_count() != 0);+ let entry = flights+ .entry((cache_dir.clone(), source_key.clone()))+ .or_default();+ entry.upgrade().unwrap_or_else(|| {+ let flight = Arc::new(Mutex::new(None));+ *entry = Arc::downgrade(&flight);+ flight+ })+ };+ let mut recent = flight.try_lock_until(deadline).ok_or_else(|| {+ io::Error::new(+ io::ErrorKind::TimedOut,+ "timed out waiting for in-process shim staging flight",+ )+ })?;+ if let Some(entry) = recent.as_ref()+ && entry.fingerprints == collect_sources(shim_path, dir, name)?+ && let Some(path) = cached_path(&cache_dir, name, entry)+ {+ return Ok(path);+ }++ let lock = lock_source_until(&cache_dir, &source_key, deadline)?;+ // The source may have changed while another process held the lock.+ let files = collect_sources(shim_path, dir, name)?;+ let key = stable_sources(&files, now).then(|| fingerprint_key(&files));+ if let Some(key) = &key+ && let Some(digest) = read_digest(&lock, key)+ {+ let entry = Arc::new(MemoEntry {+ fingerprints: files.clone(),+ digest,+ });+ if let Some(path) = cached_path(&cache_dir, name, &entry) {+ remember_digest(&source_key, &entry);+ *recent = Some(entry);+ return Ok(path);}- complete+ }+ let entry = digest(&source_key, dir, &files, now)?;+ let target = cache_dir.join(&entry.digest);+ if !cache_hit(&target, &files) {+ publish_generation(&cache_dir, &target, name, dir, &entry)?;+ }+ if let Some(key) = &key {+ let _ = write_digest(&lock, key, &entry.digest);+ }+ *recent = Some(entry);+ Ok(target.canonicalize().unwrap_or(target).join(name))+}++fn cached_path(cache_dir: &Path, name: &OsStr, entry: &MemoEntry) -> Option<PathBuf> {+ let target = cache_dir.join(&entry.digest);+ cache_hit(&target, &entry.fingerprints)+ .then(|| target.canonicalize().unwrap_or(target).join(name))+}++fn publish_generation(+ cache_dir: &Path,+ target: &Path,+ name: &OsStr,+ dir: &Path,+ entry: &MemoEntry,+) -> io::Result<()> {+ let digest = &entry.digest;+ let seq = SEQUENCE.fetch_add(1, Ordering::Relaxed);+ let path = cache_dir.join(format!(+ "{STAGING_PREFIX}{digest}.{}.{seq}",+ std::process::id()+ ));+ fs::create_dir(&path)?;+ let staging = StagingGuard {+ path,+ published: false,};- if !hit {- fs::create_dir_all(cache_dir)?;- let seq = SEQUENCE.fetch_add(1, Ordering::Relaxed);- let path = cache_dir.join(format!(- "{STAGING_PREFIX}{digest}.{}.{seq}",- std::process::id()- ));- fs::create_dir(&path)?;- let staging = StagingGuard {- path,- published: false,- };+ #[cfg(unix)]+ fs::set_permissions(&staging.path, fs::Permissions::from_mode(EXECUTABLE_MODE))?;++ for source in &entry.fingerprints {+ let path = dir.join(&source.name);+ let destination = staging.path.join(&source.name);+ fs::copy(&path, &destination)?;+ let metadata = fs::metadata(&path)?;+ source.check_metadata(&path, &metadata)?;#[cfg(unix)]- fs::set_permissions(&staging.path, fs::Permissions::from_mode(EXECUTABLE_MODE))?;-- for source in &files {- let path = dir.join(&source.name);- let destination = staging.path.join(&source.name);- fs::copy(&path, &destination)?;- let metadata = fs::metadata(&path)?;- source.check_metadata(&path, &metadata)?;- #[cfg(unix)]- {- let mode = if source.name == name {- EXECUTABLE_MODE- } else {- FIRMWARE_MODE- };- fs::set_permissions(&destination, fs::Permissions::from_mode(mode))?;- }- }- fs::write(- staging.path.join(STAMP),- format!("{}\n{BUILD_PROFILE}\n", crate::VERSION),- )?;- if staging.publish(&target, &files)? {- tracing::info!(path = %target.display(), "Published shared shim");- cleanup_stale(cache_dir, Some(&target));+ {+ let mode = if source.name == name {+ EXECUTABLE_MODE+ } else {+ FIRMWARE_MODE+ };+ fs::set_permissions(&destination, fs::Permissions::from_mode(mode))?;}}- Ok(target.canonicalize().unwrap_or(target).join(name))+ fs::write(+ staging.path.join(STAMP),+ format!("{}\n{BUILD_PROFILE}\n", crate::VERSION),+ )?;+ if staging.publish(target, &entry.fingerprints)? {+ tracing::info!(path = %target.display(), "Published shared shim");+ cleanup_stale(cache_dir, Some(target));+ }+ Ok(())}fn published_metadata(path: &Path) -> io::Result<Metadata> {@@ -425,7 +653,7 @@ fn retire_if_stale(now: SystemTime,ttl: Duration,) -> io::Result<bool> {- let _lock = LIFECYCLE_LOCK.lock();+ let _lock = LIFECYCLE_LOCK.write();if !is_expired(published_metadata(path), now, ttl) {return Ok(false);}@@ -452,9 +680,7 @@ pub(crate) fn cleanup_stale(cache_dir: &Path, active_dir: Option<&Path>) {}continue;}- if name.len() != DIGEST_HEX_LEN- || !name.iter().all(|&b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))- {+ if !digest_name(name) {continue;}if active_dir == Some(path.as_path())@@ -465,10 +691,11 @@ pub(crate) fn cleanup_stale(cache_dir: &Path, active_dir: Option<&Path>) {continue;}let profile = fs::read_to_string(path.join(STAMP)).unwrap_or_default();+ // A hit may skip a stamp write for up to one refresh interval.let ttl = match profile.lines().nth(1) {Some("debug") => STALE_TTL_DEBUG,_ => STALE_TTL_RELEASE,- };+ } + STAMP_REFRESH_INTERVAL;if !is_expired(published_metadata(&path), now, ttl) {continue;}@@ -560,6 +787,29 @@ mod tests {assert!(FileTime::from_last_modification_time(&fs::metadata(stamp).unwrap()) > old);}+ #[test]+ fn stage_shim_throttles_stamp_refresh() {+ let (_root, shim, cache) = fixture();+ let staged = stage_shim(&shim, &cache).unwrap();+ let stamp = staged.with_file_name(STAMP);+ let mtime = || FileTime::from_last_modification_time(&fs::metadata(&stamp).unwrap());+ set_file_mtime(+ &stamp,+ FileTime::from_system_time(SystemTime::now() - STAMP_REFRESH_INTERVAL / 2),+ )+ .unwrap();+ let recent = mtime();+ assert_eq!(stage_shim(&shim, &cache).unwrap(), staged);+ assert_eq!(mtime(), recent);+ set_file_mtime(+ &stamp,+ FileTime::from_system_time(SystemTime::now() - 2 * STAMP_REFRESH_INTERVAL),+ )+ .unwrap();+ assert_eq!(stage_shim(&shim, &cache).unwrap(), staged);+ assert!(mtime() > recent);+ }+#[test]#[cfg(unix)]fn stage_shim_follows_symlinked_sources() {@@ -630,14 +880,13 @@ mod tests {let key = shim.canonicalize().unwrap();let files = collect_sources(&shim, dir, name).unwrap();let now = SystemTime::now() + 2 * RACY_STAT_WINDOW;- let first = digest_at(&shim, dir, &files, now).unwrap();- let memo = MEMO.get().unwrap();- let entry = || memo.lock().get(&key).cloned().unwrap();- let first_entry = entry();- assert_eq!(first_entry.digest, first);-- assert_eq!(digest_at(&shim, dir, &files, now).unwrap(), first);- assert!(Arc::ptr_eq(&first_entry, &entry()));+ let first = digest_at(&key, dir, &files, now).unwrap();+ let entry = || MEMO.read().get(&key).cloned().unwrap();+ assert!(Arc::ptr_eq(&first, &entry()));+ assert!(Arc::ptr_eq(+ &first,+ &digest_at(&key, dir, &files, now).unwrap()+ ));let mtime = files[0].mtime;let prev_inode = files[0].inode;@@ -651,9 +900,9 @@ mod tests {assert_eq!(files[0].mtime, mtime);assert_ne!(files[0].inode, prev_inode);let now = SystemTime::now() + 2 * RACY_STAT_WINDOW;- let updated = digest_at(&shim, dir, &files, now).unwrap();- assert_ne!(updated, first);- assert_eq!(entry().digest, updated);+ let updated = digest_at(&key, dir, &files, now).unwrap();+ assert_ne!(updated.digest, first.digest);+ assert!(Arc::ptr_eq(&updated, &entry()));}#[test]@@ -665,33 +914,154 @@ mod tests {let now = SystemTime::now();set_file_mtime(&shim, FileTime::from_system_time(now)).unwrap();let files = collect_sources(&shim, dir, name).unwrap();- digest_at(&shim, dir, &files, now + RACY_STAT_WINDOW / 2).unwrap();- assert!(!MEMO.get().unwrap().lock().contains_key(&key));+ digest_at(&key, dir, &files, now + RACY_STAT_WINDOW / 2).unwrap();+ assert!(!MEMO.read().contains_key(&key));+ }++ fn assert_single_generation(cache: &Path) {+ let entries: Vec<_> = fs::read_dir(cache)+ .unwrap()+ .map(|e| e.unwrap().file_name())+ .collect();+ assert_eq!(entries.len(), 1, "unexpected cache entries: {entries:?}");+ assert!(digest_name(entries[0].as_encoded_bytes()));}#[test]- fn stage_shim_concurrent_threads_atomic_publish() {- let (_root, shim, cache) = fixture();- let barrier = std::sync::Barrier::new(8);+ fn stage_shim_concurrent_threads_hash_once_even_for_recent_sources() {+ const CALLERS: usize = 20;+ let (root, shim, _) = fixture();+ let cache = root.path().canonicalize().unwrap().join("custom.cache");+ fs::create_dir(&cache).unwrap();+ let flight_key = (cache.clone(), shim.canonicalize().unwrap());+ let lock = lock_source(&cache, &flight_key.1).unwrap();+ let now = SystemTime::now();+ let hashes = AtomicU64::new(0);std::thread::scope(|scope| {- let threads: Vec<_> = (0..8)+ let threads: Vec<_> = (0..CALLERS).map(|_| {scope.spawn(|| {- barrier.wait();- let staged = stage_shim(&shim, &cache).unwrap();+ let staged = stage_with(&shim, &cache, now, |key, dir, files, now| {+ hashes.fetch_add(1, Ordering::Relaxed);+ digest_at(key, dir, files, now)+ })+ .unwrap();assert_eq!(fs::read(&staged).unwrap(), b"shim");assert!(staged.with_file_name(STAMP).is_file());staged})}).collect();- let paths: Vec<_> = threads- .into_iter()- .map(|thread| thread.join().unwrap())- .collect();+ let deadline = std::time::Instant::now() + Duration::from_secs(10);+ // Hold the flock until every caller has joined the in-process flight.+ let joined = loop {+ if STAGE_FLIGHTS+ .lock()+ .get(&flight_key)+ .is_some_and(|f| f.strong_count() == CALLERS)+ {+ break true;+ }+ if std::time::Instant::now() > deadline {+ break false;+ }+ std::thread::sleep(Duration::from_millis(1));+ };+ drop(lock);+ assert!(joined, "callers did not join the same flight");+ let paths: Vec<_> = threads.into_iter().map(|t| t.join().unwrap()).collect();assert!(paths.iter().all(|path| path == &paths[0]));});- assert_eq!(fs::read_dir(cache).unwrap().count(), 1);+ assert_eq!(hashes.load(Ordering::Relaxed), 1);+ assert!(!MEMO.read().contains_key(&flight_key.1));+ assert_single_generation(&cache);+ }++ #[test]+ fn stage_shim_subprocess_worker() {+ let Some(root) = std::env::var_os("BOXLITE_TEST_SHIM_FLIGHT_ROOT").map(PathBuf::from)+ else {+ return;+ };+ let now = SystemTime::now() + 2 * RACY_STAT_WINDOW;+ fs::File::options()+ .create(true)+ .append(true)+ .open(root.join("ready"))+ .unwrap()+ .write_all(b"1")+ .unwrap();+ let staged = stage_with(+ &root.join("source/boxlite-shim"),+ &root.join("shims"),+ now,+ |key, dir, files, now| {+ let mut counter = fs::File::options()+ .create(true)+ .append(true)+ .open(root.join("hashes"))?;+ counter.write_all(b"1")?;+ digest_at(key, dir, files, now)+ },+ )+ .unwrap();+ assert_eq!(fs::read(staged).unwrap(), b"shim");+ }++ #[test]+ fn stage_shim_concurrent_processes_hash_stable_source_once() {+ struct ChildGuard(Vec<std::process::Child>);+ impl Drop for ChildGuard {+ fn drop(&mut self) {+ for child in &mut self.0 {+ let _ = child.kill();+ let _ = child.wait();+ }+ }+ }++ let (root, shim, cache) = fixture();+ let key = shim.canonicalize().unwrap();+ let lock = lock_source(&cache, &key).unwrap();+ let mut children = ChildGuard(+ (0..4)+ .map(|_| {+ std::process::Command::new(std::env::current_exe().unwrap())+ .args([+ "--exact",+ "jailer::shim_cache::tests::stage_shim_subprocess_worker",+ "--quiet",+ ])+ .env("BOXLITE_TEST_SHIM_FLIGHT_ROOT", root.path())+ .stdout(std::process::Stdio::null())+ .spawn()+ .unwrap()+ })+ .collect(),+ );+ let ready_path = root.path().join("ready");+ let ready_deadline = Instant::now() + Duration::from_secs(10);+ let all_ready = loop {+ if fs::read(&ready_path).is_ok_and(|bytes| bytes.len() == 4) {+ break true;+ }+ if Instant::now() >= ready_deadline {+ break false;+ }+ std::thread::sleep(Duration::from_millis(5));+ };+ assert!(all_ready, "children did not reach staging before unlock");+ std::thread::sleep(Duration::from_millis(100));+ assert!(+ !root.path().join("hashes").exists(),+ "children bypassed source lock and hashed while lock was held"+ );+ drop(lock);+ while let Some(mut child) = children.0.pop() {+ assert!(child.wait().unwrap().success());+ }+ assert_eq!(fs::read(root.path().join("hashes")).unwrap(), b"1");+ assert_single_generation(&cache);}#[test]@@ -830,7 +1200,7 @@ mod tests {old);assert!(!staged.exists());- assert_eq!(fs::read_dir(cache).unwrap().count(), 1);+ assert_single_generation(&cache);}#[test]@@ -861,7 +1231,7 @@ mod tests {old);assert!(staged.is_file());- assert_eq!(fs::read_dir(cache).unwrap().count(), 1);+ assert_single_generation(&cache);}}@@ -930,4 +1300,72 @@ mod tests {staged.parent().unwrap().to_string_lossy());}++ #[test]+ fn stage_shim_times_out_when_source_lock_is_held() {+ let (_root, shim, cache) = fixture();+ fs::create_dir(&cache).unwrap();+ let cache = cache.canonicalize().unwrap();+ let key = shim.canonicalize().unwrap();+ let _lock = lock_source(&cache, &key).unwrap();++ let err = stage_with_timeout(+ &shim,+ &cache,+ SystemTime::now(),+ Duration::from_millis(50),+ digest_at,+ )+ .unwrap_err();+ assert_eq!(err.kind(), io::ErrorKind::TimedOut);+ assert!(+ err.to_string().contains("shim source lock"),+ "unexpected timeout error: {err}"+ );+ }++ #[test]+ fn stage_shim_times_out_when_in_process_flight_is_held() {+ let (_root, shim, cache) = fixture();+ fs::create_dir(&cache).unwrap();+ let (entered_tx, entered_rx) = std::sync::mpsc::channel();+ let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();++ let shim_ref = &shim;+ let cache_ref = &cache;++ std::thread::scope(|scope| {+ let holder = scope.spawn(move || {+ stage_with_timeout(+ shim_ref,+ cache_ref,+ SystemTime::now(),+ Duration::from_secs(5),+ |key, dir, files, now| {+ entered_tx.send(()).unwrap();+ let _ = release_rx.recv();+ digest_at(key, dir, files, now)+ },+ )+ });++ entered_rx.recv().unwrap();+ let result = stage_with_timeout(+ &shim,+ &cache,+ SystemTime::now(),+ Duration::from_millis(50),+ digest_at,+ );+ drop(release_tx);++ let err = result.unwrap_err();+ assert_eq!(err.kind(), io::ErrorKind::TimedOut);+ assert!(+ err.to_string().contains("in-process shim staging"),+ "unexpected timeout error: {err}"+ );+ assert!(holder.join().unwrap().is_ok());+ });+ }}diff --git a/src/boxlite/src/vmm/controller/shim.rs b/src/boxlite/src/vmm/controller/shim.rsindex 73e263b95..14889714f 100644--- a/src/boxlite/src/vmm/controller/shim.rs+++ b/src/boxlite/src/vmm/controller/shim.rs@@ -369,13 +369,36 @@ impl VmmController for ShimController {// Measure subprocess spawn timelet shim_spawn_start = Instant::now();+ let shim_cache_dir = FilesystemLayout::shims_dir_for(&config.home_dir);+ // Stage the shim off the Tokio worker thread; keep `cmd.spawn()` on the+ // caller thread so Linux `--die-with-parent` isn't tied to a transient+ // blocking-pool thread and cancelled starts cannot spawn orphaned shims.+ let staged_shim = if self.options.advanced.security.jailer_enabled {+ let binary_path = self.binary_path.clone();+ let cache_dir = shim_cache_dir.clone();+ match tokio::task::spawn_blocking(move || {+ crate::jailer::shim_cache::stage_shim(&binary_path, &cache_dir)+ })+ .await+ .map_err(|e| BoxliteError::Engine(format!("Failed to join shim staging task: {}", e)))?+ {+ Ok(staged) => crate::jailer::StagedShim::Staged(staged),+ Err(err) => {+ tracing::warn!(error = %err, "Failed to stage shim, using original");+ crate::jailer::StagedShim::Fallback+ }+ }+ } else {+ crate::jailer::StagedShim::Unstaged+ };let spawner = ShimSpawner::new(&self.binary_path,&self.layout,self.box_id.as_str(),&self.options,)- .with_shim_cache_dir(FilesystemLayout::shims_dir_for(&config.home_dir))+ .with_shim_cache_dir(shim_cache_dir)+ .with_staged_shim(staged_shim).with_nested_virtualization(config.nested_virtualization).with_volume_access(config.volume_access.clone());let spawned = spawner.spawn(&config_json, config.detach)?;diff --git a/src/boxlite/src/vmm/controller/spawn.rs b/src/boxlite/src/vmm/controller/spawn.rsindex 972f6003d..8b178411d 100644--- a/src/boxlite/src/vmm/controller/spawn.rs+++ b/src/boxlite/src/vmm/controller/spawn.rs@@ -5,7 +5,7 @@ use std::{process::{Child, Stdio},};-use crate::jailer::{Jail, JailerBuilder, PathAccess};+use crate::jailer::{Jail, JailerBuilder, PathAccess, StagedShim};use crate::runtime::layout::BoxFilesystemLayout;use crate::runtime::options::{BoxOptions, NetworkSpec};use crate::util::configure_library_env;@@ -44,6 +44,7 @@ pub struct ShimSpawner<'a> {binary_path: &'a Path,layout: &'a BoxFilesystemLayout,shim_cache_dir: Option<PathBuf>,+ staged_shim: StagedShim,box_id: &'a str,options: &'a BoxOptions,nested_virtualization: bool,@@ -61,6 +62,7 @@ impl<'a> ShimSpawner<'a> {binary_path,layout,shim_cache_dir: None,+ staged_shim: StagedShim::Unstaged,box_id,options,nested_virtualization: false,@@ -105,6 +107,11 @@ impl<'a> ShimSpawner<'a> {self}+ pub(crate) fn with_staged_shim(mut self, staged_shim: StagedShim) -> Self {+ self.staged_shim = staged_shim;+ self+ }+pub fn with_volume_access(mut self, paths: Vec<PathAccess>) -> Self {self.volume_access = paths;self@@ -147,7 +154,8 @@ impl<'a> ShimSpawner<'a> {&self.options.network,NetworkSpec::Enabled { .. }))- .with_detach(detach);+ .with_detach(detach)+ .with_staged_shim(self.staged_shim.clone());if let Some(dir) = &self.shim_cache_dir {builder = builder.with_shim_cache_dir(dir);