use std::cell::{Cell, RefCell};
use std::rc::Rc;
use crate::child::spawn::fault::{self, SpawnPoint};
use crate::child::spawn::unique_report;
use crate::error::Error;
use crate::identity::{ppid_fault, uniq_fault, uniq_info, ReadPurpose, UniqInfo, UniqRead, LAUNCHD};
use crate::wait::exit_only::seams::force_peek_once;
pub(crate) fn reap_by_pid(pid: u32) {
let mut status = 0;
let reaped = unsafe { libc::waitpid(pid as libc::pid_t, &mut status, 0) };
assert_eq!(reaped, pid as libc::pid_t, "{}", std::io::Error::last_os_error());
}
pub(crate) fn has_not_exited(pid: u32) -> bool {
let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
let rc = unsafe {
libc::waitid(
libc::P_PID,
pid as libc::id_t,
&mut info,
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
)
};
assert_eq!(rc, 0, "waitid: {}", std::io::Error::last_os_error());
info.si_pid == 0
}
pub(crate) fn end_unsignalled_and_reap(pid: u32) {
assert_eq!(unsafe { libc::kill(pid as libc::pid_t, libc::SIGUSR1) }, 0);
let mut status = 0;
let reaped = unsafe { libc::waitpid(pid as libc::pid_t, &mut status, 0) };
assert_eq!(reaped, pid as libc::pid_t, "{}", std::io::Error::last_os_error());
assert!(
libc::WIFSIGNALED(status) && libc::WTERMSIG(status) == libc::SIGUSR1,
"something other than the test signalled the child before it did: status {status:#x}"
);
}
pub(crate) const RAN_ARGV: [&str; 2] = ["/bin/echo", "ran"];
pub(crate) fn ran_marker() -> (crate::stdio::Stdio, std::io::PipeReader) {
let (reader, writer) = std::io::pipe().expect("pipe");
let stdout = crate::stdio::Stdio::from_file(std::fs::File::from(std::os::fd::OwnedFd::from(writer)));
(stdout, reader)
}
pub(crate) fn assert_program_did_not_run(cmd: impl Sized, mut reader: std::io::PipeReader) {
use std::io::Read;
drop(cmd);
let mut out = String::new();
reader.read_to_string(&mut out).expect("read the marker pipe");
assert!(out.is_empty(), "the program ran: {out:?}");
}
pub(crate) fn vanished(err: &Error) -> bool {
matches!(err, Error::Io(e) if e.to_string().contains("reaped by another party"))
}
pub(crate) fn other_unique_id(pid: u32) -> UniqRead {
let UniqRead::Found(info) = uniq_info(pid, ReadPurpose::Kill) else {
panic!("the child's unique id must be readable")
};
UniqRead::Found(UniqInfo {
unique_id: info.unique_id ^ 1,
})
}
fn sync_blocker() -> (crate::Command, std::io::PipeWriter) {
let (stdin, writer) = crate::test_child::held_writer_stdin();
let mut cmd = crate::Command::new();
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
cmd.stdin(stdin).expect("set stdin");
(cmd, writer)
}
#[skuld::test]
fn macos_sync_spawn_identity_after_a_real_reap_is_gone() {
let (mut cmd, writer) = sync_blocker();
let _hook = fault::set_at(SpawnPoint::AfterIdentityRead, move || {
drop(writer);
reap_by_pid(fault::spawn_pid());
});
let (err, fate) = match cmd.spawn() {
Ok(child) => panic!("a child reaped before its re-read was adopted: {:?}", child.id()),
Err(e) => crate::child::spawn::failure::expect_may_have_started_with(e),
};
assert!(vanished(&err), "a reaped child is Gone, not Unassessable: {err:?}");
assert_eq!(fate, crate::error::ChildFate::Gone);
}
#[skuld::test]
fn macos_sync_spawn_identity_with_a_different_unique_id_is_gone() {
let (mut cmd, _writer) = sync_blocker();
let pid = Rc::new(Cell::new(0));
let armed: Rc<RefCell<Option<uniq_fault::Forced>>> = Rc::default();
let _hook = fault::set_at(SpawnPoint::AfterIdentityRead, {
let (pid, armed) = (Rc::clone(&pid), Rc::clone(&armed));
move || {
pid.set(fault::spawn_pid());
let other = other_unique_id(pid.get());
*armed.borrow_mut() = Some(uniq_fault::force_uniq_read_once(ReadPurpose::Running, other));
}
});
let outcome = cmd.spawn();
drop(armed);
assert_ne!(pid.get(), 0, "the hook must have run");
let (err, fate) = crate::child::spawn::failure::expect_may_have_started_with(
outcome.expect_err("a pid with another unique id is not the child"),
);
assert!(vanished(&err), "another unique id is Gone, not Unassessable: {err:?}");
assert_eq!(fate, crate::error::ChildFate::Gone);
assert!(
has_not_exited(pid.get()),
"nothing may have signalled or reaped the pid"
);
end_unsignalled_and_reap(pid.get());
}
#[skuld::test]
fn macos_sync_spawn_identity_with_a_refused_reread_is_unassessable() {
crate::log_capture::install();
let (mut cmd, _writer) = sync_blocker();
let pid = Rc::new(Cell::new(0));
let armed: Rc<RefCell<Option<Box<dyn std::any::Any>>>> = Rc::default();
let _hook = fault::set_at(SpawnPoint::AfterIdentityRead, {
let (pid, armed) = (Rc::clone(&pid), Rc::clone(&armed));
move || {
pid.set(fault::spawn_pid());
*armed.borrow_mut() = Some(Box::new(force_peek_once(Err(std::io::Error::other(
"forced re-read refusal 5d1b",
)))));
}
});
let mark = crate::log_capture::mark();
let outcome = cmd.spawn();
drop(armed);
assert_ne!(pid.get(), 0, "the hook must have run");
let adopted = outcome.as_ref().ok().map(|child| child.id());
let left = has_not_exited(pid.get());
if adopted.is_none() {
end_unsignalled_and_reap(pid.get());
}
let (err, fate) = crate::child::spawn::failure::expect_may_have_started_with(
outcome.expect_err("a refused re-read fails the spawn"),
);
assert!(
matches!(err, Error::Unassessable { .. }),
"a refusal is Unassessable, not a vanish: {err:?}"
);
assert_eq!(
fate,
crate::error::ChildFate::Running { id: None },
"the child is left, its identity unread"
);
assert!(left, "the child must be left running, unreaped");
assert!(
crate::log_capture::contains_since(
mark,
"could not be checked against its handle (forced re-read refusal 5d1b)"
),
"the failed re-read is warned at the call, naming its own error"
);
}
#[skuld::test]
fn macos_sync_spawn_identity_held_by_launchd_is_gone() {
crate::log_capture::install();
let (mut cmd, writer) = sync_blocker();
let pid = Rc::new(Cell::new(0));
let armed: Rc<RefCell<Vec<Box<dyn std::any::Any>>>> = Rc::default();
let _hook = fault::set_at(SpawnPoint::AfterIdentityRead, {
let (pid, armed) = (Rc::clone(&pid), Rc::clone(&armed));
move || arm_launchd_hold(&pid, &armed, writer)
});
let mark = crate::log_capture::mark();
let outcome = cmd.spawn();
drop(armed);
let (err, fate) = crate::child::spawn::failure::expect_may_have_started_with(
outcome.expect_err("a launchd hold fails the spawn"),
);
assert!(
matches!(&err, Error::Io(e) if e.to_string().contains("zombie is held")),
"a hold by launchd has exited, and says its zombie is held: {err:?}"
);
assert_eq!(fate, crate::error::ChildFate::Gone, "a launchd-held zombie is gone");
assert!(
crate::log_capture::contains_since(mark, &format!("child {}: launchd holds its zombie", pid.get())),
"the hold is warned at the call, naming the pid"
);
}
pub(crate) fn arm_launchd_hold(
pid: &Rc<Cell<u32>>,
armed: &Rc<RefCell<Vec<Box<dyn std::any::Any>>>>,
writer: std::io::PipeWriter,
) {
pid.set(fault::spawn_pid());
let UniqRead::Found(info) = uniq_info(pid.get(), ReadPurpose::Kill) else {
panic!("the child's unique id must be readable")
};
drop(writer);
reap_by_pid(pid.get());
let mut armed = armed.borrow_mut();
for _ in 0..2 {
armed.push(Box::new(uniq_fault::force_uniq_read_once(
ReadPurpose::Echild,
UniqRead::Found(info),
)));
}
armed.push(Box::new(ppid_fault::force_ppid_once(Ok(LAUNCHD))));
}
#[skuld::test]
fn macos_sync_spawn_takes_the_childs_own_unique_id_and_reads_its_unique_id_by_pid_only_in_the_running_peek() {
let (mut cmd, writer) = sync_blocker();
let reads = uniq_fault::record();
let child = cmd.spawn().expect("the child's own report needs no by-pid read");
assert_eq!(
reads.purposes(),
[ReadPurpose::Running],
"the only by-pid read is the identity check's re-read, none to adopt the id"
);
drop(writer);
drop(child);
}
#[skuld::test]
fn macos_sync_spawn_childs_own_read_refused_is_unassessable_and_the_program_does_not_run() {
let (stdout, reader) = ran_marker();
let mut cmd = crate::Command::new();
cmd.args(RAN_ARGV);
cmd.stdout(stdout).expect("set stdout");
let _forced = unique_report::seams::force_child_read_errno(libc::EPERM);
let err =
crate::child::spawn::failure::expect_not_started(cmd.spawn().expect_err("a refused own read fails the spawn"));
assert!(
matches!(err, Error::Unassessable { .. }),
"a refusal is Unassessable, not a vanish: {err:?}"
);
assert_program_did_not_run(cmd, reader);
}
#[skuld::test]
fn macos_sync_spawn_of_a_child_killed_before_its_report_says_it_died_before_exec() {
crate::log_capture::install();
let (mut cmd, _writer) = sync_blocker();
let _forced = unique_report::seams::force_child_killed_before_report();
let mark = crate::log_capture::mark();
let err = crate::child::spawn::failure::expect_not_started(
cmd.spawn().expect_err("a child that never reported cannot be adopted"),
);
let Error::Io(e) = &err else {
panic!("a child that died before exec is an io error, not a refusal: {err:?}")
};
assert!(e.to_string().contains("died before exec"), "{e}");
assert_eq!(e.raw_os_error(), None, "no errno is made up");
assert!(
crate::log_capture::contains_since(mark, "died before exec; nothing is signalled or waited on by pid"),
"a dead child is abandoned as a corpse"
);
assert!(
!crate::log_capture::contains_since(mark, "may still be running"),
"a dead child is not reported as possibly running"
);
}
#[skuld::test]
fn macos_sync_spawn_adopts_the_live_childs_own_unique_id() {
let (mut cmd, writer) = sync_blocker();
let child = cmd.spawn().expect("spawn");
let UniqRead::Found(info) = uniq_info(child.id().pid(), ReadPurpose::Kill) else {
panic!("the live child has a unique id")
};
assert_eq!(child.adopted_unique(), Some(info.unique_id));
drop(writer);
drop(child);
}
#[skuld::test]
fn macos_sync_spawn_failing_before_the_report_keeps_stds_error() {
let (mut cmd, _writer) = sync_blocker();
let _forced = unique_report::seams::force_hook_failure_before_report(libc::ENOENT);
let err = crate::child::spawn::failure::expect_not_started(cmd.spawn().expect_err("the hook fails the spawn"));
assert!(
matches!(&err, Error::Io(e) if e.raw_os_error() == Some(libc::ENOENT)),
"std's error stays: {err:?}"
);
}
#[skuld::test]
fn macos_sync_spawn_consults_the_report_before_attaching() {
let (mut cmd, _writer) = sync_blocker();
let _killed = unique_report::seams::force_child_killed_before_report();
fault::set_force_attach_failure(true);
let err = crate::child::spawn::failure::expect_not_started(
cmd.spawn().expect_err("a child that never reported cannot be adopted"),
);
fault::set_force_attach_failure(false);
assert!(
matches!(&err, Error::Io(e) if e.to_string().contains("died before exec")),
"the report decides before the attach does: {err:?}"
);
}
#[skuld::test]
fn macos_fdmarker_attach_reads_nothing_by_pid() {
let (mut cmd, _writer) = sync_blocker();
cmd.contain();
let reads_before_attach = Rc::new(Cell::new(None));
let _hook = fault::set_at(SpawnPoint::BeforeAttach, {
let reads = Rc::clone(&reads_before_attach);
move || reads.set(Some(crate::identity::seams::by_pid_reads()))
});
let child = cmd.spawn().expect("spawn");
assert_eq!(
Some(crate::identity::seams::by_pid_reads()),
reads_before_attach.get(),
"nothing from the attach on may read an identity by pid"
);
assert_eq!(
child.test_marker_root(),
Some(child.id()),
"the marker's root is the verified identity"
);
}
fn teardown(child: std::process::Child, unique: u64) -> crate::error::ChildFate {
super::teardown_after_attach_failure(child, unique, crate::identity::ProcessId::current())
}
fn std_blocker_with_unique() -> (std::process::Child, std::process::ChildStdin, u64) {
let mut cmd = std::process::Command::new(crate::test_child::BLOCKER_ARGV[0]);
cmd.args(&crate::test_child::BLOCKER_ARGV[1..])
.stdin(std::process::Stdio::piped());
let guard = crate::child::spawn::spawn_lock();
#[allow(clippy::disallowed_methods, reason = "spawn_lock is held by `guard`")]
let mut child = cmd.spawn().expect("spawn the blocker");
drop(guard);
let stdin = child.stdin.take().expect("piped stdin");
let Ok(Some(unique)) = crate::signal::read_identity(child.id()) else {
panic!("the blocker's unique id must be readable")
};
(child, stdin, unique)
}
pub(crate) fn is_reaped(pid: u32) -> bool {
let mut status = 0;
let rc = unsafe { libc::waitpid(pid as libc::pid_t, &mut status, libc::WNOHANG) };
rc == -1 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ECHILD)
}
#[skuld::test]
fn macos_attach_failure_teardown_kills_and_reaps_a_verified_child() {
crate::log_capture::install();
let (child, _stdin, unique) = std_blocker_with_unique();
let pid = child.id();
let mark = crate::log_capture::mark();
let fate = teardown(child, unique);
assert_eq!(fate, crate::error::ChildFate::Reaped);
let levels = crate::log_capture::levels_since(mark, &format!("pid {pid}"));
assert!(
!levels.contains(&log::Level::Warn),
"a clean teardown does not warn: {levels:?}"
);
assert!(is_reaped(pid), "the killed child must have been reaped");
}
#[skuld::test]
fn macos_attach_failure_teardown_of_a_reaped_child_only_logs_at_debug() {
crate::log_capture::install();
let (child, _stdin, unique) = std_blocker_with_unique();
let pid = child.id();
assert_eq!(unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) }, 0);
reap_by_pid(pid);
let mark = crate::log_capture::mark();
let fate = teardown(child, unique);
assert_eq!(fate, crate::error::ChildFate::Gone);
let levels = crate::log_capture::levels_since(mark, &format!("pid {pid}"));
assert!(
!levels.is_empty() && levels.iter().all(|&l| l == log::Level::Debug),
"a reaped child is a `debug`, never a `warn`: {levels:?}"
);
}
fn teardown_records(mark: usize) -> Vec<(log::Level, String)> {
crate::log_capture::records_since_on_current_thread(mark, "spawn teardown")
}
fn refuse_the_kill() -> uniq_fault::Forced {
uniq_fault::force_uniq_read_once(ReadPurpose::Kill, UniqRead::Refused(libc::EPERM))
}
#[skuld::test]
fn macos_attach_failure_teardown_with_a_refused_kill_leaves_the_child_and_reaps_by_id() {
crate::log_capture::install();
let (child, _stdin, unique) = std_blocker_with_unique();
let pid = child.id();
let other = other_unique_id(pid);
let mark = crate::log_capture::mark();
let _refused = refuse_the_kill();
let _other = uniq_fault::force_uniq_read_once(ReadPurpose::Running, other);
let fate = teardown(child, unique);
assert_eq!(fate, crate::error::ChildFate::Gone, "another process holds the pid");
let records = teardown_records(mark);
let levels: Vec<_> = records.iter().map(|r| r.0).collect();
assert_eq!(levels, vec![log::Level::Warn, log::Level::Debug], "{records:?}");
assert!(records[1].1.contains("reaped by someone else"), "{records:?}");
end_unsignalled_and_reap(pid);
}
#[skuld::test]
fn macos_attach_failure_teardown_of_an_orphaned_child_is_gone_and_warns() {
use crate::wait::exit_only::{Foreign, Peek};
crate::log_capture::install();
let (child, _stdin, unique) = std_blocker_with_unique();
let pid = child.id();
let mark = crate::log_capture::mark();
let _refused = refuse_the_kill();
let _orphaned = force_peek_once(Ok(Peek::Foreign(Foreign::Orphaned)));
let fate = teardown(child, unique);
assert_eq!(fate, crate::error::ChildFate::Gone, "a launchd-held zombie is gone");
let records = teardown_records(mark);
let levels: Vec<_> = records.iter().map(|r| r.0).collect();
assert_eq!(levels, vec![log::Level::Warn, log::Level::Warn], "{records:?}");
assert!(records[1].1.contains("launchd holds its zombie"), "{records:?}");
end_unsignalled_and_reap(pid);
}
#[skuld::test]
fn macos_attach_failure_teardown_with_a_refused_id_read_warns_it_cannot_be_shown_ours() {
crate::log_capture::install();
let (child, _stdin, unique) = std_blocker_with_unique();
let pid = child.id();
let mark = crate::log_capture::mark();
let _refused = refuse_the_kill();
let _denied = uniq_fault::force_uniq_read_once(ReadPurpose::Running, UniqRead::Refused(libc::EPERM));
let fate = teardown(child, unique);
assert_eq!(fate, crate::error::ChildFate::Unknown, "a refused read shows nothing");
let records = teardown_records(mark);
let levels: Vec<_> = records.iter().map(|r| r.0).collect();
assert_eq!(levels, vec![log::Level::Warn, log::Level::Warn], "{records:?}");
assert!(records[1].1.contains("cannot be shown to be ours"), "{records:?}");
end_unsignalled_and_reap(pid);
}
#[skuld::test]
fn macos_attach_failure_teardown_does_not_reap_a_pid_reused_after_the_wait() {
crate::log_capture::install();
let (child, _stdin, unique) = std_blocker_with_unique();
let pid = child.id();
let other = other_unique_id(pid);
let mark = crate::log_capture::mark();
let _first = uniq_fault::force_uniq_read_once(
ReadPurpose::Peek,
UniqRead::Found(crate::identity::UniqInfo { unique_id: unique }),
);
let _second = uniq_fault::force_uniq_read_once(ReadPurpose::Peek, other);
let fate = teardown(child, unique);
assert_eq!(
fate,
crate::error::ChildFate::Killed,
"the kill was delivered, and another process holds the pid"
);
let records = teardown_records(mark);
assert!(
records.iter().all(|(level, _)| *level == log::Level::Debug),
"{records:?}"
);
assert!(
records.iter().any(|(_, text)| text.contains("reaped by someone else")),
"{records:?}"
);
assert!(
!is_reaped(pid),
"the zombie must have been left: its exit record is still ours to take"
);
}
#[skuld::test]
fn macos_attach_failure_teardown_of_an_orphaned_zombie_after_the_kill_is_killed_and_warns() {
use crate::wait::exit_only::{Foreign, Peek};
crate::log_capture::install();
let (child, _stdin, unique) = std_blocker_with_unique();
let pid = child.id();
let mark = crate::log_capture::mark();
let _orphaned = force_peek_once(Ok(Peek::Foreign(Foreign::Orphaned)));
let fate = teardown(child, unique);
assert_eq!(
fate,
crate::error::ChildFate::Killed,
"the kill was delivered, and launchd holds the zombie"
);
let records = teardown_records(mark);
let levels: Vec<_> = records.iter().map(|r| r.0).collect();
assert_eq!(levels, vec![log::Level::Warn], "{records:?}");
assert!(records[0].1.contains("launchd holds its zombie"), "{records:?}");
reap_by_pid(pid);
}
#[skuld::test]
fn macos_attach_failure_teardown_of_a_child_reaped_elsewhere_after_the_kill_is_killed() {
use crate::wait::exit_only::{Foreign, Peek};
crate::log_capture::install();
let (child, _stdin, unique) = std_blocker_with_unique();
let pid = child.id();
let _reaped = force_peek_once(Ok(Peek::Foreign(Foreign::Gone)));
let fate = teardown(child, unique);
assert_eq!(fate, crate::error::ChildFate::Killed);
reap_by_pid(pid);
}
#[skuld::test]
fn macos_attach_failure_teardown_warns_when_the_consuming_record_is_not_an_exit() {
crate::log_capture::install();
let (child, _stdin, unique) = std_blocker_with_unique();
let mark = crate::log_capture::mark();
let bogus = crate::wait::exit_only::seams::force_consuming_record_once(99);
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
teardown(child, unique);
}));
drop(bogus);
assert_eq!(
outcome.is_err(),
cfg!(debug_assertions),
"a debug build asserts the contract"
);
let records = teardown_records(mark);
assert!(
records
.iter()
.any(|(level, text)| *level == log::Level::Warn && text.contains("not an exit record")),
"{records:?}"
);
}
#[skuld::test]
fn macos_a_failed_attach_kills_and_reaps_a_child_that_is_not_a_front() {
let (mut cmd, _writer) = sync_blocker();
fault::set_force_attach_failure(true);
let (err, fate) = crate::child::spawn::failure::expect_may_have_started_with(
cmd.spawn().expect_err("the forced attach failure fails the spawn"),
);
fault::set_force_attach_failure(false);
assert!(matches!(err, Error::Containment { .. }), "{err:?}");
assert_eq!(
fate,
crate::error::ChildFate::Reaped,
"killed and reaped through its verified id"
);
let Some(crate::identity::Resolved::Found(id)) = fault::take_captured() else {
panic!("the seam captured the child's identity")
};
assert!(is_reaped(id.pid()), "the killed child must have been reaped");
}
#[skuld::test]
fn macos_treewalk_attach_reads_nothing_by_pid() {
let (mut cmd, _writer) = sync_blocker();
cmd.contain_with(crate::ContainMode::TreeWalk);
cmd.suppress_fd_marker();
let reads_before_attach = Rc::new(Cell::new(None));
let _hook = fault::set_at(SpawnPoint::BeforeAttach, {
let reads = Rc::clone(&reads_before_attach);
move || reads.set(Some(crate::identity::seams::by_pid_reads()))
});
let child = cmd.spawn().expect("spawn");
assert_eq!(
Some(crate::identity::seams::by_pid_reads()),
reads_before_attach.get(),
"nothing from the attach on may read an identity by pid"
);
assert_eq!(
child.test_treewalk_root(),
Some(child.id()),
"the walk's root is the verified identity"
);
}
#[skuld::test]
fn macos_sync_spawn_of_an_unreported_child_leaves_it_running_and_says_so() {
use crate::elevation::{front::front, ElevatedVia};
crate::log_capture::install();
for front in [None, front(Some(&ElevatedVia::MacosOsascript))] {
let (mut cmd, writer) = sync_blocker();
cmd.set_elevation_front(front);
let mark = crate::log_capture::mark();
let err = {
let _unwritten = unique_report::seams::find_the_report_unwritten();
cmd.spawn().expect_err("an unreported child is not adopted")
};
let (err, fate) = crate::child::spawn::failure::expect_may_have_started_with(err);
assert_eq!(
fate,
crate::error::ChildFate::Running { id: None },
"an unreported child is left running"
);
let Some(crate::identity::Resolved::Found(id)) = crate::child::spawn::fault::take_captured() else {
panic!("the spawn captured the child");
};
let pid = id.pid();
assert!(has_not_exited(pid), "the child is left running");
assert!(
crate::log_capture::contains_since(mark, &format!("child {pid} had not reported its unique id")),
"the warning says what happened"
);
assert!(
!crate::log_capture::contains_since(mark, &format!("child {pid} died before exec")),
"an unreported child is not reported dead"
);
assert_eq!(
err.to_string().contains("it is left unreaped"),
front.is_some(),
"only a front is noted: {err}"
);
end_unsignalled_and_reap(pid);
drop(writer);
}
}