use std::cell::Cell;
use std::sync::Arc;
use crate::test_child::Console;
use std::rc::Rc;
use super::identity_macos_tests::{
end_unsignalled_and_reap, has_not_exited, is_reaped, reap_by_pid, spawn_over, std_blocker_with_unique,
sync_blocker, REFUSED_KILL_READ,
};
use super::unique_report;
use crate::error::ChildFate;
use crate::identity::{FakeKernel, HostKernel};
use crate::test_groups::{stray_signal, tracer_group, Group};
pub(crate) const SAID_REAPED: &str = "reaped it after the kill";
pub(crate) const SAID_REAPED_ELSEWHERE: &str = "reaped by someone else";
pub(crate) const SAID_REFUSED_RUNNING: &str = "could not be terminated (";
pub(crate) const HANDED_BACK: &str = "handed back to the caller in the error";
pub(crate) fn warns_of(pid: u32, mark: usize) -> Vec<String> {
let named = format!("child {pid} ");
crate::log_capture::records_since_on_current_thread(mark, &named)
.into_iter()
.filter(|(level, text)| *level == log::Level::Warn && text.starts_with("teardown after a failed spawn: "))
.map(|(_, text)| text)
.collect()
}
pub(crate) fn assert_one_warn(pid: u32, mark: usize, says: &[&str], not_says: &[&str]) {
let warns = warns_of(pid, mark);
assert_eq!(warns.len(), 1, "one event, one warn: {warns:?}");
assert!(
warns[0].contains("at least two of this process's descriptors 0 to 2 were closed"),
"{warns:?}"
);
for said in says {
assert!(warns[0].contains(said), "the warn must say {said:?}: {warns:?}");
}
for other in not_says {
assert!(!warns[0].contains(other), "the warn must not say {other:?}: {warns:?}");
}
assert!(
!warns[0].contains("died before exec"),
"a late child is not reported dead: {warns:?}"
);
}
pub(crate) fn assert_kill_sent(pid: u32, sent: &[crate::send_log::Entry]) {
let kill = (pid, crate::signal::Sig::Kill, crate::send_log::Via::Identity);
assert_eq!(
sent.iter().filter(|e| **e == kill).count(),
1,
"the teardown must send the kill: {sent:?}"
);
}
#[skuld::test]
fn macos_sync_spawn_of_a_late_reporting_child_kills_and_reaps_it_through_its_id() {
crate::log_capture::install();
let (mut cmd, writer) = sync_blocker();
let sent = Rc::new(crate::send_log::Capture::start());
let kill_missing = Rc::new(Cell::new(false));
let _release = crate::child::spawn::fault::set_between_kill_and_wait({
let (sent, missing) = (Rc::clone(&sent), Rc::clone(&kill_missing));
move || {
missing.set(
sent.entries()
.iter()
.all(|(_, sig, _)| *sig != crate::signal::Sig::Kill),
);
drop(writer);
}
});
let mark = crate::log_capture::mark();
let err = {
let _late = unique_report::seams::find_the_report_unwritten();
cmd.spawn().expect_err("a late child is not adopted")
};
assert!(!kill_missing.get(), "the kill must be sent before the wait");
let (err, fate) = crate::child::spawn::failure::expect_may_have_started_with(err);
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_eq!(fate, ChildFate::Reaped, "a late child is killed and reaped");
assert_kill_sent(pid, &sent.entries());
assert!(is_reaped(pid), "nothing is left to wait for");
let said = crate::error::said(&err);
assert!(said.contains("exec cannot be confirmed"), "{said}");
assert_one_warn(
pid,
mark,
&[SAID_REAPED],
&[SAID_REFUSED_RUNNING, SAID_REAPED_ELSEWHERE],
);
}
pub(crate) fn close_fds_0_and_1(done: &crate::test_own_process::Completion) -> crate::test_stdio::RestoreStdio {
use std::os::fd::AsRawFd;
let restore = crate::test_stdio::RestoreStdio::close(done, &[0, 1]);
let (read, write) = std::io::pipe().expect("pipe");
let fds = [read.as_raw_fd(), write.as_raw_fd()];
drop((read, write));
assert_eq!(fds, [0, 1], "precondition: a new pipe must take fds 0 and 1");
restore
}
pub(crate) fn null_stdio() -> crate::stdio::Stdio {
crate::stdio::Stdio::from_file(std::fs::File::open("/dev/null").expect("open /dev/null"))
}
#[skuld::test]
fn macos_sync_spawn_with_fds_0_and_1_closed_leaves_no_child_behind() {
use crate::test_own_process::{own_process, test_path};
use crate::test_spawn::spawn;
let Some(done) = own_process(
test_path!(macos_sync_spawn_with_fds_0_and_1_closed_leaves_no_child_behind),
spawn,
) else {
return;
};
crate::log_capture::install();
let (mut cmd, writer) = sync_blocker();
cmd.stdout(null_stdio()).expect("set stdout");
let held = unique_report::seams::hold_the_report_until_the_first_read();
let restore = close_fds_0_and_1(&done);
let spawned = cmd.spawn();
drop(restore);
drop(held);
let err = spawned.expect_err("a late child is not adopted");
let (_err, fate) = crate::child::spawn::failure::expect_may_have_started_with(err);
assert_eq!(fate, ChildFate::Reaped, "the late child is reaped");
let Some(crate::identity::Resolved::Found(id)) = crate::child::spawn::fault::take_captured() else {
panic!("the spawn captured the child");
};
assert!(is_reaped(id.pid()), "nothing is left to wait for");
drop(writer);
}
#[skuld::test]
fn macos_sync_spawn_with_fds_0_and_1_closed_tears_down_a_child_whose_report_came_first() {
use crate::test_own_process::{own_process, test_path};
use crate::test_spawn::spawn;
let Some(done) = own_process(
test_path!(macos_sync_spawn_with_fds_0_and_1_closed_tears_down_a_child_whose_report_came_first),
spawn,
) else {
return;
};
crate::log_capture::install();
let (mut cmd, writer) = sync_blocker();
cmd.stdout(null_stdio()).expect("set stdout");
let first = unique_report::seams::let_the_report_come_first();
let mark = crate::log_capture::mark();
let restore = close_fds_0_and_1(&done);
let spawned = cmd.spawn();
drop(restore);
drop(first);
let err = spawned.expect_err("a child whose exec std could not see is not adopted");
let (err, fate) = crate::child::spawn::failure::expect_may_have_started_with(err);
let said = crate::error::said(&err);
assert!(said.contains("exec cannot be confirmed"), "{said}");
assert_eq!(fate, ChildFate::Reaped, "the child is torn down through its id");
let Some(crate::identity::Resolved::Found(id)) = crate::child::spawn::fault::take_captured() else {
panic!("the spawn captured the child");
};
assert!(is_reaped(id.pid()), "nothing is left to wait for");
assert_one_warn(id.pid(), mark, &[SAID_REAPED], &[]);
drop(writer);
}
#[skuld::test]
fn macos_a_spawn_waiting_for_a_late_report_lets_another_spawn_complete() {
use crate::test_own_process::{own_process, test_path};
use crate::test_spawn::spawn;
let Some(done) = own_process(
test_path!(macos_a_spawn_waiting_for_a_late_report_lets_another_spawn_complete),
spawn,
) else {
return;
};
crate::log_capture::install();
let (mut cmd, writer) = sync_blocker();
cmd.stdout(null_stdio()).expect("set stdout");
let mut other = crate::test_child::command(Console::Hidden);
other.args(["/usr/bin/true"]);
other.stdin(null_stdio()).expect("set stdin");
other.stdout(null_stdio()).expect("set stdout");
let (said, heard) = std::sync::mpsc::channel::<&'static str>();
let _contended = crate::child::spawn::fault::on_spawn_lock_contended({
let said = said.clone();
move || {
said.send("contended").ok();
}
});
let first_word = Rc::new(Cell::new(None));
let second = Rc::new(std::cell::RefCell::new(None));
let _hook = crate::wait::block_probe::on_blocking({
let (first_word, second) = (Rc::clone(&first_word), Rc::clone(&second));
move || {
let thread = std::thread::spawn(move || {
let spawned = other.spawn();
said.send("completed").ok();
drop(spawned);
});
first_word.set(Some(heard.recv().expect("the other spawn's first word")));
unique_report::seams::release_the_report();
*second.borrow_mut() = Some(thread);
}
});
let held = unique_report::seams::hold_the_report();
let restore = close_fds_0_and_1(&done);
let spawned = cmd.spawn();
drop(restore);
drop(held);
second
.borrow_mut()
.take()
.expect("the wait blocked and started the other spawn")
.join()
.expect("the other spawn's thread");
assert_eq!(
first_word.get(),
Some("completed"),
"another spawn must complete while this one waits for its report"
);
let err = spawned.expect_err("a late child is not adopted");
let (_err, fate) = crate::child::spawn::failure::expect_may_have_started_with(err);
assert_eq!(fate, ChildFate::Reaped, "the late child is torn down");
drop(writer);
}
#[skuld::test]
fn macos_sync_spawn_of_a_late_front_hands_it_back_and_says_so() {
use crate::elevation::ElevatedVia;
crate::log_capture::install();
let (mut cmd, writer) = sync_blocker();
cmd.set_elevation_report(Some(crate::elevation::elevation_tests::report(
ElevatedVia::MacosOsascript,
)));
let sent = crate::send_log::Capture::start();
let mark = crate::log_capture::mark();
let err = {
let _late = unique_report::seams::find_the_report_unwritten();
cmd.spawn().expect_err("a late front is not adopted")
};
let said = crate::test_child::detail_of(&err);
let (_, fate, handed_back) = crate::test_child::expect_handed_back(err, writer);
assert_eq!(fate, ChildFate::Running { id: None }, "a front 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_eq!(sent.entries(), [], "a front is sent nothing");
assert!(has_not_exited(pid), "the front is left running");
assert_one_warn(
pid,
mark,
&["elevation front", HANDED_BACK],
&["was sent SIGKILL", SAID_REFUSED_RUNNING, SAID_REAPED_ELSEWHERE],
);
assert!(said.contains(HANDED_BACK), "{said}");
let status = handed_back.wait();
assert!(status.success(), "the front was signalled: {status:?}");
}
pub(crate) struct Tree {
ready: std::io::PipeReader,
hold: Option<std::io::PipeWriter>,
out: std::io::PipeReader,
}
pub(crate) const TREE_ARGV: [&str; 3] = [
"/bin/sh",
"-c",
"(printf r >&3; read x <&4; printf survived >&5) & wait",
];
pub(crate) fn tree_pipes() -> (Tree, [(i32, crate::stdio::Stdio); 3]) {
use std::os::fd::OwnedFd;
let child_end = |end: OwnedFd| crate::stdio::Stdio::from_file(std::fs::File::from(end));
let (ready, ready_w) = std::io::pipe().expect("pipe");
let (hold_r, hold) = std::io::pipe().expect("pipe");
let (out, out_w) = std::io::pipe().expect("pipe");
let ends = [
(3, child_end(ready_w.into())),
(4, child_end(hold_r.into())),
(5, child_end(out_w.into())),
];
(
Tree {
ready,
hold: Some(hold),
out,
},
ends,
)
}
impl Tree {
pub(crate) fn await_grandchild(&mut self) {
use std::io::Read;
use std::os::fd::AsRawFd;
use nix::sys::event::{EvFlags, EventFilter, FilterFlag, KEvent};
use crate::os_process::macos::kqueue::{Kqueue, Subscription};
let root = crate::child::spawn::fault::spawn_pid();
let kq = Kqueue::new().expect("kqueue");
kq.subscribe(Subscription::Readable {
fd: self.ready.as_raw_fd(),
low_water: 1,
})
.expect("watch the ready pipe");
kq.subscribe(Subscription::Process {
pid: root,
signals: false,
reap: false,
})
.unwrap_or_else(|e| panic!("the root {root} must be alive until its grandchild runs: {e}"));
let blank = KEvent::new(0, EventFilter::EVFILT_READ, EvFlags::empty(), FilterFlag::empty(), 0, 0);
let mut events = [blank; 2];
let n = loop {
match kq.native().kevent(&[], &mut events, None) {
Err(nix::errno::Errno::EINTR) => continue,
other => break other.expect("wait for the grandchild or the root's exit"),
}
};
assert!(
events[..n].iter().any(|e| e.filter() == Ok(EventFilter::EVFILT_READ)),
"the root {root} exited before its grandchild ran"
);
let mut byte = [0u8; 1];
let n = self.ready.read(&mut byte).expect("read the ready pipe");
assert_eq!(n, 1, "the grandchild must run before the teardown");
}
pub(crate) fn release(&mut self) {
self.hold = None;
}
pub(crate) fn grandchild_survived(self) -> bool {
use std::io::Read;
let Tree { ready, hold, mut out } = self;
drop((ready, hold));
let mut said = String::new();
out.read_to_string(&mut said).expect("read the grandchild's word");
!said.is_empty()
}
}
#[skuld::test]
fn macos_sync_spawn_of_a_late_contained_child_kills_its_tree() {
crate::log_capture::install();
let (tree, ends) = tree_pipes();
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(TREE_ARGV).contain();
for (fd, end) in ends {
cmd.fd(fd, end).expect("set the fd");
}
let tree = Rc::new(std::cell::RefCell::new(Some(tree)));
let _hook = crate::child::spawn::fault::set_at(crate::child::spawn::fault::SpawnPoint::BeforeLateTeardown, {
let tree = Rc::clone(&tree);
move || tree.borrow_mut().as_mut().expect("the tree").await_grandchild()
});
let mark = crate::log_capture::mark();
let err = {
let _late = unique_report::seams::find_the_report_unwritten();
cmd.spawn().expect_err("a late child is not adopted")
};
let (_err, fate) = crate::child::spawn::failure::expect_may_have_started_with(err);
let Some(crate::identity::Resolved::Found(id)) = crate::child::spawn::fault::take_captured() else {
panic!("the spawn captured the child");
};
let tree = tree.borrow_mut().take().expect("the tree");
assert!(
!tree.grandchild_survived(),
"the late child's grandchild must be killed"
);
assert_eq!(fate, ChildFate::Reaped, "the root is killed and reaped");
assert_one_warn(id.pid(), mark, &[SAID_REAPED], &["tree was not", "fully killed"]);
}
fn late_tree_walk(spoil: impl FnOnce() + 'static) -> (u32, ChildFate, bool, usize, Option<crate::error::Failures>) {
use crate::containment::ContainMode;
crate::log_capture::install();
let (tree, ends) = tree_pipes();
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(TREE_ARGV).contain_with(ContainMode::TreeWalk);
cmd.suppress_fd_marker();
for (fd, end) in ends {
cmd.fd(fd, end).expect("set the fd");
}
let tree = Rc::new(std::cell::RefCell::new(Some(tree)));
let _hook = crate::child::spawn::fault::set_at(crate::child::spawn::fault::SpawnPoint::BeforeLateTeardown, {
let tree = Rc::clone(&tree);
move || {
tree.borrow_mut().as_mut().expect("the tree").await_grandchild();
spoil();
}
});
let mark = crate::log_capture::mark();
let err = {
let _late = unique_report::seams::find_the_report_unwritten();
cmd.spawn().expect_err("a late child is not adopted")
};
let cleanup = match &err {
crate::error::Error::MayHaveStarted { cleanup, .. } => cleanup.clone(),
other => panic!("expected MayHaveStarted, got {other:?}"),
};
let (_err, fate) = crate::child::spawn::failure::expect_may_have_started_with(err);
let Some(crate::identity::Resolved::Found(id)) = crate::child::spawn::fault::take_captured() else {
panic!("the spawn captured the child");
};
let survived = tree.borrow_mut().take().expect("the tree").grandchild_survived();
(id.pid(), fate, survived, mark, cleanup)
}
#[skuld::test]
fn macos_late_tree_walk_that_fails_before_the_root_kill_says_its_tree_was_not_fully_killed() {
let (pid, fate, survived, mark, cleanup) =
late_tree_walk(|| crate::containment::enumerate::force_blind_snapshots(1));
assert!(survived, "a walk that could not take its snapshot kills nothing");
assert_eq!(fate, ChildFate::Reaped, "the root is killed and reaped");
assert_one_warn(
pid,
mark,
&[SAID_REAPED, "its tree was not fully killed", "test fault injected"],
&[],
);
let cleanup = cleanup.expect("the failed sweep is the cleanup");
assert_eq!(cleanup.iter().len(), 1, "{cleanup:?}");
assert!(
crate::error::said(&**cleanup.first()).contains("test fault injected"),
"{cleanup:?}"
);
}
#[skuld::test]
fn macos_late_tree_walk_that_leaves_a_member_says_its_tree_was_not_fully_killed() {
let (pid, fate, _, mark, cleanup) = late_tree_walk(|| {
crate::containment::treewalk::fault::force_incomplete_once(
crate::containment::treewalk::fault::LeftBehind::Descendant,
);
});
assert!(
matches!(
cleanup.as_ref().map(|failures| &**failures.first()),
Some(crate::error::Error::MembersLeft { .. })
),
"the members the walk left are the cleanup: {cleanup:?}"
);
assert_eq!(fate, ChildFate::Reaped, "the root is killed and reaped");
assert_one_warn(
pid,
mark,
&[SAID_REAPED, "its tree was not fully killed", "was not killed"],
&[],
);
}
#[skuld::test]
fn macos_late_tree_walk_that_leaves_only_the_root_is_settled_by_the_root_kill() {
let (pid, fate, survived, mark, cleanup) = late_tree_walk(|| {
crate::containment::treewalk::fault::force_incomplete_once(
crate::containment::treewalk::fault::LeftBehind::Root,
);
});
assert!(!survived, "the walk killed the grandchild");
assert!(cleanup.is_none(), "the root's kill settled the walk: {cleanup:?}");
assert_eq!(fate, ChildFate::Reaped, "the root is killed and reaped");
assert_one_warn(
pid,
mark,
&[SAID_REAPED],
&["tree was not", "fully killed", "was not killed"],
);
}
#[skuld::test]
fn macos_late_session_child_without_a_marker_is_torn_down_with_what_it_starts_after_its_report() {
use crate::containment::ContainMode;
use crate::test_own_process::{own_process, test_path};
use crate::test_spawn::spawn;
let Some(done) = own_process(
test_path!(macos_late_session_child_without_a_marker_is_torn_down_with_what_it_starts_after_its_report),
spawn,
) else {
return;
};
crate::log_capture::install();
let (tree, ends) = tree_pipes();
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(TREE_ARGV).contain_with(ContainMode::Session);
cmd.suppress_fd_marker();
cmd.stdin(null_stdio()).expect("set stdin");
cmd.stdout(null_stdio()).expect("set stdout");
for (fd, end) in ends {
cmd.fd(fd, end).expect("set the fd");
}
let tree = Rc::new(std::cell::RefCell::new(Some(tree)));
let root = Rc::new(Cell::new(None));
let _hook = crate::child::spawn::fault::set_at(crate::child::spawn::fault::SpawnPoint::BeforeLateRootKill, {
let (tree, root) = (Rc::clone(&tree), Rc::clone(&root));
move || {
root.set(Some(crate::child::spawn::fault::spawn_pid()));
unique_report::seams::release_the_child_after_its_report();
tree.borrow_mut().as_mut().expect("the tree").await_grandchild();
}
});
let sent = Rc::new(crate::send_log::Capture::start());
let kill_missing = Rc::new(Cell::new(false));
let _release = crate::child::spawn::fault::set_between_kill_and_wait({
let (tree, root, sent, missing) = (
Rc::clone(&tree),
Rc::clone(&root),
Rc::clone(&sent),
Rc::clone(&kill_missing),
);
move || {
let root = root
.get()
.expect("the root's kill comes after the first kill of its tree");
let kill = (root, crate::signal::Sig::Kill, crate::send_log::Via::Identity);
if !sent.entries().contains(&kill) {
missing.set(true);
tree.borrow_mut().as_mut().expect("the tree").release();
}
}
});
let mark = crate::log_capture::mark();
let held = unique_report::seams::hold_the_report_until_the_first_read();
let after = unique_report::seams::hold_the_child_after_its_report();
let restore = close_fds_0_and_1(&done);
let spawned = cmd.spawn();
drop(restore);
drop((held, after));
assert!(!kill_missing.get(), "the root's kill must be sent before its wait");
let err = spawned.expect_err("a late child is not adopted");
let (_err, fate) = crate::child::spawn::failure::expect_may_have_started_with(err);
let Some(crate::identity::Resolved::Found(id)) = crate::child::spawn::fault::take_captured() else {
panic!("the spawn captured the child");
};
let tree = tree.borrow_mut().take().expect("the tree");
assert!(
!tree.grandchild_survived(),
"the grandchild the child started after its first tree kill must be killed"
);
assert_eq!(fate, ChildFate::Reaped, "the root is killed and reaped");
assert_one_warn(
id.pid(),
mark,
&[SAID_REAPED],
&["tree was not", "fully killed", "not shown an unreaped zombie"],
);
}
#[skuld::test]
fn macos_sync_spawn_of_a_late_child_reaped_before_its_teardown_kills_its_marked_tree() {
crate::log_capture::install();
let (tree, ends) = tree_pipes();
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(TREE_ARGV).contain();
for (fd, end) in ends {
cmd.fd(fd, end).expect("set the fd");
}
let tree = Rc::new(std::cell::RefCell::new(Some(tree)));
let _hook = crate::child::spawn::fault::set_at(crate::child::spawn::fault::SpawnPoint::BeforeLateTeardown, {
let tree = Rc::clone(&tree);
move || {
tree.borrow_mut().as_mut().expect("the tree").await_grandchild();
let root = crate::child::spawn::fault::spawn_pid();
assert_eq!(unsafe { libc::kill(root as libc::pid_t, libc::SIGKILL) }, 0);
reap_by_pid(root);
}
});
let mark = crate::log_capture::mark();
let err = {
let _late = unique_report::seams::find_the_report_unwritten();
cmd.spawn().expect_err("a late child is not adopted")
};
let (_err, fate) = crate::child::spawn::failure::expect_may_have_started_with(err);
let Some(crate::identity::Resolved::Found(id)) = crate::child::spawn::fault::take_captured() else {
panic!("the spawn captured the child");
};
let tree = tree.borrow_mut().take().expect("the tree");
assert!(
!tree.grandchild_survived(),
"the grandchild that holds the marker must be killed"
);
assert_eq!(fate, ChildFate::Gone, "the root was reaped before the teardown");
assert_one_warn(
id.pid(),
mark,
&[SAID_REAPED_ELSEWHERE, "reached only through its marker's holders"],
&["was sent SIGKILL", "fully killed", "tree was not killed"],
);
}
#[skuld::test]
fn macos_late_child_held_by_a_tracer_is_not_answered_dead(#[fixture(tracer_group)] _group: &Group) {
use crate::test_own_process::{own_process, test_path};
use crate::test_spawn::spawn;
use crate::test_support::tracer::{self, Mode, Report, TracerHelper};
let Some(done) = own_process(
test_path!(macos_late_child_held_by_a_tracer_is_not_answered_dead),
spawn,
) else {
return;
};
crate::log_capture::install();
let pending = Rc::new(std::cell::RefCell::new(Some(tracer::start(Mode::Auto))));
let helper: Rc<std::cell::RefCell<Option<TracerHelper<'static>>>> = Rc::default();
let (mut cmd, writer) = sync_blocker();
cmd.stdout(null_stdio()).expect("set stdout");
let _attach = unique_report::seams::on_first_read({
let helper = Rc::clone(&helper);
move |pid| {
let pending = pending.borrow_mut().take().expect("the helper");
let mut attached = pending.attach_unheld(pid);
assert_eq!(attached.recv(), Report::Attached);
*helper.borrow_mut() = Some(attached);
}
});
let _release = crate::wait::block_probe::on_each_block(|block| {
if block.n == Some(1) {
unique_report::seams::release_the_report();
}
});
let held = unique_report::seams::hold_the_report();
let restore = close_fds_0_and_1(&done);
let spawned = cmd.spawn();
drop(restore);
drop(held);
let err = spawned.expect_err("a late child is not adopted");
let (_err, fate) = crate::child::spawn::failure::expect_may_have_started_with(err);
assert_eq!(
fate,
ChildFate::Reaped,
"the late child is killed, handed back and reaped"
);
let mut helper = helper.borrow_mut().take().expect("the helper attached");
assert_eq!(helper.recv(), Report::Reaped);
drop(helper);
drop(writer);
}
fn tear_down(
child: std::process::Child,
stdin: &Rc<Cell<Option<std::process::ChildStdin>>>,
unique: u64,
arm: impl FnOnce(u32) -> Vec<Box<dyn std::any::Any>>,
) -> (ChildFate, Vec<String>, Vec<crate::send_log::Entry>) {
tear_down_with(uncontained(), child, stdin, unique, arm)
}
fn uncontained() -> crate::containment::Prepared {
crate::containment::Prepared {
mode: None,
is_root: true,
marker: None,
}
}
fn tear_down_with(
prepared: crate::containment::Prepared,
child: std::process::Child,
stdin: &Rc<Cell<Option<std::process::ChildStdin>>>,
unique: u64,
arm: impl FnOnce(u32) -> Vec<Box<dyn std::any::Any>>,
) -> (ChildFate, Vec<String>, Vec<crate::send_log::Entry>) {
tear_down_over(
Arc::new(FakeKernel::over(&HostKernel)),
prepared,
child,
stdin,
unique,
|| {},
arm,
)
}
fn tear_down_over(
kernel: Arc<FakeKernel<'static>>,
prepared: crate::containment::Prepared,
child: std::process::Child,
stdin: &Rc<Cell<Option<std::process::ChildStdin>>>,
unique: u64,
after_kill: impl FnOnce() + 'static,
arm: impl FnOnce(u32) -> Vec<Box<dyn std::any::Any>>,
) -> (ChildFate, Vec<String>, Vec<crate::send_log::Entry>) {
crate::log_capture::install();
let pid = child.id();
let sent = crate::send_log::Capture::start();
let _release = crate::child::spawn::fault::set_between_kill_and_wait({
let stdin = Rc::clone(stdin);
move || {
drop(stdin.take());
after_kill();
}
});
let mark = crate::log_capture::mark();
let _armed = arm(pid);
let (fate, _cleanup) = abandon(prepared, child, unique, Arc::clone(&kernel));
assert!(
kernel.all_rows_taken(),
"a look the teardown was stated to make was not made"
);
(fate, warns_of(pid, mark), sent.entries())
}
fn abandon(
prepared: crate::containment::Prepared,
child: std::process::Child,
unique: u64,
kernel: Arc<FakeKernel<'static>>,
) -> (ChildFate, Option<crate::error::Failures>) {
use crate::child::spawn::failure::SpawnFailure;
use crate::child::spawn::policy::SpawnPolicy;
let error = crate::error::Error::Io(std::io::Error::other("the late child was not adopted"));
let failure = super::late_child::abandon_late_child(
child,
unique,
error,
crate::elevation::front::TrackedKind::Own,
prepared,
SpawnPolicy::SYNC,
crate::identity::spawn_kernel(kernel),
);
let SpawnFailure::MayHaveStarted {
fate,
unreaped,
cleanup,
..
} = failure
else {
panic!("a late child's failure says the program may have started: {failure:?}");
};
if let Some(unreaped) = unreaped {
unreaped.leak();
}
(fate, cleanup)
}
#[skuld::test]
fn macos_late_teardown_returns_a_refused_kill_for_the_cleanup() {
crate::log_capture::install();
let (blocker, unique) = std_blocker_with_unique();
let (child, _stdin) = blocker.into_parts();
let pid = child.id();
let (kernel, _refused) = refused_kill(pid);
let (fate, failures) = abandon(uncontained(), child, unique, Arc::clone(&kernel));
assert!(kernel.all_rows_taken(), "the kill made its id read");
assert!(matches!(fate, ChildFate::Running { .. }), "{fate:?}");
let failures = failures.expect("the kill was refused");
assert_eq!(failures.iter().len(), 1, "{failures:?}");
let said = crate::error::said(&**failures.first());
assert!(said.contains("killing the child"), "{said}");
end_unsignalled_and_reap(pid);
}
fn refused_kill(pid: u32) -> (std::sync::Arc<FakeKernel<'static>>, crate::oneshot_hook::Armed) {
let kernel = std::sync::Arc::new(FakeKernel::over(&HostKernel));
let armed = crate::child::spawn::fault::set_at(crate::child::spawn::fault::SpawnPoint::BeforeLateRootKill, {
let kernel = std::sync::Arc::clone(&kernel);
move || kernel.state_unique_info(pid, REFUSED_KILL_READ)
});
(kernel, armed)
}
fn only(warns: &[String]) -> &str {
assert_eq!(warns.len(), 1, "one event, one warn: {warns:?}");
&warns[0]
}
#[skuld::test]
fn macos_late_teardown_of_a_live_child_is_reaped() {
let (blocker, unique) = std_blocker_with_unique();
let (child, stdin) = blocker.into_parts();
let pid = child.id();
let stdin = Rc::new(Cell::new(Some(stdin)));
let (fate, warns, sent) = tear_down(child, &stdin, unique, |_| vec![]);
assert_eq!(fate, ChildFate::Reaped);
let warn = only(&warns);
assert_kill_sent(pid, &sent);
assert!(warn.contains(SAID_REAPED) && !warn.contains(HANDED_BACK), "{warn}");
}
#[skuld::test]
fn macos_late_teardown_with_a_refused_kill_hands_it_back_and_says_so() {
let (blocker, unique) = std_blocker_with_unique();
let (child, stdin) = blocker.into_parts();
let stdin = Rc::new(Cell::new(Some(stdin)));
let pid = child.id();
let (kernel, _refused) = refused_kill(pid);
let (fate, warns, sent) = tear_down_over(kernel, uncontained(), child, &stdin, unique, || {}, |_| vec![]);
assert_eq!(fate, ChildFate::Running { id: None });
let warn = only(&warns);
assert_eq!(sent, [], "a refused kill sends nothing");
assert!(
warn.contains(SAID_REFUSED_RUNNING) && warn.contains(HANDED_BACK),
"{warn}"
);
assert!(
!warn.contains("was sent SIGKILL") && !warn.contains("did not end it"),
"{warn}"
);
end_unsignalled_and_reap(pid);
}
#[skuld::test]
fn macos_late_teardown_of_a_contained_child_with_a_refused_kill_names_it_running() {
let (blocker, unique) = std_blocker_with_unique();
let (child, stdin) = blocker.into_parts();
let stdin = Rc::new(Cell::new(Some(stdin)));
let pid = child.id();
let walked = crate::containment::Prepared {
mode: Some(crate::containment::ContainMode::TreeWalk),
is_root: true,
marker: None,
};
let (kernel, _refused) = refused_kill(pid);
let (fate, _warns, sent) = tear_down_over(
kernel,
walked,
child,
&stdin,
unique,
|| {},
|_| {
crate::containment::enumerate::force_blind_snapshots(2);
vec![]
},
);
crate::containment::enumerate::assert_blind_snapshots_consumed();
assert!(
matches!(fate, ChildFate::Running { id: Some(id) } if id.pid() == pid),
"{fate:?}"
);
assert_eq!(sent, [], "a refused kill and blind walks send nothing");
end_unsignalled_and_reap(pid);
}
#[skuld::test]
fn macos_late_teardown_of_a_child_reaped_before_the_teardown_sends_nothing_and_is_gone() {
let (blocker, unique) = std_blocker_with_unique();
let (child, stdin) = blocker.into_parts();
let stdin = Rc::new(Cell::new(Some(stdin)));
let pid = child.id();
let (fate, warns, sent) = tear_down(child, &stdin, unique, |pid| {
assert_eq!(unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) }, 0);
reap_by_pid(pid);
vec![]
});
assert_eq!(fate, ChildFate::Gone);
let warn = only(&warns);
assert_eq!(sent, [], "nothing is sent to a pid that is not the child");
assert!(warn.contains(SAID_REAPED_ELSEWHERE), "{warn}");
assert!(
!warn.contains("was sent SIGKILL") && !warn.contains("signalled") && !warn.contains(&format!("{pid} was sent")),
"{warn}"
);
}
#[skuld::test]
fn macos_late_teardown_with_a_refused_kill_and_a_failed_peek_is_unknown() {
let (blocker, unique) = std_blocker_with_unique();
let (child, stdin) = blocker.into_parts();
let stdin = Rc::new(Cell::new(Some(stdin)));
let pid = child.id();
let (kernel, _refused) = refused_kill(pid);
kernel.state_peek(pid, Err(std::io::Error::from_raw_os_error(libc::EPERM)));
let (fate, warns, sent) = tear_down_over(kernel, uncontained(), child, &stdin, unique, || {}, |_| vec![]);
assert_eq!(fate, ChildFate::Unknown);
let warn = only(&warns);
assert_eq!(sent, [], "a refused kill sends nothing");
assert!(
warn.contains(SAID_REFUSED_RUNNING) && warn.contains("the wait failed"),
"{warn}"
);
end_unsignalled_and_reap(pid);
}
#[skuld::test]
fn macos_late_teardown_of_a_child_reaped_elsewhere_after_the_kill_is_killed() {
let (blocker, unique) = std_blocker_with_unique();
let (child, stdin) = blocker.into_parts();
let stdin = Rc::new(Cell::new(Some(stdin)));
let pid = child.id();
let (fate, warns, sent) = tear_down_over(
Arc::new(FakeKernel::over(&HostKernel)),
uncontained(),
child,
&stdin,
unique,
move || reap_by_pid(pid),
|_| vec![],
);
assert_eq!(fate, ChildFate::Killed);
assert_kill_sent(pid, &sent);
assert!(only(&warns).contains(SAID_REAPED_ELSEWHERE), "{warns:?}");
}
fn state_launchd_holds_the_zombie(kernel: &FakeKernel<'_>, pid: u32) {
kernel.state_every_peek(pid, || Err(crate::child::lifecycle::echild()));
kernel.state_every_short_bsd(pid, || {
Ok(crate::identity::short_info(crate::identity::LAUNCHD, libc::SZOMB))
});
}
#[skuld::test]
fn macos_late_teardown_of_an_orphaned_zombie_after_the_kill_is_killed_and_says_so() {
let (blocker, unique) = std_blocker_with_unique();
let (child, stdin) = blocker.into_parts();
let stdin = Rc::new(Cell::new(Some(stdin)));
let pid = child.id();
let kernel = Arc::new(FakeKernel::over(&HostKernel));
state_launchd_holds_the_zombie(&kernel, pid);
let (fate, warns, sent) = tear_down_over(kernel, uncontained(), child, &stdin, unique, || {}, |_| vec![]);
assert_eq!(fate, ChildFate::Killed);
assert_kill_sent(pid, &sent);
let warn = only(&warns);
assert!(warn.contains("launchd holds its zombie"), "{warn}");
reap_by_pid(pid);
}
#[skuld::test]
fn macos_late_teardown_with_a_failed_wait_is_killed() {
let (blocker, unique) = std_blocker_with_unique();
let (child, stdin) = blocker.into_parts();
let stdin = Rc::new(Cell::new(Some(stdin)));
let pid = child.id();
let kernel = Arc::new(
FakeKernel::over(&HostKernel)
.on_peek(pid, Ok(None))
.on_peek(pid, Err(std::io::Error::other("forced wait failure"))),
);
let (fate, warns, sent) = tear_down_over(kernel, uncontained(), child, &stdin, unique, || {}, |_| vec![]);
assert_eq!(fate, ChildFate::Killed);
assert_kill_sent(pid, &sent);
let warn = only(&warns);
assert!(
warn.contains("the wait failed") && warn.contains("forced wait failure"),
"{warn}"
);
reap_by_pid(pid);
}
struct NotZombie {
fate: ChildFate,
survived: bool,
walks_after: Vec<u32>,
holders_after: Vec<u32>,
warn: String,
}
#[derive(Clone, Copy)]
enum Elsewhere {
Reaped,
HeldByLaunchd,
}
fn late_tree_not_zombie(
contain: impl FnOnce(&mut crate::Command),
elsewhere: Elsewhere,
spoil: impl FnOnce() + 'static,
) -> NotZombie {
use crate::child::spawn::fault::{set_at, set_between_kill_and_wait, SpawnPoint};
use std::cell::RefCell;
crate::log_capture::install();
let (tree, ends) = tree_pipes();
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(TREE_ARGV);
contain(&mut cmd);
for (fd, end) in ends {
cmd.fd(fd, end).expect("set the fd");
}
let tree = Rc::new(RefCell::new(Some(tree)));
let walks = Rc::new(crate::containment::treewalk::fault::record_walks());
let holders = crate::containment::fdmarker::fault::record_holder_kills();
let _first = set_at(SpawnPoint::BeforeLateTeardown, {
let tree = Rc::clone(&tree);
move || {
tree.borrow_mut().as_mut().expect("the tree").await_grandchild();
spoil();
}
});
let marks = Rc::new(Cell::new((0, 0)));
let kernel = Arc::new(FakeKernel::over(&HostKernel));
let root = Rc::new(Cell::new(0));
let looks_before = Rc::new(Cell::new(0));
let _second = set_at(SpawnPoint::BeforeLateRootKill, {
let (walks, marks, kernel, root, looks_before) = (
Rc::clone(&walks),
Rc::clone(&marks),
Arc::clone(&kernel),
Rc::clone(&root),
Rc::clone(&looks_before),
);
move || {
let holders = crate::containment::fdmarker::fault::holder_kills_so_far();
marks.set((walks.walked().len(), holders.len()));
root.set(crate::child::spawn::fault::spawn_pid());
looks_before.set(kernel.peek_reads(root.get()));
if let Elsewhere::HeldByLaunchd = elsewhere {
state_launchd_holds_the_zombie(&kernel, root.get());
}
}
});
let _reap = matches!(elsewhere, Elsewhere::Reaped).then(|| {
let root = Rc::clone(&root);
set_between_kill_and_wait(move || reap_by_pid(root.get()))
});
let mark = crate::log_capture::mark();
let err = {
let _late = unique_report::seams::find_the_report_unwritten();
spawn_over(&mut cmd, Arc::clone(&kernel)).expect_err("a late child is not adopted")
};
assert!(
kernel.peek_reads(root.get()) > looks_before.get(),
"the root was not looked at after its kill"
);
let (_err, fate) = crate::child::spawn::failure::expect_may_have_started_with(err);
let Some(crate::identity::Resolved::Found(id)) = crate::child::spawn::fault::take_captured() else {
panic!("the spawn captured the child");
};
let survived = tree.borrow_mut().take().expect("the tree").grandchild_survived();
let (walk_mark, holder_mark) = marks.get();
let seen = NotZombie {
fate,
survived,
walks_after: walks.walked()[walk_mark..].to_vec(),
holders_after: holders.killed()[holder_mark..].to_vec(),
warn: only(&warns_of(id.pid(), mark)).to_owned(),
};
if let Elsewhere::HeldByLaunchd = elsewhere {
reap_by_pid(id.pid());
}
seen
}
const NOT_SWEPT_AGAIN: &str = "not shown an unreaped zombie, so its tree was not killed again by its pid";
#[skuld::test]
fn macos_late_marked_tree_whose_root_is_not_shown_a_zombie_still_sweeps_its_holders() {
use crate::containment::ContainMode;
let seen = late_tree_not_zombie(
|cmd| {
cmd.contain_with(ContainMode::TreeWalk);
},
Elsewhere::Reaped,
|| {
crate::containment::enumerate::force_blind_snapshots(2);
crate::containment::fdmarker::fault::set_force_root_kill_noop(true);
},
);
assert!(!seen.survived, "the grandchild holds the marker, so its sweep kills it");
assert!(
!seen.holders_after.is_empty(),
"the marker's holders are swept after the root's kill"
);
assert_eq!(
seen.walks_after,
Vec::<u32>::new(),
"the root's pid is not walked again"
);
assert_eq!(seen.fate, ChildFate::Killed);
assert!(
seen.warn.contains("its tree was not fully killed") && !seen.warn.contains(NOT_SWEPT_AGAIN),
"{}",
seen.warn
);
}
#[skuld::test]
fn macos_late_walked_tree_whose_root_is_not_shown_a_zombie_is_not_walked_again() {
use crate::containment::ContainMode;
let seen = late_tree_not_zombie(
|cmd| {
cmd.contain_with(ContainMode::TreeWalk).suppress_fd_marker();
},
Elsewhere::HeldByLaunchd,
|| {},
);
assert!(!seen.survived, "the first sweep kills the grandchild");
assert_eq!(
seen.walks_after,
Vec::<u32>::new(),
"the root's pid is not walked again"
);
assert_eq!(seen.fate, ChildFate::Killed);
assert!(seen.warn.contains(NOT_SWEPT_AGAIN), "{}", seen.warn);
}
#[skuld::test]
fn macos_late_session_tree_whose_root_was_reaped_elsewhere_after_its_kill_says_its_group_was_not_killed() {
use crate::containment::ContainMode;
let seen = late_tree_not_zombie(
|cmd| {
cmd.contain_with(ContainMode::Session).suppress_fd_marker();
},
Elsewhere::Reaped,
|| {},
);
assert!(!seen.survived, "the first sweep kills the grandchild");
assert_eq!(seen.fate, ChildFate::Killed);
assert!(
seen.warn.contains("its tree was not fully killed")
&& seen.warn.contains("so its tree did not kill its process group")
&& !seen.warn.contains(NOT_SWEPT_AGAIN),
"{}",
seen.warn
);
}
struct Unforce(fn(bool));
impl Drop for Unforce {
fn drop(&mut self) {
(self.0)(false);
}
}
fn force(set: fn(bool)) -> Box<dyn std::any::Any> {
set(true);
Box::new(Unforce(set))
}
#[skuld::test]
fn macos_late_teardown_of_an_unreadable_child_without_a_marker_says_its_tree_was_not_killed() {
let (blocker, unique) = std_blocker_with_unique();
let (child, stdin) = blocker.into_parts();
let stdin = Rc::new(Cell::new(Some(stdin)));
let pid = child.id();
let walked = crate::containment::Prepared {
mode: Some(crate::containment::ContainMode::TreeWalk),
is_root: true,
marker: None,
};
let (fate, warns, sent) = tear_down_with(walked, child, &stdin, unique, |_| {
vec![force(crate::child::spawn::fault::set_force_identity_unknown)]
});
assert_eq!(fate, ChildFate::Reaped);
assert_kill_sent(pid, &sent);
let warn = only(&warns);
assert!(
warn.contains("its tree was not killed: the child's identity could not be read"),
"{warn}"
);
}
#[skuld::test]
fn macos_late_teardown_of_an_unreadable_marked_child_sweeps_its_holders() {
use crate::child::spawn::fault::{set_at, SpawnPoint};
crate::log_capture::install();
let (tree, ends) = tree_pipes();
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(TREE_ARGV).contain();
for (fd, end) in ends {
cmd.fd(fd, end).expect("set the fd");
}
let tree = Rc::new(std::cell::RefCell::new(Some(tree)));
let unknown = Rc::new(std::cell::RefCell::new(None));
let _hook = set_at(SpawnPoint::BeforeLateTeardown, {
let (tree, unknown) = (Rc::clone(&tree), Rc::clone(&unknown));
move || {
tree.borrow_mut().as_mut().expect("the tree").await_grandchild();
*unknown.borrow_mut() = Some(force(crate::child::spawn::fault::set_force_identity_unknown));
}
});
let mark = crate::log_capture::mark();
let err = {
let _late = unique_report::seams::find_the_report_unwritten();
cmd.spawn().expect_err("a late child is not adopted")
};
drop(unknown.borrow_mut().take());
let (_err, _fate) = crate::child::spawn::failure::expect_may_have_started_with(err);
let Some(crate::identity::Resolved::Found(id)) = crate::child::spawn::fault::take_captured() else {
panic!("the spawn captured the child");
};
let tree = tree.borrow_mut().take().expect("the tree");
assert!(!tree.grandchild_survived(), "the marker's holders are swept");
let warn = only(&warns_of(id.pid(), mark)).to_owned();
assert!(
warn.contains(
"the child's identity could not be read, so its tree is reached only through its marker's holders"
),
"{warn}"
);
}
#[skuld::test]
fn macos_late_teardown_whose_tree_attach_fails_says_its_tree_was_not_killed() {
let (blocker, unique) = std_blocker_with_unique();
let (child, stdin) = blocker.into_parts();
let stdin = Rc::new(Cell::new(Some(stdin)));
let pid = child.id();
let walked = crate::containment::Prepared {
mode: Some(crate::containment::ContainMode::TreeWalk),
is_root: true,
marker: None,
};
let (fate, warns, sent) = tear_down_with(walked, child, &stdin, unique, |_| {
vec![force(crate::child::spawn::fault::set_force_attach_failure)]
});
assert_eq!(fate, ChildFate::Reaped);
assert_kill_sent(pid, &sent);
let warn = only(&warns);
assert!(
warn.contains("its tree was not killed: ") && warn.contains("forced attach failure"),
"{warn}"
);
}
#[skuld::test]
fn macos_late_tree_checks_the_root_again_before_a_send_by_number(#[fixture(stray_signal)] _stray: &Group) {
use crate::child::spawn::fault::{set_at, SpawnPoint};
use crate::graceful_hooks::{at, HookPoint};
use std::cell::RefCell;
crate::log_capture::install();
let (mut cmd, writer) = sync_blocker();
cmd.contain_with(crate::ContainMode::Session);
cmd.suppress_fd_marker();
let capture: Rc<RefCell<Option<crate::send_log::Capture>>> = Rc::default();
let reap: Rc<RefCell<Option<crate::oneshot_hook::Armed>>> = Rc::default();
let _second = set_at(SpawnPoint::BeforeLateRootKill, {
let (capture, reap) = (Rc::clone(&capture), Rc::clone(&reap));
move || {
let pid = crate::child::spawn::fault::spawn_pid();
*capture.borrow_mut() = Some(crate::send_log::Capture::start());
*reap.borrow_mut() = Some(at(HookPoint::AfterRootLook, move || {
crate::test_child::reaped_elsewhere::reap_behind(pid);
}));
}
});
let err = {
let _late = unique_report::seams::find_the_report_unwritten();
cmd.spawn().expect_err("a late child is not adopted")
};
drop(writer);
let steps = capture
.borrow()
.as_ref()
.expect("the root's kill came after the first sweep")
.group_steps();
drop((reap.borrow_mut().take(), capture.borrow_mut().take()));
crate::child::foreign_reap_after_look_tests::assert_nothing_by_number(&steps);
crate::child::spawn::failure::expect_may_have_started_with(err);
}