use crate::test_child::{await_member_ready, member_command};
use crate::test_groups::{setuid, Group};
use std::io::BufRead;
use std::os::fd::{AsFd, AsRawFd};
use super::{holders, holds_marker, holds_marker_query, pipe_handle_of, MarkerQuery, PipeFdInfo, PROC_PIDFDPIPEINFO};
pub(crate) fn inert_root() -> crate::identity::ProcessId {
crate::identity::ProcessId::from_parts_for_test(0x7FFF_FFF0, crate::identity::Key::for_test(1))
}
pub(crate) fn install_on(
cmd: &mut std::process::Command,
reserved: &[std::os::fd::RawFd],
) -> Result<super::PreparedMarker, crate::error::Error> {
crate::child::spawn::in_child::register_alone(cmd, |steps| super::install(steps, reserved, &host_kernel()))
}
fn refusing_reads_of(prepared: super::PreparedMarker, pid: crate::identity::RawPid) -> super::PreparedMarker {
reading_through(prepared, crate::identity::unreadable(pid))
}
fn reading_through(
prepared: super::PreparedMarker,
kernel: impl crate::identity::Kernel + Send + 'static,
) -> super::PreparedMarker {
super::PreparedMarker {
kernel: crate::identity::spawn_kernel(kernel),
..prepared
}
}
fn all_pids() -> Vec<crate::identity::RawPid> {
crate::containment::enumerate::snapshot().0
}
fn test_spawn_lock() -> crate::child::spawn::SpawnLockGuard {
crate::child::spawn::spawn_lock()
}
#[skuld::test]
fn a_live_pipe_has_a_nonzero_handle_distinct_per_end() {
let (r, w) = std::io::pipe().expect("pipe");
let hw = pipe_handle_of(w.as_fd()).expect("the write end is a pipe");
let hr = pipe_handle_of(r.as_fd()).expect("the read end is a pipe");
assert_ne!(hw, 0, "a live pipe's handle must be non-zero");
assert_ne!(hw, hr, "the two ends of a pipe are distinct kernel objects");
}
#[skuld::test]
fn many_simultaneously_live_pipes_never_share_a_handle() {
const N: usize = 50;
let mut pipes = Vec::with_capacity(N);
for _ in 0..N {
pipes.push(std::io::pipe().expect("pipe"));
}
let mut handles: Vec<u64> = Vec::with_capacity(N * 2);
for (r, w) in &pipes {
handles.push(pipe_handle_of(r.as_fd()).expect("read end handle"));
handles.push(pipe_handle_of(w.as_fd()).expect("write end handle"));
}
let unique: std::collections::HashSet<u64> = handles.iter().copied().collect();
assert_eq!(
unique.len(),
handles.len(),
"{} simultaneously-live pipe handles must all be distinct; found {} unique among {}",
N,
unique.len(),
handles.len()
);
}
#[skuld::test]
fn a_non_pipe_descriptor_has_no_pipe_handle() {
let f = std::fs::File::open("/dev/null").expect("open /dev/null");
assert!(
pipe_handle_of(f.as_fd()).is_none(),
"a character device is not a pipe and must not yield a pipe handle"
);
}
#[skuld::test]
fn holding_the_read_end_keeps_the_handle_from_being_reissued() {
let (read, write) = std::io::pipe().expect("pipe");
let handle = pipe_handle_of(write.as_fd()).expect("write end handle");
drop(write);
for _ in 0..2000 {
let (r2, w2) = std::io::pipe().expect("churn pipe");
let h2 = pipe_handle_of(w2.as_fd()).expect("churn handle");
assert_ne!(
h2, handle,
"a new pipe took the marker's handle while the read end was still held — \
the sweep could match an unrelated process"
);
drop((r2, w2));
}
drop(read);
}
#[skuld::test]
fn the_sweep_finds_this_process_holding_the_marker() {
let (_r, w) = std::io::pipe().expect("pipe");
let handle = pipe_handle_of(w.as_fd()).expect("write end handle");
let me = std::process::id();
let found = holders(handle, &all_pids());
assert!(
found.iter().any(|h| h.pid == me),
"the sweep must find pid {me}, which holds the marker; found {found:?}"
);
assert!(
holds_marker(me, handle),
"the single-pid membership check must agree with the sweep"
);
}
#[skuld::test]
fn proc_pidlistfds_denial_returns_zero_with_eperm_not_negative() {
let n = unsafe {
*libc::__error() = 0;
libc::proc_pidinfo(1, libc::PROC_PIDLISTFDS, 0, std::ptr::null_mut(), 0)
};
let e = std::io::Error::last_os_error();
assert_eq!(
n, 0,
"an EPERM denial from PROC_PIDLISTFDS is measured to return 0 on this platform, not a \
negative value — a `< 0` failure gate would silently miss it"
);
assert_eq!(
e.raw_os_error(),
Some(libc::EPERM),
"pid 1 (launchd, root-owned) must be denied to an unprivileged caller with EPERM; got {e}"
);
}
#[skuld::test]
fn proc_pidfdinfo_on_a_non_pipe_fd_returns_zero_with_ebadf_not_a_type_specific_code() {
let me = std::process::id() as libc::c_int;
let mut info: PipeFdInfo = unsafe { std::mem::zeroed() };
let size = std::mem::size_of::<PipeFdInfo>() as libc::c_int;
let file = std::fs::File::open("/dev/null").expect("open /dev/null");
let n = unsafe {
*libc::__error() = 0;
libc::proc_pidfdinfo(
me,
file.as_raw_fd(),
PROC_PIDFDPIPEINFO,
&mut info as *mut _ as *mut libc::c_void,
size,
)
};
let e = std::io::Error::last_os_error();
assert_eq!(
n, 0,
"a non-pipe fd is measured to return 0, not a negative value; got {n}"
);
assert_eq!(
e.raw_os_error(),
Some(libc::EBADF),
"a non-pipe fd is measured to fail with EBADF specifically (not ENOENT/EINVAL); got {e}"
);
}
#[skuld::test]
fn holds_marker_query_reports_denied_not_not_held_for_an_unqueryable_pid() {
assert_eq!(
holds_marker_query(1, 0),
MarkerQuery::Denied,
"pid 1 must be unqueryable (EPERM) to an unprivileged caller; a Denied fd-list read \
must not be reported as NotHeld"
);
}
#[skuld::test]
fn a_dead_handle_finds_no_holders() {
assert!(
!holds_marker(std::process::id(), 0),
"handle 0 is never a valid pipe_handle and must not be reported as held"
);
}
#[skuld::test]
fn the_marker_fd_is_chosen_clear_of_reserved_child_fds_stdio_and_the_conventional_shell_range() {
use super::{safe_marker_fd, HIGH_FLOOR};
assert_eq!(
safe_marker_fd(7, &[]),
HIGH_FLOOR,
"even a low, uncontested candidate is raised clear of the conventional shell-\
redirection range (3-9), not merely clear of stdio"
);
assert_eq!(
safe_marker_fd(HIGH_FLOOR + 3, &[]),
HIGH_FLOOR + 3,
"a candidate already above the floor is kept"
);
assert!(
safe_marker_fd(7, &[HIGH_FLOOR]) > HIGH_FLOOR,
"a candidate colliding with a reserved fd must move up, even above the floor"
);
assert!(
safe_marker_fd(4, &[3, 4, HIGH_FLOOR + 5]) > HIGH_FLOOR + 5,
"the marker must clear the HIGHEST reserved fd, whether below or above the floor"
);
assert!(safe_marker_fd(1, &[]) >= 3, "the marker must never sit on a stdio slot");
assert!(
safe_marker_fd(0, &[3]) >= HIGH_FLOOR,
"the high floor applies regardless of how low the reserved set is"
);
}
#[skuld::test]
fn install_places_the_marker_above_every_reserved_child_fd() {
let _serialize = test_spawn_lock();
let reserved = [3, 4, 5, 6, 7, 8, 9, 10];
let mut cmd = std::process::Command::new("/usr/bin/true");
let prepared = install_on(&mut cmd, &reserved).expect("install");
assert!(
prepared.fd > 10,
"the marker landed on fd {}, which a user mapping would dup2 over",
prepared.fd
);
}
#[skuld::test]
fn a_child_with_a_colliding_fd_mapping_still_holds_the_marker() {
let _serialize = test_spawn_lock();
use crate::child::spawn::fd_map::{self, FdMapping};
let (_probe_r, probe_w) = std::io::pipe().expect("probe pipe");
let natural = super::safe_marker_fd(probe_w.as_fd().as_raw_fd(), &[]);
drop(probe_w);
let filler = std::fs::File::open("/dev/null").expect("open /dev/null");
let mut cmd = std::process::Command::new("/bin/sh");
cmd.arg("-c")
.arg("echo $$; read _ignored")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped());
let mut steps = crate::child::spawn::in_child::InChild::default();
let host = host_kernel();
let prepared = super::install(&mut steps, &[natural], &host).expect("install");
let handle = prepared.handle;
fd_map::install(
&mut steps,
vec![FdMapping {
parent_fd: filler.into(),
child_fd: natural,
}],
)
.expect("unique child fd");
steps.register(&mut cmd);
#[allow(
clippy::disallowed_methods,
reason = "the test holds spawn_lock for its whole body via `_serialize`"
)]
let mut child = cmd.spawn().expect("spawn sh");
drop(cmd);
let mut out = std::io::BufReader::new(child.stdout.take().expect("piped stdout"));
let mut line = String::new();
out.read_line(&mut line).expect("read pid line");
let kid: crate::identity::RawPid = line.trim().parse().expect("child pid");
assert!(
holds_marker(kid, handle),
"a user fd mapping on fd {natural} must not clobber the marker in the child"
);
let _keep_alive = prepared.read;
drop(child.stdin.take()); _ = child.wait();
}
#[skuld::test]
fn install_hands_the_marker_to_the_child_and_keeps_the_supervisor_out() {
let _serialize = test_spawn_lock();
let mut cmd = std::process::Command::new("/bin/sh");
cmd.arg("-c")
.arg("echo $$; read _ignored")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped());
let prepared = install_on(&mut cmd, &[]).expect("install");
let handle = prepared.handle;
#[allow(
clippy::disallowed_methods,
reason = "the test holds spawn_lock for its whole body via `_serialize`"
)]
let mut child = cmd.spawn().expect("spawn sh");
drop(cmd);
let mut out = std::io::BufReader::new(child.stdout.take().expect("piped stdout"));
let mut line = String::new();
out.read_line(&mut line).expect("read pid line");
let kid: crate::identity::RawPid = line.trim().parse().expect("child pid");
let found = holders(handle, &all_pids());
assert!(
found.iter().any(|h| h.pid == kid),
"the child must inherit the marker across exec; found {found:?}"
);
assert!(
!found.iter().any(|h| h.pid == std::process::id()),
"the supervisor must not hold the marker, or a sweep could signal it; found {found:?}"
);
let _keep_alive = prepared.read;
drop(child.stdin.take());
_ = child.wait();
}
#[skuld::test]
fn a_child_holding_a_non_cloexec_marker_produces_no_exec_warning() {
let _serialize = test_spawn_lock();
crate::log_capture::install();
let mut cmd = std::process::Command::new("/bin/sh");
cmd.arg("-c")
.arg("echo $$; read _ignored")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped());
let prepared = install_on(&mut cmd, &[]).expect("install");
let handle = prepared.handle;
#[allow(
clippy::disallowed_methods,
reason = "the test holds spawn_lock for its whole body via `_serialize`"
)]
let mut child = cmd.spawn().expect("spawn sh");
drop(cmd);
let mut out = std::io::BufReader::new(child.stdout.take().expect("piped stdout"));
let mut line = String::new();
out.read_line(&mut line).expect("read pid line");
let kid: crate::identity::RawPid = line.trim().parse().expect("child pid");
let mark = crate::log_capture::mark();
let found = holders(handle, &all_pids());
let theirs = found.iter().find(|h| h.pid == kid).expect("the child holds the marker");
assert!(
!theirs.clexec,
"fd_map::preserve clears FD_CLOEXEC in the child, so the marker survives its next exec"
);
assert!(
!crate::log_capture::contains_since(
mark,
&format!("fd marker {handle:#x}: holder pid {kid} will lose the marker")
),
"no exec warning is due for pid {kid}, whose own descriptor survives exec"
);
let _keep_alive = prepared.read;
drop(child.stdin.take());
_ = child.wait();
}
#[skuld::test]
fn a_cloexec_holder_is_reported_and_warned_about() {
crate::log_capture::install();
let (_r, w) = std::io::pipe().expect("pipe");
let handle = pipe_handle_of(w.as_fd()).expect("write end handle");
let me = std::process::id();
let mark = crate::log_capture::mark();
let found = holders(handle, &all_pids());
let theirs = found
.iter()
.find(|h| h.pid == me)
.expect("this process holds the marker");
assert!(theirs.clexec, "std::io::pipe() sets FD_CLOEXEC on both ends by default");
assert!(
crate::log_capture::contains_since(
mark,
&format!("fd marker {handle:#x}: holder pid {me} will lose the marker at its next exec")
),
"an imminent membership loss must leave a log line naming the marker and the pid"
);
}
#[skuld::test]
fn a_child_that_closes_the_marker_leaves_the_holder_set() {
let _serialize = test_spawn_lock();
let mut cmd = high_fd_shell();
cmd.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped());
let prepared = install_on(&mut cmd, &[]).expect("install");
let (handle, marker_fd) = (prepared.handle, prepared.fd);
cmd.arg("-c").arg(format!(
"echo $$; read _go; exec {marker_fd}>&-; echo closed; read _ignored"
));
#[allow(
clippy::disallowed_methods,
reason = "the test holds spawn_lock for its whole body via `_serialize`"
)]
let mut child = cmd.spawn().expect("spawn bash");
drop(cmd);
let mut stdin = child.stdin.take().expect("piped stdin");
let mut out = std::io::BufReader::new(child.stdout.take().expect("piped stdout"));
let mut line = String::new();
out.read_line(&mut line).expect("read pid line");
let kid: crate::identity::RawPid = line.trim().parse().expect("child pid");
assert!(
holds_marker(kid, handle),
"the child inherited the marker, and must still hold it while blocked before its own close"
);
use std::io::Write;
stdin.write_all(b"go\n").expect("release the child into its close");
line.clear();
out.read_line(&mut line).expect("read closed line");
assert_eq!(
line.trim(),
"closed",
"the child must confirm the close before the second check"
);
assert!(
!holds_marker(kid, handle),
"close(fd) leaves the containment set — the documented limit"
);
let _keep_alive = prepared.read;
drop(stdin);
_ = child.wait();
}
#[skuld::test]
fn each_install_failure_arm_fails_and_says_which_step_failed() {
use super::fault::{set_fault, Fault};
let _spawn_lock = test_spawn_lock();
for (fault, marker) in [
(Fault::Pipe, "fd marker: pipe() failed"),
(Fault::Place, "fd marker: could not place the marker descriptor"),
(Fault::Handle, "fd marker: the marker pipe has no readable handle"),
] {
let mut cmd = std::process::Command::new("/usr/bin/true");
set_fault(Some(fault));
let failed = install_on(&mut cmd, &[]).err();
assert!(
matches!(failed, Some(crate::error::Error::Containment { ref detail, .. }) if detail == marker),
"a failed {fault:?} step must fail with {marker:?}, got {failed:?}"
);
assert!(
super::fault::take_fault().is_none(),
"the seam must be consumed by install"
);
}
}
#[skuld::test]
fn the_kill_filter_excludes_this_process_and_pid_one() {
assert!(
!super::is_signalable(std::process::id()),
"the supervisor is never a sweep target"
);
assert!(!super::is_signalable(1), "pid 1 is never a sweep target");
assert!(!super::is_signalable(0), "pid 0 is never a sweep target");
assert!(
super::is_signalable(std::process::id() + 1),
"an ordinary pid is signalable"
);
}
#[skuld::test]
fn hard_kill_reaches_a_setsid_double_forked_orphan_the_ppid_walk_cannot() {
let _serialize = test_spawn_lock();
let mut cmd = std::process::Command::new("/bin/sh");
cmd.arg("-c")
.arg("exec 3<&0; cat <&3 3<&- & echo $!")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped());
unsafe {
use std::os::unix::process::CommandExt;
cmd.pre_exec(|| {
if libc::setsid() == -1 {
return Err(std::io::Error::last_os_error());
}
Ok(())
});
}
let prepared = install_on(&mut cmd, &[]).expect("install");
#[allow(
clippy::disallowed_methods,
reason = "the test holds spawn_lock for its whole body via `_serialize`"
)]
let mut child = cmd.spawn().expect("spawn sh");
drop(cmd);
let mut stdin = child.stdin.take().expect("piped stdin");
let mut out = std::io::BufReader::new(child.stdout.take().expect("piped stdout"));
let mut line = String::new();
out.read_line(&mut line).expect("read orphan pid");
let orphan: crate::identity::RawPid = line.trim().parse().expect("orphan pid");
child.wait().expect("reap sh");
let (_, parents, _) = crate::containment::enumerate::snapshot();
let ppid = parents.iter().find(|(p, _)| *p == orphan).map(|(_, pp)| *pp);
assert_eq!(ppid, Some(1), "precondition: the orphan must be reparented to launchd");
let orphan_id = crate::identity::ProcessId::of(orphan)
.found()
.expect("the orphan's identity");
let marker = super::Marker::new(prepared, inert_root(), None);
let mut killed = Vec::new();
marker
.hard_kill(
Some(&crate::test_support::stated_root::StatedRoot::unreaped()),
&mut killed,
)
.expect("hard_kill");
assert!(
killed.contains(&orphan_id),
"the orphan is among the members the sweep reached, for the wait: {killed:?}"
);
assert!(
!killed.contains(&inert_root()),
"the root is not: its owner waits for it: {killed:?}"
);
crate::test_child::write_to_possibly_dead_stdin(&mut stdin, b"x");
drop(stdin);
let mut rest = Vec::new();
std::io::Read::read_to_end(&mut out, &mut rest).expect("read to EOF on the orphan's stdout");
assert!(rest.is_empty(), "unexpected trailing output from the orphan: {rest:?}");
}
#[skuld::test]
fn hard_kill_never_reaches_a_pid_that_closed_the_marker_before_the_sweep() {
let _serialize = test_spawn_lock();
let mut cmd = high_fd_shell();
cmd.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped());
let prepared = install_on(&mut cmd, &[]).expect("install");
let (handle, marker_fd) = (prepared.handle, prepared.fd);
cmd.arg("-c").arg(format!(
r#"echo $$; exec {marker_fd}>&-; echo closed; while read x; do echo "$x"; done"#
));
#[allow(
clippy::disallowed_methods,
reason = "the test holds spawn_lock for its whole body via `_serialize`"
)]
let mut child = cmd.spawn().expect("spawn bash");
drop(cmd);
let mut out = std::io::BufReader::new(child.stdout.take().expect("piped stdout"));
let mut line = String::new();
out.read_line(&mut line).expect("read child pid");
let kid: crate::identity::RawPid = line.trim().parse().expect("child pid");
line.clear();
out.read_line(&mut line).expect("read closed confirmation");
assert_eq!(
line.trim(),
"closed",
"the child must confirm the close before the sweep runs"
);
assert!(
!holds_marker(kid, handle),
"precondition: the escapee no longer holds the marker"
);
let marker = super::Marker::new(prepared, inert_root(), None);
let mut killed = Vec::new();
marker
.hard_kill(
Some(&crate::test_support::stated_root::StatedRoot::unreaped()),
&mut killed,
)
.expect("hard_kill");
assert!(
killed.iter().all(|id| id.pid() != kid),
"a holder that closed the marker is not among the members the sweep reached: {killed:?}"
);
let mut stdin = child.stdin.take().expect("piped stdin");
std::io::Write::write_all(&mut stdin, b"still-here\n").expect("write probe line");
line.clear();
out.read_line(&mut line).expect("read probe echo");
assert_eq!(
line.trim(),
"still-here",
"the escapee closed the marker before hard_kill ran and must survive it"
);
drop(stdin);
_ = child.wait();
}
#[skuld::test]
fn pid_is_live_group_member_confirms_membership_and_rejects_mismatch_or_death() {
let _serialize = test_spawn_lock();
#[allow(
clippy::disallowed_methods,
reason = "the test holds spawn_lock for its whole body via `_serialize`"
)]
let mut child = member_command(0).spawn().expect("spawn member"); await_member_ready(&mut child);
let pid = child.id() as crate::identity::RawPid;
let pgid = child.id() as i32;
assert!(
super::pid_is_live_group_member(pid, pgid),
"a live child must be confirmed a member of its own pgid"
);
assert!(
!super::pid_is_live_group_member(pid, pgid.wrapping_add(1)),
"a mismatched pgid must not be confirmed, even for a live pid"
);
child.kill().expect("kill");
child.wait().expect("reap");
assert!(
!super::pid_is_live_group_member(pid, pgid),
"a reaped pid must not be confirmed a member of anything — getpgid must fail ESRCH"
);
}
fn high_fd_shell() -> std::process::Command {
std::process::Command::new("/bin/bash")
}
#[skuld::test]
fn sweep_pass_refires_the_group_signal_on_a_later_pass_that_confirms_a_new_live_member() {
let _serialize = test_spawn_lock();
crate::log_capture::install();
let mut p_cmd = member_command(0); let scratch = install_on(&mut p_cmd, &[]).expect("install scratch marker on P");
#[allow(
clippy::disallowed_methods,
reason = "the test holds spawn_lock for its whole body via `_serialize`"
)]
let mut p_child = p_cmd.spawn().expect("spawn P");
drop(p_cmd);
await_member_ready(&mut p_child); let pgid = p_child.id() as i32;
let pass1_marker = super::Marker::new(scratch, inert_root(), Some(pgid));
let mut reached = Vec::new();
let mut state = super::SweepState::new(&mut reached);
pass1_marker.sweep_pass(
nix::sys::signal::Signal::SIGKILL,
&mut state,
true,
super::Scope::Full(Some(&crate::test_support::stated_root::StatedRoot::unreaped())),
);
drop(pass1_marker);
let mut t_cmd = member_command(pgid);
let prepared = install_on(&mut t_cmd, &[]).expect("install marker on T");
#[allow(
clippy::disallowed_methods,
reason = "the test holds spawn_lock for its whole body via `_serialize`"
)]
let mut t_child = t_cmd.spawn().expect("spawn T");
drop(t_cmd);
await_member_ready(&mut t_child);
let mut q_cmd = member_command(pgid);
#[allow(
clippy::disallowed_methods,
reason = "the test holds spawn_lock for its whole body via `_serialize`"
)]
let mut q_child = q_cmd.spawn().expect("spawn Q");
await_member_ready(&mut q_child);
let handle = prepared.handle;
let marker = super::Marker::new(prepared, inert_root(), Some(pgid));
let mark = crate::log_capture::mark();
log::debug!(
"fd marker {:#x}: skipping this pass's group signal — no live member confirmed this \
pass's pgid, so it may have been recycled",
0u64
);
marker.sweep_pass(
nix::sys::signal::Signal::SIGKILL,
&mut state,
false,
super::Scope::Full(Some(&crate::test_support::stated_root::StatedRoot::unreaped())),
);
assert!(
!crate::log_capture::contains_since(
mark,
&format!("fd marker {handle:#x}: skipping this pass's group signal")
),
"pass 2 must not skip the group signal: a live, getpgid-confirmed member (T) was just \
found in this pass's own holder scan"
);
use std::os::unix::process::ExitStatusExt;
let status = q_child.wait().expect("reap Q");
assert_eq!(
status.signal(),
Some(libc::SIGKILL),
"Q must have died from the pass-2 group signal (killpg on pgid), the only channel that \
reaches it; got {status:?}"
);
_ = t_child.kill();
_ = t_child.wait();
}
#[skuld::test]
fn kill_holder_leaves_a_denied_pid_unsignalled_and_reports_incomplete() {
let _serialize = test_spawn_lock();
let mut cmd = std::process::Command::new("/usr/bin/true");
let prepared = install_on(&mut cmd, &[]).expect("install");
let marker = super::Marker::new(prepared, inert_root(), None);
let id = match crate::identity::ProcessId::of(1) {
crate::identity::Resolved::Found(id) => id,
other => panic!(
"pid 1 must resolve via the documented sysctl fallback for this test's oracle to \
hold; got {other:?}"
),
};
crate::log_capture::install();
let mark = crate::log_capture::mark();
let outcome = marker.kill_holder(id, nix::sys::signal::Signal::SIGKILL);
assert!(
matches!(
outcome,
Some(crate::containment::treewalk::KillOutcome::NotAttempted(_))
),
"a Denied re-check on a supposedly-known holder must be a kill not attempted (which the sweep \
folds into `incomplete`), not silently succeed: {outcome:?}"
);
let warns = crate::log_capture::records_since_on_current_thread(mark, "pid 1 (a confirmed holder");
assert!(
matches!(&warns[..], [(log::Level::Warn, text)]
if text.starts_with("fd marker ") && text.contains("not signalled, left running")),
"{warns:?}"
);
}
#[skuld::test]
fn a_refired_group_signal_that_fails_again_keeps_both_failures() {
let _serialize = test_spawn_lock();
let mut p_cmd = member_command(0); let prepared = install_on(&mut p_cmd, &[]).expect("install marker on P");
#[allow(
clippy::disallowed_methods,
reason = "the test holds spawn_lock for its whole body via `_serialize`"
)]
let mut p_child = p_cmd.spawn().expect("spawn P");
drop(p_cmd);
await_member_ready(&mut p_child);
let pgid = p_child.id() as i32;
let marker = super::Marker::new(prepared, inert_root(), Some(pgid));
let mut reached = Vec::new();
let mut state = super::SweepState::new(&mut reached);
state.group_result = Err(crate::error::Error::Io(std::io::Error::from_raw_os_error(libc::EPERM)));
let sends = crate::containment::unix::fault::record_kill_group();
sends.fail_with_unassessable();
marker.sweep_pass(
nix::sys::signal::Signal::SIGKILL,
&mut state,
false,
super::Scope::Full(Some(&crate::test_support::stated_root::StatedRoot::unreaped())),
);
assert_eq!(
sends.killed(),
[pgid],
"the later pass must re-fire the group signal, or the row proves nothing"
);
let said = crate::error::said(state.group_result.as_ref().expect_err("both passes failed"));
assert!(
said.contains("os error 1") && said.contains("forced by a test"),
"the group result must keep both failures: {said}"
);
_ = p_child.kill(); _ = p_child.wait();
}
#[skuld::test]
fn finish_sweep_names_only_the_causes_that_apply() {
const INCOMPLETE: &str = "could not be assessed or signalled";
const FORKING: &str = "still forking";
let finish = |incomplete, still_forking| super::Marker::finish_sweep(0x1, Ok(()), incomplete, still_forking);
let message = |result: Result<(), crate::error::Error>| match result {
Err(crate::error::Error::Unassessable { detail, .. }) => detail,
other => panic!("expected an Unassessable error; got {other:?}"),
};
let incomplete_only = message(finish(true, false));
assert!(incomplete_only.contains(INCOMPLETE) && !incomplete_only.contains(FORKING));
let forking_only = message(finish(false, true));
assert!(forking_only.contains(FORKING) && !forking_only.contains(INCOMPLETE));
let both = message(finish(true, true));
assert!(both.contains(INCOMPLETE) && both.contains(FORKING));
assert!(finish(false, false).is_ok(), "a sweep with neither cause is Ok");
}
#[skuld::test]
fn a_sweep_that_failed_twice_leads_with_the_groups_failure() {
use crate::error::Error;
let group = Error::Containment {
detail: "the group could not be signalled".to_owned(),
source: Some(Error::io_cause(std::io::Error::from_raw_os_error(libc::EPERM))),
};
let swept = super::Marker::finish_sweep(0x1, Err(group), true, false).expect_err("both failed");
assert!(
matches!(&swept, Error::Containment { detail, .. } if detail.contains("group")),
"{swept:?}"
);
assert_eq!(crate::error::first_os_code(&swept), Some(libc::EPERM));
let Error::Containment {
source: Some(source), ..
} = &swept
else {
panic!("{swept:?}");
};
assert!(
matches!(&**source, Error::Several(list) if list.iter().len() == 2),
"the incomplete summary is the group's peer: {source:?}"
);
}
#[skuld::test]
fn a_pass_counts_only_the_identities_no_earlier_pass_had_seen() {
let _serialize = test_spawn_lock();
let mut cmd = std::process::Command::new("/bin/sh");
cmd.arg("-c")
.arg("exec 3<&0; cat <&3 3<&- & echo $!; wait")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped());
let prepared = install_on(&mut cmd, &[]).expect("install");
#[allow(
clippy::disallowed_methods,
reason = "the test holds spawn_lock for its whole body via `_serialize`"
)]
let mut sh = cmd.spawn().expect("spawn sh");
drop(cmd);
let mut out = std::io::BufReader::new(sh.stdout.take().expect("piped stdout"));
let mut line = String::new();
out.read_line(&mut line).expect("read cat's pid");
let cat = crate::identity::ProcessId::of(line.trim().parse().expect("cat's pid"))
.found()
.expect("cat resolves");
let sh_id = crate::identity::ProcessId::of(sh.id()).found().expect("sh resolves");
let marker = super::Marker::new(prepared, inert_root(), None);
let mut reached = Vec::new();
let mut state = super::SweepState::new(&mut reached);
state.seen.insert(sh_id);
let found = marker.sweep_pass(
nix::sys::signal::Signal::SIGKILL,
&mut state,
false,
super::Scope::HoldersOnly { except: None },
);
assert_eq!(found, 1, "cat is the only identity no earlier pass had seen");
assert!(state.seen.contains(&cat));
drop(state);
assert_eq!(reached, [cat], "the pass signals cat alone");
_ = sh.kill();
_ = sh.wait();
}
#[skuld::test]
fn hard_kill_reports_err_on_a_genuinely_blind_pass() {
let _serialize = test_spawn_lock();
let mut cmd = std::process::Command::new("/usr/bin/true");
let prepared = install_on(&mut cmd, &[]).expect("install");
drop(cmd);
let marker = super::Marker::new(prepared, inert_root(), None);
crate::containment::enumerate::force_blind_snapshots(1);
let result = marker.hard_kill(
Some(&crate::test_support::stated_root::StatedRoot::unreaped()),
&mut Vec::new(),
);
assert!(
result.is_err(),
"a sweep whose only pass was blind must report Err, not silently converge as Ok(())"
);
}
#[skuld::test]
fn a_pass_whose_root_cannot_be_read_skips_the_walk_and_is_incomplete() {
let _serialize = test_spawn_lock();
crate::log_capture::install();
let mut cmd = std::process::Command::new("/usr/bin/true");
let prepared = install_on(&mut cmd, &[]).expect("install");
drop(cmd);
let root = inert_root();
let marker = super::Marker::new(refusing_reads_of(prepared, root.pid()), root, None);
let mut reached = Vec::new();
let mut state = super::SweepState::new(&mut reached);
state.seen.insert(root);
let walks = crate::containment::treewalk::fault::record_walks();
let mark = crate::log_capture::mark();
let found = marker.sweep_pass(
nix::sys::signal::Signal::SIGKILL,
&mut state,
true,
super::Scope::Full(Some(&crate::test_support::stated_root::StatedRoot::unreaped())),
);
assert!(state.incomplete, "an unreadable root is not a complete walk");
assert_eq!(found, 0, "nothing was found or signalled");
assert_eq!(
walks.walked(),
Vec::<u32>::new(),
"no walk began from a root that could not be read"
);
let warned = crate::log_capture::records_since_on_current_thread(
mark,
&format!(
"fd marker {:#x}: the root's descendants could not be walked",
marker.handle
),
);
assert_eq!(warned.len(), 1, "{warned:?}");
}
#[skuld::test]
fn a_pass_with_a_child_that_cannot_be_read_does_not_signal_it_and_is_incomplete() {
use std::io::Read as _;
use std::os::unix::process::ExitStatusExt as _;
let _serialize = test_spawn_lock();
let mut cmd = std::process::Command::new("/usr/bin/true");
let prepared = install_on(&mut cmd, &[]).expect("install");
drop(cmd);
let mut root_cmd = std::process::Command::new("/bin/sh");
root_cmd
.arg("-c")
.arg("exec 3<&0; sh -c 'read _ignored; echo released' <&3 3<&- & echo $$; wait")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped());
#[allow(
clippy::disallowed_methods,
reason = "the test holds spawn_lock for its whole body via `_serialize`"
)]
let mut root_child = root_cmd.spawn().expect("spawn the root");
crate::test_child::await_member_ready(&mut root_child);
let root = crate::identity::ProcessId::of(root_child.id())
.found()
.expect("the live root resolves");
let children = root
.children(crate::Recursive::No)
.expect("the root's children are readable");
let [child] = children[..] else {
panic!("the root has exactly one child, got {children:?}");
};
let marker = super::Marker::new(refusing_reads_of(prepared, child.pid()), root, None);
let mut reached = Vec::new();
let mut state = super::SweepState::new(&mut reached);
state.seen.insert(root);
let found = marker.sweep_pass(
nix::sys::signal::Signal::SIGKILL,
&mut state,
true,
super::Scope::Full(Some(&crate::test_support::stated_root::StatedRoot::unreaped())),
);
assert!(
state.incomplete,
"a child the walk could not read is not a complete walk"
);
assert_eq!(found, 0, "nothing was found or signalled");
drop(root_child.stdin.take());
let mut printed = String::new();
root_child
.stdout
.take()
.expect("piped stdout")
.read_to_string(&mut printed)
.expect("read to EOF");
assert_eq!(
printed, "released\n",
"the unreadable child must not have been signalled"
);
let status = root_child.wait().expect("reap the root");
assert_eq!((status.signal(), status.code()), (None, Some(0)));
}
fn held_child() -> (std::process::Child, super::PreparedMarker) {
let mut cmd = member_command(0);
let prepared = install_on(&mut cmd, &[]).expect("install the marker on the child");
#[allow(
clippy::disallowed_methods,
reason = "the caller holds spawn_lock for its whole body"
)]
let mut child = cmd.spawn().expect("spawn the child");
drop(cmd);
await_member_ready(&mut child);
(child, prepared)
}
#[skuld::test]
fn a_holder_its_kernel_cannot_read_is_not_signalled_and_the_sweep_is_incomplete() {
use crate::identity::{FakeKernel, HostKernel, ReadErr};
let _serialize = test_spawn_lock();
let (holder, prepared) = held_child();
let pid = holder.id();
let kernel = std::sync::Arc::new(
FakeKernel::over(&HostKernel)
.on_bsd_info(pid, Err(ReadErr::Refused(libc::EPERM)))
.on_kinfo_refused(pid, libc::EPERM),
);
let root = inert_root();
let marker = super::Marker::new(reading_through(prepared, std::sync::Arc::clone(&kernel)), root, None);
let mut reached = Vec::new();
let mut state = super::SweepState::new(&mut reached);
state.seen.insert(root);
let found = marker.sweep_pass(
nix::sys::signal::Signal::SIGKILL,
&mut state,
true,
super::Scope::Full(Some(&crate::test_support::stated_root::StatedRoot::unreaped())),
);
assert!(
kernel.all_rows_taken(),
"the holder was read through the marker's kernel"
);
assert!(state.incomplete, "a holder that cannot be read is not a complete sweep");
assert_eq!(found, 0, "nothing was found or signalled");
crate::child::spawn::identity_macos_tests::end_unsignalled_and_reap(pid);
}
#[skuld::test]
fn a_sweeps_kill_of_a_walked_member_reads_its_identity_through_the_markers_kernel() {
use crate::identity::{FakeKernel, HostKernel};
let _serialize = test_spawn_lock();
let (member, prepared) = held_child();
let pid = member.id();
let root = crate::identity::ProcessId::of(pid)
.found()
.expect("the live member resolves");
let kernel = std::sync::Arc::new(
FakeKernel::over(&HostKernel).on_unique_info(pid, crate::child::spawn::identity_macos_tests::REFUSED_KILL_READ),
);
let marker = super::Marker::new(reading_through(prepared, std::sync::Arc::clone(&kernel)), root, None);
let mut reached = Vec::new();
let mut state = super::SweepState::new(&mut reached);
marker.sweep_pass(
nix::sys::signal::Signal::SIGKILL,
&mut state,
true,
super::Scope::Full(Some(&crate::test_support::stated_root::StatedRoot::unreaped())),
);
assert!(
kernel.all_rows_taken(),
"the kill read the member's identity through the marker's kernel"
);
assert!(
state.incomplete,
"a member whose kill was refused is not a complete sweep"
);
crate::child::spawn::identity_macos_tests::end_unsignalled_and_reap(pid);
}
#[skuld::test]
fn a_holders_kill_reads_its_identity_through_the_markers_kernel() {
use crate::identity::{FakeKernel, HostKernel};
let _serialize = test_spawn_lock();
let (holder, prepared) = held_child();
let pid = holder.id();
let id = crate::identity::ProcessId::of(pid)
.found()
.expect("the live holder resolves");
let kernel = std::sync::Arc::new(
FakeKernel::over(&HostKernel).on_unique_info(pid, crate::child::spawn::identity_macos_tests::REFUSED_KILL_READ),
);
let marker = super::Marker::new(
reading_through(prepared, std::sync::Arc::clone(&kernel)),
inert_root(),
None,
);
let outcome = marker.kill_holder(id, nix::sys::signal::Signal::SIGKILL);
assert!(
matches!(
outcome,
Some(crate::containment::treewalk::KillOutcome::NotAttempted(_))
),
"{outcome:?}"
);
assert!(
kernel.all_rows_taken(),
"the kill read the holder's identity through the marker's kernel"
);
crate::child::spawn::identity_macos_tests::end_unsignalled_and_reap(pid);
}
#[skuld::test]
fn two_group_errors_fold_into_one_variant_with_both_below_it() {
use crate::error::Error;
let ordinary = |detail: &str| Error::Containment {
detail: detail.to_owned(),
source: Some(Error::io_cause(std::io::Error::from_raw_os_error(libc::EPERM))),
};
let mechanism = || Error::Io(std::io::Error::from_raw_os_error(libc::EIO));
let below = |error: &Error| {
let (Error::Containment { source, detail } | Error::Unassessable { source, detail }) = error else {
panic!("{error:?}");
};
let Some(source) = source else {
panic!("no cause: {error:?}");
};
let Error::Several(list) = &**source else {
panic!("expected Several, got {source:?}");
};
(
detail.clone(),
list.iter()
.map(|m| crate::error::first_os_code(&**m))
.collect::<Vec<_>>(),
)
};
let both_ordinary = super::combine_group_errors(ordinary("first words"), ordinary("latest words"));
assert!(matches!(both_ordinary, Error::Containment { .. }), "{both_ordinary:?}");
let (detail, codes) = below(&both_ordinary);
assert_eq!(codes, [Some(libc::EPERM), Some(libc::EPERM)]);
assert!(!detail.contains("words"), "{detail}");
let one_containment = super::combine_group_errors(ordinary("first words"), mechanism());
assert!(
matches!(one_containment, Error::Containment { .. }),
"{one_containment:?}"
);
assert_eq!(below(&one_containment).1, [Some(libc::EPERM), Some(libc::EIO)]);
let none_containment = super::combine_group_errors(
Error::Unassessable {
detail: "unknown".to_owned(),
source: None,
},
Error::Unassessable {
detail: "unknown too".to_owned(),
source: Some(Error::io_cause(std::io::Error::from_raw_os_error(libc::EIO))),
},
);
assert!(
matches!(none_containment, Error::Unassessable { .. }),
"{none_containment:?}"
);
assert_eq!(below(&none_containment).1, [None, Some(libc::EIO)]);
}
fn marker_without_holders(
root: crate::identity::ProcessId,
pgid: Option<i32>,
kernel: crate::identity::SpawnKernel,
) -> super::Marker {
let mut cmd = std::process::Command::new("true");
let prepared = install_on(&mut cmd, &[]).expect("install a scratch marker");
drop(cmd);
super::Marker::new(super::PreparedMarker { kernel, ..prepared }, root, pgid)
}
fn host_kernel() -> crate::identity::SpawnKernel {
crate::identity::spawn_kernel(crate::identity::HostKernel)
}
#[skuld::test]
fn a_terminate_whose_group_cannot_be_signalled_says_nothing_was_sent() {
let _serialize = test_spawn_lock();
let marker = marker_without_holders(inert_root(), Some(0), host_kernel());
let root = crate::test_support::stated_root::StatedRoot::unreaped();
match marker.terminate_tree(Some(&root)) {
crate::containment::TerminateOutcome::NotSent(crate::error::Error::Unassessable { source: None, .. }) => {}
other => panic!("expected NotSent(Unassessable), got {other:?}"),
}
}
#[skuld::test]
fn a_terminate_that_sent_nothing_keeps_the_members_it_could_not_reach() {
let _serialize = test_spawn_lock();
let root_id = inert_root();
let marker = marker_without_holders(
root_id,
Some(0),
crate::identity::spawn_kernel(crate::identity::unreadable(root_id.pid())),
);
let root = crate::test_support::stated_root::StatedRoot::unreaped();
match marker.terminate_tree(Some(&root)) {
crate::containment::TerminateOutcome::NotSent(crate::error::Error::Unassessable {
detail,
source: Some(source),
}) => {
assert!(
detail.contains("not a valid group id"),
"the group's failure first: {detail}"
);
assert!(
matches!(&*source, crate::error::Error::Unassessable { detail, .. } if detail.contains("incomplete")),
"{source:?}"
);
}
other => panic!("expected NotSent(the group's refusal over the incomplete walk), got {other:?}"),
}
}
#[skuld::test]
fn a_group_send_that_fails_while_a_holder_is_signalled_is_sent() {
use std::os::unix::process::ExitStatusExt;
let _serialize = test_spawn_lock();
let mut holder_cmd = member_command(0);
let prepared = install_on(&mut holder_cmd, &[]).expect("install the marker on the holder");
#[allow(
clippy::disallowed_methods,
reason = "the test holds spawn_lock for its whole body via `_serialize`"
)]
let mut holder = holder_cmd.spawn().expect("spawn the holder");
drop(holder_cmd);
await_member_ready(&mut holder);
let marker = super::Marker::new(prepared, inert_root(), Some(0));
let root = crate::test_support::stated_root::StatedRoot::unreaped();
let outcome = marker.terminate_tree(Some(&root));
let status = holder.wait().expect("reap the holder");
assert_eq!(status.signal(), Some(libc::SIGTERM), "the holder was sent the SIGTERM");
match outcome {
crate::containment::TerminateOutcome::Sent {
result: Err(crate::error::Error::Unassessable { source: None, .. }),
..
} => {}
other => panic!("expected Sent with the group's refusal, got {other:?}"),
}
}
#[skuld::test]
fn a_skipped_kill_names_the_walk_and_the_group_only_when_there_is_one() {
let _serialize = test_spawn_lock();
let reaped = crate::test_support::stated_root::StatedRoot::with_state(4242, || crate::signal::RootState::Reaped);
let skipped = |marker| {
let kill = crate::containment::Tree::contained(crate::containment::Mechanism::Marker(marker))
.kill(Some(&reaped))
.outcome();
let skipped = kill
.skipped()
.expect("the reaped root's kill by its number is skipped")
.to_owned();
kill.into_result().expect("the holders-only sweep");
skipped
};
let root = crate::identity::ProcessId::from_parts_for_test(4242, crate::identity::Key::for_test(1));
let rooted = skipped(marker_without_holders(root, None, host_kernel()));
assert!(
rooted.contains("root pid 4242") && !rooted.contains("pgid"),
"{rooted:?}"
);
let grouped = skipped(marker_without_holders(root, Some(4243), host_kernel()));
assert!(
grouped.contains("pgid 4243") && grouped.contains("root pid 4242"),
"{grouped:?}"
);
}
#[skuld::test]
fn a_sweep_warns_once_of_a_member_that_refuses_the_kill(#[fixture(setuid)] _group: &Group) {
use std::io::Read as _;
crate::log_capture::install();
let mut cmd = crate::test_privilege::setuid_blocker_command();
cmd.contain();
cmd.stdin(crate::Stdio::pipe()).expect("stdin pipe");
cmd.stdout(crate::Stdio::pipe()).expect("stdout pipe");
cmd.stderr(crate::Stdio::null()).expect("stderr null");
let mut child = cmd.spawn().expect("spawn the setuid helper");
let stdin = child.stdin().expect("piped stdin");
let mut ready = [0u8; 1];
child
.stdout()
.expect("piped stdout")
.read_exact(&mut ready)
.expect("the helper reports ready");
assert_eq!(ready, *b"+");
let mark = crate::log_capture::mark();
child.kill_tree().expect_err("the root refuses the kill");
let warned = crate::log_capture::warns_since(mark, "was sent no SIGKILL");
assert_eq!(warned.len(), 1, "{warned:?}");
drop(stdin);
assert!(child.wait().expect("the helper exits on EOF").success());
}