use std::cell::{Cell, RefCell};
use crate::test_child::Console;
use std::io::Read;
use std::os::fd::OwnedFd;
use std::rc::Rc;
use rustix::io::Errno;
use rustix::net::ReturnFlags;
use super::fault::{self, ChildFault};
use super::{classify_send, parse_report, Delivery, Outcome, Report, REPORT_ERRNO, REPORT_LEN, REPORT_PIDFD};
use crate::child::spawn::failure::expect_not_started;
use crate::child::spawn::SpawnFailure;
use crate::command::Command;
use crate::error::ChildFate;
use crate::error::Error;
use crate::identity::FakeKernel;
use crate::os_process::linux::open::probe_pidfd_support_with;
use crate::stdio::Stdio;
use crate::test_child::fixture_path;
use crate::test_child::namespaces as ns;
use crate::test_groups::{namespaces, setuid, Group};
fn marker_command() -> (Command, std::io::PipeReader) {
let (reader, writer) = std::io::pipe().expect("pipe");
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(["sh", "-c", "echo ran"]);
cmd.stdout(Stdio::from_file(std::fs::File::from(OwnedFd::from(writer))))
.expect("set stdout");
(cmd, reader)
}
fn program_ran(cmd: Command, mut reader: std::io::PipeReader) -> bool {
drop(cmd);
let mut out = String::new();
reader.read_to_string(&mut out).expect("read the marker to EOF");
out == "ran\n"
}
pub(crate) fn assert_no_child_of_this_thread(what: &str) {
let rc = unsafe {
libc::waitid(
libc::P_ALL,
0,
std::ptr::null_mut(),
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT | libc::__WNOTHREAD,
)
};
let err = std::io::Error::last_os_error();
assert!(
rc == -1 && err.raw_os_error() == Some(libc::ECHILD),
"{what}: this thread must have no child, got rc {rc} ({err})"
);
}
fn raw_command(program: &str) -> (std::process::Command, super::Pending) {
let mut std_cmd = std::process::Command::new(program);
let pending = super::register(&mut std_cmd);
(std_cmd, pending)
}
fn assert_ends_closed(ends: Option<fault::Ends>, what: &str) -> fault::Ends {
let ends = ends.unwrap_or_else(|| panic!("{what}: the end probes saw no run"));
assert!(
!ends.child_end_copy_held,
"{what}: the spawning thread must close its copy of the child's end as soon as spawn() returns"
);
assert!(
ends.eof_reached,
"{what}: the helper must read EOF once the wait for the child is over"
);
ends
}
#[skuld::test]
fn a_normal_spawn_runs_the_program_and_forks_once() {
let (mut cmd, reader) = marker_command();
fault::reset_spawns();
let probes = fault::arm_end_probes();
let child = cmd.spawn().expect("a normal spawn succeeds");
drop(probes);
assert_ends_closed(fault::take_ends(), "a normal spawn");
assert_eq!(fault::spawns(), 1);
assert!(child.wait().expect("wait").success());
assert_no_child_of_this_thread("after the wait");
assert!(program_ran(cmd, reader));
}
#[skuld::test]
fn a_refused_probe_fails_unsupported() {
for (errno, name) in [
(Errno::PERM, "EPERM"),
(Errno::ACCESS, "EACCES"),
(Errno::NODEV, "ENODEV"),
(Errno::NOSYS, "ENOSYS"),
] {
let kernel = FakeKernel::new().on_pidfd_open(std::process::id(), Err(errno));
let err = probe_pidfd_support_with(&kernel).expect_err("a refused pidfd_open must fail the probe");
assert_eq!(
err.to_string(),
format!(
"spawn is not supported on linux: cosca requires pidfd_open (Linux \u{2265} 5.3), \
refused here: pidfd_open answered {name}"
),
"{err:?}"
);
}
}
#[skuld::test]
fn a_probe_that_hits_emfile_fails_io() {
let kernel = FakeKernel::new().on_pidfd_open(std::process::id(), Err(Errno::MFILE));
match probe_pidfd_support_with(&kernel).expect_err("a failed probe must fail") {
Error::Io(e) => assert_eq!(e.to_string(), "pidfd_open: Too many open files (os error 24)"),
other => panic!("expected Io, got {other:?}"),
}
}
#[skuld::test]
fn emfile_in_the_child_fails_io_and_the_program_never_runs() {
let (mut cmd, reader) = marker_command();
fault::reset_spawns();
fault::reset_leaked_pid();
let forced = fault::fail_child_pidfd_open(Errno::MFILE);
let err = cmd.spawn().err();
drop(forced);
match err.expect("a failed pidfd_open must fail the spawn") {
Error::Io(e) => assert_eq!(e.to_string(), "pidfd_open: Too many open files (os error 24)"),
other => panic!("expected Io, got {other:?}"),
}
assert_eq!(fault::spawns(), 1, "the child was forked and held");
assert_eq!(fault::take_leaked_pid(), None, "std collected the aborted child");
assert_no_child_of_this_thread("after the abort");
assert!(!program_ran(cmd, reader), "the aborted child must never exec");
}
#[skuld::test]
fn a_refusal_in_the_child_is_unsupported_and_the_program_never_runs() {
let (mut cmd, reader) = marker_command();
fault::reset_spawns();
let forced = fault::fail_child_pidfd_open(Errno::PERM);
let err = cmd.spawn().err();
drop(forced);
let err = err.expect("a refused pidfd_open must fail the spawn");
assert_eq!(
err.to_string(),
"spawn is not supported on linux: cosca requires pidfd_open (Linux \u{2265} 5.3), \
refused here: pidfd_open answered EPERM",
"{err:?}"
);
assert_eq!(fault::spawns(), 1);
assert_no_child_of_this_thread("after the abort");
assert!(!program_ran(cmd, reader));
}
#[skuld::test]
fn a_truncated_report_is_an_error_and_a_whole_one_is_read() {
let fd = || OwnedFd::from(std::fs::File::open("/dev/null").expect("open /dev/null"));
let message = |tag: i32, value: i32| {
let mut message = [0u8; REPORT_LEN];
message[..4].copy_from_slice(&tag.to_ne_bytes());
message[4..].copy_from_slice(&value.to_ne_bytes());
message
};
let truncated = parse_report(REPORT_LEN, ReturnFlags::CTRUNC, &message(REPORT_PIDFD, 0), vec![], 0);
match truncated {
Err(Error::Io(e)) => assert!(e.to_string().contains("could not be received"), "{e}"),
other => panic!("a truncated report must be an error, got {other:?}"),
}
assert!(matches!(
parse_report(
REPORT_LEN,
ReturnFlags::empty(),
&message(REPORT_PIDFD, 0),
vec![fd()],
0
),
Ok(Report::Pidfd(_))
));
assert!(matches!(
parse_report(
REPORT_LEN,
ReturnFlags::empty(),
&message(REPORT_ERRNO, libc::EPERM),
vec![],
0
),
Ok(Report::Errno(Errno::PERM))
));
assert!(matches!(
parse_report(0, ReturnFlags::empty(), &[0; REPORT_LEN], vec![], 0),
Ok(Report::Eof)
));
}
#[skuld::test]
fn only_a_closed_end_makes_an_undelivered_go_mean_gone() {
assert!(matches!(classify_send(Ok(1)), Some(Delivery::Delivered)));
assert!(classify_send(Err(Errno::INTR)).is_none(), "EINTR must send again");
for errno in [Errno::PIPE, Errno::CONNRESET] {
assert!(matches!(classify_send(Err(errno)), Some(Delivery::Gone)), "{errno:?}");
}
for errno in [Errno::NOBUFS, Errno::NOMEM, Errno::AGAIN] {
match classify_send(Err(errno)) {
Some(Delivery::Failed(e)) => assert_eq!(e.raw_os_error(), Some(errno.raw_os_error())),
other => panic!("{errno:?} must fail the spawn, got {other:?}"),
}
}
}
#[skuld::test]
fn an_undelivered_go_ahead_fails_the_spawn_and_ends_the_childs_wait() {
let (mut cmd, reader) = marker_command();
let holder = fault::arm_fork_holder();
let forced = fault::force_go_send_errnos([Errno::NOBUFS]);
let err = cmd.spawn().err();
drop(forced);
let shut = fault::parent_end_shut();
drop(holder);
assert_eq!(
shut,
Some(true),
"the helper must shut the parent's end, whatever copies of it exist"
);
match err.expect("an undelivered go-ahead must fail the spawn") {
Error::Io(e) => assert_eq!(
e.to_string(),
"pidfd handshake: sending the child its go-ahead: No buffer space available (os error 105)"
),
other => panic!("expected Io, got {other:?}"),
}
assert_no_child_of_this_thread("std collected the aborted child");
assert!(!program_ran(cmd, reader));
}
#[skuld::test]
fn a_child_gone_before_its_go_ahead_fails_the_spawn_and_is_reaped() {
let (mut cmd, reader) = marker_command();
let armed = fault::arm_child_fault(ChildFault::SigkillAfterReport);
let held = fault::hold_verdict_until_spawn_returns(|_| {});
let err = cmd.spawn().err();
drop(held);
drop(armed);
let err = expect_not_started(err.expect("a child that never ran the program must fail the spawn"));
assert!(
err.to_string().ends_with("died before exec: the program never ran"),
"{err}"
);
assert_no_child_of_this_thread("the child is reaped through its pidfd");
assert!(!program_ran(cmd, reader));
}
#[skuld::test]
fn a_spawn_that_fails_after_the_child_execed_kills_and_reaps_it() {
let (reader, writer) = std::io::pipe().expect("pipe");
let (mut std_cmd, pending) = raw_command(crate::test_child::BLOCKER_ARGV[0]);
std_cmd
.args(&crate::test_child::BLOCKER_ARGV[1..])
.stdin(std::process::Stdio::from(OwnedFd::from(reader)))
.stdout(std::process::Stdio::null());
let teardown = crate::child::spawn::fault::release_between_kill_and_wait(writer);
let guard = super::super::spawn_lock();
let handshake = pending.open(&guard).expect("open");
#[allow(clippy::disallowed_methods, reason = "spawn_lock is held by `guard`")]
let result = handshake.run(|| {
let child = std_cmd.spawn()?;
drop(child);
Err::<std::process::Child, _>(std::io::Error::other("post-fork failure (test)"))
});
drop(guard);
match result {
Err(SpawnFailure::NotStarted(Error::Io(e))) => assert_eq!(e.to_string(), "post-fork failure (test)"),
other => panic!("expected the spawn's own error, got {:?}", other.err()),
}
teardown.assert_killed();
let recorded = teardown.recorded();
assert_eq!(recorded.len(), 1, "{recorded:?}");
assert_no_child_of_this_thread("the child is reaped through its pidfd");
}
#[skuld::test]
fn a_later_hook_failure_leaves_nothing_to_kill() {
let (mut std_cmd, pending) = raw_command("true");
unsafe {
std::os::unix::process::CommandExt::pre_exec(&mut std_cmd, || {
Err(std::io::Error::from_raw_os_error(libc::EIO))
});
}
let fired = Rc::new(Cell::new(false));
let hook = crate::child::spawn::fault::set_between_kill_and_wait({
let fired = Rc::clone(&fired);
move || fired.set(true)
});
let guard = super::super::spawn_lock();
let handshake = pending.open(&guard).expect("open");
#[allow(clippy::disallowed_methods, reason = "spawn_lock is held by `guard`")]
let result = handshake.run(|| std_cmd.spawn());
drop(guard);
drop(hook);
match result {
Err(SpawnFailure::NotStarted(Error::Io(e))) => assert_eq!(e.raw_os_error(), Some(libc::EIO), "{e:?}"),
other => panic!(
"expected the hook's error, got {:?}",
other.err().map(|e| Error::from(e).to_string())
),
}
assert!(!fired.get(), "a child std collected must not be signalled");
assert_no_child_of_this_thread("std collected the child");
}
#[skuld::test]
fn a_child_that_fails_before_reporting_ends_the_spawn() {
let (mut cmd, reader) = marker_command();
let armed = fault::arm_child_fault(ChildFault::Fail);
let probes = fault::arm_end_probes();
let err = cmd.spawn().err();
drop(probes);
assert_ends_closed(fault::take_ends(), "a child that fails before reporting");
drop(armed);
match err.expect("a child that fails before exec fails the spawn") {
Error::Io(e) => assert_eq!(e.raw_os_error(), Some(libc::EIO), "{e:?}"),
other => panic!("expected Io, got {other:?}"),
}
assert_no_child_of_this_thread("std collected the failed child");
assert!(!program_ran(cmd, reader));
}
#[skuld::test]
fn eof_reaches_the_helper_through_a_forked_copy_of_the_childs_end() {
let (mut cmd, reader) = marker_command();
let holder = fault::arm_fork_holder();
let armed = fault::arm_child_fault(ChildFault::Fail);
let probes = fault::arm_end_probes();
let err = cmd.spawn().err();
drop(probes);
drop(armed);
let ends = assert_ends_closed(fault::take_ends(), "a failed spawn with a forked copy");
drop(holder);
assert!(ends.eof_forced, "only a forced EOF reaches the helper through the copy");
match err.expect("a child that fails before exec fails the spawn") {
Error::Io(e) => assert_eq!(e.raw_os_error(), Some(libc::EIO), "{e:?}"),
other => panic!("expected Io, got {other:?}"),
}
assert_no_child_of_this_thread("std collected the failed child");
assert!(!program_ran(cmd, reader));
}
#[skuld::test]
fn eof_reaches_the_helper_when_a_killed_child_leaves_a_forked_copy() {
let (mut cmd, reader) = marker_command();
fault::reset_leaked_pid();
let holder = fault::arm_fork_holder();
let armed = fault::arm_child_fault(ChildFault::Sigkill);
let probes = fault::arm_end_probes();
let err = cmd.spawn().err();
drop(probes);
drop(armed);
let ends = assert_ends_closed(fault::take_ends(), "a killed child with a forked copy");
drop(holder);
assert!(ends.eof_forced, "only a forced EOF reaches the helper through the copy");
assert!(matches!(err, Some(Error::Io(_))), "{err:?}");
let pid = fault::take_leaked_pid()
.expect("the unreaped child is named")
.expect("it has a pid");
let reaped = unsafe { libc::waitpid(pid as i32, std::ptr::null_mut(), 0) };
assert_eq!(reaped, pid as i32);
assert!(!program_ran(cmd, reader));
}
#[skuld::test]
fn a_spawn_that_returns_before_the_hooks_run_still_runs_the_program() {
use std::io::{Seek, Write};
use std::os::fd::AsRawFd;
use crate::test_own_process::{own_process, test_path};
use crate::test_spawn::spawn;
use crate::test_stdio::RestoreStdio;
let Some(done) = own_process(
test_path!(a_spawn_that_returns_before_the_hooks_run_still_runs_the_program),
spawn,
) else {
return;
};
let mut file = tempfile::tempfile().expect("tempfile");
let (gate_read, gate_write) = std::io::pipe().expect("open the gate");
let gate_write = Rc::new(RefCell::new(Some(gate_write)));
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(["sh", "-c", "echo ran"]);
for slot in [1, 2] {
cmd.fd(slot, Stdio::from_file(file.try_clone().expect("clone the file")))
.expect("wire the slot to the file");
}
let armed = fault::arm_child_fault(ChildFault::Gate(gate_read.as_raw_fd()));
let probes = fault::arm_end_probes();
let release_gate = {
let gate_write = Rc::clone(&gate_write);
move || {
if let Some(mut gate) = gate_write.borrow_mut().take() {
gate.write_all(b"x").expect("release the child");
}
}
};
let release = fault::before_awaiting_the_child_do(release_gate.clone());
let released_at_the_end = fault::wait_over_do(release_gate);
let restore = RestoreStdio::close(&done, &[1, 2]);
let spawned = cmd.spawn();
drop(restore);
drop(release);
drop(released_at_the_end);
drop(probes);
drop(armed);
if let Some(mut gate) = gate_write.borrow_mut().take() {
gate.write_all(b"x").expect("release the child");
}
assert_ends_closed(fault::take_ends(), "a spawn that returns before the hooks run");
let child = spawned.expect("the spawn must succeed");
assert!(child.wait().expect("wait").success());
let mut written = String::new();
file.rewind().expect("rewind the file");
file.read_to_string(&mut written).expect("read the file");
assert_eq!(written, "ran\n");
}
#[skuld::test]
fn a_child_killed_before_reporting_is_left_unreaped_and_named() {
use std::os::unix::process::ExitStatusExt;
let (mut cmd, reader) = marker_command();
fault::reset_leaked_pid();
let armed = fault::arm_child_fault(ChildFault::Sigkill);
let probes = fault::arm_end_probes();
let err = cmd.spawn().err();
drop(probes);
drop(armed);
assert_ends_closed(fault::take_ends(), "a child killed before it reports");
let err = err.expect("a child killed before it reports fails the spawn");
let pid = fault::take_leaked_pid()
.expect("the unreaped child is named")
.expect("it has a pid");
assert_eq!(
err.to_string(),
format!("the spawned child (pid {pid}) died before it could send its pidfd")
);
let mut status = 0;
let reaped = unsafe { libc::waitpid(pid as i32, &mut status, 0) };
assert_eq!(reaped, pid as i32);
assert_eq!(std::process::ExitStatus::from_raw(status).signal(), Some(libc::SIGKILL));
assert!(!program_ran(cmd, reader));
}
fn killed_child_with_a_failing_watch(fault_kind: fault::WatchFault) -> String {
let (mut cmd, reader) = marker_command();
fault::reset_leaked_pid();
let holder = fault::arm_fork_holder();
let armed = fault::arm_child_fault(ChildFault::Sigkill);
let watch = fault::fail_watch(fault_kind);
let probes = fault::arm_end_probes();
let err = cmd.spawn().err();
drop(probes);
drop(watch);
drop(armed);
let ends = fault::take_ends();
drop(holder);
let ends = assert_ends_closed(ends, &format!("a killed child, a held copy and {fault_kind:?}"));
assert!(
ends.eof_forced,
"{fault_kind:?}: only a forced EOF reaches the helper through the copy"
);
let err = err
.expect("a child killed before it reports fails the spawn")
.to_string();
if let Some(Some(pid)) = fault::take_leaked_pid() {
let reaped = unsafe { libc::waitpid(pid as i32, std::ptr::null_mut(), 0) };
assert_eq!(reaped, pid as i32);
}
assert!(!program_ran(cmd, reader));
err
}
#[skuld::test]
fn a_watch_that_cannot_be_set_up_forces_eof_and_names_the_cause() {
for fault_kind in [
fault::WatchFault::Open(Errno::MFILE),
fault::WatchFault::Open(Errno::NFILE),
fault::WatchFault::Open(Errno::NOMEM),
fault::WatchFault::Move(Errno::MFILE),
fault::WatchFault::Peek(Errno::INVAL),
fault::WatchFault::Poll(Errno::INVAL),
] {
let (fault::WatchFault::Open(errno)
| fault::WatchFault::Move(errno)
| fault::WatchFault::Peek(errno)
| fault::WatchFault::Poll(errno)) = fault_kind;
let said = killed_child_with_a_failing_watch(fault_kind);
assert!(
said.contains("its exit could not be watched") && said.contains(&errno.to_string()),
"{fault_kind:?}: {said}"
);
}
}
#[skuld::test]
fn a_number_that_names_no_child_forces_eof() {
for errno in [Errno::SRCH, Errno::NOENT, Errno::INVAL] {
let said = killed_child_with_a_failing_watch(fault::WatchFault::Open(errno));
assert!(said.ends_with("died before it could send its pidfd"), "{errno}: {said}");
}
}
#[skuld::test]
fn a_spawn_that_fails_before_the_fork_ends_the_helper() {
let (_std_cmd, pending) = raw_command("true");
let guard = super::super::spawn_lock();
let handshake = pending.open(&guard).expect("open");
let probes = fault::arm_end_probes();
let result = handshake.run(|| Err::<std::process::Child, _>(std::io::Error::other("failed before the fork")));
drop(probes);
assert_ends_closed(fault::take_ends(), "a spawn that fails before the fork");
drop(guard);
match result {
Err(SpawnFailure::NotStarted(Error::Io(e))) => assert_eq!(e.to_string(), "failed before the fork"),
other => panic!("expected the spawn's own error, got {:?}", other.err()),
}
}
#[skuld::test]
fn the_helper_is_joined_before_the_spawn_returns() {
let (mut cmd, reader) = marker_command();
let probe = fault::arm_helper_probe();
let child = cmd.spawn().expect("spawn");
assert!(
probe.finished(),
"the helper thread must be joined before spawn returns"
);
assert!(child.wait().expect("wait").success());
assert!(program_ran(cmd, reader));
}
#[skuld::test]
fn a_panic_after_the_spawn_still_fires_the_wait_over_hook() {
use std::panic::{catch_unwind, AssertUnwindSafe};
let (mut cmd, _reader) = marker_command();
let fired = Rc::new(std::cell::Cell::new(false));
let after = fault::after_spawn_returns_do(|_| panic!("the after-spawn hook panicked on purpose"));
let over = fault::wait_over_do({
let fired = Rc::clone(&fired);
move || fired.set(true)
});
let result = catch_unwind(AssertUnwindSafe(|| cmd.spawn().err()));
drop(over);
drop(after);
assert!(result.is_err(), "the hook's panic goes on");
assert!(fired.get(), "the wait-over hook must fire on the way out");
}
#[skuld::test]
fn a_panic_after_the_spawn_still_opens_the_helper_probe() {
use std::panic::{catch_unwind, AssertUnwindSafe};
let (mut cmd, _reader) = marker_command();
let probe = fault::arm_helper_probe();
let after = fault::after_spawn_returns_do(|_| panic!("the after-spawn hook panicked on purpose"));
let result = catch_unwind(AssertUnwindSafe(|| cmd.spawn().err()));
drop(after);
assert!(result.is_err(), "the hook's panic goes on");
assert!(probe.finished(), "the helper must have run to its end");
let unwound = fault::take_unwound().expect("the run unwound");
assert_eq!(
unwound.probe_open,
Some(true),
"the probe's gate must be open by the time the unwind guards are done, not at the join"
);
}
#[skuld::test]
fn a_panic_after_the_spawn_forces_eof_through_a_held_copy() {
use std::panic::{catch_unwind, AssertUnwindSafe};
let (mut cmd, _reader) = marker_command();
let holder = fault::arm_fork_holder();
let armed = fault::arm_child_fault(ChildFault::Sigkill);
let after = fault::after_spawn_returns_do(|_| panic!("the after-spawn hook panicked on purpose"));
let result = catch_unwind(AssertUnwindSafe(|| cmd.spawn().err()));
drop(after);
drop(armed);
let unwound = fault::take_unwound();
drop(holder);
assert!(result.is_err(), "the hook's panic goes on");
assert_eq!(
unwound.map(|u| u.eof_reached),
Some(true),
"the helper must read EOF by the time the unwind guards are done"
);
}
#[skuld::test]
fn a_panic_inside_the_wait_forces_eof_through_a_held_copy() {
use std::panic::{catch_unwind, AssertUnwindSafe};
let (mut cmd, _reader) = marker_command();
let holder = fault::arm_fork_holder();
let armed = fault::arm_child_fault(ChildFault::Sigkill);
let watch = fault::fail_watch(fault::WatchFault::Poll(Errno::INVAL));
let before = fault::before_awaiting_the_child_do(|| panic!("the wait's hook panicked on purpose"));
let result = catch_unwind(AssertUnwindSafe(|| cmd.spawn().err()));
drop(before);
drop(watch);
drop(armed);
let unwound = fault::take_unwound();
drop(holder);
assert!(result.is_err(), "the hook's panic goes on");
assert_eq!(
unwound.map(|u| u.eof_reached),
Some(true),
"the helper must read EOF by the time the unwind guards are done"
);
}
fn own_procfs() {
ns::enter_private_mount_ns();
ns::mount_proc(std::path::Path::new("/proc"));
}
#[skuld::test]
fn namespaces_a_reused_number_never_reaches_the_handshake(#[fixture(namespaces)] _group: &Group) {
ns::run(fixture_path!(fixture_reused_number_driver));
}
#[skuld::test]
fn fixture_reused_number_driver() {
if !ns::is_child() {
return;
}
ns::enter_new_pid_ns_for_children();
ns::run(fixture_path!(fixture_reused_number_init));
}
#[skuld::test]
fn fixture_reused_number_init() {
if !ns::is_child_in_new_pid_ns() {
return;
}
own_procfs();
let (mut cmd, reader) = marker_command();
let reuser: Rc<RefCell<Option<std::process::Child>>> = Rc::default();
let armed = fault::arm_child_fault(ChildFault::SigkillAfterReport);
let held = fault::hold_verdict_until_spawn_returns({
let reuser = Rc::clone(&reuser);
move |pid| {
let pid = pid.expect("the spawned child's pid");
let mut status = 0;
let reaped = unsafe { libc::waitpid(pid as i32, &mut status, 0) };
assert_eq!(
reaped,
pid as i32,
"reap the child: {}",
std::io::Error::last_os_error()
);
ns::set_last_pid(pid - 1);
#[allow(clippy::disallowed_methods, reason = "the enclosing cosca spawn holds spawn_lock")]
let next = std::process::Command::new("cat")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::null())
.spawn()
.expect("spawn the reuser");
assert_eq!(
next.id(),
pid,
"precondition: the reuser takes the reaped child's number"
);
*reuser.borrow_mut() = Some(next);
}
});
let err = cmd.spawn().err();
drop(held);
drop(armed);
let mut reuser = reuser.borrow_mut().take().expect("the verdict hook ran");
let untouched = reuser.try_wait();
assert!(
matches!(untouched, Ok(None)),
"the reuser of the number must be neither signalled nor reaped, got {untouched:?}"
);
let err = err.expect("a child that never ran the program must fail the spawn");
assert!(
err.to_string().ends_with("died before exec: the program never ran"),
"{err}"
);
reuser.kill().expect("kill the reuser");
reuser.wait().expect("reap the reuser");
assert!(!program_ran(cmd, reader));
}
#[skuld::test]
fn namespaces_a_reused_number_never_holds_the_spawn_when_the_child_dies_unreported(
#[fixture(namespaces)] _group: &Group,
) {
ns::run(fixture_path!(fixture_unreported_death_driver));
}
#[skuld::test]
fn fixture_unreported_death_driver() {
if !ns::is_child() {
return;
}
ns::enter_new_pid_ns_for_children();
ns::run(fixture_path!(fixture_unreported_death_init));
}
#[skuld::test]
fn fixture_unreported_death_init() {
if !ns::is_child_in_new_pid_ns() {
return;
}
own_procfs();
let (mut cmd, reader) = marker_command();
fault::reset_leaked_pid();
let reuser: Rc<RefCell<Option<std::process::Child>>> = Rc::default();
let armed = fault::arm_child_fault(ChildFault::Sigkill);
let probes = fault::arm_end_probes();
let after = fault::after_spawn_returns_do({
let reuser = Rc::clone(&reuser);
move |pid| {
let pid = pid.expect("the spawned child's pid");
let reaped = unsafe { libc::waitpid(pid as i32, std::ptr::null_mut(), 0) };
assert_eq!(
reaped,
pid as i32,
"reap the child: {}",
std::io::Error::last_os_error()
);
ns::set_last_pid(pid - 1);
#[allow(clippy::disallowed_methods, reason = "the enclosing cosca spawn holds spawn_lock")]
let next = std::process::Command::new("cat")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::null())
.spawn()
.expect("spawn the reuser");
assert_eq!(
next.id(),
pid,
"precondition: the reuser takes the reaped child's number"
);
*reuser.borrow_mut() = Some(next);
}
});
let err = cmd.spawn().err();
drop(after);
drop(probes);
drop(armed);
let mut reuser = reuser.borrow_mut().take().expect("the after-spawn hook ran");
let running = reuser.try_wait();
let ends = fault::take_ends();
reuser.kill().expect("kill the reuser");
reuser.wait().expect("reap the reuser");
assert!(
matches!(running, Ok(None)),
"the spawn returned only once the reuser exited: {running:?}"
);
assert_ends_closed(ends, "a child that died before reporting");
let err = err.expect("a child that died before reporting fails the spawn");
assert_eq!(
err.to_string(),
format!(
"the spawned child (pid {}) died before it could send its pidfd",
reuser.id()
)
);
assert!(!program_ran(cmd, reader));
}
#[skuld::test]
#[should_panic(expected = "the verdict hook panicked on purpose")]
fn a_panicking_verdict_hook_fails_the_spawn_instead_of_hanging_it() {
let (mut cmd, _reader) = marker_command();
let armed = fault::arm_child_fault(ChildFault::SigkillAfterReport);
let held = fault::hold_verdict_until_spawn_returns(|_| panic!("the verdict hook panicked on purpose"));
drop(cmd.spawn());
drop(held);
drop(armed);
}
#[skuld::test]
fn the_verdict_hook_runs_under_a_guard_that_opens_the_hold() {
let (mut cmd, _reader) = marker_command();
let guarded = Rc::new(Cell::new(None));
let armed = fault::arm_child_fault(ChildFault::SigkillAfterReport);
let held = fault::hold_verdict_until_spawn_returns({
let guarded = Rc::clone(&guarded);
move |_| guarded.set(Some(fault::verdict_guarded()))
});
drop(cmd.spawn());
drop(held);
drop(armed);
assert_eq!(guarded.get(), Some(true), "the hook ran, under the guard");
assert!(!fault::verdict_guarded(), "the guard is gone once the spawn returns");
}
#[skuld::test]
fn namespaces_a_spawn_from_a_thread_that_unshared_its_pid_namespace_names_the_cause(
#[fixture(namespaces)] _group: &Group,
) {
ns::run(fixture_path!(fixture_unshared_thread));
}
#[skuld::test]
fn fixture_unshared_thread() {
if !ns::is_child() {
return;
}
ns::enter_new_pid_ns_for_children();
let (mut cmd, reader) = marker_command();
fault::reset_spawns();
let Err(err) = cmd.spawn() else {
panic!("the spawn must fail");
};
assert!(
err.to_string().starts_with(
"starting the pidfd handshake thread (Linux refuses new threads to a thread that has \
unshared or entered a pid or time namespace for its children"
),
"{err}"
);
assert_eq!(fault::spawns(), 0, "nothing may be forked");
assert!(!program_ran(cmd, reader));
}
fn help_with_report(seams: &fault::HelperSeams) -> Outcome {
let (parent_end, child_end) = rustix::net::socketpair(
rustix::net::AddressFamily::UNIX,
rustix::net::SocketType::SEQPACKET,
rustix::net::SocketFlags::CLOEXEC,
None,
)
.expect("socketpair");
let pidfd = rustix::process::pidfd_open(rustix::process::getpid(), rustix::process::PidfdFlags::empty())
.expect("a pidfd on this process");
super::send_report(
std::os::fd::AsRawFd::as_raw_fd(&child_end),
REPORT_PIDFD,
0,
std::os::fd::AsRawFd::as_raw_fd(&pidfd),
)
.expect("send the report");
drop(pidfd);
super::help(&parent_end, seams)
}
#[skuld::test]
fn a_pidfd_that_cannot_move_above_stdio_is_still_handed_on() {
let seams = fault::HelperSeams::failing_move(Errno::MFILE);
match help_with_report(&seams) {
Outcome::Failed(Error::Io(e), Some(_)) => assert_eq!(e.raw_os_error(), Some(libc::EMFILE), "{e:?}"),
Outcome::Failed(e, pidfd) => panic!("expected EMFILE with the pidfd, got {e:?}, pidfd {}", pidfd.is_some()),
_ => panic!("a failed move must fail the spawn"),
}
}
#[skuld::test]
fn an_abandoned_child_is_worded_by_its_cause() {
crate::log_capture::install();
let ended_cat = || {
let (mut cat, _pidfd) = cat_with_pidfd();
drop(cat.stdin.take());
crate::test_child::wait_until_zombie(cat.id());
cat
};
let said = |mark| {
let said = crate::log_capture::records_since_on_current_thread(mark, "it is left unreaped");
assert_eq!(said.len(), 1, "{said:?}");
said[0].1.clone()
};
let mark = crate::log_capture::mark();
let failed = Outcome::Failed(Error::Io(std::io::Error::other("the report was cut short")), None);
let err = super::conclude(Ok(ended_cat()), failed, super::LeftFront::NotAFront, None).err();
assert_eq!(
err.map(|e| e.expect_not_started().to_string()).as_deref(),
Some("the report was cut short")
);
let why = said(mark);
assert!(
why.contains("the report was cut short") && !why.contains("died"),
"{why}"
);
let mark = crate::log_capture::mark();
super::conclude(Ok(ended_cat()), Outcome::NoReport, super::LeftFront::NotAFront, None).err();
let why = said(mark);
assert!(why.contains("died before it sent its pidfd"), "{why}");
}
#[skuld::test]
fn namespaces_a_thread_taking_the_number_never_holds_the_spawn(#[fixture(namespaces)] _group: &Group) {
ns::run(fixture_path!(fixture_thread_reuse_driver));
}
#[skuld::test]
fn fixture_thread_reuse_driver() {
if !ns::is_child() {
return;
}
ns::enter_new_pid_ns_for_children();
ns::run(fixture_path!(fixture_thread_reuse_init));
}
#[skuld::test]
fn fixture_thread_reuse_init() {
if !ns::is_child_in_new_pid_ns() {
return;
}
own_procfs();
let (mut cmd, reader) = marker_command();
fault::reset_leaked_pid();
let (stop_tx, stop_rx) = std::sync::mpsc::channel::<()>();
let (tid_tx, tid_rx) = std::sync::mpsc::channel::<u32>();
let reuser: Rc<RefCell<Option<std::thread::JoinHandle<()>>>> = Rc::default();
let holder = fault::arm_fork_holder();
let armed = fault::arm_child_fault(ChildFault::Sigkill);
let probes = fault::arm_end_probes();
let after = fault::after_spawn_returns_do({
let reuser = Rc::clone(&reuser);
move |pid| {
let pid = pid.expect("the spawned child's pid");
let reaped = unsafe { libc::waitpid(pid as i32, std::ptr::null_mut(), 0) };
assert_eq!(
reaped,
pid as i32,
"reap the child: {}",
std::io::Error::last_os_error()
);
ns::set_last_pid(pid - 1);
let thread = std::thread::spawn(move || {
let tid = unsafe { libc::syscall(libc::SYS_gettid) } as u32;
tid_tx.send(tid).expect("report the thread's id");
_ = stop_rx.recv();
});
assert_eq!(
tid_rx.recv().expect("the thread's id"),
pid,
"precondition: the thread takes the reaped child's number"
);
*reuser.borrow_mut() = Some(thread);
}
});
let err = cmd.spawn().err();
drop(after);
drop(probes);
drop(armed);
let ends = fault::take_ends();
drop(holder);
drop(stop_tx);
reuser
.borrow_mut()
.take()
.expect("the after-spawn hook ran")
.join()
.expect("join the thread");
let ends = assert_ends_closed(ends, "a thread that took a reaped child's number");
assert!(ends.eof_forced, "a number that names no leader means the child is gone");
let pid = fault::take_leaked_pid()
.expect("the unreaped child is named")
.expect("it has a pid");
assert_eq!(
err.expect("a child that died before reporting fails the spawn")
.to_string(),
format!("the spawned child (pid {pid}) died before it could send its pidfd")
);
assert!(!program_ran(cmd, reader));
}
#[skuld::test]
fn a_failed_open_leaves_no_numbers_live() {
let mut cmd = std::process::Command::new("true");
let pending = super::register(&mut cmd);
let guard = crate::child::spawn::spawn_lock();
let armed = fault::fail_done_fd(Errno::MFILE);
let opened = pending.open(&guard);
drop(armed);
assert!(opened.is_err(), "the forced failure fails the open");
#[allow(clippy::disallowed_methods, reason = "spawn_lock is held by `guard`")]
let spawned = cmd.spawn();
assert_eq!(spawned.expect_err("never published").raw_os_error(), Some(libc::EBADF));
}
struct NoChild<const TOKIO: bool = true>;
impl<const TOKIO: bool> super::Spawned for NoChild<TOKIO> {
const ERR_PROVES_NO_EXEC: bool = !TOKIO;
fn pid(&self) -> Option<u32> {
None
}
fn reap_unexecuted(self, _: OwnedFd, _: Option<std::time::Duration>) -> ChildFate {
panic!("no child was handed back");
}
fn abandon_unreported(self, _: &str) {
panic!("no child was handed back");
}
}
fn sudo_front() -> super::LeftFront {
super::LeftFront::Here(
crate::elevation::front::front(Some(&crate::elevation::ElevatedVia::Wrapped(
crate::elevation::Backend::Sudo,
)))
.expect("sudo leaves a front"),
)
}
fn cat_with_pidfd() -> (std::process::Child, OwnedFd) {
let cat = crate::test_spawn::spawn(std::process::Command::new("cat").stdin(std::process::Stdio::piped()))
.expect("spawn cat");
let pid = rustix::process::Pid::from_raw(cat.id() as i32).expect("a positive pid");
let pidfd = rustix::process::pidfd_open(pid, rustix::process::PidfdFlags::empty()).expect("pidfd_open");
(cat, pidfd)
}
fn group_leading_cat_with_pidfd() -> (std::process::Child, OwnedFd) {
use std::os::unix::process::CommandExt as _;
let cat = crate::test_spawn::spawn(
std::process::Command::new("cat")
.stdin(std::process::Stdio::piped())
.process_group(0),
)
.expect("spawn cat");
let pid = rustix::process::Pid::from_raw(cat.id() as i32).expect("a positive pid");
let pidfd = rustix::process::pidfd_open(pid, rustix::process::PidfdFlags::empty()).expect("pidfd_open");
(cat, pidfd)
}
#[skuld::test]
fn a_dropped_child_whose_kill_is_refused_is_left_running_and_warned(#[fixture(setuid)] _group: &Group) {
crate::log_capture::install();
let (child, stdin) = crate::test_privilege::spawn_setuid_blocker();
let pidfd = child
.proc
.pidfd()
.expect("a Linux child has a pidfd")
.try_clone_to_owned()
.expect("duplicate the pidfd");
let mark = crate::log_capture::mark();
let (_, fate) = super::conclude(
Err::<NoChild, _>(std::io::Error::other("tokio failed")),
Outcome::Opened(pidfd),
super::LeftFront::NotAFront,
None,
)
.err()
.expect("the spawn fails")
.expect_may_have_started_with();
assert_eq!(fate, ChildFate::Running { id: None });
let warns = crate::log_capture::records_since_on_current_thread(mark, "leaving it running");
assert_eq!(warns.len(), 1, "{warns:?}");
drop(stdin);
assert!(child.wait().expect("wait").success());
}
#[skuld::test]
fn a_dropped_front_is_left_and_noted() {
let (mut cat, pidfd) = cat_with_pidfd();
let (err, fate) = super::conclude(
Err::<NoChild, _>(std::io::Error::other("tokio failed")),
Outcome::Opened(pidfd),
sudo_front(),
None,
)
.err()
.expect("the spawn fails")
.expect_may_have_started_with();
assert_eq!(
fate,
ChildFate::Running { id: None },
"a front is left running, its identity unread"
);
let text = err.to_string();
assert!(text.contains("the spawned child is what sudo left"), "{text}");
assert!(text.contains("; left unreaped"), "{text}");
drop(cat.stdin.take());
assert!(cat.wait().expect("wait").success(), "the front was signalled");
}
#[skuld::test]
fn a_collected_front_is_no_front() {
let (mut cat, pidfd) = cat_with_pidfd();
drop(cat.stdin.take());
cat.wait().expect("collect the child");
let (err, fate) = super::conclude(
Err::<NoChild, _>(std::io::Error::other("exec failed")),
Outcome::Opened(pidfd),
sudo_front(),
None,
)
.err()
.expect("the spawn fails")
.expect_may_have_started_with();
assert_eq!(fate, ChildFate::Gone, "std had collected it");
assert!(!err.to_string().contains("what sudo left"), "{err}");
}
#[skuld::test]
fn a_front_gone_before_its_go_is_no_front() {
let (mut cat, pidfd) = cat_with_pidfd();
let pid = cat.id();
cat.kill().expect("kill the child");
crate::test_child::wait_until_zombie(pid);
let err = super::conclude(
Err::<NoChild, _>(std::io::Error::other("killed on its way")),
Outcome::Gone(pidfd),
sudo_front(),
None,
)
.err()
.expect("the spawn fails")
.expect_not_started();
assert!(!err.to_string().contains("what sudo left"), "{err}");
assert_eq!(crate::child::front_kill_tests::reap(pid), None, "the teardown reaps it");
}
#[skuld::test]
fn a_not_started_failure_carries_the_fate_of_the_child_it_held() {
let io = |what: &str| std::io::Error::other(what.to_string());
let killed = || {
let (mut cat, pidfd) = cat_with_pidfd();
cat.kill().expect("kill the child");
crate::test_child::wait_until_zombie(cat.id());
pidfd
};
let (_, fate) = super::conclude(
Err::<NoChild, _>(io("gone")),
Outcome::Gone(killed()),
super::LeftFront::NotAFront,
None,
)
.err()
.expect("the spawn fails")
.expect_not_started_with_child();
assert_eq!(fate, ChildFate::Reaped);
let (_, fate) = super::conclude(
Err::<NoChild, _>(io("x")),
Outcome::Failed(Error::Io(io("helper")), Some(killed())),
super::LeftFront::NotAFront,
None,
)
.err()
.expect("the spawn fails")
.expect_not_started_with_child();
assert_eq!(fate, ChildFate::Reaped);
let outcomes = || {
[
Outcome::Failed(Error::Io(io("helper")), None),
Outcome::NoReport,
Outcome::Unwatched("cause".into()),
]
};
for outcome in outcomes() {
let failure = super::conclude(Err::<NoChild, _>(io("x")), outcome, super::LeftFront::NotAFront, None)
.err()
.expect("the spawn fails");
assert!(matches!(failure, SpawnFailure::NotStartedUnreaped(_)), "{failure:?}");
}
for outcome in outcomes() {
let failure = super::conclude(
Err::<NoChild<false>, _>(io("x")),
outcome,
super::LeftFront::NotAFront,
None,
)
.err()
.expect("the spawn fails");
assert!(matches!(failure, SpawnFailure::NotStarted(_)), "{failure:?}");
}
}
#[skuld::test]
fn a_returned_childs_failure_carries_its_teardowns_fate() {
let (mut cat, pidfd) = cat_with_pidfd();
drop(cat.stdin.take());
cat.wait().expect("collect the child");
let (_, fate) = super::conclude(Ok(cat), Outcome::Gone(pidfd), super::LeftFront::NotAFront, None)
.err()
.expect("the spawn fails")
.expect_not_started_with_child();
assert_eq!(fate, ChildFate::Gone);
let (cat, pidfd) = cat_with_pidfd();
let (_, fate) = super::conclude(
Ok(cat),
Outcome::Failed(Error::Io(std::io::Error::other("helper")), Some(pidfd)),
super::LeftFront::NotAFront,
None,
)
.err()
.expect("the spawn fails")
.expect_not_started_with_child();
assert_eq!(fate, ChildFate::Reaped);
}
#[skuld::test]
fn a_returned_child_with_no_pidfd_is_killed() {
for outcome in [
Outcome::Failed(Error::Io(std::io::Error::other("helper")), None),
Outcome::NoReport,
Outcome::Unwatched("forced".to_string()),
] {
let (mut cat, _pidfd) = cat_with_pidfd();
drop(cat.stdin.take());
crate::test_child::wait_until_zombie(cat.id());
let (_, fate) = super::conclude(Ok(cat), outcome, super::LeftFront::NotAFront, None)
.err()
.expect("the spawn fails")
.expect_not_started_with_child();
assert_eq!(fate, ChildFate::Killed);
}
}
#[skuld::test]
fn a_group_roots_failure_carries_its_teardowns_fate() {
let (mut cat, pidfd) = group_leading_cat_with_pidfd();
cat.kill().expect("kill the child");
crate::test_child::wait_until_zombie(cat.id());
let (_, fate) = super::conclude(
Err::<NoChild, _>(std::io::Error::other("tokio failed")),
Outcome::Opened(pidfd),
super::LeftFront::GroupRoot,
None,
)
.err()
.expect("the spawn fails")
.expect_may_have_started_with();
assert_eq!(fate, ChildFate::Reaped);
}
#[skuld::test]
fn an_unpeekable_dropped_front_is_left_and_noted() {
let (mut cat, pidfd) = cat_with_pidfd();
let _unpeekable = crate::wait::exit_only::seams::force_peek_once(Err(std::io::Error::from_raw_os_error(libc::EIO)));
let (err, fate) = super::conclude(
Err::<NoChild, _>(std::io::Error::other("tokio failed")),
Outcome::Opened(pidfd),
sudo_front(),
None,
)
.err()
.expect("the spawn fails")
.expect_may_have_started_with();
crate::wait::exit_only::seams::assert_peeks_exhausted();
assert_eq!(
fate,
ChildFate::Running { id: None },
"a front that cannot be peeked is taken to be there"
);
assert!(err.to_string().contains("the spawned child is what sudo left"), "{err}");
drop(cat.stdin.take());
assert!(cat.wait().expect("wait").success(), "the front was signalled");
}
#[skuld::test]
fn a_child_left_to_its_leaf_keeps_its_pidfd_and_is_sent_nothing() {
use std::os::fd::AsRawFd as _;
let (mut cat, pidfd) = cat_with_pidfd();
let raw = pidfd.as_raw_fd();
let left: super::LeftPidfd = Rc::new(Cell::new(None));
let (err, fate) = super::conclude(
Err::<NoChild, _>(std::io::Error::other("tokio failed")),
Outcome::Opened(pidfd),
super::LeftFront::ToLeaf(Rc::clone(&left)),
None,
)
.err()
.expect("the spawn fails")
.expect_may_have_started_with();
assert_eq!(
err.to_string(),
Error::Io(std::io::Error::other("tokio failed")).to_string()
);
assert_eq!(
fate,
ChildFate::Unknown,
"the leaf's abandonment answers, not the handshake"
);
let (stashed, past) = left.take().expect("the pidfd is left for the leaf");
assert_eq!(stashed.as_raw_fd(), raw, "the pidfd it was given");
assert_eq!(past, crate::child::owned::teardown::Past::Clean);
drop(cat.stdin.take());
assert!(cat.wait().expect("wait").success(), "the front was signalled");
}
#[skuld::test]
fn conclude_answers_whether_the_program_could_have_started() {
let io = |what: &str| std::io::Error::other(what.to_string());
let failed = |what: &str| Error::Io(io(what));
let answered = |result: Result<super::Held<NoChild>, SpawnFailure>| result.err().expect("the spawn fails");
let (mut cat, pidfd) = cat_with_pidfd();
let teardown = crate::child::spawn::fault::release_between_kill_and_wait(cat.stdin.take());
let (_, fate) = answered(super::conclude(
Err::<NoChild, _>(io("tokio")),
Outcome::Opened(pidfd),
super::LeftFront::NotAFront,
None,
))
.expect_may_have_started_with();
assert_eq!(fate, crate::error::ChildFate::Reaped);
teardown.assert_killed();
drop(teardown);
let (_cat, pidfd) = cat_with_pidfd();
super::conclude(
Err::<NoChild<false>, _>(io("std")),
Outcome::Opened(pidfd),
super::LeftFront::NotAFront,
None,
)
.err()
.expect("the spawn fails")
.expect_not_started();
let (mut cat, pidfd) = cat_with_pidfd();
cat.kill().expect("kill the child");
crate::test_child::wait_until_zombie(cat.id());
answered(super::conclude(
Err::<NoChild, _>(io("gone")),
Outcome::Gone(pidfd),
super::LeftFront::NotAFront,
None,
))
.expect_not_started();
answered(super::conclude(
Err::<NoChild, _>(io("x")),
Outcome::Failed(failed("helper"), None),
super::LeftFront::NotAFront,
None,
))
.expect_not_started();
answered(super::conclude(
Err::<NoChild, _>(io("x")),
Outcome::NoReport,
super::LeftFront::NotAFront,
None,
))
.expect_not_started();
answered(super::conclude(
Err::<NoChild, _>(io("x")),
Outcome::Unwatched("cause".into()),
super::LeftFront::NotAFront,
None,
))
.expect_not_started();
let (cat, pidfd) = cat_with_pidfd();
super::conclude(Ok(cat), Outcome::Gone(pidfd), super::LeftFront::NotAFront, None)
.err()
.expect("the spawn fails")
.expect_not_started();
let (cat, pidfd) = cat_with_pidfd();
super::conclude(
Ok(cat),
Outcome::Failed(failed("helper"), Some(pidfd)),
super::LeftFront::NotAFront,
None,
)
.err()
.expect("the spawn fails")
.expect_not_started();
assert_no_child_of_this_thread("every cat is reaped through its pidfd");
}
#[skuld::test]
fn conclude_answers_every_remaining_pair() {
let io = |what: &str| std::io::Error::other(what.to_string());
let failed = |what: &str| Error::Io(io(what));
let ended_cat = || {
let (mut cat, pidfd) = cat_with_pidfd();
drop(cat.stdin.take());
crate::test_child::wait_until_zombie(cat.id());
(cat, pidfd)
};
let (cat, pidfd) = ended_cat();
let held = super::conclude(Ok(cat), Outcome::Opened(pidfd), super::LeftFront::NotAFront, None)
.expect("a child told to go is held");
let mut cat = held.child;
cat.wait().expect("collect the child");
let (cat, _pidfd) = ended_cat();
let error = super::conclude(
Ok(cat),
Outcome::Failed(failed("helper"), None),
super::LeftFront::NotAFront,
None,
)
.err()
.expect("the spawn fails")
.expect_not_started();
assert!(matches!(&error, Error::Io(e) if e.to_string() == "helper"), "{error:?}");
let (cat, _pidfd) = ended_cat();
let error = super::conclude(Ok(cat), Outcome::NoReport, super::LeftFront::NotAFront, None)
.err()
.expect("the spawn fails")
.expect_not_started();
assert!(
matches!(&error, Error::Io(e) if e.to_string().contains("died before it could send its pidfd")),
"{error:?}"
);
let (cat, _pidfd) = ended_cat();
let error = super::conclude(
Ok(cat),
Outcome::Unwatched("cause".into()),
super::LeftFront::NotAFront,
None,
)
.err()
.expect("the spawn fails")
.expect_not_started();
assert!(
matches!(&error, Error::Io(e) if e.to_string().contains("its exit could not be watched (cause)")),
"{error:?}"
);
let (cat, pidfd) = cat_with_pidfd();
let mut cat = cat;
drop(cat.stdin.take());
cat.wait().expect("collect the child");
let error = super::conclude(
Err::<NoChild, _>(io("spawn")),
Outcome::Failed(failed("helper"), Some(pidfd)),
super::LeftFront::NotAFront,
None,
)
.err()
.expect("the spawn fails")
.expect_not_started();
assert!(matches!(&error, Error::Io(e) if e.to_string() == "helper"), "{error:?}");
}
#[skuld::test]
fn a_child_ended_through_its_pidfd_is_said_reaped_under_the_failed_spawns_name() {
crate::log_capture::install();
let (cat, pidfd) = cat_with_pidfd();
let pid = cat.id();
let mark = crate::log_capture::mark();
let fate = super::end_through_pidfd(
Some(pid),
pidfd,
super::Past::Clean,
None,
&mut crate::child::spawn::Diagnosis::default(),
)
.fate;
assert_eq!(fate, ChildFate::Reaped);
assert_eq!(
crate::log_capture::records_since_on_current_thread(mark, ""),
[(
log::Level::Debug,
format!("teardown after a failed spawn: teardown of child {pid}: reaped it after the kill")
)]
);
drop(cat);
}