Skip to content

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

fix(guest,jailer): preserve exec NOFILE rlimits and raise host shim default (#3198)

lfld2871568c8f751d8
diff --git a/src/boxlite/src/jailer/README.md b/src/boxlite/src/jailer/README.md
index e8462c68d..ded157fad 100644
--- a/src/boxlite/src/jailer/README.md
+++ b/src/boxlite/src/jailer/README.md
@@ -165,6 +165,8 @@ during upgrades, and reduces macOS per-inode code-signature validation overhead.
| Memory | RLIMIT_AS | Prevent OOM |
| CPU time | RLIMIT_CPU | Prevent CPU monopolization |
+At startup, the jailer sets both `RLIMIT_NOFILE` limits to `ResourceLimits.max_open_files` (default `65536` for virtio-fs inode FDs), clamped to the host process's inherited `rlim_max` when finite so constrained hosts and macOS do not fail with `EPERM`. Inside the guest, container `init` and `exec` processes (both TTY and non-TTY) set `RLIMIT_NOFILE` to `1048576` / `1048576`.
+
At startup, the jailer sets both `RLIMIT_FSIZE` limits to the configured
`ResourceLimits.max_file_size` in bytes. If the setting is absent, the shim
inherits both limits from the host launcher.
diff --git a/src/boxlite/src/jailer/common/rlimit.rs b/src/boxlite/src/jailer/common/rlimit.rs
index 29df52a28..53a909c94 100644
--- a/src/boxlite/src/jailer/common/rlimit.rs
+++ b/src/boxlite/src/jailer/common/rlimit.rs
@@ -55,7 +55,7 @@ pub fn get_rlimit(resource: RlimitResource) -> Result<(u64, u64), io::Error> {
/// * `Err(errno)` - Failed to set a limit (returns raw errno)
pub fn apply_limits_raw(limits: &ResourceLimits) -> Result<(), i32> {
if let Some(max_files) = limits.max_open_files {
- set_rlimit_raw(libc::RLIMIT_NOFILE, max_files)?;
+ set_nofile_rlimit_raw(max_files)?;
}
if let Some(max_fsize) = limits.max_file_size {
@@ -92,8 +92,64 @@ pub fn apply_limits_raw(limits: &ResourceLimits) -> Result<(), i32> {
Ok(())
}
+/// Read macOS `kern.maxfilesperproc` in normal parent context (not async-signal-safe).
+#[cfg(target_os = "macos")]
+pub(crate) fn macos_maxfilesperproc() -> Option<u64> {
+ let mut val: libc::c_int = 0;
+ let mut size = std::mem::size_of::<libc::c_int>();
+ let ret = unsafe {
+ libc::sysctlbyname(
+ c"kern.maxfilesperproc".as_ptr(),
+ (&mut val as *mut libc::c_int).cast(),
+ &mut size,
+ std::ptr::null_mut(),
+ 0,
+ )
+ };
+ if ret == 0 && val > 0 {
+ Some(val as u64)
+ } else {
+ None
+ }
+}
+
+/// Clamp `max_open_files` to the host's per-process kernel cap before entering
+/// `pre_exec`. On macOS, `rlim_max` is often `RLIM_INFINITY` while
+/// `kern.maxfilesperproc` is below 65536, causing `setrlimit` to return `EINVAL`.
+pub(crate) fn clamp_max_open_files_for_host(limit: u64) -> u64 {
+ #[cfg(target_os = "macos")]
+ if let Some(maxfiles) = macos_maxfilesperproc() {
+ return limit.min(maxfiles);
+ }
+ limit
+}
+
+/// Set `RLIMIT_NOFILE` - async-signal-safe version.
+///
+/// Queries the current `rlim_max` and clamps the target to it when finite,
+/// preventing `EPERM` on macOS or constrained hosts where the desired default
+/// exceeds the inherited hard limit.
+#[inline]
+#[allow(clippy::unnecessary_cast)]
+fn set_nofile_rlimit_raw(limit: u64) -> Result<(), i32> {
+ let mut current = libc::rlimit {
+ rlim_cur: 0,
+ rlim_max: 0,
+ };
+ let effective = if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut current) } == 0
+ && current.rlim_max != libc::RLIM_INFINITY
+ {
+ (limit as libc::rlim_t).min(current.rlim_max)
+ } else {
+ limit as libc::rlim_t
+ };
+
+ set_rlimit_raw(libc::RLIMIT_NOFILE, effective as u64)
+}
+
/// Set a specific resource limit - async-signal-safe version.
#[inline]
+#[allow(clippy::unnecessary_cast)]
fn set_rlimit_raw(resource: RlimitResource, limit: u64) -> Result<(), i32> {
let rlim = libc::rlimit {
rlim_cur: limit as libc::rlim_t,
@@ -144,6 +200,58 @@ mod tests {
assert!(soft <= hard, "Soft limit should be <= hard limit");
assert!(soft > 0, "Should have some file descriptors available");
}
+
+ #[test]
+ fn test_set_file_limit_clamps_to_rlim_max() {
+ use std::os::unix::process::CommandExt;
+ use std::process::Command;
+
+ let mut child = Command::new("/bin/sh");
+ child.arg("-c").arg("ulimit -Hn && ulimit -Sn");
+
+ // Lower the child's hard limit to 1024 before applying a larger limit
+ // (65536), so clamping is exercised without mutating the test runner.
+ unsafe {
+ child.pre_exec(|| {
+ let capped = libc::rlimit {
+ rlim_cur: 512,
+ rlim_max: 1024,
+ };
+ if libc::setrlimit(libc::RLIMIT_NOFILE, &capped) != 0 {
+ return Err(io::Error::last_os_error());
+ }
+ let limits = ResourceLimits {
+ max_open_files: Some(65536),
+ ..Default::default()
+ };
+ apply_limits_raw(&limits).map_err(io::Error::from_raw_os_error)
+ });
+ }
+
+ let output = child
+ .output()
+ .expect("run child with clamped RLIMIT_NOFILE");
+ assert!(
+ output.status.success(),
+ "child failed (EPERM if not clamped): {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let stdout = String::from_utf8(output.stdout).unwrap();
+ let values: Vec<u64> = stdout
+ .lines()
+ .map(|line| line.trim().parse::<u64>().expect("numeric ulimit"))
+ .collect();
+ assert_eq!(values, vec![1024, 1024]);
+ }
+
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn test_macos_maxfilesperproc_clamp() {
+ let maxfiles = macos_maxfilesperproc().expect("kern.maxfilesperproc should be readable");
+ assert!(maxfiles > 0);
+ assert_eq!(clamp_max_open_files_for_host(u64::MAX), maxfiles);
+ assert_eq!(clamp_max_open_files_for_host(1), 1);
+ }
}
#[cfg(all(test, target_os = "linux"))]
diff --git a/src/boxlite/src/jailer/pre_exec.rs b/src/boxlite/src/jailer/pre_exec.rs
index 9b0c0b411..3cd8e4972 100644
--- a/src/boxlite/src/jailer/pre_exec.rs
+++ b/src/boxlite/src/jailer/pre_exec.rs
@@ -65,13 +65,17 @@ use std::process::Command;
/// - Most Rust standard library functions
pub fn add_pre_exec_hook(
cmd: &mut Command,
- resource_limits: ResourceLimits,
+ mut resource_limits: ResourceLimits,
pid_writer: Option<PidFileWriter>,
preserved_fds: Vec<(RawFd, i32)>,
detach: bool,
) {
use std::os::unix::process::CommandExt;
+ if let Some(limit) = resource_limits.max_open_files {
+ resource_limits.max_open_files = Some(common::rlimit::clamp_max_open_files_for_host(limit));
+ }
+
// Detach=false → child's own process group at Command-build time
// so a later `killpg(shim_pid, SIGKILL)` reaps the shim plus its
// grandchildren (libkrun threads, gvproxy) atomically.
diff --git a/src/boxlite/src/runtime/advanced_options.rs b/src/boxlite/src/runtime/advanced_options.rs
index ed3271d12..5ba77bd7c 100644
--- a/src/boxlite/src/runtime/advanced_options.rs
+++ b/src/boxlite/src/runtime/advanced_options.rs
@@ -231,7 +231,10 @@ impl Default for SecurityOptions {
sanitize_env: true,
env_allowlist: vec!["RUST_LOG".to_string()],
resource_limits: ResourceLimits {
- max_open_files: Some(1024),
+ // virtio-fs keeps an open host FD per cached inode in the shim;
+ // 1024 exhausts quickly on package installs and builds. Clamped to
+ // the host's current `rlim_max` in `jailer::common::rlimit`.
+ max_open_files: Some(65536),
max_file_size: None,
// Per-box cgroup `pids.max` — the fork-bomb cap for the box's
// host-side process tree (bwrap + shim + libkrun/gvproxy
diff --git a/src/boxlite/src/runtime/options.rs b/src/boxlite/src/runtime/options.rs
index ec76b1964..8171a04f7 100644
--- a/src/boxlite/src/runtime/options.rs
+++ b/src/boxlite/src/runtime/options.rs
@@ -2963,6 +2963,7 @@ mod tests {
assert!(direct.close_fds);
assert!(direct.sanitize_env);
assert_eq!(direct.uid, Some(65534));
+ assert_eq!(direct.resource_limits.max_open_files, Some(65536));
#[cfg(target_os = "linux")]
{
assert!(direct.seccomp_enabled);
diff --git a/src/guest/src/container/capabilities.rs b/src/guest/src/container/capabilities.rs
index c8b70ca6b..0e6564371 100644
--- a/src/guest/src/container/capabilities.rs
+++ b/src/guest/src/container/capabilities.rs
@@ -159,6 +159,7 @@ impl CapabilitySet {
}
/// Canonical names accepted by libcontainer's tenant builder.
+ #[cfg(test)]
pub(crate) fn names(&self) -> Vec<String> {
let mut names: Vec<String> = self
.0
diff --git a/src/guest/src/container/spec.rs b/src/guest/src/container/spec.rs
index a4e13db6d..0568322b4 100644
--- a/src/guest/src/container/spec.rs
+++ b/src/guest/src/container/spec.rs
@@ -510,6 +510,21 @@ fn build_namespace(typ: LinuxNamespaceType) -> BoxliteResult<oci_spec::runtime::
.map_err(|e| BoxliteError::Internal(format!("Failed to build {:?} namespace: {}", typ, e)))
}
+/// Build default OCI resource limits (`RLIMIT_NOFILE` = 1048576 / 1048576).
+///
+/// Matches Docker's defaults so applications (databases, web servers, build
+/// tools) can open many files/connections in both container init and exec.
+fn default_container_rlimits() -> BoxliteResult<Vec<oci_spec::runtime::PosixRlimit>> {
+ Ok(vec![PosixRlimitBuilder::default()
+ .typ(PosixRlimitType::RlimitNofile)
+ .hard(1024u64 * 1024u64)
+ .soft(1024u64 * 1024u64)
+ .build()
+ .map_err(|e| {
+ BoxliteError::Internal(format!("Failed to build rlimit: {}", e))
+ })?])
+}
+
/// Build process specification
fn build_process_spec(
entrypoint: &[String],
@@ -526,16 +541,7 @@ fn build_process_spec(
.build()
.map_err(|e| BoxliteError::Internal(format!("Failed to build user spec: {}", e)))?;
- // Build rlimits
- // Set NOFILE to 1048576 to match Docker's defaults
- // This allows applications to open many files/connections (databases, web servers, etc.)
- #[allow(unused)]
- let rlimits = vec![PosixRlimitBuilder::default()
- .typ(PosixRlimitType::RlimitNofile)
- .hard(1024u64 * 1024u64)
- .soft(1024u64 * 1024u64)
- .build()
- .map_err(|e| BoxliteError::Internal(format!("Failed to build rlimit: {}", e)))?];
+ let rlimits = default_container_rlimits()?;
ProcessBuilder::default()
// OCI `process.terminal`: with it set, the runtime allocates a PTY for
@@ -552,21 +558,29 @@ fn build_process_spec(
.map_err(|e| BoxliteError::Internal(format!("Failed to build process spec: {}", e)))
}
-/// Build an OCI `Process` for a TTY tenant exec, with `terminal=true`.
+/// Build an OCI `Process` for a tenant exec (`terminal = true` for PTY, `false` for pipe stdio).
///
-/// libcontainer 0.6's `check_terminal` rejects a console socket unless the
-/// process declares `terminal=true` (and the build is detached). The tenant
-/// builder has no per-exec terminal setter, so this Process is serialized to a
-/// process.json and passed via `ContainerBuilder::with_process`. Same shape as
-/// `build_process_spec` but with the terminal flag on.
-pub(crate) fn build_tty_exec_process(
+/// libcontainer 0.6's `check_terminal` requires `terminal=true` (and detached)
+/// when a console socket is provided, and `TenantContainerBuilder` has no
+/// per-exec terminal or rlimits setter. Both TTY and non-TTY exec serialize this
+/// `Process` to a `process.json` and pass it via `ContainerBuilder::with_process`
+/// so `rlimits`, capabilities, user, cwd, env, and `no_new_privileges` are
+/// applied uniformly.
+pub(crate) fn build_exec_process(
args: &[String],
env: &[String],
cwd: &str,
uid: u32,
gid: u32,
capabilities: CapabilitySet,
+ terminal: bool,
) -> BoxliteResult<oci_spec::runtime::Process> {
+ if !Path::new(cwd).is_absolute() {
+ return Err(BoxliteError::Config(format!(
+ "exec working directory must be an absolute path: {cwd}"
+ )));
+ }
+
let user = UserBuilder::default()
.uid(uid)
.gid(gid)
@@ -574,15 +588,16 @@ pub(crate) fn build_tty_exec_process(
.map_err(|e| BoxliteError::Internal(format!("Failed to build user spec: {}", e)))?;
ProcessBuilder::default()
- .terminal(true)
+ .terminal(terminal)
.user(user)
.args(args.to_vec())
.env(env)
.cwd(cwd)
.capabilities(capabilities.to_oci()?)
+ .rlimits(default_container_rlimits()?)
.no_new_privileges(false)
.build()
- .map_err(|e| BoxliteError::Internal(format!("Failed to build tty exec process: {}", e)))
+ .map_err(|e| BoxliteError::Internal(format!("Failed to build exec process: {}", e)))
}
/// Build root filesystem specification
@@ -981,13 +996,14 @@ mod tests {
.to_oci()
.expect("build expected OCI capability sets");
- let process = build_tty_exec_process(
+ let process = build_exec_process(
&["sh".to_string()],
&["PATH=/bin".to_string()],
"/",
0,
0,
resolved.clone(),
+ true,
)
.expect("build tty exec process");
@@ -1003,6 +1019,52 @@ mod tests {
assert_eq!(capabilities.ambient(), &None);
}
+ #[test]
+ fn exec_process_sets_default_nofile_rlimits() {
+ for terminal in [true, false] {
+ let process = build_exec_process(
+ &["sh".to_string()],
+ &["PATH=/bin".to_string()],
+ "/",
+ 0,
+ 0,
+ CapabilitySet::default(),
+ terminal,
+ )
+ .expect("build exec process");
+
+ assert_eq!(process.terminal(), Some(terminal));
+ let rlimits = process
+ .rlimits()
+ .as_ref()
+ .expect("exec process should set rlimits");
+ let nofile = rlimits
+ .iter()
+ .find(|r| r.typ() == PosixRlimitType::RlimitNofile)
+ .expect("RLIMIT_NOFILE should be present");
+ assert_eq!(nofile.soft(), 1048576);
+ assert_eq!(nofile.hard(), 1048576);
+ }
+ }
+
+ #[test]
+ fn exec_process_rejects_relative_cwd() {
+ let err = build_exec_process(
+ &["sh".to_string()],
+ &["PATH=/bin".to_string()],
+ "relative/dir",
+ 0,
+ 0,
+ CapabilitySet::default(),
+ false,
+ )
+ .expect_err("relative cwd should be rejected");
+ assert!(
+ matches!(err, BoxliteError::Config(_)),
+ "expected Config error, got: {err:?}"
+ );
+ }
+
// ==================
// Empty / root
// ==================
diff --git a/src/guest/src/container/zygote.rs b/src/guest/src/container/zygote.rs
index fc94b9733..8383b1571 100644
--- a/src/guest/src/container/zygote.rs
+++ b/src/guest/src/container/zygote.rs
@@ -26,11 +26,15 @@ use std::collections::HashMap;
use std::io::{IoSlice, IoSliceMut};
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};
use std::path::PathBuf;
+use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Mutex, OnceLock};
/// Global zygote instance. Initialized once in main() before tokio starts.
pub(crate) static ZYGOTE: OnceLock<Zygote> = OnceLock::new();
+/// Monotonic sequence counter for unique temporary `exec-process-*.json` files.
+static EXEC_PROCESS_SEQ: AtomicU64 = AtomicU64::new(0);
+
/// Handle to the zygote process, held by the parent (tokio) process.
///
/// The zygote is a single-threaded child process that handles all
@@ -387,65 +391,45 @@ fn do_build(spec: BuildSpec, fds: Option<[RawFd; 3]>) -> BuildResult {
}
// libcontainer 0.6's check_terminal requires a console socket iff
- // (detached && terminal). The tenant builder has no per-exec terminal
- // setter, so the two exec shapes diverge here.
- let pid = if spec.console_socket.is_some() {
- // TTY exec: hand youki a process.json with terminal=true (via
- // with_process) and detach=true, so it allocates the PTY, relays
- // the master fd over the console socket (received by ConsoleSocket),
- // and returns the pid (guest main reaps it — see as_sibling below).
- // The PTY path passes no stdio fds — youki wires the PTY slave instead.
- let env_vec: Vec<String> = spec.env.iter().map(|(k, v)| format!("{k}={v}")).collect();
- let cwd = spec.cwd.to_str().unwrap_or("/");
- let process = super::spec::build_tty_exec_process(
- &spec.args,
- &env_vec,
- cwd,
- spec.uid,
- spec.gid,
- spec.capabilities.clone(),
- )
- .map_err(|e| format!("build tty exec process: {e}"))?;
- let process_json = serde_json::to_vec(&process)
- .map_err(|e| format!("serialize tty process.json: {e}"))?;
- let process_path = spec
- .state_root
- .join(format!("exec-process-{}.json", spec.container_id));
- std::fs::write(&process_path, process_json)
- .map_err(|e| format!("write tty process.json: {e}"))?;
- let result = builder
- .as_tenant()
- .as_sibling(true) // reparent to guest main; see the non-TTY arm
- .with_detach(true)
- .with_process(Some(process_path.clone()))
- .build();
- if let Err(error) = &result {
- rejection = command_rejection(error);
- }
- let _ = std::fs::remove_file(&process_path);
- result.map_err(|e| format!("build failed: {e}"))?
- } else {
- // Non-TTY exec: stdio via the passed pipe fds, no console socket,
- // terminal=false, non-detached.
- builder
- .as_tenant()
- // CLONE_PARENT so the tenant reparents to guest main (not the
- // zygote); guest main's reaper owns its exit. The zygote never waits.
- .as_sibling(true)
- .with_capabilities(spec.capabilities.names())
- .with_no_new_privs(false)
- .with_detach(false)
- .with_cwd(Some(spec.cwd))
- .with_env(spec.env)
- .with_container_args(spec.args)
- .with_user(Some(spec.uid))
- .with_group(Some(spec.gid))
- .build()
- .map_err(|e| {
- rejection = command_rejection(&e);
- format!("build failed: {e}")
- })?
- };
+ // (detached && terminal). Both TTY and non-TTY exec pass an explicit
+ // OCI Process via `with_process` so `rlimits` (and capabilities, user,
+ // cwd, env, no_new_privileges) apply uniformly. Non-TTY exec keeps
+ // `with_detach(false)` and `terminal=false`, preserving stdio pipe fds
+ // passed via `with_stdin`/`with_stdout`/`with_stderr`.
+ let is_tty = spec.console_socket.is_some();
+ let env_vec: Vec<String> = spec.env.iter().map(|(k, v)| format!("{k}={v}")).collect();
+ let cwd = spec.cwd.to_str().unwrap_or("/");
+ let process = super::spec::build_exec_process(
+ &spec.args,
+ &env_vec,
+ cwd,
+ spec.uid,
+ spec.gid,
+ spec.capabilities.clone(),
+ is_tty,
+ )
+ .map_err(|e| format!("build exec process: {e}"))?;
+ let process_json =
+ serde_json::to_vec(&process).map_err(|e| format!("serialize process.json: {e}"))?;
+ let seq = EXEC_PROCESS_SEQ.fetch_add(1, Ordering::Relaxed);
+ let process_path = spec
+ .state_root
+ .join(format!("exec-process-{}-{seq}.json", spec.container_id));
+ std::fs::write(&process_path, process_json)
+ .map_err(|e| format!("write process.json: {e}"))?;
+ let result = builder
+ .as_tenant()
+ // CLONE_PARENT so the tenant reparents to guest main (not the
+ // zygote); guest main's reaper owns its exit. The zygote never waits.
+ .as_sibling(true)
+ .with_detach(is_tty)
+ .with_process(Some(process_path.clone()))
+ .build();
+ if let Err(error) = &result {
+ rejection = command_rejection(error);
+ }
+ let _ = std::fs::remove_file(&process_path);
+ let pid = result.map_err(|e| format!("build failed: {e}"))?;
Ok(pid)
};
diff --git a/src/shared/src/constants.rs b/src/shared/src/constants.rs
index 770b28f15..3bb08234e 100644
--- a/src/shared/src/constants.rs
+++ b/src/shared/src/constants.rs
@@ -8,12 +8,6 @@ use std::path::{Component, Path};
pub mod container {
/// Default container hostname
pub const DEFAULT_HOSTNAME: &str = "boxlite";
-
- /// Default RLIMIT_NOFILE soft limit
- pub const RLIMIT_NOFILE_SOFT: u64 = 1024;
-
- /// Default RLIMIT_NOFILE hard limit
- pub const RLIMIT_NOFILE_HARD: u64 = 1024;
}
/// Network constants