use crate::tokio::Command;
use crate::wait::exit_only::seams::{force_peek_once, force_peeks};
use crate::wait::exit_only::{Foreign, Peek};
struct Witness {
#[cfg(target_os = "macos")]
pid: u32,
#[cfg(target_os = "linux")]
pidfd: std::os::fd::OwnedFd,
}
impl Witness {
fn kill(&self) {
#[cfg(target_os = "linux")]
{
use std::os::fd::AsFd;
rustix::process::pidfd_send_signal(self.pidfd.as_fd(), rustix::process::Signal::KILL).expect("kill");
}
#[cfg(target_os = "macos")]
assert_eq!(unsafe { libc::kill(self.pid as libc::pid_t, libc::SIGKILL) }, 0);
}
fn new(pid: u32) -> Witness {
Witness {
#[cfg(target_os = "macos")]
pid,
#[cfg(target_os = "linux")]
pidfd: rustix::process::pidfd_open(
rustix::process::Pid::from_raw(pid as i32).expect("pid"),
rustix::process::PidfdFlags::empty(),
)
.expect("pidfd_open"),
}
}
fn wait_exited(&self) {
#[cfg(target_os = "linux")]
{
use std::os::fd::AsFd;
let fd = self.pidfd.as_fd();
let mut fds = [rustix::event::PollFd::new(&fd, rustix::event::PollFlags::IN)];
loop {
match rustix::event::poll(&mut fds, None) {
Ok(n) if n > 0 => return,
Ok(_) | Err(rustix::io::Errno::INTR) => {}
Err(e) => panic!("poll(pidfd): {e}"),
}
}
}
#[cfg(target_os = "macos")]
{
let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
let rc = unsafe {
libc::waitid(
libc::P_PID,
self.pid as libc::id_t,
&mut info,
libc::WEXITED | libc::WNOWAIT,
)
};
assert_eq!(rc, 0, "waitid: {}", std::io::Error::last_os_error());
}
}
fn reap(&self) -> Result<(), std::io::Error> {
#[cfg(target_os = "linux")]
{
use std::os::fd::AsFd;
let record = rustix::process::waitid(
rustix::process::WaitId::PidFd(self.pidfd.as_fd()),
rustix::process::WaitIdOptions::EXITED,
)?;
assert!(record.is_some(), "an exited child has a record");
Ok(())
}
#[cfg(target_os = "macos")]
{
let mut status = 0;
let reaped = unsafe { libc::waitpid(self.pid as libc::pid_t, &mut status, 0) };
if reaped == self.pid as libc::pid_t {
Ok(())
} else {
Err(std::io::Error::last_os_error())
}
}
}
}
fn exited_unreaped(kill_on_drop: bool) -> (crate::tokio::Child, Witness) {
let (stdin, writer) = crate::test_child::held_writer_stdin();
let mut cmd = Command::new();
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
cmd.stdin(stdin).expect("set stdin");
cmd.kill_on_drop(kill_on_drop);
let child = cmd.spawn().expect("spawn");
let witness = Witness::new(child.id().pid());
drop(writer);
witness.wait_exited();
(child, witness)
}
fn force_evidence() -> impl Sized {
force_peek_once(Ok(Peek::Foreign(Foreign::Gone)))
}
#[skuld::test]
async fn tokio_bypass_drop_of_a_detached_child_after_a_foreign_reap_reaps_nothing() {
let (mut child, witness) = exited_unreaped(true);
child.detach();
let _evidence = force_evidence();
drop(child);
witness.reap().expect("the drop must not have reaped the child by pid");
}
#[skuld::test]
async fn tokio_bypass_drop_after_a_refused_kill_and_a_foreign_reap_reaps_nothing() {
crate::tokio::test_runtime::assert_current_thread();
crate::log_capture::install();
let mark = crate::log_capture::mark();
let (child, witness) = exited_unreaped(true);
let _looks = force_peeks([Ok(Peek::Running), Ok(Peek::Foreign(Foreign::Gone))]);
let _refused = super::fault::force_kill_failure();
let kills = super::drop_fault::record();
drop(child);
assert_eq!(kills.kills(), 1, "the drop reached its refused root kill");
assert!(
!crate::log_capture::contains_since(mark, "could not be terminated on drop"),
"a forgotten child must not be reported as left running"
);
witness.reap().expect("the drop must not have reaped the child by pid");
}
fn reap_now_after_a_refused_kill(evidence: fn() -> Box<dyn std::any::Any>) {
use std::cell::RefCell;
use std::rc::Rc;
use crate::child::spawn::fault;
let slot: Rc<RefCell<Option<Witness>>> = Rc::default();
let armed: Rc<RefCell<Option<Box<dyn std::any::Any>>>> = Rc::default();
let (point, force): (fault::SpawnPoint, fn(bool)) = if cfg!(target_os = "macos") {
(fault::SpawnPoint::BeforeIdentity, fault::set_force_identity_vanished)
} else {
(fault::SpawnPoint::BeforeAttach, fault::set_force_attach_failure)
};
let _hook = fault::set_at(point, {
let slot = Rc::clone(&slot);
let armed = Rc::clone(&armed);
move || {
let witness = Witness::new(fault::spawn_pid());
witness.wait_exited();
*armed.borrow_mut() = Some(evidence());
*slot.borrow_mut() = Some(witness);
}
});
force(true);
fault::set_force_kill_failure_leaving_child_alive_as("reap_now refused", std::io::ErrorKind::PermissionDenied);
let backend_drops = super::fault::count_backend_drops();
crate::log_capture::install();
let mark = crate::log_capture::mark();
let mut cmd = Command::new();
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
cmd.stdin(crate::stdio::Stdio::null()).expect("stdin");
let err = cmd.spawn().err();
force(false);
drop(armed);
assert!(err.is_some(), "the forced failure fails the spawn");
assert!(
crate::log_capture::contains_since(mark, "reap_now refused); it is not waited on"),
"a forgotten child was handed nowhere, and the warning must say so"
);
assert!(
!crate::log_capture::contains_since(mark, "handed to the pidfd teardown"),
"nothing was handed to the pidfd teardown"
);
assert_eq!(backend_drops.get(), 0, "tokio's Child must have been forgotten");
let witness = slot.borrow_mut().take().expect("the hook ran");
witness
.reap()
.expect("reap_now's refused-kill arm must not reap the child by pid");
}
#[skuld::test]
async fn reap_now_after_a_refused_kill_and_a_foreign_reap_reaps_nothing() {
reap_now_after_a_refused_kill(|| Box::new(force_peek_once(Ok(Peek::Foreign(Foreign::Gone)))));
}
#[skuld::test]
async fn reap_now_after_a_refused_kill_and_a_failed_look_reaps_nothing() {
reap_now_after_a_refused_kill(|| Box::new(force_peek_once(Err(std::io::Error::other("forced peek failure 6e2a")))));
}
#[skuld::test]
async fn try_wait_after_a_foreign_reap_takes_nothing() {
let (mut child, witness) = exited_unreaped(false);
let _evidence = force_evidence();
let err = child.try_wait().expect_err("a foreign-reaped child has no status");
assert!(
matches!(&err, crate::error::Error::Io(e) if e.raw_os_error() == Some(libc::ECHILD)),
"{err:?}"
);
witness.reap().expect("try_wait must not have reaped the child by pid");
}
#[skuld::test]
async fn wait_after_a_foreign_reap_takes_nothing() {
let (mut child, witness) = exited_unreaped(false);
let _evidence = force_evidence();
let err = child.wait().await.expect_err("a foreign-reaped child has no status");
assert!(
matches!(&err, crate::error::Error::Io(e) if e.raw_os_error() == Some(libc::ECHILD)),
"{err:?}"
);
witness.reap().expect("wait must not have reaped the child by pid");
}
#[skuld::test]
async fn try_wait_and_wait_on_a_child_that_cannot_be_verified_say_so() {
let (mut child, witness) = exited_unreaped(false);
let backend_drops = super::fault::count_backend_drops();
for use_wait in [false, true] {
let _failed = force_peek_once(Err(std::io::Error::other("forced peek failure 8c4f")));
let err = if use_wait {
child.wait().await.map(Some)
} else {
child.try_wait()
}
.expect_err("an unverifiable child has no status to give");
assert!(
matches!(&err, crate::error::Error::Unassessable { detail, .. } if detail.contains("cannot be shown to be ours")),
"{use_wait}: {err:?}"
);
assert!(
!child.os.proc.as_ref().expect("backend").is_reaped(),
"{use_wait}: not forgotten"
);
}
witness.reap().expect("neither call may reap the child by pid");
drop(backend_drops);
}
#[skuld::test]
async fn finish_elevated_after_a_refused_kill_and_a_foreign_reap_reaps_nothing() {
let (child, witness) = exited_unreaped(true);
let _evidence = force_evidence();
let _refused = super::fault::force_kill_failure();
let err = crate::tokio::spawn::finish_elevated(
child,
Err(crate::error::Error::Io(std::io::Error::other("no password"))),
)
.expect_err("the password write failed")
.expect_may_have_started_with();
let (err, fate) = err;
assert!(matches!(err, crate::error::Error::Elevation { .. }), "{err:?}");
assert_eq!(fate, crate::error::ChildFate::Gone);
witness
.reap()
.expect("finish_elevated's refused-kill arm must not reap the child by pid");
}
#[skuld::test]
async fn a_panicking_logger_in_the_tree_teardown_warn_does_not_reap_the_child_by_pid() {
crate::tokio::test_runtime::assert_current_thread();
crate::log_capture::install();
let (stdin, writer) = crate::test_child::held_writer_stdin();
let mut cmd = Command::new();
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
cmd.stdin(stdin).expect("set stdin");
cmd.contain_with(crate::ContainMode::Session);
let child = cmd.spawn().expect("spawn");
let witness = Witness::new(child.id().pid());
drop(writer);
witness.wait_exited();
witness
.reap()
.expect("the child is ours to reap: this is the foreign reap");
let backend_drops = super::fault::count_backend_drops();
let unwound = {
let _panics = crate::log_capture::panic_on("the root is already reaped, so this drop does not");
std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || drop(child)))
};
assert!(unwound.is_err(), "the logger must have panicked out of the drop");
assert_eq!(
backend_drops.get(),
0,
"tokio's Child must have been forgotten, not dropped into a by-pid reap"
);
}
#[skuld::test]
async fn a_panicking_refused_kill_warn_in_drop_does_not_strand_or_reap_by_pid() {
crate::tokio::test_runtime::assert_current_thread();
crate::log_capture::install();
let (stdin, writer) = crate::test_child::held_writer_stdin();
let mut cmd = Command::new();
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
cmd.stdin(stdin).expect("set stdin");
cmd.kill_on_drop(true);
let child = cmd.spawn().expect("spawn");
let witness = Witness::new(child.id().pid());
let _refused = super::fault::force_kill_failure();
let drops = super::fault::count_backend_drops();
let unwound = {
let _panics = crate::log_capture::panic_on("could not be terminated on drop");
std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || drop(child)))
};
assert!(unwound.is_err(), "the logger must have panicked out of the drop");
let released = drops.get();
drop(writer);
witness.wait_exited();
let reaped_by_us = witness.reap().is_ok();
assert_eq!(
released, 1,
"a child shown ours must reach tokio's drop (reaped_by_us={reaped_by_us})"
);
}
#[skuld::test]
async fn an_unwind_out_of_drop_closes_the_untaken_stdin_pipe() {
crate::tokio::test_runtime::assert_current_thread();
use std::os::fd::AsRawFd;
crate::log_capture::install();
let mut cmd = Command::new();
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
cmd.stdin(crate::stdio::Stdio::pipe_in()).expect("set stdin");
cmd.kill_on_drop(true);
let child = cmd.spawn().expect("spawn");
let witness = Witness::new(child.id().pid());
let crate::tokio::child::ProcSource::Tokio { stdin, .. } = child.os.proc.as_ref().expect("backend") else {
panic!("a fresh child is a tokio backend");
};
let fd = stdin.as_ref().expect("tokio's piped stdin").as_raw_fd();
let is_open = || {
unsafe { libc::fcntl(fd, libc::F_GETFD) != -1 }
};
assert!(is_open(), "before: this process holds the write end");
let _refused = super::fault::force_kill_failure();
let unwound = {
let _panics = crate::log_capture::panic_on("could not be terminated on drop");
std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || drop(child)))
};
assert!(unwound.is_err(), "the logger must have panicked out of the drop");
let still_open = is_open();
witness.kill();
witness.wait_exited();
drop(witness.reap()); assert!(
!still_open,
"after the unwind this process still holds the stdin write end"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
async fn a_failed_identity_peek_is_unknown_kills_the_child_and_forgets_the_tokio_child() {
use std::cell::RefCell;
use std::rc::Rc;
use crate::child::spawn::fault;
use crate::error::Error;
crate::tokio::test_runtime::assert_current_thread();
crate::log_capture::install();
let slot: Rc<RefCell<Option<Witness>>> = Rc::default();
let armed: Rc<RefCell<Option<Box<dyn std::any::Any>>>> = Rc::default();
let _hook = fault::set_at(fault::SpawnPoint::BeforeIdentity, {
let (slot, armed) = (Rc::clone(&slot), Rc::clone(&armed));
move || {
*slot.borrow_mut() = Some(Witness::new(fault::spawn_pid()));
*armed.borrow_mut() = Some(Box::new(force_peeks([Err(std::io::Error::other(
"forced identity-check failure 91c4",
))])));
}
});
let forgets = super::drop_fault::record();
let backend_drops = super::fault::count_backend_drops();
let reaps = crate::child::spawn::fault::record_teardown_reaps();
let mark = crate::log_capture::mark();
let (stdin, _writer) = crate::test_child::held_writer_stdin();
let mut cmd = Command::new();
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
cmd.stdin(stdin).expect("stdin");
let err = cmd.spawn().err();
drop(armed);
let (err, fate) = crate::child::spawn::failure::expect_may_have_started_with(
err.expect("a failed identity peek fails the spawn"),
);
assert_eq!(
fate,
crate::error::ChildFate::Reaped,
"the pidfd pins the child, so it is killed and reaped"
);
assert!(
matches!(err, Error::Unassessable { .. }),
"a failed peek is Unassessable, not a vanish: {err:?}"
);
assert!(
crate::log_capture::contains_since(
mark,
"could not be checked against its handle (forced identity-check failure 91c4)"
),
"the failed peek is warned at the call, naming its own error"
);
assert_eq!(forgets.forgets(), 1, "tokio's Child must have been forgotten");
assert_eq!(backend_drops.get(), 0, "tokio's Child must not have been dropped");
let witness = slot.borrow_mut().take().expect("the hook ran");
let recorded = reaps.recorded();
assert_eq!(
recorded.len(),
1,
"the teardown must have reaped the child: {recorded:?}"
);
assert_eq!(
std::os::unix::process::ExitStatusExt::signal(&recorded[0].1),
Some(libc::SIGKILL),
"the teardown must have killed the child through its pidfd"
);
assert!(
witness.reap().is_err(),
"the child is reaped already: nothing is left for the test to reap"
);
}
#[cfg(target_os = "linux")]
fn refused_kill_teardown(attach_failure: bool, armed_in_hook: Option<fn() -> Box<dyn std::any::Any>>) {
use std::cell::RefCell;
use std::rc::Rc;
use crate::child::spawn::fault;
let slot: Rc<RefCell<Option<Witness>>> = Rc::default();
let armed: Rc<RefCell<Option<Box<dyn std::any::Any>>>> = Rc::default();
let _hook = fault::set_at(fault::SpawnPoint::BeforeIdentity, {
let (slot, armed) = (Rc::clone(&slot), Rc::clone(&armed));
move || {
*slot.borrow_mut() = Some(Witness::new(fault::spawn_pid()));
*armed.borrow_mut() = armed_in_hook.map(|arm| arm());
}
});
fault::set_force_attach_failure(attach_failure);
fault::set_force_kill_failure_leaving_child_alive_as("teardown refused", std::io::ErrorKind::PermissionDenied);
let forgets = super::drop_fault::record();
let backend_drops = super::fault::count_backend_drops();
let reaps = fault::record_teardown_reaps();
crate::log_capture::install();
let mark = crate::log_capture::mark();
let (stdin, _writer) = crate::test_child::held_writer_stdin();
let mut cmd = Command::new();
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
cmd.stdin(stdin).expect("stdin");
let err = cmd.spawn().err();
fault::set_force_attach_failure(false);
drop(armed);
assert!(err.is_some(), "the forced failure fails the spawn");
assert!(
crate::log_capture::contains_since(
mark,
"had its teardown kill refused and is handed to the pidfd teardown"
),
"the forget must say the kill was refused and the child handed on"
);
assert!(
!crate::log_capture::contains_since(mark, "was reaped by someone else"),
"the child was not reaped by someone else"
);
assert_eq!(forgets.forgets(), 1, "tokio's Child must have been forgotten");
assert_eq!(
backend_drops.get(),
0,
"tokio's Child must not have been released to its drop"
);
let recorded = reaps.recorded();
assert_eq!(
recorded.len(),
1,
"the pidfd teardown must have reaped the child: {recorded:?}"
);
assert_eq!(
std::os::unix::process::ExitStatusExt::signal(&recorded[0].1),
Some(libc::SIGKILL)
);
let witness = slot.borrow_mut().take().expect("the hook ran");
assert!(witness.reap().is_err(), "the child is reaped already");
}
#[cfg(target_os = "linux")]
#[skuld::test]
async fn reap_now_after_a_refused_kill_on_a_live_child_reaps_through_the_pidfd() {
crate::tokio::test_runtime::assert_current_thread();
refused_kill_teardown(true, None);
}
#[cfg(target_os = "linux")]
#[skuld::test]
async fn a_failed_identity_peek_with_a_refused_kill_reaps_through_the_pidfd() {
use crate::wait::exit_only::seams::force_peeks;
crate::tokio::test_runtime::assert_current_thread();
refused_kill_teardown(
false,
Some(|| {
Box::new(force_peeks([Err(std::io::Error::other(
"forced identity-check failure 77a1",
))]))
}),
);
}