use super::{fork_running, reap, reap_status};
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_panic_after_fork_running_still_reaps_the_child() {
use std::cell::RefCell;
use std::os::fd::AsFd;
let probe: RefCell<Option<std::os::fd::OwnedFd>> = RefCell::new(None);
let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let guard = fork_running(&[], || {
unsafe { libc::pause() };
});
let child = rustix::process::Pid::from_raw(guard.pid() as i32).expect("a positive pid");
*probe.borrow_mut() =
Some(rustix::process::pidfd_open(child, rustix::process::PidfdFlags::empty()).expect("open a probe pidfd"));
panic!("forced panic between the fork and any cleanup the caller would otherwise do");
}));
assert!(unwound.is_err(), "the forced panic must actually unwind");
let probe = probe.into_inner().expect("the probe pidfd was opened before the panic");
assert_eq!(
rustix::process::waitid(
rustix::process::WaitId::PidFd(probe.as_fd()),
rustix::process::WaitIdOptions::EXITED | rustix::process::WaitIdOptions::NOHANG,
)
.unwrap_err(),
rustix::io::Errno::CHILD,
"the guard must have reaped the child during unwind"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn drop_without_a_panic_reaps_the_child() {
use std::os::fd::AsFd;
let guard = fork_running(&[], || {
unsafe { libc::pause() };
});
let child = rustix::process::Pid::from_raw(guard.pid() as i32).expect("a positive pid");
let probe = rustix::process::pidfd_open(child, rustix::process::PidfdFlags::empty()).expect("open a probe pidfd");
drop(guard);
assert_eq!(
rustix::process::waitid(
rustix::process::WaitId::PidFd(probe.as_fd()),
rustix::process::WaitIdOptions::EXITED | rustix::process::WaitIdOptions::NOHANG,
)
.unwrap_err(),
rustix::io::Errno::CHILD,
"a normal drop must have reaped the child"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn drop_retries_waitid_on_eintr() {
use std::os::fd::AsFd;
let guard = fork_running(&[], || {
unsafe { libc::pause() };
});
let child = rustix::process::Pid::from_raw(guard.pid() as i32).expect("a positive pid");
let probe = rustix::process::pidfd_open(child, rustix::process::PidfdFlags::empty()).expect("open a probe pidfd");
crate::containment::cgroup::fault::set_force_kill_on_drop_waitid_eintr(true);
drop(guard);
assert!(
!crate::containment::cgroup::fault::take_force_kill_on_drop_waitid_eintr(),
"the fault must be consumed by the retry loop"
);
assert_eq!(
rustix::process::waitid(
rustix::process::WaitId::PidFd(probe.as_fd()),
rustix::process::WaitIdOptions::EXITED | rustix::process::WaitIdOptions::NOHANG,
)
.unwrap_err(),
rustix::io::Errno::CHILD,
"the child must still be reaped despite the injected EINTR"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn drop_reports_a_kill_failure_without_blocking() {
use std::os::fd::AsFd;
let guard = fork_running(&[], || {
unsafe { libc::pause() };
});
let child_pid = guard.pid();
let child = rustix::process::Pid::from_raw(child_pid as i32).expect("a positive pid");
let probe = rustix::process::pidfd_open(child, rustix::process::PidfdFlags::empty()).expect("open a probe pidfd");
crate::containment::cgroup::fault::set_force_kill_on_drop_kill_failure(true);
let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(guard)));
assert_eq!(
unwound.is_err(),
cfg!(debug_assertions),
"a failed kill should panic on its asserted contract only with debug_assertions on"
);
assert!(
!crate::containment::cgroup::fault::take_force_kill_on_drop_kill_failure(),
"the fault must be consumed by the failed kill"
);
match rustix::process::waitid(
rustix::process::WaitId::PidFd(probe.as_fd()),
rustix::process::WaitIdOptions::EXITED | rustix::process::WaitIdOptions::NOHANG,
) {
Ok(None) => {}
other => panic!("a forced kill failure must leave the child alive and unreaped, got {other:?}"),
}
unsafe { libc::kill(child_pid as i32, libc::SIGKILL) };
reap(child_pid);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn defuse_disarms_the_guard() {
use std::io::Write;
use std::os::fd::{AsFd, AsRawFd};
let (gate_read, mut gate_write) = std::io::pipe().expect("open the gate");
let gate = gate_read.as_raw_fd();
let (ack_read, ack_write) = std::io::pipe().expect("open the ack pipe");
let ack_write_fd = ack_write.as_raw_fd();
let guard = fork_running(&[gate, ack_write_fd], move || {
super::block_on(gate);
unsafe {
if libc::write(ack_write_fd, b"a".as_ptr().cast(), 1) != 1 {
libc::_exit(1);
}
libc::pause();
}
});
let child = rustix::process::Pid::from_raw(guard.pid() as i32).expect("a positive pid");
let probe = rustix::process::pidfd_open(child, rustix::process::PidfdFlags::empty()).expect("open a probe pidfd");
_ = guard.defuse();
drop(ack_write);
gate_write.write_all(b"g").expect("release the child");
let mut byte = 0u8;
let n = unsafe { libc::read(ack_read.as_raw_fd(), (&raw mut byte).cast(), 1) };
_ = rustix::process::pidfd_send_signal(probe.as_fd(), rustix::process::Signal::KILL);
_ = rustix::process::waitid(
rustix::process::WaitId::PidFd(probe.as_fd()),
rustix::process::WaitIdOptions::EXITED,
);
assert_eq!(
n, 1,
"a defused guard must not have killed the child before it could ack"
);
}
#[cfg(target_os = "linux")]
fn read_report_byte(pipe: &mut impl std::io::Read) -> Option<u8> {
let mut byte = 0u8;
loop {
match pipe.read(std::slice::from_mut(&mut byte)) {
Ok(1) => return Some(byte),
Ok(_) => return None,
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => return None,
Err(e) => panic!("read failed unexpectedly: {e}"),
}
}
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn read_report_byte_retries_an_interrupted_read() {
struct InterruptedOnce(bool);
impl std::io::Read for InterruptedOnce {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
if !std::mem::replace(&mut self.0, true) {
return Err(std::io::ErrorKind::Interrupted.into());
}
buf[0] = 1;
Ok(1)
}
}
assert_eq!(read_report_byte(&mut InterruptedOnce(false)), Some(1));
}
#[cfg(target_os = "linux")]
fn describe_status(status: i32) -> String {
if libc::WIFEXITED(status) {
let code = libc::WEXITSTATUS(status);
if code == super::REPORT_WRITE_FAILED_EXIT {
format!("exit {code} (REPORT_WRITE_FAILED_EXIT: the child's report write failed)")
} else {
format!("exit {code}")
}
} else {
format!("raw wait status {status:#x}")
}
}
#[cfg(target_os = "linux")]
fn set_nonblocking(fd: std::os::fd::RawFd) {
let fd = unsafe { rustix::fd::BorrowedFd::borrow_raw(fd) };
let flags = rustix::fs::fcntl_getfl(fd).unwrap_or_else(|e| panic!("fcntl F_GETFL failed: {e}"));
rustix::fs::fcntl_setfl(fd, flags | rustix::fs::OFlags::NONBLOCK)
.unwrap_or_else(|e| panic!("fcntl F_SETFL O_NONBLOCK failed: {e}"));
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn fork_running_holds_spawn_lock_across_the_fork() {
use std::os::fd::AsRawFd;
use std::sync::mpsc;
let (mut report_read, report_write) = std::io::pipe().expect("open the report pipe");
set_nonblocking(report_read.as_raw_fd());
let report_write_fd = report_write.as_raw_fd();
let (tx_hook, rx_hook) = mpsc::channel::<bool>();
let fork_thread = std::thread::spawn(move || {
let _report_guard = crate::containment::cgroup::fault::set_fork_running_lock_held_report_fd(report_write_fd);
let _hook_guard = crate::containment::cgroup::fault::set_after_fork_still_locked(move || {
_ = tx_hook.send(crate::child::spawn::spawn_lock_held_by_this_thread());
});
fork_running(&[], || {})
});
let guard = match fork_thread.join() {
Ok(guard) => guard,
Err(payload) => std::panic::resume_unwind(payload),
};
let status = reap_status(guard.defuse());
drop(report_write);
let hook_saw_held = rx_hook.recv().expect("the post-fork hook must have run");
assert!(
hook_saw_held,
"spawn_lock must still be held when the post-fork hook runs"
);
assert_eq!(
read_report_byte(&mut report_read),
Some(1),
"the child must report that spawn_lock was held, from the forking thread's own point of \
view, at the exact instant of the fork (child ended: {})",
describe_status(status)
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn fork_running_child_exits_with_a_dedicated_code_when_its_report_write_fails() {
use std::os::fd::AsRawFd;
let (report_read, _report_write) = std::io::pipe().expect("open the report pipe");
let _report_guard =
crate::containment::cgroup::fault::set_fork_running_lock_held_report_fd(report_read.as_raw_fd());
let guard = fork_running(&[], || {});
let status = reap_status(guard.defuse());
assert!(
libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == super::REPORT_WRITE_FAILED_EXIT,
"a child whose report write failed must exit with REPORT_WRITE_FAILED_EXIT, got {}",
describe_status(status)
);
}
#[cfg(target_os = "linux")]
#[derive(Debug, PartialEq, Eq)]
enum LockProbe {
Contended,
Forked { holder_released: bool },
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn fork_running_waits_for_a_held_spawn_lock() {
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{mpsc, Arc};
let released = Arc::new(AtomicBool::new(false));
let (tx_held, rx_held) = mpsc::channel::<()>();
let (tx_release, rx_release) = mpsc::channel::<()>();
let holder = {
let released = Arc::clone(&released);
std::thread::spawn(move || {
let lock = crate::child::spawn::spawn_lock();
tx_held.send(()).expect("the test thread is waiting for the holder");
_ = rx_release.recv();
released.store(true, Ordering::SeqCst);
drop(lock);
})
};
rx_held.recv().expect("the holder must take the lock");
let (tx_probe, rx_probe) = mpsc::channel::<LockProbe>();
let fork_thread = {
let released = Arc::clone(&released);
let tx_contended = tx_probe.clone();
std::thread::spawn(move || {
let _contended_guard = crate::containment::cgroup::fault::set_fork_running_lock_contended(move || {
_ = tx_contended.send(LockProbe::Contended);
});
let _hook_guard = crate::containment::cgroup::fault::set_after_fork_still_locked(move || {
_ = tx_probe.send(LockProbe::Forked {
holder_released: released.load(Ordering::SeqCst),
});
});
fork_running(&[], || {})
})
};
let first = rx_probe.recv();
tx_release.send(()).expect("the holder is waiting to be released");
holder.join().expect("the holder must not panic");
let guard = match fork_thread.join() {
Ok(guard) => guard,
Err(payload) => std::panic::resume_unwind(payload),
};
reap(guard.defuse());
assert_eq!(
first,
Ok(LockProbe::Contended),
"fork_running must find spawn_lock held and wait, not fork first"
);
assert_eq!(
rx_probe.recv(),
Ok(LockProbe::Forked { holder_released: true }),
"fork_running must not fork before the holder released spawn_lock"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn fork_running_under_an_outer_spawn_lock_panics_naming_the_reentry() {
let outer = crate::child::spawn::spawn_lock();
let unwound = std::panic::catch_unwind(|| {
_ = fork_running(&[], || {});
});
drop(outer);
let payload = unwound.expect_err("fork_running must refuse to run under an outer spawn_lock");
let message = payload
.downcast_ref::<String>()
.map(String::as_str)
.or_else(|| payload.downcast_ref::<&str>().copied())
.unwrap_or("<non-string panic payload>");
assert!(
message.contains("spawn_lock re-entered"),
"the panic must name the re-entry, got: {message}"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn fork_running_child_keeps_only_the_descriptors_it_was_told_to() {
use std::io::Read;
use std::os::fd::AsRawFd;
let (mut ready_read, ready_write) = std::io::pipe().expect("open the ready pipe");
let ready_fd = ready_write.as_raw_fd();
let (_other_read, _other_write) = std::io::pipe().expect("open the other pipe");
let guard = fork_running(&[ready_fd], move || {
unsafe {
if libc::write(ready_fd, b"r".as_ptr().cast(), 1) != 1 {
libc::_exit(1);
}
libc::pause();
}
});
let mut byte = [0u8; 1];
ready_read.read_exact(&mut byte).expect("the child reports it is ready");
let mut held: Vec<i32> = std::fs::read_dir(format!("/proc/{}/fd", guard.pid()))
.expect("list the child's descriptors")
.map(|entry| {
let name = entry.expect("a descriptor entry").file_name();
name.to_str()
.and_then(|n| n.parse().ok())
.expect("a numeric descriptor")
})
.filter(|&fd| fd > 2)
.collect();
held.sort_unstable();
assert_eq!(
held,
[ready_fd],
"the child holds exactly the descriptor it was told to keep"
);
}