use std::any::Any;
use std::ffi::CString;
use std::fs;
use std::fs::File;
use std::io;
use std::io::Write;
use std::os::fd::AsRawFd;
use std::os::fd::FromRawFd;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::MetadataExt;
use std::os::unix::fs::PermissionsExt;
use std::panic;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Mutex;
use std::sync::OnceLock;
use std::sync::atomic::AtomicI32;
use std::sync::atomic::Ordering;
use anyhow::anyhow;
use detcore_model::config::MountInfoRootRewrite;
use hermit::Context;
use hermit::Error;
use hermit::FailureKind;
use hermit::HERMIT_DEADLINE_EXIT;
use hermit::SerializableError;
use hermit::SkidOvershootError;
use hermit::capture_mountinfo_identity_order;
use nix::sched::CpuSet;
use nix::sched::sched_getaffinity;
use nix::sys::signal::SaFlags;
use nix::sys::signal::SigAction;
use nix::sys::signal::SigHandler;
use nix::sys::signal::SigSet;
use nix::sys::signal::Signal;
use nix::sys::signal::sigaction;
use nix::unistd::Pid;
use reverie::process::Container;
use reverie::process::ExitStatus;
use reverie::process::Mount;
use reverie::process::MountFlags;
use reverie::process::Namespace;
use reverie::process::RunError;
const GROUP_FILE: &str = "/etc/group";
const NSCD_DIR: &str = "/var/run/nscd";
const OVERFLOW_GID: &str = "65534";
const DETERMINISTIC_GROUP_ROOT: &[u8] = b"/tmpvol/.hermit/etc/group";
const DETERMINISTIC_NSCD_ROOT: &[u8] = b"/tmpvol/.hermit/run/nscd";
const DETERMINISTIC_TMP_ROOT: &[u8] = b"/tmpvol/.hermit/tmp";
#[derive(Debug)]
struct MountInfoRootSource {
source: Option<File>,
target: PathBuf,
deterministic_root: Option<Vec<u8>>,
rewrite_descendant_roots: bool,
raw_mountpoint_prefix: Option<Vec<u8>>,
deterministic_mountpoint_prefix: Option<Vec<u8>>,
}
fn open_path(path: &Path) -> io::Result<File> {
let path = CString::new(path.as_os_str().as_bytes())
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "path contains NUL"))?;
let fd = unsafe { libc::open(path.as_ptr(), libc::O_PATH | libc::O_CLOEXEC) };
if fd < 0 {
return Err(io::Error::last_os_error());
}
Ok(unsafe { File::from_raw_fd(fd) })
}
fn mount_id_for_fd(fd: i32) -> io::Result<u64> {
let contents = fs::read(format!("/proc/self/fdinfo/{fd}"))?;
detcore_model::procfs::parse_fdinfo_mount_id(&contents).ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData,
"fdinfo must contain exactly one decimal mnt_id field",
)
})
}
fn mountinfo_root_for_id(raw_mount_id: u64) -> io::Result<Vec<u8>> {
let contents = fs::read("/proc/self/mountinfo")?;
let rows = detcore_model::procfs::parse_mountinfo(&contents).ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidData, "mountinfo has a malformed row")
})?;
rows.into_iter()
.find(|row| row.raw_mount_id == raw_mount_id)
.map(|row| row.root)
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData,
"mountinfo omitted the proven mount ID",
)
})
}
fn mountinfo_escape_path(path: &Path) -> Vec<u8> {
let mut encoded = Vec::new();
for byte in path.as_os_str().as_bytes() {
match byte {
b' ' => encoded.extend_from_slice(b"\\040"),
b'\t' => encoded.extend_from_slice(b"\\011"),
b'\n' => encoded.extend_from_slice(b"\\012"),
b'\\' => encoded.extend_from_slice(b"\\134"),
byte => encoded.push(*byte),
}
}
encoded
}
impl MountInfoRootSource {
fn new(source: &Path, target: &Path, deterministic_root: &[u8]) -> Result<Self, Error> {
Ok(Self {
source: Some(open_path(source).with_context(|| {
format!(
"Failed to pin mountinfo provenance source {}",
source.display()
)
})?),
target: target.to_path_buf(),
deterministic_root: Some(deterministic_root.to_vec()),
rewrite_descendant_roots: false,
raw_mountpoint_prefix: None,
deterministic_mountpoint_prefix: None,
})
}
fn private_tmp(source: &Path) -> Result<Self, Error> {
let mut provenance = Self::new(source, Path::new("/tmp"), DETERMINISTIC_TMP_ROOT)?;
provenance.rewrite_descendant_roots = true;
provenance.raw_mountpoint_prefix = Some(mountinfo_escape_path(source));
provenance.deterministic_mountpoint_prefix = Some(b"/tmp".to_vec());
Ok(provenance)
}
fn translated_tmp_mountpoint(staging_path: &Path) -> Self {
Self {
source: None,
target: PathBuf::from("/tmp"),
deterministic_root: None,
rewrite_descendant_roots: false,
raw_mountpoint_prefix: Some(mountinfo_escape_path(staging_path)),
deterministic_mountpoint_prefix: Some(b"/tmp".to_vec()),
}
}
fn resolve(&self) -> Result<MountInfoRootRewrite, Error> {
let target = open_path(&self.target).with_context(|| {
format!(
"Failed to pin mountinfo provenance target {}",
self.target.display()
)
})?;
let target_metadata = target.metadata().with_context(|| {
format!(
"Failed to inspect pinned mountinfo provenance target {}",
self.target.display()
)
})?;
if let Some(source) = &self.source {
let source_metadata = source.metadata().with_context(|| {
format!(
"Failed to inspect pinned mountinfo provenance source for {}",
self.target.display()
)
})?;
if (source_metadata.dev(), source_metadata.ino())
!= (target_metadata.dev(), target_metadata.ino())
{
return Err(Error::msg(format!(
"Refusing mountinfo provenance for {}: the completed mount target does not match \
the pinned Hermit-owned source",
self.target.display()
)));
}
}
let raw_mount_id = mount_id_for_fd(target.as_raw_fd()).with_context(|| {
format!(
"Failed to identify the mount containing proven target {}",
self.target.display()
)
})?;
let observed_root = (self.rewrite_descendant_roots || self.deterministic_root.is_none())
.then(|| mountinfo_root_for_id(raw_mount_id))
.transpose()
.with_context(|| {
format!(
"Failed to identify the proven mount root for {}",
self.target.display()
)
})?;
let deterministic_root = self
.deterministic_root
.clone()
.or_else(|| observed_root.clone())
.expect("an explicit or observed root is required");
Ok(MountInfoRootRewrite {
raw_mount_id,
deterministic_root: deterministic_root.clone(),
raw_root_prefix: self.rewrite_descendant_roots.then(|| {
observed_root
.clone()
.expect("descendant rewriting captured the observed root")
}),
deterministic_root_prefix: self.rewrite_descendant_roots.then_some(deterministic_root),
raw_mountpoint_prefix: self.raw_mountpoint_prefix.clone(),
deterministic_mountpoint_prefix: self.deterministic_mountpoint_prefix.clone(),
})
}
}
pub(super) struct IdentityGuard {
_group_file: Option<tempfile::NamedTempFile>,
_nscd_dir: Option<tempfile::TempDir>,
mountinfo_roots: Vec<MountInfoRootSource>,
user_mount_targets: Vec<PathBuf>,
}
impl IdentityGuard {
pub(super) fn empty() -> Self {
Self {
_group_file: None,
_nscd_dir: None,
mountinfo_roots: Vec::new(),
user_mount_targets: Vec::new(),
}
}
pub(super) fn add_private_tmp(&mut self, source: &Path) -> Result<(), Error> {
self.mountinfo_roots
.push(MountInfoRootSource::private_tmp(source)?);
Ok(())
}
pub(super) fn add_translated_tmp_mountpoint(&mut self, staging_path: &Path) {
self.mountinfo_roots
.push(MountInfoRootSource::translated_tmp_mountpoint(staging_path));
}
pub(super) fn discard_mounts_shadowed_by(
&mut self,
mounts: &mut Vec<Mount>,
overriding_target: &Path,
) {
let resolution_changed = self
.user_mount_targets
.iter()
.any(|earlier| overriding_target.starts_with(earlier));
let resolved_override = if resolution_changed {
overriding_target.to_path_buf()
} else {
canonical_mount_target(overriding_target)
};
mounts.retain(|mount| {
!canonical_mount_target(mount.get_target()).starts_with(&resolved_override)
});
self.mountinfo_roots.retain(|source| {
!canonical_mount_target(&source.target).starts_with(&resolved_override)
});
self.user_mount_targets
.push(overriding_target.to_path_buf());
}
pub(super) fn mountinfo_root_rewrites(&self) -> Result<Vec<MountInfoRootRewrite>, Error> {
self.mountinfo_roots
.iter()
.map(MountInfoRootSource::resolve)
.collect()
}
pub(super) fn mountinfo_identity_order(&self) -> Result<Vec<u64>, Error> {
capture_mountinfo_identity_order()
.context("Failed to capture guest mountinfo identity order")
}
}
fn canonical_mount_target(path: &Path) -> PathBuf {
for ancestor in path.ancestors() {
if let Ok(mut canonical) = fs::canonicalize(ancestor)
&& let Ok(suffix) = path.strip_prefix(ancestor)
{
canonical.push(suffix);
return canonical;
}
}
path.to_path_buf()
}
#[cfg(test)]
pub(super) fn mount_target_is_shadowed(target: &Path, overriding_target: &Path) -> bool {
canonical_mount_target(target).starts_with(canonical_mount_target(overriding_target))
}
fn frozen_group_file() -> Result<tempfile::NamedTempFile, Error> {
let mut contents = fs::read_to_string(GROUP_FILE)
.context("Failed to read the host group database for the guest")?;
let has_overflow_group = contents.lines().any(|line| {
line.split(':')
.nth(2)
.is_some_and(|gid| gid == OVERFLOW_GID)
});
if !has_overflow_group {
if !contents.ends_with('\n') {
contents.push('\n');
}
contents.push_str("nobody:x:");
contents.push_str(OVERFLOW_GID);
contents.push_str(":\n");
}
let mut group_file = tempfile::NamedTempFile::new()
.context("Failed to create the frozen group database for the guest")?;
group_file
.write_all(contents.as_bytes())
.context("Failed to populate the frozen group database for the guest")?;
group_file
.as_file()
.set_permissions(fs::Permissions::from_mode(0o644))
.context("Failed to set permissions on the frozen guest group database")?;
Ok(group_file)
}
pub(super) fn identity_hardening_mounts() -> Result<(Vec<Mount>, IdentityGuard), Error> {
let group_file = frozen_group_file()?;
let mut mountinfo_roots = vec![MountInfoRootSource::new(
group_file.path(),
Path::new(GROUP_FILE),
DETERMINISTIC_GROUP_ROOT,
)?];
let mut mounts = vec![Mount::bind(group_file.path(), GROUP_FILE).readonly()];
let nscd_dir = if Path::new(NSCD_DIR).is_dir() {
let directory =
tempfile::TempDir::new().context("Failed to create the empty guest nscd directory")?;
let target = canonical_mount_target(Path::new(NSCD_DIR));
mountinfo_roots.push(MountInfoRootSource::new(
directory.path(),
&target,
DETERMINISTIC_NSCD_ROOT,
)?);
mounts.push(Mount::bind(directory.path(), target).readonly());
Some(directory)
} else {
None
};
Ok((
mounts,
IdentityGuard {
_group_file: Some(group_file),
_nscd_dir: nscd_dir,
mountinfo_roots,
user_mount_targets: Vec::new(),
},
))
}
fn choose_affinity_core(allowed: &[usize]) -> Option<usize> {
(!allowed.is_empty()).then(|| allowed[rand::random_range(0..allowed.len())])
}
fn cpu_ids(affinity: &CpuSet) -> Vec<usize> {
(0..CpuSet::count())
.filter(|cpu| affinity.is_set(*cpu).unwrap_or(false))
.collect()
}
pub(super) fn apply_affinity(container: &mut Container, pin_threads: bool) {
if pin_threads {
let affinity = sched_getaffinity(Pid::from_raw(0))
.expect("failed to query the tracer's allowed CPU affinity mask");
let allowed = cpu_ids(&affinity);
let rand_core = choose_affinity_core(&allowed)
.expect("the tracer's allowed CPU affinity mask is empty");
tracing::info!("Pinning tracer and guest threads to core {}", rand_core);
container.affinity(rand_core);
}
}
pub fn default_container(pin_threads: bool) -> Container {
let mut container = Container::new();
container
.unshare(Namespace::PID)
.map_root()
.hostname("hermetic-container.local")
.domainname("local")
.mount(Mount::proc().allow_readonly_fallback());
apply_affinity(&mut container, pin_threads);
container
}
pub(super) fn image_container(
rootfs: &Path,
tmpfs: &Path,
pin_threads: bool,
private_tmp: bool,
) -> Result<(Container, IdentityGuard), Error> {
let mut container = Container::new();
container
.unshare(Namespace::PID)
.map_root()
.hostname("hermetic-container.local")
.domainname("local");
container.mount(Mount::bind(rootfs, rootfs).readonly());
container.mount(Mount::bind(tmpfs, rootfs.join("tmp")).rshared());
let proc_target = rootfs.join("proc");
container.mount(Mount::proc().allow_readonly_fallback().target(&proc_target));
let dev_root = rootfs.join("dev");
for node in crate::image::DEV_BIND_TARGETS {
container.mount(Mount::bind(
Path::new("/dev").join(node),
dev_root.join(node),
));
}
container.mount(
Mount::devpts(dev_root.join("pts"))
.data("newinstance,ptmxmode=0666")
.flags(MountFlags::MS_NOSUID | MountFlags::MS_NOEXEC),
);
container.chroot(rootfs);
apply_affinity(&mut container, pin_threads);
let mut identity_sources = IdentityGuard::empty();
if private_tmp {
identity_sources.add_private_tmp(tmpfs)?;
}
Ok((container, identity_sources))
}
pub(super) fn deterministic_container() -> Result<(Container, IdentityGuard), Error> {
let mut container = default_container(true);
let (mounts, identity_guard) = identity_hardening_mounts()?;
container.mounts(mounts);
Ok((container, identity_guard))
}
fn arm_parent_death_signal() -> Result<(), Error> {
if unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL) } == -1 {
return Err(std::io::Error::last_os_error()).context(
"Failed to arm the container init parent-death signal \
(prctl(PR_SET_PDEATHSIG, SIGKILL)); refusing to start a guest that \
an expiring deadline could not then kill",
);
}
Ok(())
}
const CONTAINER_INIT_STOP_SIGNALS: [Signal; 3] = [Signal::SIGTERM, Signal::SIGINT, Signal::SIGHUP];
extern "C" fn on_container_init_stop_signal(signal: libc::c_int) {
unsafe { libc::_exit(128 + signal) }
}
fn install_container_init_stop_handlers() -> Result<(), Error> {
let action = SigAction::new(
SigHandler::Handler(on_container_init_stop_signal),
SaFlags::empty(),
SigSet::empty(),
);
let mut unblock = SigSet::empty();
for signal in CONTAINER_INIT_STOP_SIGNALS {
unsafe { sigaction(signal, &action) }
.with_context(|| format!("Failed to install the container init {signal} handler"))?;
unblock.add(signal);
}
unblock
.thread_unblock()
.context("Failed to unblock the container init stop signals")?;
Ok(())
}
static STOP_SIGNAL_BRIDGE_HOLDER: AtomicI32 = AtomicI32::new(0);
extern "C" fn bridge_container_init_stop_signal(signal: libc::c_int) {
if unsafe { libc::getpid() } != STOP_SIGNAL_BRIDGE_HOLDER.load(Ordering::Relaxed) {
on_container_init_stop_signal(signal);
}
unsafe {
let mut default: libc::sigaction = std::mem::zeroed();
default.sa_sigaction = libc::SIG_DFL;
libc::sigaction(signal, &default, std::ptr::null_mut());
let mut unblock: libc::sigset_t = std::mem::zeroed();
libc::sigemptyset(&mut unblock);
libc::sigaddset(&mut unblock, signal);
libc::sigprocmask(libc::SIG_UNBLOCK, &unblock, std::ptr::null_mut());
libc::raise(signal);
}
}
fn current_signal_action(signal: Signal) -> Result<libc::sigaction, Error> {
let mut current: libc::sigaction = unsafe { std::mem::zeroed() };
if unsafe { libc::sigaction(signal as libc::c_int, std::ptr::null(), &mut current) } == -1 {
return Err(std::io::Error::last_os_error())
.with_context(|| format!("Failed to read the {signal} disposition"));
}
Ok(current)
}
#[must_use = "the bridge is removed when this guard is dropped"]
pub(super) struct ContainerInitStopSignalBridge {
bridged: [bool; CONTAINER_INIT_STOP_SIGNALS.len()],
handler: libc::sighandler_t,
}
impl ContainerInitStopSignalBridge {
pub(super) fn install() -> Result<Self, Error> {
let handler: extern "C" fn(libc::c_int) = bridge_container_init_stop_signal;
let mut guard = Self {
bridged: [false; CONTAINER_INIT_STOP_SIGNALS.len()],
handler: handler as libc::sighandler_t,
};
let holder = unsafe { libc::getpid() };
if holder == 1 {
return Ok(guard);
}
STOP_SIGNAL_BRIDGE_HOLDER.store(holder, Ordering::Relaxed);
let mut bridge: libc::sigaction = unsafe { std::mem::zeroed() };
bridge.sa_sigaction = guard.handler;
bridge.sa_flags = libc::SA_RESTART;
unsafe {
libc::sigemptyset(&mut bridge.sa_mask);
for signal in CONTAINER_INIT_STOP_SIGNALS {
libc::sigaddset(&mut bridge.sa_mask, signal as libc::c_int);
}
}
for (index, signal) in CONTAINER_INIT_STOP_SIGNALS.into_iter().enumerate() {
if current_signal_action(signal)?.sa_sigaction != libc::SIG_DFL {
continue;
}
if unsafe { libc::sigaction(signal as libc::c_int, &bridge, std::ptr::null_mut()) }
== -1
{
return Err(std::io::Error::last_os_error()).with_context(|| {
format!("Failed to install the container init {signal} bridge")
});
}
guard.bridged[index] = true;
}
Ok(guard)
}
}
impl Drop for ContainerInitStopSignalBridge {
fn drop(&mut self) {
let default = SigAction::new(SigHandler::SigDfl, SaFlags::empty(), SigSet::empty());
for (index, signal) in CONTAINER_INIT_STOP_SIGNALS.into_iter().enumerate() {
if !self.bridged[index] {
continue;
}
let still_bridged = current_signal_action(signal)
.is_ok_and(|current| current.sa_sigaction == self.handler);
if still_bridged {
let _ = unsafe { sigaction(signal, &default) };
}
}
}
}
pub(super) fn stall_container_init_before_arming_if_asked() {
if std::env::var_os(CONTAINER_INIT_ARMING_STALL_ENV).as_deref()
!= Some(std::ffi::OsStr::new("1"))
{
return;
}
let mut name = [0u8; 16];
unsafe {
libc::prctl(libc::PR_GET_NAME, name.as_mut_ptr());
libc::prctl(libc::PR_SET_NAME, c"unarmed-init".as_ptr());
}
std::thread::sleep(CONTAINER_INIT_ARMING_STALL);
unsafe { libc::prctl(libc::PR_SET_NAME, name.as_ptr()) };
}
pub(super) const CONTAINER_INIT_ARMING_STALL_ENV: &str =
"HERMIT_INTERNAL_STALL_CONTAINER_INIT_BEFORE_ARMING";
pub(super) const CONTAINER_INIT_ARMING_STALL: std::time::Duration =
std::time::Duration::from_secs(60);
pub(super) fn arm_container_init_guards() -> Result<(), SerializableError> {
arm_parent_death_signal().map_err(SerializableError::from)?;
install_container_init_stop_handlers().map_err(SerializableError::from)?;
Ok(())
}
static PANIC_LOCATION: OnceLock<Mutex<Option<String>>> = OnceLock::new();
fn panic_location() -> &'static Mutex<Option<String>> {
PANIC_LOCATION.get_or_init(|| Mutex::new(None))
}
fn install_panic_location_hook() {
static INSTALLED: OnceLock<()> = OnceLock::new();
INSTALLED.get_or_init(|| {
let previous = panic::take_hook();
panic::set_hook(Box::new(move |info| {
if let Some(location) = info.location() {
let recorded = format!(
"{}:{}:{}",
location.file(),
location.line(),
location.column()
);
if let Ok(mut slot) = panic_location().lock() {
*slot = Some(recorded);
}
}
previous(info);
}));
});
}
fn take_panic_location() -> String {
panic_location()
.lock()
.ok()
.and_then(|mut slot| slot.take())
.unwrap_or_else(|| "<unknown location>".to_string())
}
fn panic_message(payload: &(dyn Any + Send)) -> String {
if let Some(message) = payload.downcast_ref::<&'static str>() {
(*message).to_string()
} else if let Some(message) = payload.downcast_ref::<String>() {
message.clone()
} else {
"<panic payload was not a string>".to_string()
}
}
fn inject_test_fault(site: &str) {
if std::env::var("HERMIT_TEST_CONTAINER_CHILD_FAULT_SITE").is_ok_and(|want| want != site) {
return;
}
match std::env::var("HERMIT_TEST_CONTAINER_CHILD_FAULT")
.ok()
.as_deref()
{
Some("panic") => {
panic!("deliberate container-child panic for fault-injection testing at site {site}")
}
Some("segv") => {
unsafe { std::ptr::null_mut::<u8>().write_volatile(1) };
}
_ => {}
}
}
#[cfg(test)]
fn catch_child_panic<F, T>(f: &mut F) -> Result<T, SerializableError>
where
F: FnMut() -> Result<T, Error>,
{
install_panic_location_hook();
match panic::catch_unwind(panic::AssertUnwindSafe(|| {
inject_test_fault("with_container");
f()
})) {
Ok(result) => result.map_err(SerializableError::from),
Err(payload) => {
let location = take_panic_location();
Err(SerializableError::from(anyhow!(
"panic in container child at {location}: {}",
panic_message(&*payload)
))
.into_panic())
}
}
}
pub(super) fn catch_child_panic_at<F, T>(
site: &'static str,
mut f: F,
) -> Result<T, SerializableError>
where
F: FnMut() -> Result<T, Error>,
{
install_panic_location_hook();
match panic::catch_unwind(panic::AssertUnwindSafe(|| {
inject_test_fault(site);
f()
})) {
Ok(result) => result.map_err(SerializableError::from),
Err(payload) => Err(SerializableError::from(anyhow!(
"panic in container child at {}: {}",
take_panic_location(),
panic_message(&*payload)
))
.into_panic()),
}
}
#[derive(Debug)]
pub struct ContainerChildExit(pub ExitStatus);
impl std::fmt::Display for ContainerChildExit {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Sandbox container exited unexpectedly: {:?}", self.0)
}
}
impl std::error::Error for ContainerChildExit {}
#[derive(Debug)]
pub struct PolicyRefusal;
impl std::fmt::Display for PolicyRefusal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Hermit refused the run: a fail-closed policy stopped it before completion. \
This is not a hermit failure; the refusal reason is above."
)
}
}
impl std::error::Error for PolicyRefusal {}
#[derive(Debug)]
pub struct RunTimeoutMarker;
impl std::fmt::Display for RunTimeoutMarker {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "the --timeout bound fired")
}
}
impl std::error::Error for RunTimeoutMarker {}
#[derive(Debug)]
pub struct SignalDeath(pub i32);
impl std::fmt::Display for SignalDeath {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Hermit's container was terminated by signal {}. This is not a hermit \
failure and not a refusal: hermit did not choose to stop this run.",
self.0
)
}
}
impl std::error::Error for SignalDeath {}
#[derive(Debug)]
pub struct ContainerChildPanic(pub Error);
impl std::fmt::Display for ContainerChildPanic {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl std::error::Error for ContainerChildPanic {}
#[cfg(test)]
pub fn with_container<F, T>(container: &mut Container, mut f: F) -> Result<T, Error>
where
F: FnMut() -> Result<T, Error>,
T: serde::Serialize + serde::de::DeserializeOwned,
{
classify_container_result(container.run(|| {
arm_container_init_guards()?;
catch_child_panic(&mut f)
}))
}
pub fn classify_container_result<T>(
ran: Result<Result<T, SerializableError>, RunError>,
) -> Result<T, Error> {
match ran {
Ok(Ok(value)) => Ok(value),
Ok(Err(reported)) => {
let kind = reported.kind();
let error = Error::from(reported);
Err(match kind {
FailureKind::Panic => Error::new(ContainerChildPanic(error)),
FailureKind::PolicyRefusal => error.context(PolicyRefusal),
FailureKind::SkidOvershoot { count } => error
.context(SkidOvershootError::new(count))
.context(PolicyRefusal),
FailureKind::RunTimeout => error.context(RunTimeoutMarker),
FailureKind::Error => error,
})
}
Err(RunError::ExitStatus(status))
if status.code() == Some(detcore_model::HERMIT_POLICY_REFUSAL_EXIT) =>
{
Err(Error::new(PolicyRefusal))
}
Err(RunError::ExitStatus(status)) if status.code() == Some(HERMIT_DEADLINE_EXIT) => {
Err(Error::new(RunTimeoutMarker))
}
Err(RunError::ExitStatus(status))
if status
.code()
.and_then(detcore_model::signal_from_exit_status)
.is_some() =>
{
let signal = status
.code()
.and_then(detcore_model::signal_from_exit_status)
.expect("guard just matched");
Err(Error::new(SignalDeath(signal)))
}
Err(RunError::ExitStatus(status)) => Err(Error::new(ContainerChildExit(status))),
Err(error @ RunError::Spawn(_)) => {
Err(Error::new(error).context("Sandbox container failed to spawn"))
}
}
}
#[cfg(test)]
#[path = "../../../tests/common/readonly_proc.rs"]
mod readonly_proc;
#[cfg(test)]
mod tests {
use super::*;
const STOP_SIGNAL_BUDGET: std::time::Duration = std::time::Duration::from_secs(5);
fn in_isolated_process<T>(body: impl FnMut() -> Result<T, String>) -> T
where
T: serde::Serialize + serde::de::DeserializeOwned,
{
Container::new()
.run(body)
.expect("the isolated test process should run to completion")
.unwrap_or_else(|error| panic!("{error}"))
}
fn set_default_stop_dispositions() -> Result<(), String> {
let default = SigAction::new(SigHandler::SigDfl, SaFlags::empty(), SigSet::empty());
for signal in CONTAINER_INIT_STOP_SIGNALS {
unsafe { sigaction(signal, &default) }.map_err(|error| format!("{signal}: {error}"))?;
}
Ok(())
}
fn enter_new_pid_namespace() -> Result<(), String> {
if unsafe { libc::unshare(libc::CLONE_NEWUSER | libc::CLONE_NEWPID) } == -1 {
return Err(format!("unshare: {}", io::Error::last_os_error()));
}
Ok(())
}
fn fork_waiting_child(prepare: fn() -> bool) -> Result<libc::pid_t, String> {
let mut fds = [0; 2];
if unsafe { libc::pipe(fds.as_mut_ptr()) } == -1 {
return Err(format!("pipe: {}", io::Error::last_os_error()));
}
match unsafe { libc::fork() } {
-1 => Err(format!("fork: {}", io::Error::last_os_error())),
0 => unsafe {
libc::close(fds[0]);
if !prepare() {
libc::_exit(99);
}
libc::write(fds[1], [1u8].as_ptr().cast(), 1);
libc::close(fds[1]);
loop {
libc::pause();
}
},
child => {
let mut ready = 0u8;
let read = unsafe {
libc::close(fds[1]);
let read = libc::read(fds[0], (&mut ready as *mut u8).cast(), 1);
libc::close(fds[0]);
read
};
if read != 1 {
return Err(format!(
"child {child} exited without reporting that it was ready, so its \
preparation failed"
));
}
Ok(child)
}
}
}
fn signal_and_reap(child: libc::pid_t, signal: Signal) -> Result<Option<i32>, String> {
if unsafe { libc::kill(child, signal as libc::c_int) } == -1 {
return Err(format!(
"kill({child}, {signal}): {}",
io::Error::last_os_error()
));
}
let deadline = std::time::Instant::now() + STOP_SIGNAL_BUDGET;
loop {
let mut status = 0;
match unsafe { libc::waitpid(child, &mut status, libc::WNOHANG) } {
reaped if reaped == child => return Ok(Some(status)),
-1 => return Err(format!("waitpid({child}): {}", io::Error::last_os_error())),
_ => {}
}
if std::time::Instant::now() >= deadline {
unsafe {
libc::kill(child, libc::SIGKILL);
libc::waitpid(child, &mut status, 0);
}
return Ok(None);
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
}
fn describe_wait_status(status: Option<i32>) -> String {
match status {
None => format!("still running {STOP_SIGNAL_BUDGET:?} after the signal"),
Some(status) if libc::WIFEXITED(status) => {
format!("exited {}", libc::WEXITSTATUS(status))
}
Some(status) if libc::WIFSIGNALED(status) => {
format!("killed by signal {}", libc::WTERMSIG(status))
}
Some(status) => format!("wait status {status:#x}"),
}
}
#[test]
fn a_namespace_init_honours_stop_signals_sent_before_it_arms() {
for signal in CONTAINER_INIT_STOP_SIGNALS {
let status = in_isolated_process(|| {
set_default_stop_dispositions()?;
let _bridge = ContainerInitStopSignalBridge::install()
.map_err(|error| format!("{error:#}"))?;
enter_new_pid_namespace()?;
let init = fork_waiting_child(|| true)?;
signal_and_reap(init, signal)
});
assert!(
status.is_some_and(|status| libc::WIFEXITED(status)
&& libc::WEXITSTATUS(status) == 128 + signal as i32),
"{signal}: a namespace init that had not armed its own handlers should \
exit {}, as `on_container_init_stop_signal` does; it {}",
128 + signal as i32,
describe_wait_status(status)
);
}
}
#[test]
fn the_process_holding_the_bridge_still_dies_from_stop_signals() {
fn hold_the_bridge() -> bool {
if set_default_stop_dispositions().is_err() {
return false;
}
match ContainerInitStopSignalBridge::install() {
Ok(bridge) => {
std::mem::forget(bridge);
true
}
Err(_) => false,
}
}
for signal in CONTAINER_INIT_STOP_SIGNALS {
let status = in_isolated_process(|| {
let holder = fork_waiting_child(hold_the_bridge)?;
signal_and_reap(holder, signal)
});
assert!(
status
.is_some_and(|status| libc::WIFSIGNALED(status)
&& libc::WTERMSIG(status) == signal as i32),
"{signal}: the process holding the bridge should be killed by {signal}; it {}",
describe_wait_status(status)
);
}
}
#[test]
fn the_bridge_leaves_ignored_and_handled_signals_alone_and_restores_the_default() {
extern "C" fn someone_elses_handler(_signal: libc::c_int) {}
let dispositions = in_isolated_process(|| {
let read = || -> Result<Vec<libc::sighandler_t>, String> {
CONTAINER_INIT_STOP_SIGNALS
.into_iter()
.map(|signal| {
current_signal_action(signal)
.map(|action| action.sa_sigaction)
.map_err(|error| format!("{error:#}"))
})
.collect()
};
let actions = [
SigHandler::SigDfl,
SigHandler::SigIgn,
SigHandler::Handler(someone_elses_handler),
];
for (signal, handler) in CONTAINER_INIT_STOP_SIGNALS.into_iter().zip(actions) {
let action = SigAction::new(handler, SaFlags::empty(), SigSet::empty());
unsafe { sigaction(signal, &action) }
.map_err(|error| format!("{signal}: {error}"))?;
}
let before = read()?;
let bridge =
ContainerInitStopSignalBridge::install().map_err(|error| format!("{error:#}"))?;
let during = read()?;
let installed = bridge.handler;
drop(bridge);
Ok((before, during, read()?, installed))
});
let (before, during, after, installed) = dispositions;
let other = before[2];
assert_eq!(
before[..2],
[libc::SIG_DFL, libc::SIG_IGN],
"SIGTERM starts at SIG_DFL and SIGINT at SIG_IGN"
);
assert!(
![libc::SIG_DFL, libc::SIG_IGN, installed].contains(&other),
"SIGHUP starts at a handler that is not the bridge"
);
assert_eq!(
during,
vec![installed, libc::SIG_IGN, other],
"only SIGTERM, the signal at SIG_DFL, is bridged while the guard is held"
);
assert_eq!(
after, before,
"dropping the guard restores every disposition it found"
);
}
#[test]
fn the_bridge_is_not_installed_by_a_process_that_is_pid_1() {
fn install_as_pid_1() -> bool {
if unsafe { libc::getpid() } != 1 || set_default_stop_dispositions().is_err() {
return false;
}
let Ok(bridge) = ContainerInitStopSignalBridge::install() else {
return false;
};
let untouched = CONTAINER_INIT_STOP_SIGNALS.into_iter().all(|signal| {
current_signal_action(signal)
.is_ok_and(|action| action.sa_sigaction == libc::SIG_DFL)
});
drop(bridge);
untouched
}
in_isolated_process(|| {
enter_new_pid_namespace()?;
let init = fork_waiting_child(install_as_pid_1)?;
signal_and_reap(init, Signal::SIGKILL).map(drop)
});
}
fn namespace_proc_contents() -> Result<(String, String), String> {
Ok((
fs::read_to_string("/proc/mounts").map_err(|error| error.to_string())?,
fs::read_to_string("/proc/self/status").map_err(|error| error.to_string())?,
))
}
#[test]
fn default_container_uses_readonly_proc_fallback() {
let (mounts, status) = Container::new()
.run(|| {
readonly_proc::deny_writable_mounts().map_err(|error| error.to_string())?;
default_container(false)
.run(namespace_proc_contents)
.map_err(|error| format!("{error:?}"))?
})
.unwrap()
.expect("default container should retry its denied proc mount read-only");
readonly_proc::assert_readonly_proc(&mounts, &status, 1);
}
#[test]
fn image_container_uses_readonly_proc_fallback() {
let rootfs = tempfile::tempdir().unwrap();
let tmpfs = tempfile::tempdir().unwrap();
for directory in ["proc", "tmp", "dev/pts"] {
fs::create_dir_all(rootfs.path().join(directory)).unwrap();
}
for node in crate::image::DEV_BIND_TARGETS {
File::create(rootfs.path().join("dev").join(node)).unwrap();
}
let (mounts, status) = Container::new()
.run(|| {
readonly_proc::deny_writable_mounts().map_err(|error| error.to_string())?;
let (mut container, _identity) =
image_container(rootfs.path(), tmpfs.path(), false, true)
.map_err(|error| error.to_string())?;
container
.run(namespace_proc_contents)
.map_err(|error| format!("{error:?}"))?
})
.unwrap()
.expect("image container should retry its denied proc mount read-only");
readonly_proc::assert_readonly_proc(&mounts, &status, 1);
}
#[test]
fn image_container_accepts_a_rootfs_on_a_nosuid_nodev_filesystem() {
fn root_mount_flags() -> Result<(bool, bool, bool), String> {
let mut stat = std::mem::MaybeUninit::<libc::statvfs>::uninit();
let rc = unsafe { libc::statvfs(c"/".as_ptr(), stat.as_mut_ptr()) };
if rc != 0 {
return Err(format!("statvfs /: {}", io::Error::last_os_error()));
}
let flags = unsafe { stat.assume_init() }.f_flag;
Ok((
flags & libc::ST_RDONLY != 0,
flags & libc::ST_NOSUID != 0,
flags & libc::ST_NODEV != 0,
))
}
let base = tempfile::tempdir().unwrap();
let base_path = base.path().to_owned();
let flags = Container::new()
.map_root()
.mount(Mount::tmpfs(&base_path).flags(MountFlags::MS_NOSUID | MountFlags::MS_NODEV))
.run(move || -> Result<(bool, bool, bool), String> {
let rootfs = base_path.join("rootfs");
let tmpfs = base_path.join("scratch");
for directory in ["proc", "tmp", "dev/pts"] {
fs::create_dir_all(rootfs.join(directory)).map_err(|e| e.to_string())?;
}
for node in crate::image::DEV_BIND_TARGETS {
File::create(rootfs.join("dev").join(node)).map_err(|e| e.to_string())?;
}
fs::create_dir(&tmpfs).map_err(|e| e.to_string())?;
let (mut container, _identity) = image_container(&rootfs, &tmpfs, false, true)
.map_err(|error| error.to_string())?;
container
.run(root_mount_flags)
.map_err(|error| format!("{error:?}"))?
})
.expect("run the outer namespace holding the nosuid,nodev filesystem")
.expect("an image root on a nosuid,nodev filesystem must mount read-only");
assert_eq!(
flags,
(true, true, true),
"image root (read-only, nosuid, nodev) flags inside the container"
);
}
#[test]
fn a_refusal_reported_through_the_error_channel_is_still_a_refusal() {
let refusal = SerializableError::from(anyhow::Error::new(
detcore::UnsupportedSyscallError(reverie::syscalls::Sysno::kexec_load),
));
assert_eq!(
refusal.kind(),
FailureKind::PolicyRefusal,
"an UnsupportedSyscallError must be classified at the boundary, which is the \
last place its TYPE still exists -- past it everything is strings"
);
let classified = classify_container_result::<()>(Ok(Err(refusal)))
.expect_err("a refusal is not a success");
assert!(
classified.downcast_ref::<PolicyRefusal>().is_some(),
"record mode must report the same class as run mode for the same policy"
);
assert!(
classified.downcast_ref::<ContainerChildPanic>().is_none(),
"a refusal is not a panic"
);
assert!(
format!("{classified:#}").contains("kexec_load"),
"the refused syscall must survive into the reported chain: {classified:#}"
);
let ordinary = SerializableError::from(anyhow::anyhow!("something broke"));
assert_eq!(ordinary.kind(), FailureKind::Error);
let classified = classify_container_result::<()>(Ok(Err(ordinary)))
.expect_err("an error is not a success");
assert!(classified.downcast_ref::<PolicyRefusal>().is_none());
}
#[test]
fn skid_overshoot_count_survives_the_container_boundary() {
let reported = SerializableError::from(Error::new(SkidOvershootError::new(3)));
assert_eq!(reported.kind(), FailureKind::SkidOvershoot { count: 3 });
let classified = classify_container_result::<()>(Ok(Err(reported)))
.expect_err("a skid overshoot is not a success");
assert!(classified.downcast_ref::<PolicyRefusal>().is_some());
assert_eq!(
classified
.downcast_ref::<SkidOvershootError>()
.expect("the parent must recover the typed cause")
.count(),
3
);
}
#[test]
fn a_container_child_exiting_in_the_signal_band_is_not_an_internal_failure() {
use reverie::process::ExitStatus;
let signal_death = classify_container_result::<()>(Err(RunError::ExitStatus(
ExitStatus::Exited(detcore_model::HERMIT_SIGINT_DEATH_EXIT),
)))
.expect_err("a signal death is not a success");
assert!(
signal_death.downcast_ref::<SignalDeath>().is_some(),
"Exited(130) must classify as a signal death, not as an unchosen child \
exit -- LiteInst and the exit-code path both key on this distinction"
);
assert!(
signal_death.downcast_ref::<ContainerChildExit>().is_none(),
"a signal death must not also read as an unaccounted container exit"
);
let refusal = classify_container_result::<()>(Err(RunError::ExitStatus(
ExitStatus::Exited(detcore_model::HERMIT_POLICY_REFUSAL_EXIT),
)))
.expect_err("a refusal is not a success");
assert!(refusal.downcast_ref::<PolicyRefusal>().is_some());
assert!(
refusal.downcast_ref::<SignalDeath>().is_none(),
"122 must not parse as a signal death; the const-assert pins them disjoint"
);
let unchosen =
classify_container_result::<()>(Err(RunError::ExitStatus(ExitStatus::Exited(7))))
.expect_err("an unaccounted exit is not a success");
assert!(unchosen.downcast_ref::<ContainerChildExit>().is_some());
assert!(unchosen.downcast_ref::<SignalDeath>().is_none());
}
#[test]
fn child_panic_becomes_an_error_naming_message_and_location() {
let mut f = || -> Result<(), Error> { panic!("divergence detail that must survive") };
let reported =
catch_child_panic(&mut f).expect_err("a panic must not be reported as success");
assert_eq!(
reported.kind(),
FailureKind::Panic,
"a caught panic must be tagged as one at the catch site"
);
let error = Error::from(reported);
let rendered = format!("{error:#}");
assert!(
rendered.contains("divergence detail that must survive"),
"panic message was lost: {rendered}"
);
assert!(
rendered.contains("container.rs:"),
"panic location was lost, which is the half catch_unwind does not give us: {rendered}"
);
}
#[test]
fn ordinary_results_pass_through_unchanged() {
let mut ok = || -> Result<u32, Error> { Ok(7) };
assert_eq!(catch_child_panic(&mut ok).unwrap(), 7);
let mut err = || -> Result<u32, Error> { Err(anyhow!("a plain error, not a panic")) };
let reported = catch_child_panic(&mut err).unwrap_err();
assert_eq!(
reported.kind(),
FailureKind::Error,
"an ordinary reported error must NOT be tagged as a panic"
);
let rendered = format!("{:#}", Error::from(reported));
assert!(
rendered.contains("a plain error, not a panic"),
"{rendered}"
);
assert!(
!rendered.contains("panic in container child"),
"an ordinary error must not be relabelled as a panic: {rendered}"
);
}
#[test]
fn identity_hardening_freezes_group_with_overflow_entry() {
let (mounts, guard) =
identity_hardening_mounts().expect("identity hardening mounts should be constructible");
assert!(
!mounts.is_empty(),
"expected at least the frozen /etc/group mount"
);
let group_file = guard
._group_file
.as_ref()
.expect("identity hardening must produce a frozen group file");
let contents = fs::read_to_string(group_file.path())
.expect("frozen group database should be readable");
assert!(
contents
.lines()
.any(|line| line.split(':').nth(2) == Some(OVERFLOW_GID)),
"frozen group database must resolve overflow gid {OVERFLOW_GID}:\n{contents}"
);
}
#[test]
fn mountinfo_provenance_uses_object_identity_not_temp_name_or_target() {
let actual = tempfile::NamedTempFile::new().expect("create actual temporary source");
let target = actual.path().to_path_buf();
let matching =
MountInfoRootSource::new(actual.path(), &target, b"/tmpvol/.hermit/matching").unwrap();
let guard = IdentityGuard {
_group_file: Some(actual),
_nscd_dir: None,
mountinfo_roots: vec![matching],
user_mount_targets: Vec::new(),
};
let rewrites = guard.mountinfo_root_rewrites().unwrap();
assert_eq!(rewrites.len(), 1);
assert_eq!(rewrites[0].deterministic_root, b"/tmpvol/.hermit/matching");
assert_eq!(rewrites[0].raw_root_prefix, None);
assert_eq!(rewrites[0].raw_mountpoint_prefix, None);
assert_ne!(rewrites[0].raw_mount_id, 0);
}
#[test]
fn private_tmp_provenance_marks_descendant_roots_for_rewriting() {
let private_tmp = tempfile::TempDir::new().expect("create private tmp");
let provenance = MountInfoRootSource::private_tmp(private_tmp.path()).unwrap();
assert!(provenance.rewrite_descendant_roots);
assert_eq!(
provenance.raw_mountpoint_prefix.as_deref(),
Some(mountinfo_escape_path(private_tmp.path()).as_slice())
);
assert_eq!(
provenance.deterministic_mountpoint_prefix.as_deref(),
Some(b"/tmp".as_slice())
);
}
#[test]
fn image_container_registers_only_an_automatic_private_tmp() {
let rootfs = tempfile::TempDir::new().expect("create image rootfs");
let private_tmp = tempfile::TempDir::new().expect("create private tmp");
let (_, generated) = image_container(rootfs.path(), private_tmp.path(), false, true)
.expect("construct image container with generated tmp");
assert_eq!(generated.mountinfo_roots.len(), 1);
let (_, supplied) = image_container(rootfs.path(), private_tmp.path(), false, false)
.expect("construct image container with user tmp");
assert!(supplied.mountinfo_roots.is_empty());
}
#[test]
fn fdinfo_mount_id_parser_refuses_malformed_duplicates_and_missing_fields() {
assert_eq!(
detcore_model::procfs::parse_fdinfo_mount_id(b"pos:\t0\nmnt_id:\t37\n").unwrap(),
37
);
for malformed in [
"pos:\t0\n",
"mnt_id:\tbad\nmnt_id:\t37\n",
"mnt_id:\t37\nmnt_id:\t38\n",
"mnt_id:\t37 trailing\n",
"mnt_id:\t18446744073709551616\n",
] {
assert!(
detcore_model::procfs::parse_fdinfo_mount_id(malformed.as_bytes()).is_none(),
"accepted malformed fdinfo: {malformed:?}"
);
}
}
#[test]
fn mountinfo_provenance_refuses_a_same_target_lookalike() {
let actual = tempfile::NamedTempFile::new().expect("create actual temporary source");
let lookalike = tempfile::NamedTempFile::new().expect("create lookalike temporary source");
let target = actual.path().to_path_buf();
let same_target_wrong_source =
MountInfoRootSource::new(lookalike.path(), &target, b"/tmpvol/.hermit/lookalike")
.unwrap();
let guard = IdentityGuard {
_group_file: Some(actual),
_nscd_dir: None,
mountinfo_roots: vec![same_target_wrong_source],
user_mount_targets: Vec::new(),
};
let error = guard.mountinfo_root_rewrites().unwrap_err().to_string();
assert!(error.contains("does not match the pinned Hermit-owned source"));
}
#[test]
fn explicit_tmp_mount_discards_private_tmp_provenance_before_resolution() {
let private_tmp = tempfile::TempDir::new().expect("create private tmp");
let mut guard = IdentityGuard::empty();
guard.add_private_tmp(private_tmp.path()).unwrap();
assert_eq!(guard.mountinfo_roots.len(), 1);
let mut mounts = Vec::new();
guard.discard_mounts_shadowed_by(&mut mounts, Path::new("/tmp"));
assert!(guard.mountinfo_roots.is_empty());
}
#[test]
fn ordered_user_mounts_do_not_reuse_stale_host_resolution() {
let var_run_is_run = fs::canonicalize("/var/run").ok() == fs::canonicalize("/run").ok();
if !var_run_is_run {
return;
}
let mut guard = IdentityGuard::empty();
guard.mountinfo_roots.push(MountInfoRootSource {
source: None,
target: PathBuf::from("/run/nscd"),
deterministic_root: Some(DETERMINISTIC_NSCD_ROOT.to_vec()),
rewrite_descendant_roots: false,
raw_mountpoint_prefix: None,
deterministic_mountpoint_prefix: None,
});
let mut mounts = vec![Mount::bind("/tmp", "/run/nscd")];
guard.discard_mounts_shadowed_by(&mut mounts, Path::new("/var"));
guard.discard_mounts_shadowed_by(&mut mounts, Path::new("/var/run/nscd"));
assert_eq!(mounts.len(), 1);
assert_eq!(guard.mountinfo_roots.len(), 1);
for direct_target in ["/run", "/var/run/nscd"] {
let mut guard = IdentityGuard::empty();
guard.mountinfo_roots.push(MountInfoRootSource {
source: None,
target: PathBuf::from("/run/nscd"),
deterministic_root: Some(DETERMINISTIC_NSCD_ROOT.to_vec()),
rewrite_descendant_roots: false,
raw_mountpoint_prefix: None,
deterministic_mountpoint_prefix: None,
});
let mut mounts = vec![Mount::bind("/tmp", "/run/nscd")];
guard.discard_mounts_shadowed_by(&mut mounts, Path::new(direct_target));
assert!(mounts.is_empty(), "{direct_target} must shadow /run/nscd");
assert!(guard.mountinfo_roots.is_empty());
}
}
#[test]
fn shadow_detection_follows_the_host_var_run_target() {
let var_run_is_run = fs::canonicalize("/var/run").ok() == fs::canonicalize("/run").ok();
assert_eq!(
mount_target_is_shadowed(Path::new("/var/run/nscd"), Path::new("/var")),
!var_run_is_run
);
assert_eq!(
mount_target_is_shadowed(Path::new("/var/run/nscd"), Path::new("/run")),
var_run_is_run
);
assert!(!mount_target_is_shadowed(
Path::new("/var/run/nscd"),
Path::new("/var/lib")
));
}
#[test]
fn affinity_core_is_an_actual_member_of_a_sparse_allowed_mask() {
let mut affinity = CpuSet::new();
for cpu in [7, 31, 211] {
affinity.set(cpu).expect("valid sparse CPU id");
}
let allowed = cpu_ids(&affinity);
assert_eq!(allowed, [7, 31, 211]);
for _ in 0..128 {
let selected = choose_affinity_core(&allowed).expect("non-empty mask");
assert!(allowed.contains(&selected), "selected CPU {selected}");
}
assert_eq!(choose_affinity_core(&[]), None);
}
}