use std::sync::Arc;
use crate::test_child::Console;
use std::time::{Duration, Instant};
use super::fixtures::{spawn_std_blocker, status, try_wait, wait_status, Blocker};
use crate::child::owned::{ChildWaitOutcome, OwnedChild};
use crate::error::Error;
use crate::identity::{ppid_fault, uniq_fault, ReadPurpose, UniqRead, LAUNCHD};
use crate::os_process::child::{Foreign, OsChild, PeekOutcome, TryReapOutcome};
use crate::os_process::macos::child::MacChild;
use crate::os_process::macos::kqueue::test_hooks;
use crate::os_process::{Exit, OsProcess};
use crate::signal::{Sent, Sig};
use crate::test_groups::{setuid, Group};
use crate::wait::exit_only::macos_tests::{echild_yet_resolvable, found, held_by_a_tracer, unique_of};
use crate::wait::exit_only::seams::{self as exit_seams, HolderStep};
fn far() -> Instant {
Instant::now() + Duration::from_secs(3600)
}
fn is_foreign(outcome: &Result<ChildWaitOutcome, crate::error::Error>) -> bool {
matches!(outcome, Ok(ChildWaitOutcome::Foreign(_)))
}
#[skuld::test]
fn a_reap_that_finds_none_after_reapable_takes_the_echild_path() {
let mut b = Blocker::spawn();
b.end_child_and_confirm_exit();
let none = exit_seams::force_empty_reap_once();
let outcome = b.owned.wait(None);
drop(none);
assert!(is_foreign(&outcome), "{outcome:?}");
assert!(format!("{:?}", b.owned).contains("N"), "{:?}", b.owned);
wait_status(&b.owned);
}
#[skuld::test]
fn a_second_peek_runs_after_every_first_reap() {
let mut b = Blocker::spawn();
b.end_child_and_confirm_exit();
exit_seams::holder_steps();
wait_status(&b.owned);
assert_eq!(exit_seams::holder_steps(), [HolderStep::SecondPeek]);
}
const MARKER: &str = "COSCA_TEST_SHARED_SIGIGN";
const CASE_ENV: &str = "COSCA_TEST_SHARED_SIGIGN_CASE";
fn run_case(path: &str, case: &str) {
crate::test_child::run_fixture_case(path, MARKER, CASE_ENV, case);
}
fn ignoring_sigchld_with_a_sibling() -> (
OwnedChild,
std::process::Child,
std::process::ChildStdin,
crate::wait::block_probe::Armed,
) {
crate::test_child::set_signal_ignored(libc::SIGCHLD, true);
let (sibling, sibling_stdin) = spawn_std_blocker();
let (root, root_stdin) = spawn_std_blocker();
let id = super::fixtures::identity_of(&root);
let owned = OwnedChild::adopt(root, id).unwrap_or_else(|(e, _)| panic!("adopt: {e}"));
let mut root_stdin = Some(root_stdin);
let end = crate::wait::block_probe::on_blocking(move || drop(root_stdin.take()));
(owned, sibling, sibling_stdin, end)
}
#[skuld::test]
fn a_wait_on_a_child_the_kernel_reaped_returns_while_a_sibling_lives() {
if !crate::test_child::is_marked_fixture_reexec(MARKER) {
return run_case(
crate::test_child::fixture_path!(a_wait_on_a_child_the_kernel_reaped_returns_while_a_sibling_lives),
"",
);
}
let (owned, _sibling, _stdin, _end) = ignoring_sigchld_with_a_sibling();
let outcome = owned.wait(None);
assert!(is_foreign(&outcome), "the kernel reaped the root: {outcome:?}");
}
#[skuld::test]
fn a_wait_timeout_far_past_the_bound_returns_echild() {
if !crate::test_child::is_marked_fixture_reexec(MARKER) {
return run_case(
crate::test_child::fixture_path!(a_wait_timeout_far_past_the_bound_returns_echild),
"",
);
}
let (owned, _sibling, _stdin, _end) = ignoring_sigchld_with_a_sibling();
let outcome = owned.wait(Some(far()));
assert!(is_foreign(&outcome), "the kernel reaped the root: {outcome:?}");
}
#[skuld::test]
fn a_sync_drop_of_a_child_the_kernel_reaped_returns() {
if !crate::test_child::is_marked_fixture_reexec(MARKER) {
return run_case(
crate::test_child::fixture_path!(a_sync_drop_of_a_child_the_kernel_reaped_returns),
"",
);
}
crate::test_child::set_signal_ignored(libc::SIGCHLD, true);
let (_sibling, _sibling_stdin) = spawn_std_blocker();
use std::io::Read as _;
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(["sh", "-c", "cat; echo eof"]);
let (stdin, writer) = crate::test_child::held_writer_stdin();
let teardown = crate::child::spawn::fault::release_at_drop_kill(writer);
cmd.stdin(stdin).expect("stdin");
cmd.stdout(crate::Stdio::pipe()).expect("stdout");
let mut child = cmd.spawn().expect("spawn");
let mut stdout = child.stdout().expect("piped stdout");
drop(child);
teardown.assert_released();
let mut printed = Vec::new();
stdout
.read_to_end(&mut printed)
.expect("the pipe ends once `cat` is gone");
assert!(
printed.is_empty(),
"the drop's kill must end the shell first: {printed:?}"
);
}
#[skuld::test]
fn try_wait_on_a_pid_with_another_unique_id_is_echild_and_consumes_nothing() {
let mut b = Blocker::spawn();
b.end_child_and_confirm_exit();
let other = unique_of(b.pid) ^ 1;
let forced = uniq_fault::force_uniq_read_once(ReadPurpose::Peek, found(other));
let outcome = try_wait(&b.owned);
drop(forced);
assert!(is_foreign(&outcome), "another process holds the pid: {outcome:?}");
wait_status(&b.owned);
}
#[skuld::test]
fn a_wait_on_a_pid_with_another_unique_id_never_reaches_the_reap() {
let mut b = Blocker::spawn();
b.end_child_and_confirm_exit();
let other = unique_of(b.pid) ^ 1;
let forced = uniq_fault::force_uniq_read_once(ReadPurpose::Peek, found(other));
let outcome = b.owned.wait(None);
drop(forced);
assert!(is_foreign(&outcome), "another process holds the pid: {outcome:?}");
wait_status(&b.owned);
}
#[skuld::test]
fn kill_sends_nothing_to_a_pid_with_another_unique_id() {
let mut b = Blocker::spawn();
let log = crate::send_log::Capture::start();
let other = unique_of(b.pid) ^ 1;
let forced = uniq_fault::force_uniq_read_once(ReadPurpose::Kill, found(other));
b.owned
.signal(Sig::Kill)
.expect("a pid that is not ours is gone, not an error");
drop(forced);
assert_eq!(log.entries(), []);
b.end_child();
let status = wait_status(&b.owned);
assert!(status.success(), "the child was signalled: {status:?}");
}
#[skuld::test]
fn kill_signals_a_live_child_through_its_audit_token() {
let b = Blocker::spawn();
let log = crate::send_log::Capture::start();
b.owned.signal(Sig::Kill).expect("kill");
assert_eq!(log.entries(), [(b.pid, Sig::Kill, crate::send_log::Via::Identity)]);
let status = wait_status(&b.owned);
assert_eq!(super::fixtures::signal_of(status), Some(libc::SIGKILL));
}
#[skuld::test]
fn kill_on_an_own_unreaped_zombie_is_delivered() {
let mut b = Blocker::spawn();
b.end_child_and_confirm_exit();
assert_eq!(b.owned.signal(Sig::Kill).expect("kill"), crate::signal::Sent::Delivered);
let status = wait_status(&b.owned);
assert!(status.success(), "{status:?}");
}
#[derive(Debug)]
pub(super) struct SharedMac(Arc<MacChild>);
impl OsProcess for SharedMac {
fn signal(&self, sig: Sig) -> Result<Sent, Error> {
self.0.signal(sig)
}
fn exited(&self) -> Result<Exit<'_>, Error> {
self.0.exited()
}
}
impl OsChild for SharedMac {
fn pid(&self) -> Option<u32> {
self.0.pid()
}
fn peek(&self) -> Result<PeekOutcome, Error> {
self.0.peek()
}
fn try_reap(&self) -> Result<TryReapOutcome<'_>, Error> {
self.0.try_reap()
}
}
pub(super) fn watch(pid: u32, unique: u64) -> (OwnedChild, Arc<MacChild>) {
let mac = Arc::new(MacChild::new(pid, unique).expect("watch the child"));
(OwnedChild::new(Box::new(SharedMac(Arc::clone(&mac)))), mac)
}
#[skuld::test]
fn a_wait_on_a_child_whose_tracer_dies_during_its_exit_is_woken_by_the_tracers_exit() {
use std::cell::Cell;
use std::rc::Rc;
let (pid, unique) = echild_yet_resolvable();
let (owned, _mac) = watch(pid, unique);
let (mut tracer, tracer_stdin) = spawn_std_blocker();
let tracer_pid = tracer.id();
let exited = Rc::new(Cell::new(false));
let _parent = ppid_fault::force_ppid_with({
let exited = Rc::clone(&exited);
move || Ok(if exited.get() { LAUNCHD } else { tracer_pid })
});
let _end = crate::wait::block_probe::on_round(0, move || {
drop(tracer_stdin);
crate::test_child::wait_until_zombie(tracer_pid);
exited.set(true);
});
let _ = test_hooks::take_events();
let outcome = owned.wait(None).expect("wait");
let events = test_hooks::take_events();
assert!(
events
.iter()
.any(|&(filter, fflags)| filter == libc::EVFILT_PROC && fflags & libc::NOTE_EXIT != 0),
"the tracer's exit must wake the wait: {events:?}"
);
assert_eq!(outcome, ChildWaitOutcome::Foreign(Foreign::Orphaned));
tracer.wait().expect("reap the stand-in tracer");
}
pub(super) fn on_rounds(
mac: &Arc<MacChild>,
mut hook: impl FnMut(u32, &MacChild) -> bool + 'static,
) -> crate::wait::block_probe::Rounds {
let mac = Arc::clone(mac);
crate::wait::block_probe::on_every_round(move |round| {
if !hook(round, &mac) {
test_hooks::send_signal(std::process::id(), libc::SIGCHLD);
}
})
}
#[skuld::test]
fn a_wait_on_a_child_a_tracer_attaches_to_late_is_woken_by_the_attach() {
use std::cell::{Cell, RefCell};
use std::rc::Rc;
let (pid, unique) = echild_yet_resolvable();
let (mut tracer, tracer_stdin) = spawn_std_blocker();
let tracer_pid = tracer.id();
let holder = Rc::new(Cell::new(pid));
let _parent = ppid_fault::force_ppid_with({
let holder = Rc::clone(&holder);
move || Ok(holder.get())
});
let (owned, mac) = watch(pid, unique);
let attach_woke = Rc::new(Cell::new(None));
let tracer_stdin = RefCell::new(Some(tracer_stdin));
let _rounds = on_rounds(&mac, {
let attach_woke = Rc::clone(&attach_woke);
move |round, mac| match round {
0 => {
holder.set(tracer_pid);
test_hooks::send_signal(pid, libc::SIGCONT);
attach_woke.set(Some(mac.event_pending()));
attach_woke.get() == Some(true)
}
1 => {
drop(tracer_stdin.borrow_mut().take());
crate::test_child::wait_until_zombie(tracer_pid);
holder.set(LAUNCHD);
true
}
_ => false,
}
});
let outcome = owned.wait(None).expect("wait");
assert_eq!(attach_woke.get(), Some(true), "the attach's signal must wake the wait");
assert_eq!(outcome, ChildWaitOutcome::Foreign(Foreign::Orphaned));
tracer.wait().expect("reap the stand-in tracer");
}
fn started_by_us_traced_by(tracer: u32) -> (libc::pid_t, libc::pid_t) {
(std::process::id() as libc::pid_t, tracer as libc::pid_t)
}
#[skuld::test]
fn a_wait_on_a_child_whose_tracer_is_traced_is_woken_by_that_tracers_exit() {
use std::cell::Cell;
use std::rc::Rc;
let (pid, unique) = echild_yet_resolvable();
let (tracer, tracer_stdin) = spawn_std_blocker();
let (outer, outer_stdin) = spawn_std_blocker();
let (tracer_pid, outer_pid) = (tracer.id(), outer.id());
let holder = Rc::new(Cell::new(tracer_pid));
let _parent = ppid_fault::force_ppid_with({
let holder = Rc::clone(&holder);
move || Ok(holder.get())
});
let _traced = crate::identity::kinfo::fault::force_parents(tracer_pid, move || started_by_us_traced_by(outer_pid));
let (owned, mac) = watch(pid, unique);
let exit_woke = Rc::new(Cell::new(None));
let _rounds = on_rounds(&mac, {
let exit_woke = Rc::clone(&exit_woke);
move |round, mac| {
if round != 0 {
return false;
}
holder.set(LAUNCHD);
test_hooks::send_signal(outer_pid, libc::SIGCHLD);
exit_woke.set(Some(mac.event_pending()));
exit_woke.get() == Some(true)
}
});
let outcome = owned.wait(None).expect("wait");
assert_eq!(
exit_woke.get(),
Some(true),
"the SIGCHLD that the traced tracer's exit sends its tracer must wake the wait"
);
assert_eq!(outcome, ChildWaitOutcome::Foreign(Foreign::Orphaned));
for (mut child, stdin) in [(tracer, tracer_stdin), (outer, outer_stdin)] {
drop(stdin);
child.wait().expect("reap a stand-in tracer");
}
}
#[skuld::test]
fn a_wait_on_a_child_whose_tracer_is_exiting_at_launchd_peeks_again_on_a_backoff() {
use std::cell::Cell;
use std::rc::Rc;
let (pid, unique) = echild_yet_resolvable();
let (mut tracer, tracer_stdin) = spawn_std_blocker();
let tracer_pid = tracer.id();
let holder = Rc::new(Cell::new(tracer_pid));
let _parent = ppid_fault::force_ppid_with({
let holder = Rc::clone(&holder);
move || Ok(holder.get())
});
let _dying = crate::identity::kinfo::fault::force_parents(tracer_pid, || started_by_us_traced_by(LAUNCHD));
let (owned, mac) = watch(pid, unique);
let _pause = crate::wait::block_probe::on_pause({
let holder = Rc::clone(&holder);
move || holder.set(LAUNCHD)
});
let _rounds = on_rounds(&mac, move |round, _| {
holder.set(LAUNCHD);
round != 0
});
crate::wait::block_probe::take();
let outcome = owned.wait(None).expect("wait");
let armed = crate::wait::block_probe::take();
assert!(
matches!(armed.first(), Some(Some(_))),
"the first block must be a timed pause, to look again: {armed:?}"
);
assert_eq!(outcome, ChildWaitOutcome::Foreign(Foreign::Orphaned));
drop(tracer_stdin);
tracer.wait().expect("reap the stand-in tracer");
}
#[skuld::test]
fn a_running_peek_of_a_pid_with_another_unique_id_is_foreign() {
let mut b = Blocker::spawn();
let unique = unique_of(b.pid);
let forced = uniq_fault::force_uniq_read_once(ReadPurpose::Running, found(unique ^ 1));
let outcome = try_wait(&b.owned);
drop(forced);
assert!(is_foreign(&outcome), "another process holds the pid: {outcome:?}");
for read in [UniqRead::Refused(libc::EPERM), found(unique)] {
let forced = uniq_fault::force_uniq_read_once(ReadPurpose::Running, read);
assert_eq!(
try_wait(&b.owned).expect("try_wait"),
ChildWaitOutcome::DeadlinePassed,
"{read:?}"
);
drop(forced);
}
b.end_child();
wait_status(&b.owned);
}
#[skuld::test]
fn the_kqueue_wait_keeps_waiting_for_a_child_that_answers_echild_yet_resolves() {
use crate::wait::macos::{await_reapable, Waited};
let (pid, unique) = echild_yet_resolvable();
let _forced = (held_by_a_tracer(), held_by_a_tracer());
let waited = await_reapable(pid, Some(unique), Some(Instant::now())).expect("wait");
assert_eq!(waited, Waited::DeadlinePassed);
}
#[skuld::test]
fn the_kqueue_wait_reports_gone_for_a_pid_with_another_unique_id() {
use crate::wait::macos::{await_reapable, Waited};
let (pid, unique) = echild_yet_resolvable();
let waited = await_reapable(pid, Some(unique ^ 1), Some(Instant::now())).expect("wait");
assert_eq!(waited, Waited::Gone);
}
#[skuld::test]
fn a_wait_on_a_zombie_launchd_holds_warns_it_is_not_ours_to_reap() {
crate::log_capture::install();
let (stdin, writer) = crate::test_child::held_writer_stdin();
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
cmd.stdin(stdin).expect("set stdin");
let mut child = cmd.spawn().expect("spawn");
let pid = child.pid();
drop(writer);
crate::test_child::wait_until_zombie(pid);
let mark = crate::log_capture::mark();
child
.proc
.script_over(|f| f.reaps([crate::os_process::fake::ReapAnswer::Foreign(Foreign::Orphaned)]));
_ = child.wait();
let records = crate::log_capture::records_since_on_current_thread(mark, &format!("pid {pid}"));
assert!(
records
.iter()
.any(|(level, text)| *level == log::Level::Warn && text.contains("not ours to reap")),
"{records:?}"
);
drop(child);
}
#[skuld::test]
fn a_reap_that_finds_no_exit_record_after_the_peek_saw_one_looks_again() {
let mut b = Blocker::spawn();
b.end_child_and_confirm_exit();
let _forced = exit_seams::force_peeks([
Ok(PeekOutcome::Exit(crate::os_process::child::ExitRecord::Status(
std::process::ExitStatus::default(),
))),
Ok(PeekOutcome::Running),
]);
crate::wait::block_probe::take();
let status = wait_status(&b.owned);
assert!(status.success(), "{status:?}");
exit_seams::assert_peeks_exhausted();
assert!(
!crate::wait::block_probe::take().is_empty(),
"the second look follows a backoff"
);
}
fn spawn_root_child() -> (std::process::Child, std::process::ChildStdin) {
use std::io::Read as _;
let helper = crate::test_privilege::setuid::setuid_helper();
let mut cmd = std::process::Command::new(helper);
cmd.args(["setuid-stdin-block", "root"])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null());
let mut child = crate::test_spawn::spawn(&mut cmd).expect("spawn the setuid helper");
let stdin = child.stdin.take().expect("piped stdin");
let mut ready = [0u8; 1];
child
.stdout
.take()
.expect("piped stdout")
.read_exact(&mut ready)
.expect("the helper reports ready");
assert_eq!(ready, *b"+");
(child, stdin)
}
#[skuld::test]
fn setuid_kill_of_a_root_child_is_permission_denied(#[fixture(setuid)] _group: &Group) {
let (child, stdin) = spawn_root_child();
let id = super::fixtures::identity_of(&child);
unique_of(id.pid());
let owned = OwnedChild::adopt(child, id).unwrap_or_else(|(e, _)| panic!("adopt: {e}"));
let err = owned
.signal(Sig::Kill)
.expect_err("this caller may not signal a root process")
.into_io();
assert_eq!(err.kind(), std::io::ErrorKind::PermissionDenied, "{err}");
drop(stdin);
let status = wait_status(&owned);
assert!(status.success(), "{status:?}");
}
#[skuld::test]
fn setuid_child_kill_is_permission_denied(#[fixture(setuid)] _group: &Group) {
let (child, stdin) = crate::test_privilege::spawn_setuid_blocker();
let err = child.kill().expect_err("this caller may not signal a root process");
assert!(
matches!(&err, crate::error::Error::Io(e) if e.kind() == std::io::ErrorKind::PermissionDenied),
"{err:?}"
);
drop(stdin);
let status = child.wait().expect("the helper exits on EOF");
assert!(status.success(), "{status:?}");
}
#[skuld::test]
fn a_refused_id_read_at_the_exit_check_consumes_nothing() {
let mut b = Blocker::spawn();
b.end_child_and_confirm_exit();
let forced = uniq_fault::force_uniq_read_once(ReadPurpose::Peek, UniqRead::Refused(libc::EPERM));
let err = try_wait(&b.owned)
.expect_err("an unverifiable exit is not consumed")
.into_io();
drop(forced);
assert_eq!(err.kind(), std::io::ErrorKind::PermissionDenied, "{err}");
let forced = uniq_fault::force_uniq_read_once(ReadPurpose::Peek, UniqRead::Refused(libc::EACCES));
let err = b.owned.wait(None).expect_err("nor by a wait").into_io();
drop(forced);
assert_eq!(err.kind(), std::io::ErrorKind::PermissionDenied, "{err}");
let status = wait_status(&b.owned);
assert!(status.success(), "{status:?}");
}
#[skuld::test]
fn a_try_wait_during_a_holders_wait_does_not_strand_the_holder() {
let mut b = Blocker::spawn();
let (reached_tx, reached_rx) = std::sync::mpsc::channel();
let (staged_tx, staged_rx) = std::sync::mpsc::channel::<()>();
let holder = std::thread::spawn({
let owned = std::sync::Arc::clone(&b.owned);
move || {
let _blocking = crate::wait::block_probe::on_blocking(move || {
_ = reached_tx.send(());
staged_rx.recv().expect("the test stages the exit");
});
owned.wait(None)
}
});
reached_rx.recv().expect("the holder must reach its wait");
b.end_child_and_confirm_exit();
let peeked = status(try_wait(&b.owned));
assert!(peeked.success(), "{peeked:?}");
staged_tx.send(()).expect("the holder is waiting for the stage");
let status = status(holder.join().expect("holder"));
assert!(status.success(), "{status:?}");
}
#[skuld::test]
fn try_wait_during_a_wait_errors_when_a_running_childs_unique_id_is_unreadable() {
let mut b = Blocker::spawn();
let (reached_tx, reached_rx) = std::sync::mpsc::channel();
let holder = std::thread::spawn({
let owned = std::sync::Arc::clone(&b.owned);
move || {
let _blocking = crate::wait::block_probe::on_blocking(move || _ = reached_tx.send(()));
owned.wait(None)
}
});
reached_rx.recv().expect("the holder must reach its wait");
let forced = uniq_fault::force_uniq_read_once(ReadPurpose::Running, UniqRead::Refused(libc::EPERM));
let err = try_wait(&b.owned)
.expect_err("a running child that cannot be shown to be ours")
.into_io();
drop(forced);
assert_eq!(err.kind(), std::io::ErrorKind::PermissionDenied, "{err}");
b.end_child();
let status = status(holder.join().expect("holder"));
assert!(status.success(), "{status:?}");
}
#[skuld::test]
fn a_try_wait_that_drains_note_exit_then_a_wait_still_returns() {
let mut b = Blocker::spawn();
b.end_child_and_confirm_exit();
let forced = exit_seams::force_peeks([Ok(PeekOutcome::Running), Ok(PeekOutcome::Running)]);
assert_eq!(try_wait(&b.owned).expect("try_wait"), ChildWaitOutcome::DeadlinePassed);
let status = wait_status(&b.owned);
drop(forced);
assert!(status.success(), "{status:?}");
exit_seams::assert_peeks_exhausted();
}