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};
fn all_pids() -> Vec<crate::identity::RawPid> {
crate::containment::enumerate::snapshot().0
}
fn test_spawn_lock() -> std::sync::MutexGuard<'static, ()> {
crate::child::spawn::spawn_lock()
}
#[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");
}
#[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()
);
}
#[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"
);
}
#[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);
}
#[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"
);
}
#[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}"
);
}
#[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}"
);
}
#[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"
);
}
#[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"
);
}
#[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"
);
}
#[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 = super::install(&mut cmd, &reserved).expect("install");
assert!(
prepared.fd > 10,
"the marker landed on fd {}, which a user mapping would dup2 over",
prepared.fd
);
}
#[test]
fn a_child_with_a_colliding_fd_mapping_still_holds_the_marker() {
let _serialize = test_spawn_lock();
use command_fds::{CommandFdExt, 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 prepared = super::install(&mut cmd, &[natural]).expect("install");
let handle = prepared.handle;
cmd.fd_mappings(vec![FdMapping {
parent_fd: filler.into(),
child_fd: natural,
}])
.expect("unique child fd");
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()); let _ = child.wait();
}
#[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 = super::install(&mut cmd, &[]).expect("install");
let handle = prepared.handle;
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());
let _ = child.wait();
}
#[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 = super::install(&mut cmd, &[]).expect("install");
let handle = prepared.handle;
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,
"preserved_fds 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());
let _ = child.wait();
}
#[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"
);
}
#[test]
fn a_child_that_closes_the_marker_leaves_the_holder_set() {
let _serialize = test_spawn_lock();
let mut cmd = std::process::Command::new("/bin/sh");
cmd.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped());
let prepared = super::install(&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"
));
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 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);
let _ = child.wait();
}
#[test]
fn each_install_failure_arm_falls_back_and_says_which_step_failed() {
use super::fault::{set_fault, Fault};
let _serialize = super::fault::lock_for_log_assertion();
crate::log_capture::install();
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 mark = crate::log_capture::mark();
assert!(
super::install(&mut cmd, &[]).is_none(),
"a failed {fault:?} step must yield no marker"
);
assert!(
crate::log_capture::contains_since(mark, marker),
"the {fault:?} failure must log {marker:?}"
);
assert!(
super::fault::take_fault().is_none(),
"the seam must be consumed by install"
);
}
}
#[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"
);
}
#[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("sleep 600 & echo $!")
.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 = super::install(&mut cmd, &[]).expect("install");
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 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 marker = super::Marker::new(prepared, None, None, false);
marker.hard_kill().expect("hard_kill");
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:?}");
}
#[test]
fn hard_kill_never_reaches_a_pid_that_closed_the_marker_before_the_sweep() {
let _serialize = test_spawn_lock();
let mut cmd = std::process::Command::new("/bin/sh");
cmd.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped());
let prepared = super::install(&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"#
));
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 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, None, None, false);
marker.hard_kill().expect("hard_kill");
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);
let _ = child.wait();
}
#[test]
fn hard_kill_reports_incomplete_for_a_denied_root_even_with_nothing_else_to_signal() {
let (read, write) = std::io::pipe().expect("pipe");
let handle = super::pipe_handle_of(write.as_fd()).expect("handle");
let read_handle = super::pipe_handle_of(read.as_fd()).expect("read handle");
let prepared = super::PreparedMarker {
read: std::os::fd::OwnedFd::from(read),
handle,
read_handle,
fd: write.as_fd().as_raw_fd(),
};
drop(write);
let marker = super::Marker::new(prepared, None, None, true);
let err = marker.hard_kill().expect_err("a denied root must report incomplete");
assert!(
matches!(err, crate::error::Error::Unassessable { source: None, .. }),
"unexpected error shape: {err:?}"
);
}
#[test]
fn pid_is_live_group_member_confirms_membership_and_rejects_mismatch_or_death() {
use std::os::unix::process::CommandExt;
let _serialize = test_spawn_lock();
let mut cmd = std::process::Command::new("/bin/sleep");
cmd.arg("600").process_group(0); let mut child = cmd.spawn().expect("spawn sleep");
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 member_command(pgid: i32) -> std::process::Command {
use std::os::unix::process::CommandExt;
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())
.process_group(pgid);
cmd
}
fn await_member_ready(child: &mut std::process::Child) {
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 the member's announcement");
let announced: crate::identity::RawPid = line.trim().parse().expect("the announcement carries a pid");
assert_eq!(
announced,
child.id(),
"the announcement must come from the member itself"
);
child.stdout = Some(out.into_inner());
}
#[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 = super::install(&mut p_cmd, &[]).expect("install scratch marker on P");
#[allow(clippy::zombie_processes)]
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, None, Some(pgid), false);
let mut seen: std::collections::HashSet<crate::identity::ProcessId> = std::collections::HashSet::new();
let mut group_result: Result<(), crate::error::Error> = Ok(());
let mut incomplete = false;
pass1_marker.sweep_pass(
nix::sys::signal::Signal::SIGKILL,
&mut seen,
&mut group_result,
&mut incomplete,
true,
);
drop(pass1_marker);
let mut t_cmd = member_command(pgid);
let prepared = super::install(&mut t_cmd, &[]).expect("install marker on T");
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);
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, None, Some(pgid), false);
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 seen,
&mut group_result,
&mut incomplete,
false,
);
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:?}"
);
let _ = t_child.kill();
let _ = t_child.wait();
}
#[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 = super::install(&mut cmd, &[]).expect("install");
let marker = super::Marker::new(prepared, None, None, false);
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:?}"
),
};
assert!(
marker.kill_holder(id, nix::sys::signal::Signal::SIGKILL),
"a Denied re-check on a supposedly-known holder must report incomplete (true), not \
silently succeed"
);
}
#[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 = super::install(&mut cmd, &[]).expect("install");
let marker = super::Marker::new(prepared, None, None, false);
crate::containment::enumerate::force_blind_snapshot_for_next_call(true);
let result = marker.hard_kill();
assert!(
result.is_err(),
"a sweep whose only pass was blind must report Err, not silently converge as Ok(())"
);
}