#[cfg(target_os = "linux")]
use crate::os_process::linux::fork::{fork_with_pidfd, CloneKind, Fork};
#[cfg(target_os = "linux")]
pub(crate) fn fork_running(keep: &[std::os::fd::RawFd], body: impl FnOnce()) -> KillOnDrop {
let guard =
crate::child::spawn::spawn_lock_tracked(crate::containment::cgroup::fault::run_fork_running_lock_contended);
fork_running_held(Held::Owned(guard), Some(keep), body)
}
#[cfg(target_os = "linux")]
pub(crate) fn fork_running_locked(guard: &crate::child::spawn::SpawnLockGuard, body: impl FnOnce()) -> KillOnDrop {
debug_assert!(
crate::child::spawn::spawn_lock_held_by_this_thread(),
"fork_running_locked: the guard must be this thread's spawn_lock"
);
fork_running_held(Held::Borrowed(guard), None, body)
}
#[cfg(target_os = "linux")]
#[allow(
dead_code,
reason = "held only for their Drop / as proof the lock is held; never read"
)]
enum Held<'a> {
Owned(crate::child::spawn::SpawnLockGuard),
Borrowed(&'a crate::child::spawn::SpawnLockGuard),
}
#[cfg(target_os = "linux")]
impl Held<'_> {
fn release(self) {
drop(self);
}
}
#[cfg(target_os = "linux")]
fn fork_running_held(held: Held<'_>, keep: Option<&[std::os::fd::RawFd]>, body: impl FnOnce()) -> KillOnDrop {
let report_fd = crate::containment::cgroup::fault::take_fork_running_lock_held_report_fd();
let kept: Option<Vec<std::os::fd::RawFd>> = keep.map(|keep| {
let mut kept: Vec<_> = (0..=2).chain(keep.iter().copied()).chain(report_fd).collect();
kept.sort_unstable();
kept.dedup();
kept
});
let forked = unsafe { fork_with_pidfd(CloneKind::Plain) };
match forked {
Err(errno) => panic!("fork: {}", std::io::Error::from_raw_os_error(errno)),
Ok(Fork::Child) => {
if let Some(kept) = &kept {
if !close_range_except(kept) {
unsafe { libc::_exit(CLOSE_RANGE_FAILED_EXIT) };
}
}
if let Some(fd) = report_fd {
let held: u8 = crate::child::spawn::spawn_lock_held_by_this_thread().into();
let written = unsafe { libc::write(fd, (&raw const held).cast(), 1) };
if written != 1 {
unsafe { libc::_exit(REPORT_WRITE_FAILED_EXIT) };
}
}
std::mem::forget(held);
body();
unsafe { libc::_exit(0) }
}
Ok(Fork::Parent(new)) => {
let kod = KillOnDrop {
pid: new.pid as u32,
pidfd: Some(new.pidfd),
closes_fds: keep.is_some(),
};
crate::containment::cgroup::fault::run_after_fork_still_locked();
held.release();
kod
}
}
}
#[cfg(target_os = "linux")]
pub(crate) const REPORT_WRITE_FAILED_EXIT: i32 = 113;
#[cfg(target_os = "linux")]
pub(crate) const CLOSE_RANGE_FAILED_EXIT: i32 = 114;
#[cfg(target_os = "linux")]
const CLOSE_RANGE_FAILED_MESSAGE: &str = "the forked child exited 114: if it came from fork_running, its close_range \
failed (it needs Linux 5.9, and a seccomp profile that allows it)";
#[cfg(target_os = "linux")]
pub(crate) fn close_range_except(keep: &[std::os::fd::RawFd]) -> bool {
let close_gap = |first: std::os::fd::RawFd, last: std::os::fd::RawFd| {
if first > last {
return true;
}
let rc = unsafe {
libc::syscall(
libc::SYS_close_range,
first as libc::c_long,
last as libc::c_long,
0 as libc::c_long,
)
};
rc == 0
};
let mut prev_end: std::os::fd::RawFd = -1;
for &fd in keep {
if !close_gap(prev_end + 1, fd - 1) {
return false;
}
prev_end = fd;
}
close_gap(prev_end + 1, std::os::fd::RawFd::MAX)
}
#[cfg(target_os = "linux")]
#[must_use = "dropping this immediately kills and reaps the child; bind it for as long as the child must live"]
pub(crate) struct KillOnDrop {
pid: u32,
pidfd: Option<std::os::fd::OwnedFd>,
closes_fds: bool,
}
#[cfg(target_os = "linux")]
impl KillOnDrop {
pub(crate) fn pid(&self) -> u32 {
self.pid
}
#[must_use = "the pid still needs reaping by some other means; dropping it here leaks the child"]
pub(crate) fn defuse(mut self) -> u32 {
self.pidfd = None;
self.pid
}
}
#[cfg(target_os = "linux")]
impl Drop for KillOnDrop {
fn drop(&mut self) {
use std::io::Write;
use std::os::fd::AsFd;
let Some(pidfd) = self.pidfd.take() else {
return;
};
let panicking = std::thread::panicking();
let killed = if crate::containment::cgroup::fault::take_force_kill_on_drop_kill_failure() {
Err(rustix::io::Errno::PERM)
} else {
rustix::process::pidfd_send_signal(pidfd.as_fd(), rustix::process::Signal::KILL)
};
if killed.is_err() {
_ = writeln!(std::io::stderr(), "KillOnDrop: pidfd_send_signal: {killed:?}");
if !panicking {
debug_assert!(killed.is_ok(), "pidfd_send_signal: {killed:?}");
}
return;
}
let reaped = loop {
if crate::containment::cgroup::fault::take_force_kill_on_drop_waitid_eintr() {
continue;
}
match rustix::process::waitid(
rustix::process::WaitId::PidFd(pidfd.as_fd()),
rustix::process::WaitIdOptions::EXITED,
) {
Err(rustix::io::Errno::INTR) => continue,
other => break other,
}
};
if reaped.is_err() {
if panicking {
_ = writeln!(std::io::stderr(), "KillOnDrop: waitid: {reaped:?}");
} else {
debug_assert!(reaped.is_ok(), "waitid: {reaped:?}");
}
} else if self.closes_fds
&& reaped
.is_ok_and(|status| status.is_some_and(|status| status.exit_status() == Some(CLOSE_RANGE_FAILED_EXIT)))
{
if panicking {
_ = writeln!(std::io::stderr(), "KillOnDrop: {CLOSE_RANGE_FAILED_MESSAGE}");
} else {
panic!("{CLOSE_RANGE_FAILED_MESSAGE}");
}
}
}
}
#[cfg(target_os = "linux")]
pub(crate) fn reap(pid: u32) {
reap_status(pid);
}
#[cfg(target_os = "linux")]
pub(crate) fn reap_status(pid: u32) -> i32 {
let mut status = 0;
let reaped = unsafe { libc::waitpid(pid as i32, &mut status, 0) };
assert_eq!(reaped, pid as i32, "waitpid: {}", std::io::Error::last_os_error());
assert!(
!(libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == CLOSE_RANGE_FAILED_EXIT),
"{CLOSE_RANGE_FAILED_MESSAGE}"
);
status
}
#[cfg(target_os = "linux")]
const BLOCK_ON_READ_FAILED_EXIT: i32 = 111;
#[cfg(target_os = "linux")]
pub(crate) fn block_on(gate: std::os::fd::RawFd) {
let mut byte = 0u8;
let n = loop {
let n = unsafe { libc::read(gate, (&raw mut byte).cast(), 1) };
if n == -1 {
if std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted {
continue;
}
unsafe { libc::_exit(BLOCK_ON_READ_FAILED_EXIT) };
}
break n;
};
debug_assert_eq!(n, 1, "read");
}
#[cfg(target_os = "linux")]
pub(crate) unsafe fn place_in_pre_exec(procs_fd: std::os::fd::RawFd) -> std::io::Result<()> {
match unsafe { crate::containment::cgroup::place_self_in_cgroup(procs_fd) } {
0 => Ok(()),
errno => Err(std::io::Error::from_raw_os_error(i32::from(errno))),
}
}
#[cfg(target_os = "linux")]
pub(crate) fn alone(name: &str) -> bool {
const ALONE: &str = "COSCA_TESTCFG_ALONE";
if std::env::var_os(ALONE).is_some_and(|alone| alone == name) {
return true;
}
let out = crate::test_spawn::output_captured(
crate::test_reexec::with_json_events(
crate::test_reexec::command(std::env::current_exe().expect("this test binary")).args([
name,
"--exact",
crate::test_reexec::NOCAPTURE,
"--test-threads=1",
]),
)
.env(ALONE, name),
)
.expect("run the test alone");
let stdout = String::from_utf8_lossy(&out.stdout);
if let Err(why) = crate::test_reexec::suite_passed_exactly_one(&out) {
panic!(
"{why}\n{}\n--- stdout ---\n{stdout}\n--- stderr ---\n{}",
out.status,
String::from_utf8_lossy(&out.stderr)
);
}
false
}
#[cfg(target_os = "linux")]
pub(crate) fn pidfd_of(pid: u32) -> std::os::fd::OwnedFd {
rustix::process::pidfd_open(
rustix::process::Pid::from_raw(pid as i32).expect("a positive pid"),
rustix::process::PidfdFlags::empty(),
)
.expect("open a pidfd")
}
#[cfg(target_os = "linux")]
pub(crate) fn handle_of(pid: u32, pidfd: &std::os::fd::OwnedFd) -> crate::containment::ChildHandle<'_> {
crate::containment::ChildHandle {
pid,
pidfd: std::os::fd::AsFd::as_fd(pidfd),
}
}
#[cfg(target_os = "linux")]
pub(crate) fn entered_leaf_at(leaf_path: std::path::PathBuf) -> crate::containment::cgroup::CgroupLeaf {
let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path);
leaf.record_placement(crate::containment::cgroup::PlacementReport::Placed);
leaf.take_placement(handle_of(std::process::id(), &pidfd_of(std::process::id())))
.expect("the child reported Placed");
leaf
}
#[cfg(target_os = "linux")]
pub(crate) struct FakeLeaf {
_dir: tempfile::TempDir,
pub(crate) leaf: std::path::PathBuf,
pub(crate) events: std::path::PathBuf,
pub(crate) kill: std::path::PathBuf,
}
#[cfg(target_os = "linux")]
impl FakeLeaf {
pub(crate) fn new(name: &str, populated: bool) -> FakeLeaf {
let dir = tempfile::tempdir().expect("tempdir");
let leaf = dir.path().join(name);
std::fs::create_dir(&leaf).expect("create the leaf");
let events = dir.path().join(format!("{name}.events"));
std::fs::write(&events, format!("populated {}\nfrozen 0\n", u8::from(populated))).expect("write cgroup.events");
std::os::unix::fs::symlink(&events, leaf.join("cgroup.events")).expect("link cgroup.events");
let kill = dir.path().join(format!("{name}.kill"));
std::fs::write(&kill, b"").expect("create cgroup.kill");
std::os::unix::fs::symlink(&kill, leaf.join("cgroup.kill")).expect("link cgroup.kill");
FakeLeaf {
_dir: dir,
leaf,
events,
kill,
}
}
pub(crate) fn kill_written(&self) -> Vec<u8> {
std::fs::read(&self.kill).expect("read cgroup.kill")
}
pub(crate) fn clear_kill(&self) {
std::fs::write(&self.kill, b"").expect("clear cgroup.kill");
}
pub(crate) fn set_populated(events: &std::path::Path, populated: bool) {
use std::os::unix::fs::FileExt as _;
let file = std::fs::OpenOptions::new()
.write(true)
.open(events)
.expect("open cgroup.events");
file.write_all_at(if populated { b"1" } else { b"0" }, "populated ".len() as u64)
.expect("flip populated");
}
pub(crate) fn set_unreadable(events: &std::path::Path) {
std::fs::write(events, "frozen 0\n").expect("write a cgroup.events with no populated field");
}
pub(crate) fn is_populated(events: &std::path::Path) -> bool {
let contents = std::fs::read_to_string(events).expect("read cgroup.events");
contents.lines().any(|l| l.trim() == "populated 1")
}
pub(crate) fn remove(leaf: &std::path::Path) {
for entry in std::fs::read_dir(leaf).expect("list the leaf") {
let entry = entry.expect("leaf entry");
if entry.file_type().expect("the entry's type").is_dir() {
std::fs::remove_dir_all(entry.path()).expect("remove a leaf directory");
} else {
std::fs::remove_file(entry.path()).expect("remove a leaf file");
}
}
std::fs::remove_dir(leaf).expect("remove the leaf");
}
pub(crate) fn rmdir(leaf: &std::path::Path, events: &std::path::Path) -> std::io::Result<()> {
if !leaf.exists() {
return Err(std::io::Error::from_raw_os_error(libc::ENOENT));
}
if FakeLeaf::is_populated(events) {
return Err(std::io::Error::from_raw_os_error(libc::EBUSY));
}
FakeLeaf::remove(leaf);
Ok(())
}
}
#[cfg(target_os = "linux")]
pub(crate) fn remove_drained_leaf(leaf_path: &std::path::Path) {
let leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path.to_path_buf());
leaf.wait_drained(None).expect("wait for the drain");
match std::fs::remove_dir(leaf_path) {
Ok(()) => {}
Err(e) if e.raw_os_error() == Some(libc::ENOENT) => {}
Err(e) => panic!("remove the leaf: {e}"),
}
}
#[cfg(target_os = "linux")]
pub(crate) fn signal_when_drain_blocks(tx: std::sync::mpsc::Sender<()>) -> crate::wait::block_probe::Armed {
crate::wait::block_probe::on_each_drain_block(move || {
tx.send(()).expect("the receiver outlives the armed hook");
})
}
#[cfg(target_os = "linux")]
struct WaitObserverGuard {
_signal: crate::wait::block_probe::Armed,
}
#[cfg(target_os = "linux")]
impl Drop for WaitObserverGuard {
fn drop(&mut self) {
crate::containment::cgroup::fault::take_wait_site_park_notifier();
crate::containment::cgroup::fault::take_drain_zero_remaining_notifier();
}
}
#[cfg(target_os = "linux")]
pub(crate) struct WaitObserver;
#[cfg(target_os = "linux")]
impl WaitObserver {
pub(crate) fn run<T>(
f: impl FnOnce() -> T,
) -> (T, Vec<crate::containment::cgroup::fault::WaitSitePark>, usize, usize) {
let (block_tx, block_rx) = std::sync::mpsc::channel();
let (result, parks, zero_remainings) = Self::run_with_block_sender(block_tx, f);
(result, parks, block_rx.try_iter().count(), zero_remainings)
}
pub(crate) fn run_with_block_sender<T>(
block_tx: std::sync::mpsc::Sender<()>,
f: impl FnOnce() -> T,
) -> (T, Vec<crate::containment::cgroup::fault::WaitSitePark>, usize) {
use crate::containment::cgroup::fault;
let (park_tx, park_rx) = std::sync::mpsc::channel();
let (zero_tx, zero_rx) = std::sync::mpsc::channel();
fault::set_wait_site_park_notifier(park_tx);
fault::set_drain_zero_remaining_notifier(zero_tx);
let _guard = WaitObserverGuard {
_signal: signal_when_drain_blocks(block_tx),
};
let result = f();
(result, park_rx.try_iter().collect(), zero_rx.try_iter().count())
}
}
#[cfg(target_os = "linux")]
#[must_use]
pub(crate) struct WaitDeadlineArgGuard;
#[cfg(target_os = "linux")]
impl WaitDeadlineArgGuard {
pub(crate) fn install() -> (Self, std::sync::mpsc::Receiver<std::time::Instant>) {
let (tx, rx) = std::sync::mpsc::channel();
crate::containment::cgroup::fault::set_wait_deadline_arg_notifier(tx);
(Self, rx)
}
}
#[cfg(target_os = "linux")]
impl Drop for WaitDeadlineArgGuard {
fn drop(&mut self) {
crate::containment::cgroup::fault::take_wait_deadline_arg_notifier();
}
}
#[cfg(target_os = "linux")]
pub(crate) fn assert_bounded_conclusion(
parks: &[crate::containment::cgroup::fault::WaitSitePark],
blocks: usize,
zero_remainings: usize,
expected_deadline: std::time::Instant,
) {
assert_eq!(
zero_remainings, 1,
"a bounded call that finds a member still alive must conclude exactly once through \
the zero-remaining shortcut, got {zero_remainings}"
);
assert_eq!(
blocks,
parks.len(),
"drain_step announced blocking {blocks} times, but the wait site's own wait call \
returned {} times — every announced block must show up as a wait-site return",
parks.len()
);
assert!(
parks.iter().all(|p| p.deadline == Some(expected_deadline)),
"every park in a bounded call must report the caller's own requested deadline instant \
exactly, got {parks:?}"
);
let timed_out = parks.iter().filter(|p| !p.woken).count();
assert!(
timed_out <= 1,
"at most one park can genuinely time out before the call concludes, got {parks:?}"
);
if let Some(pos) = parks.iter().rposition(|p| !p.woken) {
assert_eq!(pos, parks.len() - 1, "a timed-out park must be the last, got {parks:?}");
}
}
#[cfg(target_os = "linux")]
pub(crate) fn kill_record(landed: bool) -> std::sync::Arc<crate::containment::cgroup::KillRecord> {
let record = crate::containment::cgroup::KillRecord::default();
if landed {
record.record(Ok(()));
}
std::sync::Arc::new(record)
}
#[cfg(test)]
#[path = "test_support_tests.rs"]
mod test_support_tests;