use super::failure::{expect_may_have_started_with, expect_not_started};
use super::fault;
use crate::command::Command;
use crate::error::ChildFate;
use crate::error::Error;
use crate::test_child::Console;
#[cfg(target_os = "linux")]
use crate::test_groups::{cgroup, setuid, Group};
#[cfg(target_os = "macos")]
fn blocker() -> Command {
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
cmd.stdin(crate::test_child::leaked_writer_stdin())
.expect("set stdin pipe");
cmd
}
pub(super) fn teardown_blocker() -> (Command, fault::TeardownBlocker) {
let fault::TeardownBlockerParts {
argv,
stdin,
stdout,
guard,
} = fault::teardown_blocker_parts();
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(argv);
cmd.stdin(stdin).expect("set stdin pipe");
if let Some(stdout) = stdout {
cmd.stdout(stdout).expect("set stdout");
}
(cmd, guard)
}
#[cfg(unix)]
fn blocker_with_held_stdin() -> (Command, crate::PipeWriter) {
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 pipe");
(cmd, writer)
}
#[cfg(unix)]
fn raw_status(raw: u32) -> std::process::ExitStatus {
std::os::unix::process::ExitStatusExt::from_raw(raw as i32)
}
#[cfg(windows)]
fn raw_status(raw: u32) -> std::process::ExitStatus {
std::os::windows::process::ExitStatusExt::from_raw(raw)
}
#[skuld::test]
fn a_teardown_reap_is_recorded_only_while_its_recorder_lives() {
fault::record_teardown_reap(1, raw_status(9));
let recorder = fault::record_teardown_reaps();
assert_eq!(recorder.recorded(), vec![], "a reap from before arming is not recorded");
fault::record_teardown_reap(2, raw_status(9));
assert_eq!(recorder.recorded(), vec![(2, raw_status(9))]);
drop(recorder);
let later = fault::record_teardown_reaps();
assert_eq!(later.recorded(), vec![], "a dropped recorder leaves nothing behind");
}
#[cfg(not(target_os = "macos"))]
#[skuld::test]
fn identity_failure_reaps_the_spawned_child() {
let (mut cmd, teardown) = teardown_blocker();
fault::set_force_identity_vanished(true);
let err = cmd.spawn().err();
fault::set_force_identity_vanished(false);
let (err, fate) = expect_may_have_started_with(err.expect("forced identity-vanish must make spawn return Err"));
assert!(
matches!(err, Error::Io(_)),
"identity-vanish surfaces as an Io error, got {err:?}"
);
assert_eq!(fate, ChildFate::Reaped, "the teardown killed and reaped the child");
fault::assert_child_reaped(fault::take_captured().expect("seam captured the child's identity"));
teardown.assert_killed();
}
#[cfg(all(unix, not(target_os = "macos")))]
#[skuld::test]
fn an_unreadable_identity_fails_a_tree_walk_spawn_and_reaps_the_child() {
let (mut cmd, teardown) = teardown_blocker();
cmd.contain_with(crate::ContainMode::TreeWalk);
fault::set_force_identity_unknown(true);
let err = cmd.spawn().err();
fault::set_force_identity_unknown(false);
let (err, fate) = expect_may_have_started_with(err.expect("a tree walk without an identity must fail the spawn"));
assert!(matches!(err, Error::Unassessable { .. }), "{err:?}");
assert_eq!(
fate,
ChildFate::Reaped,
"the handle pins the child, so the teardown reaps it"
);
fault::assert_child_reaped(fault::take_captured().expect("seam captured the child's identity"));
teardown.assert_killed();
}
#[cfg(unix)]
#[skuld::test]
fn an_unreadable_identity_keeps_the_child_without_one() {
let (mut cmd, _teardown) = teardown_blocker();
fault::set_force_identity_unknown(true);
let spawned = cmd.spawn();
fault::set_force_identity_unknown(false);
let child = spawned.expect("an unreadable identity keeps the child");
let Some(crate::identity::Resolved::Found(captured)) = fault::take_captured() else {
panic!("the seam captured the child's identity");
};
assert_eq!(child.id(), None, "the read failed, so the child has no identity");
assert_eq!(child.pid(), captured.pid(), "the pid is the spawned child's");
assert_eq!(child.try_wait().expect("try_wait"), None, "the child is still running");
assert_eq!(
child.is_alive(),
crate::identity::Liveness::Alive,
"is_alive looks through the handle"
);
child.kill().expect("a kept child is killed through its handle");
let status = child.wait().expect("a kept child is waited on");
assert!(!status.success(), "the kill ended the child: {status:?}");
assert_eq!(child.is_alive(), crate::identity::Liveness::Dead);
}
#[cfg(target_os = "linux")]
fn assert_contained_root_is_kept_without_an_identity(mode: crate::ContainMode, expected: crate::Containment) {
let (mut cmd, _teardown) = teardown_blocker();
cmd.contain_with(mode);
fault::set_force_identity_unknown(true);
let spawned = cmd.spawn();
fault::set_force_identity_unknown(false);
let child = spawned.expect("an unreadable identity keeps a root whose containment needs none");
assert_eq!(child.id(), None, "the read failed, so the child has no identity");
assert_eq!(
child.containment(),
expected,
"{mode:?} attached as the wrong mechanism"
);
child
.kill_tree()
.expect("the mechanism kills the tree by pid or handle");
child.wait().expect("the kept child is waited on");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_unreadable_identity_keeps_a_session_root() {
assert_contained_root_is_kept_without_an_identity(crate::ContainMode::Session, crate::Containment::Session);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_unreadable_identity_keeps_a_strongest_root_in_a_process_group() {
let (mode, _forced) = super::identity_group_tests::Container::Leafless.arm();
assert_contained_root_is_kept_without_an_identity(mode, crate::Containment::ProcessGroup);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_unreadable_identity_keeps_a_cgroup_root(#[fixture(cgroup)] _group: &Group) {
assert_contained_root_is_kept_without_an_identity(crate::ContainMode::Strongest, crate::Containment::CgroupV2);
}
#[cfg(target_os = "macos")]
#[skuld::test]
fn macos_an_unreadable_identity_keeps_a_session_or_process_group_root() {
for (mode, expected) in [
(crate::ContainMode::Session, crate::Containment::Session),
(crate::ContainMode::Strongest, crate::Containment::ProcessGroup),
] {
let (mut cmd, _teardown) = teardown_blocker();
cmd.contain_with(mode).suppress_fd_marker();
fault::set_force_identity_unknown(true);
let spawned = cmd.spawn();
fault::set_force_identity_unknown(false);
let child = spawned.expect("an unreadable identity keeps a root whose containment needs none");
assert_eq!(child.id(), None, "the read failed, so the child has no identity");
assert_eq!(
child.containment(),
expected,
"{mode:?} attached as the wrong mechanism"
);
child.kill().expect("a kept child is killed through its handle");
child.wait().expect("the kept child is waited on");
}
}
#[cfg(unix)]
#[skuld::test]
fn a_kept_child_without_an_identity_is_killed_and_reaped_on_drop() {
let (mut cmd, teardown) = teardown_blocker();
fault::set_force_identity_unknown(true);
let spawned = cmd.spawn();
fault::set_force_identity_unknown(false);
let child = spawned.expect("an unreadable identity keeps the child");
assert_eq!(child.id(), None);
drop(child);
teardown.assert_killed();
}
#[cfg(not(target_os = "macos"))]
#[skuld::test]
fn attach_failure_reaps_the_spawned_child() {
let (mut cmd, teardown) = teardown_blocker();
fault::set_force_attach_failure(true);
let err = cmd.spawn().err();
fault::set_force_attach_failure(false);
let (err, fate) = expect_may_have_started_with(err.expect("forced attach failure must make spawn return Err"));
assert_eq!(fate, ChildFate::Reaped, "the teardown killed and reaped the child");
assert!(
matches!(err, Error::Containment { .. }),
"a real attach failure surfaces as Error::Containment, got {err:?}"
);
fault::assert_child_reaped(fault::take_captured().expect("seam captured the child's identity"));
teardown.assert_killed();
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_child_whose_teardown_kill_is_refused_is_handed_back(#[fixture(setuid)] _group: &Group) {
use crate::child::spawn::fault::SpawnPoint;
use crate::test_child::expect_handed_back;
crate::log_capture::install();
let arms: [(fn(bool), bool); 2] = [
(fault::set_force_identity_vanished, false),
(fault::set_force_attach_failure, true),
];
for (force_arm, identified) in arms {
let (mut cmd, writer, until_root) = crate::test_privilege::setuid_blocker_for_a_failing_spawn();
let _root = fault::set_at(SpawnPoint::BeforeIdentity, until_root);
let mark = crate::log_capture::mark();
force_arm(true);
let err = cmd.spawn().expect_err("the forced arm fails the spawn");
force_arm(false);
let Some(crate::identity::Resolved::Found(id)) = fault::take_captured() else {
panic!("the seam captured the child's identity");
};
let (_, fate, handed_back) = expect_handed_back(err, writer);
assert_eq!(
fate,
ChildFate::Running {
id: identified.then_some(id)
}
);
assert_eq!(handed_back.unreaped().pid(), Some(id.pid()));
assert_eq!(handed_back.unreaped().id(), identified.then_some(id));
let warns = crate::log_capture::records_since_on_current_thread(mark, "handed back to the caller");
assert_eq!(warns.len(), 1, "{warns:?}");
let status = handed_back.wait();
assert!(status.success(), "the helper exits on EOF: {status:?}");
}
}
#[skuld::test]
fn spawn_unelevated_runs_a_plain_child() {
let mut c = crate::test_child::command(Console::Hidden);
#[cfg(unix)]
c.args(["true"]);
#[cfg(windows)]
c.args(["cmd", "/C", "exit 0"]);
let kill_on_drop = c.kill_on_drop_flag();
let child = super::spawn_unelevated(&mut c, kill_on_drop).expect("spawn");
assert!(child.wait().expect("wait").success());
}
#[skuld::test]
fn non_elevated_spawn_skips_the_elevation_branch() {
let mut c = crate::test_child::command(Console::Hidden);
#[cfg(unix)]
c.args(["true"]);
#[cfg(windows)]
c.args(["cmd", "/C", "exit 0"]);
let child = super::spawn(&mut c).expect("non-elevated spawn");
assert!(child.wait().expect("wait").success());
}
#[cfg(windows)]
#[skuld::test]
fn elevated_pipe_is_rejected_deterministically_regardless_of_privilege() {
let mut c = crate::test_child::command(Console::Hidden);
c.args(["whoami"]).elevate();
c.stdout(crate::stdio::Stdio::pipe()).unwrap();
assert!(matches!(
super::spawn(&mut c),
Err(super::SpawnFailure::NotStarted(crate::error::Error::Unsupported { .. }))
));
}
#[cfg(windows)]
#[skuld::test]
fn an_elevated_executable_or_raw_executable_is_refused_by_spawn() {
let program = r"C:\no-such-dir\tool";
for setter in ["executable", "raw_executable"] {
let mut c = crate::test_child::command(Console::Hidden);
match setter {
"executable" => c.executable(program),
_ => c.raw_executable(program),
};
c.args([program]).elevate();
match c.spawn() {
Err(Error::Unsupported { op, detail, .. }) => {
assert!(op.contains(&format!("{setter}()")), "{setter}: {op}");
assert_eq!(detail, crate::elevation::SETTER_REFUSAL, "{setter}");
}
other => panic!("{setter}: expected Unsupported, got {:?}", other.map(|_| "a child")),
}
}
}
#[cfg(windows)]
#[skuld::test]
fn routes_to_raw_backend_answers_for_executables_and_high_descriptors() {
use crate::stdio::Stdio;
let mut argv_only = crate::test_child::command(Console::Hidden);
argv_only.args(["cmd", "/C", "exit 0"]);
assert!(
!super::routes_to_raw_backend(&argv_only),
"an argv-only command stays on the std path"
);
let mut exe_only = crate::test_child::command(Console::Hidden);
exe_only.executable("cmd").args(["cmd", "/C", "exit 0"]);
assert!(super::routes_to_raw_backend(&exe_only), "an executable() routes to raw");
let mut raw_exe_only = crate::test_child::command(Console::Hidden);
raw_exe_only.raw_executable("cmd").args(["cmd", "/C", "exit 0"]);
assert!(
super::routes_to_raw_backend(&raw_exe_only),
"a raw_executable() routes to raw too"
);
let mut high_fd_only = crate::test_child::command(Console::Hidden);
high_fd_only.args(["cmd", "/C", "exit 0"]);
high_fd_only.fd(3, Stdio::pipe_out()).unwrap();
assert!(
super::routes_to_raw_backend(&high_fd_only),
"a descriptor >= 3 routes to raw even with no executable(): std cannot carry it, and the \
std path's fd >= 3 collection is unix-only, so it would be dropped in silence"
);
let mut both = crate::test_child::command(Console::Hidden);
both.executable("cmd").args(["cmd", "/C", "exit 0"]);
both.fd(3, Stdio::pipe_out()).unwrap();
assert!(super::routes_to_raw_backend(&both));
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_sync_identity_failure_settles_the_leaf_verdict_before_the_kill(#[fixture(cgroup)] _group: &Group) {
use std::cell::Cell;
use std::rc::Rc;
use crate::containment::cgroup::fault as cgroup_fault;
use crate::send_log::Capture;
use crate::signal::Sig;
let (mut cmd, teardown) = teardown_blocker();
cmd.contain();
let capture = Rc::new(Capture::start());
let sends_at_settle = Rc::new(Cell::new(None));
let _hook = cgroup_fault::set_on_take_placement({
let (capture, sends_at_settle) = (Rc::clone(&capture), Rc::clone(&sends_at_settle));
move || sends_at_settle.set(Some(capture.entries().len()))
});
fault::set_force_identity_vanished(true);
let err = cmd.spawn().err();
fault::set_force_identity_vanished(false);
err.expect("a vanished identity must fail the spawn");
let Some(crate::identity::Resolved::Found(child)) = fault::take_captured() else {
panic!("the seam must capture the child's identity");
};
assert_eq!(
sends_at_settle.get(),
Some(0),
"the verdict must be settled, and before anything is sent to the child"
);
assert!(
capture
.entries()
.iter()
.any(|&(pid, sig, _)| pid == child.pid() && sig == Sig::Kill),
"the child must be killed after the verdict: {:?}",
capture.entries()
);
teardown.assert_killed();
}
#[cfg(windows)]
#[skuld::test]
fn a_refused_raw_spawn_does_not_clear_our_handle_inheritance() {
use crate::containment::windows::observe;
let mut refused = crate::test_child::command(Console::Hidden);
refused
.executable("cmd")
.args(["cmd", "/C", "exit 0"])
.contain()
.creation_flags(windows::Win32::System::Threading::CREATE_SUSPENDED.0);
observe::take_inheritance_cleared();
let err = expect_not_started(refused.spawn().expect_err("a reserved bit must be refused"));
assert!(matches!(err, Error::Unsupported { .. }), "got {err:?}");
assert!(
!observe::take_inheritance_cleared(),
"the refusal ran after the mutation it was supposed to precede"
);
for (slot, target, what) in [
(3, crate::Stdio::inherit(), "inherit on fd 3 has no parent stream"),
(100_000, crate::Stdio::null(), "the descriptor table is too large"),
] {
let mut refused = crate::test_child::command(Console::Hidden);
refused.executable("cmd").args(["cmd", "/C", "exit 0"]).contain();
refused.fd(slot, target).expect("configure the slot");
let err = expect_not_started(refused.spawn().expect_err(what));
assert!(matches!(err, Error::Unsupported { .. }), "{what}: got {err:?}");
assert!(
!observe::take_inheritance_cleared(),
"{what}: the refusal ran after the mutation it was supposed to precede"
);
}
let mut allowed = crate::test_child::command(Console::Hidden);
allowed.executable("cmd").args(["cmd", "/C", "exit 0"]).contain();
let child = allowed
.spawn()
.expect("the same command without the reserved bit spawns");
assert!(
observe::take_inheritance_cleared(),
"the seam must record a real call, else the negative leg above proves nothing"
);
child.wait().expect("reap");
}
#[cfg(windows)]
#[skuld::test]
fn a_raw_spawn_refusing_an_env_nul_does_not_clear_our_handle_inheritance() {
use crate::containment::windows::observe;
let mut refused = crate::test_child::command(Console::Hidden);
refused
.executable("cmd")
.args(["cmd", "/C", "exit 0"])
.contain()
.env("A\0B", "x");
observe::take_inheritance_cleared();
let err = expect_not_started(refused.spawn().expect_err("an embedded NUL must be refused"));
assert!(
matches!(err, Error::Io(ref e) if e.kind() == std::io::ErrorKind::InvalidInput),
"got {err:?}"
);
assert!(
!observe::take_inheritance_cleared(),
"the refusal ran after the mutation it was supposed to precede"
);
}
#[cfg(windows)]
#[skuld::test]
fn a_refused_std_spawn_does_not_clear_our_handle_inheritance() {
use crate::containment::windows::observe;
let mut refused = crate::test_child::command(Console::Hidden);
refused
.args(["cmd", "/C", "exit 0"])
.contain()
.creation_flags(windows::Win32::System::Threading::CREATE_SUSPENDED.0);
assert!(
!crate::child::spawn::routes_to_raw_backend(&refused),
"this leg is only a std-path proof while the command stays off the raw backend"
);
observe::take_inheritance_cleared();
let err = expect_not_started(refused.spawn().expect_err("a reserved bit must be refused"));
assert!(matches!(err, Error::Unsupported { .. }), "got {err:?}");
assert!(
!observe::take_inheritance_cleared(),
"the refusal ran after the mutation it was supposed to precede"
);
let mut allowed = crate::test_child::command(Console::Hidden);
allowed.args(["cmd", "/C", "exit 0"]).contain();
let child = allowed
.spawn()
.expect("the same command without the reserved bit spawns");
assert!(
observe::take_inheritance_cleared(),
"the seam must record a real call, else the negative leg above proves nothing"
);
child.wait().expect("reap");
}
#[cfg(target_os = "linux")]
fn attach_entered_leaf(leaf_path: &std::path::Path) {
std::fs::create_dir(leaf_path).expect("create the leaf");
std::fs::write(leaf_path.join("occupant"), "").expect("keep the leaf unremovable");
std::fs::write(leaf_path.join("cgroup.kill"), b"").expect("create cgroup.kill");
fault::set_attachment_override(crate::containment::Attachment {
containment: crate::containment::Containment::CgroupV2,
attached: crate::containment::Attached::Cgroup(crate::containment::cgroup::test_support::entered_leaf_at(
leaf_path.to_path_buf(),
)),
graceful: crate::graceful::GracefulMechanism::Process,
});
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn kill_on_drop_false_disarms_the_leaf_only_when_the_spawn_commits() {
for commit in [false, true] {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-commit-leaf");
attach_entered_leaf(&leaf_path);
let (mut cmd, stdin) = blocker_with_held_stdin();
cmd.kill_on_drop(false);
let mut child = super::spawn_uncommitted(&mut cmd).expect("spawn");
if commit {
child = child.commit_kill_on_drop().expect("commit");
}
child.kill().expect("end the stand-in root");
drop(stdin);
let status = child.wait().expect("reap the stand-in root");
assert_eq!(
std::os::unix::process::ExitStatusExt::signal(&status),
Some(libc::SIGKILL),
"the stand-in root must die of the kill, got {status:?}"
);
drop(child);
let expected: &[u8] = if commit { b"" } else { b"1" };
assert_eq!(
std::fs::read(leaf_path.join("cgroup.kill")).expect("read cgroup.kill"),
expected,
"committed: {commit}"
);
}
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_failed_password_write_kills_the_contained_tree() {
crate::log_capture::install();
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-password-leaf");
attach_entered_leaf(&leaf_path);
let (mut cmd, teardown) = teardown_blocker();
cmd.kill_on_drop(false);
let child = super::spawn_uncommitted(&mut cmd).expect("spawn");
child.attached.disarm().expect("disarm");
let written = Err(Error::Elevation {
kind: crate::error::ElevationErrorKind::AuthFailed,
detail: "forced password-write failure".into(),
});
let mark = crate::log_capture::mark();
let (err, fate) = super::finish_elevated(child, written)
.expect_err("a failed write fails the spawn")
.expect_may_have_started_with();
assert_eq!(fate, ChildFate::Reaped);
teardown.assert_killed();
assert!(
matches!(
err,
Error::Elevation {
kind: crate::error::ElevationErrorKind::AuthFailed,
..
}
),
"got {err:?}"
);
assert_eq!(
std::fs::read(leaf_path.join("cgroup.kill")).expect("read cgroup.kill"),
crate::containment::cgroup::KILL_PAYLOAD,
"the failed spawn must kill its tree through the leaf"
);
assert_eq!(
crate::log_capture::levels_since(mark, &super::teardown_warn_marker(&leaf_path)),
Vec::<log::Level>::new(),
"a successful tree kill must not warn"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_failed_password_write_removes_the_leaf_once_the_tree_drains() {
use crate::containment::cgroup::fault as leaf_fault;
use crate::containment::cgroup::test_support::{entered_leaf_at, FakeLeaf};
crate::log_capture::install();
let name = "cosca-password-drains-leaf";
let fake = FakeLeaf::new(name, true);
let (path, events) = (fake.leaf.clone(), fake.events.clone());
leaf_fault::set_rmdir_hook(move |_| FakeLeaf::rmdir(&path, &events));
let (blocking, wait_reached) = std::sync::mpsc::channel();
leaf_fault::set_drain_blocking_notifier(blocking);
let members = fake.events.clone();
let exiting = std::thread::spawn(move || {
if wait_reached.recv().is_ok() {
FakeLeaf::set_populated(&members, false);
}
});
fault::set_attachment_override(crate::containment::Attachment {
containment: crate::containment::Containment::CgroupV2,
attached: crate::containment::Attached::Cgroup(entered_leaf_at(fake.leaf.clone())),
graceful: crate::graceful::GracefulMechanism::Process,
});
let (mut cmd, teardown) = teardown_blocker();
cmd.kill_on_drop(false);
let child = super::spawn_uncommitted(&mut cmd).expect("spawn");
let mark = crate::log_capture::mark();
let (err, fate) = super::finish_elevated(child, failed_write())
.expect_err("a failed write fails the spawn")
.expect_may_have_started_with();
assert_eq!(fate, ChildFate::Reaped);
teardown.assert_killed();
leaf_fault::take_drain_blocking_notifier();
exiting.join().expect("the exiting thread");
leaf_fault::take_rmdir_hook();
assert!(matches!(err, Error::Elevation { .. }), "got {err:?}");
assert!(
!fake.leaf.exists(),
"the drained leaf must be removed by the handle's drop"
);
assert_eq!(
crate::log_capture::levels_since(mark, name),
Vec::<log::Level>::new(),
"a leaf that was removed must not be warned about"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_failed_password_write_warns_when_the_tree_kill_fails() {
crate::log_capture::install();
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-password-kill-fail-leaf");
attach_entered_leaf(&leaf_path);
let (mut cmd, teardown) = teardown_blocker();
cmd.kill_on_drop(false);
let child = super::spawn_uncommitted(&mut cmd).expect("spawn");
child.attached.disarm().expect("disarm");
std::fs::remove_file(leaf_path.join("cgroup.kill")).expect("remove the fixture's cgroup.kill file");
std::fs::create_dir(leaf_path.join("cgroup.kill")).expect("make cgroup.kill a directory");
let mark = crate::log_capture::mark();
let (err, fate) = super::finish_elevated(child, failed_write())
.expect_err("a failed write fails the spawn")
.expect_may_have_started_with();
assert_eq!(fate, ChildFate::Reaped);
teardown.assert_killed();
assert!(
matches!(
err,
Error::Elevation {
kind: crate::error::ElevationErrorKind::AuthFailed,
..
}
),
"got {err:?}"
);
let marker = super::teardown_warn_marker(&leaf_path);
assert_eq!(
crate::log_capture::levels_since(mark, &marker),
[log::Level::Warn],
"a forced tree-kill failure must be logged at warn"
);
let errno_text = std::io::Error::from_raw_os_error(libc::EISDIR).to_string();
let records = crate::log_capture::records_since(mark, &marker);
assert!(
records[0].contains(&errno_text),
"the warning must name the OS reason the write failed, got {records:?}"
);
}
#[cfg(unix)]
#[skuld::test]
fn a_failed_password_write_reports_a_failed_root_reap() {
crate::log_capture::install();
let (mut cmd, teardown) = teardown_blocker();
let child = cmd.spawn().expect("spawn");
let pid = child.pid();
fault::set_force_reap_failure("cosca-finish-elevated-reap-4c1e");
let mark = crate::log_capture::mark();
let (err, fate, handed_back) = super::finish_elevated(child, failed_write())
.expect_err("a failed write fails the spawn")
.expect_may_have_started_parts(());
assert_eq!(fate, ChildFate::Killed, "killed, but not reaped");
handed_back.unreaped();
drop(handed_back);
let Error::Elevation { detail, .. } = &err else {
panic!("got {err:?}");
};
assert!(
detail.contains(&format!(
"the elevated child pid {pid}: the wait failed: cosca-finish-elevated-reap-4c1e"
)),
"the note must say the wait failed, got {detail:?}"
);
assert!(
!detail.contains("was terminated"),
"a child that was not reaped is not reported as terminated: {detail:?}"
);
assert_eq!(
crate::log_capture::levels_since(mark, &format!("the elevated child pid {pid}: the wait failed")),
[log::Level::Warn]
);
assert_eq!(teardown.recorded(), vec![], "a failed reap is not recorded");
assert!(
fault::take_force_reap_failure().is_none(),
"the teardown consumed the forced failure"
);
}
#[cfg(unix)]
#[skuld::test]
fn finish_elevated_words_a_root_its_delivered_kill_reached_by_how_the_wait_ended() {
use crate::child::lifecycle::Settlement;
use crate::child::owned::owned_tests::teardown_lines::said_of;
use crate::child::owned::ChildWaitOutcome;
use crate::error::ChildFate;
use crate::os_process::child::{ExitRecord, Foreign};
let id = crate::identity::ProcessId::from_parts_for_test(42, crate::identity::Key::for_test(1));
for exited_front in [false, true] {
let who = if exited_front {
"the elevated child pid 42 (it had already exited)"
} else {
"the elevated child pid 42"
};
let rows = [
(
Ok(ChildWaitOutcome::Exited(ExitRecord::Unreadable { si_code: 7 })),
ChildFate::Reaped,
Some(format!(
"{who}: reaped it after the kill; the child's exit record was unreadable (si_code 7)"
)),
),
(
Ok(ChildWaitOutcome::Foreign(Foreign::Orphaned)),
ChildFate::Killed,
Some(format!(
"{who}: not ours to reap (launchd holds its zombie, because its tracer died)"
)),
),
];
for (answer, fate, said) in rows {
let (note, torn) =
super::root_after_a_delivered_kill(42, Some(id), exited_front, &Settlement::new(answer, true));
assert_eq!(Some(¬e), said.as_ref(), "{exited_front}");
assert_eq!(
said_of(&torn),
said.map(|said| (log::Level::Warn, said)),
"{exited_front}"
);
assert_eq!(torn.fate(), fate, "{exited_front}");
assert!(
!torn.uncollected(),
"{exited_front}: collected, or not ours: nothing to hand back"
);
}
let elsewhere = Settlement::new(Ok(ChildWaitOutcome::Foreign(Foreign::Gone)), true);
let (note, torn) = super::root_after_a_delivered_kill(42, Some(id), exited_front, &elsewhere);
assert_eq!(note, format!("{who}: reaped by someone else"));
assert_eq!(
said_of(&torn),
Some((log::Level::Debug, format!("{who}: reaped by someone else"))),
"{exited_front}: a foreign reap is not a warn"
);
assert_eq!(torn.fate(), ChildFate::Killed);
}
}
#[cfg(unix)]
#[skuld::test]
fn finish_elevated_words_a_root_whose_kill_was_refused_by_what_the_look_found() {
use crate::child::owned::teardown::Disposition;
use crate::child::owned::OwnedChild;
use crate::os_process::child::{ExitRecord, Foreign};
use crate::os_process::fake::{FakeProcess, ReapAnswer};
let refusal = || "the elevated child could not be terminated (denied)".to_owned();
let rows = [
(
ReapAnswer::Reaped(ExitRecord::Status(Default::default())),
format!("{}: it has exited, and was reaped", refusal()),
),
(
ReapAnswer::Foreign(Foreign::Gone),
format!("{}: reaped by someone else", refusal()),
),
(ReapAnswer::Running, refusal()),
];
for (reap, said) in rows {
let child = OwnedChild::new(Box::new(FakeProcess::new([]).with_pid(42).reaps([reap])));
let denied = Error::Io(std::io::Error::from(std::io::ErrorKind::PermissionDenied));
let looked = child.look_after_refused_kill(None, denied, Disposition::HandBack);
assert_eq!(super::root_after_a_refused_kill(refusal(), looked.refused_look()), said);
}
let unreadable = crate::child::lifecycle::Settlement::new(
Ok(crate::child::owned::ChildWaitOutcome::Exited(ExitRecord::Unreadable {
si_code: 7,
})),
false,
);
assert_eq!(
super::root_after_a_refused_kill(refusal(), Some(&unreadable)),
format!(
"{}: it has exited, and was reaped; the child's exit record was unreadable (si_code 7)",
refusal()
)
);
}
#[cfg(unix)]
#[skuld::test]
fn report_tree_teardown_reports_only_a_failed_teardown() {
crate::log_capture::install();
let failed = || {
Some(Err(crate::containment::dispatch::Unsettled {
first: Error::Io(std::io::Error::from_raw_os_error(libc::EISDIR)),
others: Vec::new(),
}))
};
for (name, tree, reported) in [
("cosca-report-failed", failed(), true),
(
"cosca-report-worked",
Some(Ok(crate::containment::dispatch::SettleOutcome::Killed)),
false,
),
("cosca-report-not-tried", None, false),
] {
let mark = crate::log_capture::mark();
let (note, warn) = super::report_tree_teardown(tree, &name);
assert_eq!(
warn.as_deref()
.is_some_and(|text| text.contains(super::TREE_TEARDOWN_WARN) && text.contains(name)),
reported,
"{name}: the carried warn text, got {warn:?}"
);
assert_eq!(
note.contains("its contained tree could not be killed"),
reported,
"{name}: {note:?}"
);
assert_eq!(
note.contains(name),
reported,
"{name}: the note names the subject, got {note:?}"
);
assert_eq!(
crate::log_capture::levels_since(mark, name),
Vec::<log::Level>::new(),
"{name}: it logs nothing itself"
);
}
}
#[cfg(target_os = "linux")]
fn reaped(pid: u32) -> bool {
let mut status = 0;
let r = unsafe { libc::waitpid(pid as i32, &mut status, libc::WNOHANG) };
r == -1 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ECHILD)
}
#[cfg(unix)]
fn failed_write() -> Result<(), Error> {
Err(Error::Elevation {
kind: crate::error::ElevationErrorKind::AuthFailed,
detail: "forced password-write failure".into(),
})
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_failed_password_write_kills_and_reaps_a_delegated_root() {
fault::set_attachment_override(crate::containment::Attachment {
containment: crate::containment::Containment::Delegated,
attached: crate::containment::Attached::Delegated,
graceful: crate::graceful::GracefulMechanism::Process,
});
let (mut cmd, teardown) = teardown_blocker();
cmd.kill_on_drop(false);
let child = super::spawn_uncommitted(&mut cmd).expect("spawn");
let pid = child.pid();
let (err, fate) = super::finish_elevated(child, failed_write())
.expect_err("a failed write fails the spawn")
.expect_may_have_started_with();
assert_eq!(fate, ChildFate::Reaped);
teardown.assert_killed();
let reaped = reaped(pid);
if !reaped {
unsafe { libc::kill(pid as i32, libc::SIGKILL) };
}
assert!(reaped, "the root must be killed and reaped, got {err:?}");
assert!(err.to_string().contains("was terminated"), "got {err:?}");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_failed_password_write_reaps_the_root_when_the_tree_kill_fails() {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-unkillable-leaf");
std::fs::create_dir(&leaf_path).expect("create the leaf");
std::fs::create_dir(leaf_path.join("cgroup.kill")).expect("make cgroup.kill unwritable");
fault::set_attachment_override(crate::containment::Attachment {
containment: crate::containment::Containment::CgroupV2,
attached: crate::containment::Attached::Cgroup(crate::containment::cgroup::test_support::entered_leaf_at(
leaf_path.clone(),
)),
graceful: crate::graceful::GracefulMechanism::Process,
});
let (mut cmd, teardown) = teardown_blocker();
cmd.kill_on_drop(false);
let child = super::spawn_uncommitted(&mut cmd).expect("spawn");
let pid = child.pid();
let (err, fate) = super::finish_elevated(child, failed_write())
.expect_err("a failed write fails the spawn")
.expect_may_have_started_with();
assert_eq!(fate, ChildFate::Reaped);
teardown.assert_killed();
assert!(reaped(pid), "the root was killed, so it must be reaped, got {err:?}");
let detail = err.to_string();
assert!(detail.contains("was terminated"), "the root was killed, got {detail}");
assert!(
detail.contains("its contained tree could not be killed"),
"the tree's failure is reported, got {detail}"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_failed_tree_kill_and_an_unknown_root_share_one_warn() {
crate::log_capture::install();
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-unkillable-leaf");
std::fs::create_dir(&leaf_path).expect("create the leaf");
std::fs::create_dir(leaf_path.join("cgroup.kill")).expect("make cgroup.kill unwritable");
fault::set_attachment_override(crate::containment::Attachment {
containment: crate::containment::Containment::CgroupV2,
attached: crate::containment::Attached::Cgroup(crate::containment::cgroup::test_support::entered_leaf_at(
leaf_path.clone(),
)),
graceful: crate::graceful::GracefulMechanism::Process,
});
let (mut cmd, teardown) = teardown_blocker();
cmd.kill_on_drop(false);
let mut child = super::spawn_uncommitted(&mut cmd).expect("spawn");
let pid = child.pid();
let mark = crate::log_capture::mark();
let unsure = child
.proc
.script_over(|f| f.peeks([Err(std::io::Error::other("forced peek failure 7a2e"))]));
let (err, _fate) = super::finish_elevated(child, failed_write())
.expect_err("a failed write fails the spawn")
.expect_may_have_started_with();
unsure.assert_peeks_exhausted();
teardown.assert_killed();
assert!(reaped(pid), "the root was killed through its handle, got {err:?}");
let warns: Vec<_> = crate::log_capture::records_since_on_current_thread(mark, "")
.into_iter()
.filter(|(level, text)| *level <= log::Level::Warn && !text.contains("was not removed"))
.collect();
assert_eq!(warns.len(), 1, "{warns:?}");
assert!(
warns[0]
.1
.contains("tree teardown after a failed password write failed")
&& warns[0].1.contains("RootState::Unknown"),
"the one warn names the tree's failure and the unknown root: {warns:?}"
);
}
#[cfg(target_os = "macos")]
#[skuld::test]
fn a_refused_own_identity_read_is_unassessable_and_the_program_does_not_run() {
use crate::child::spawn::identity_macos_tests::{ran_marker, RAN_ARGV};
let (stdout, reader) = ran_marker();
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(RAN_ARGV);
cmd.stdout(stdout).expect("set stdout");
let forced = crate::child::spawn::unique_report::seams::force_child_read_errno(libc::EPERM);
let err = cmd.spawn().err();
drop(forced);
match expect_not_started(err.expect("a refused identity read must fail the spawn")) {
Error::Unassessable { detail, source } => {
assert!(detail.contains("did not start"), "{detail}");
assert_eq!(source.and_then(|e| e.raw_os_error()), Some(libc::EPERM));
}
other => panic!("expected Unassessable, got {other:?}"),
}
crate::child::spawn::identity_macos_tests::assert_program_did_not_run(cmd, reader);
}
#[cfg(target_os = "macos")]
struct LeftChild(crate::identity::ProcessId);
#[cfg(target_os = "macos")]
impl Drop for LeftChild {
fn drop(&mut self) {
let pid = self.0.pid() as libc::pid_t;
unsafe {
libc::kill(pid, libc::SIGKILL);
let mut status = 0;
libc::waitpid(pid, &mut status, 0);
}
}
}
#[cfg(target_os = "macos")]
fn captured_child() -> LeftChild {
let Some(crate::identity::Resolved::Found(id)) = fault::take_captured() else {
panic!("the failed spawn captured the child's identity");
};
LeftChild(id)
}
#[cfg(target_os = "macos")]
fn assert_left_alone(mark: usize, warning: &str, left: &LeftChild) {
let pid = left.0.pid();
assert!(
crate::log_capture::contains_since(mark, &format!("child {pid} {warning}")),
"the warning must name the child"
);
assert_eq!(
left.0.is_alive(),
crate::identity::Liveness::Alive,
"the child must not have been killed"
);
let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
let rc = unsafe {
libc::waitid(
libc::P_PID,
pid as libc::id_t,
&mut info,
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
)
};
assert_eq!(rc, 0, "waitid: {}", std::io::Error::last_os_error());
assert_eq!(unsafe { info.si_pid() }, 0, "the child must still be running");
}
#[cfg(target_os = "macos")]
fn open_fd_count() -> usize {
std::fs::read_dir("/dev/fd").expect("read /dev/fd").count()
}
#[cfg(target_os = "macos")]
#[skuld::test]
fn macos_identity_gone_closes_our_pipe_ends() {
macos_failed_spawn_closes_our_pipe_ends(
|| fault::set_force_identity_vanished(true),
|| fault::set_force_identity_vanished(false),
false,
ChildFate::Gone,
);
}
#[cfg(target_os = "macos")]
#[skuld::test]
fn macos_attach_failure_closes_our_pipe_ends() {
macos_failed_spawn_closes_our_pipe_ends(
|| fault::set_force_attach_failure(true),
|| fault::set_force_attach_failure(false),
false,
ChildFate::Reaped,
);
}
#[cfg(target_os = "macos")]
fn macos_failed_spawn_closes_our_pipe_ends(
arm: impl FnOnce(),
disarm: impl FnOnce(),
tree_walk: bool,
expected: ChildFate,
) {
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
cmd.stdin(crate::stdio::Stdio::pipe_in()).expect("piped stdin");
if tree_walk {
cmd.contain_with(crate::ContainMode::TreeWalk);
}
let before = open_fd_count();
arm();
let err = cmd.spawn().err();
disarm();
let _left = captured_child();
drop(cmd);
let (_err, fate) = expect_may_have_started_with(err.expect("the forced failure must fail the spawn"));
assert_eq!(fate, expected);
assert_eq!(open_fd_count(), before, "the failed spawn must close our pipe ends");
}
#[cfg(unix)]
#[skuld::test]
fn finish_elevated_after_a_foreign_reap_does_not_claim_a_kill() {
let (mut cmd, writer) = blocker_with_held_stdin();
let child = cmd.spawn().expect("spawn");
foreign_reap(&child, writer);
let (detail, fate) = finish_elevated_detail_and_fate(child);
assert!(detail.contains("could not be terminated"), "{detail}");
assert!(detail.contains("it was already reaped"), "{detail}");
assert!(!detail.contains("was killed"), "{detail}");
assert_eq!(fate, ChildFate::Gone, "reaped by someone else");
}
#[cfg(unix)]
#[skuld::test]
fn finish_elevated_after_a_foreign_reap_sends_no_killpg_to_a_process_group() {
#[cfg(target_os = "linux")]
let _old_kernel = crate::containment::unix::fault::refuse_pidfd_group_flag();
let recorder = crate::containment::unix::fault::record_kill_group();
let (mut cmd, writer) = blocker_with_held_stdin();
cmd.contain_with(crate::containment::ContainMode::Session);
let child = cmd.spawn().expect("spawn");
assert!(
child.attached.signals_a_group(),
"the test needs a group named by the root's pid, which ContainMode::Session makes"
);
foreign_reap(&child, writer);
let detail = finish_elevated_detail(child);
assert_eq!(
recorder.killed(),
Vec::<i32>::new(),
"a reaped root's group number may name another group: no killpg ({detail})"
);
assert!(detail.contains("process group"), "{detail}");
assert!(detail.contains("already reaped"), "{detail}");
}
#[cfg(unix)]
fn foreign_reap(child: &crate::Child, writer: crate::PipeWriter) {
let pid = child.pid();
drop(writer);
crate::test_child::wait_until_zombie(pid);
let mut status = 0;
let reaped = unsafe { libc::waitpid(pid as libc::pid_t, &mut status, 0) };
assert_eq!(reaped, pid as libc::pid_t, "{}", std::io::Error::last_os_error());
}
#[cfg(unix)]
#[skuld::test]
fn a_tree_kill_is_left_to_try_unless_none_was_made_or_it_killed_or_unvouched_the_tree() {
use crate::containment::dispatch::{SettleOutcome, Unsettled, UnvouchedKind};
let unsettled = || Unsettled {
first: Error::Containment {
detail: "refused".into(),
},
others: Vec::new(),
};
let table = [
("none made", None, false),
("killed", Some(Ok(SettleOutcome::Killed)), false),
(
"unvouched",
Some(Ok(SettleOutcome::Unvouched {
kind: UnvouchedKind::RootSeenRunning,
})),
false,
),
("skipped", Some(Ok(SettleOutcome::Skipped)), true),
("left members", Some(Err(unsettled())), true),
];
for (label, tree, want) in table {
assert_eq!(super::tree_needs_another_kill(&tree), want, "{label}");
}
}
#[cfg(unix)]
fn finish_elevated_detail(child: crate::Child) -> String {
finish_elevated_detail_and_fate(child).0
}
#[cfg(unix)]
fn finish_elevated_detail_and_fate(child: crate::Child) -> (String, ChildFate) {
let (err, fate) = super::finish_elevated(
child,
Err(Error::Elevation {
kind: crate::error::ElevationErrorKind::AuthFailed,
detail: "forced password-write failure".into(),
}),
)
.expect_err("the spawn fails")
.expect_may_have_started_with();
let Error::Elevation { detail, .. } = err else {
panic!("expected an Elevation error, got {err:?}");
};
(detail, fate)
}
#[cfg(target_os = "macos")]
#[skuld::test]
fn macos_identity_gone_forgets_the_child_and_signals_nothing() {
crate::log_capture::install();
let mark = crate::log_capture::mark();
let mut cmd = blocker();
fault::set_force_identity_vanished(true);
let err = cmd.spawn().err();
fault::set_force_identity_vanished(false);
let left = captured_child();
let (err, fate) = expect_may_have_started_with(err.expect("a vanished identity fails the spawn"));
assert!(matches!(err, Error::Io(_)), "{err:?}");
assert_eq!(fate, ChildFate::Gone, "the check found it reaped by someone else");
assert_left_alone(mark, "was reaped by someone else", &left);
}
#[skuld::test]
fn spawn_pid_is_cleared_once_the_hook_has_run() {
fault::run_at(fault::SpawnPoint::BeforeIdentity, 4242);
assert!(
std::panic::catch_unwind(fault::spawn_pid).is_err(),
"spawn_pid must panic outside a hook"
);
}
const MISSING_PROGRAM: &str = "cosca-no-such-program-142";
#[skuld::test]
fn a_failed_exec_did_not_start_the_program() {
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args([MISSING_PROGRAM]);
let err = expect_not_started(cmd.spawn().expect_err("a missing program fails the spawn"));
assert!(
matches!(err, Error::Io(ref e) if e.kind() == std::io::ErrorKind::NotFound),
"{err:?}"
);
}
#[skuld::test]
fn a_refused_stdio_setup_did_not_start_the_program() {
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
cmd.stdout(crate::stdio::Stdio::merge(crate::stdio::Fd::STDERR))
.expect("stdout");
cmd.stderr(crate::stdio::Stdio::merge(crate::stdio::Fd::STDOUT))
.expect("stderr");
let err = expect_not_started(cmd.spawn().expect_err("a merge into a merge is refused"));
assert!(matches!(err, Error::Unsupported { .. }), "{err:?}");
}
#[cfg(unix)]
#[skuld::test]
fn run_to_completion_failures_after_the_spawn_may_have_started() {
let mut missing = crate::test_child::command(Console::Hidden);
missing.args([MISSING_PROGRAM]);
expect_not_started(missing.read().expect_err("a missing program fails"));
expect_not_started(missing.output().expect_err("a missing program fails"));
expect_not_started(missing.status().expect_err("a missing program fails"));
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(["printf", "\\377"]);
let (err, fate) = expect_may_have_started_with(cmd.read().expect_err("invalid UTF-8 fails `read`"));
assert_eq!(fate, ChildFate::Reaped, "`read` collected the exit");
assert!(
matches!(err, Error::Io(ref e) if e.kind() == std::io::ErrorKind::InvalidData),
"{err:?}"
);
}
#[skuld::test]
fn a_command_with_no_program_did_not_start() {
let err = expect_not_started(
crate::test_child::command(Console::Hidden)
.spawn()
.expect_err("no program, no spawn"),
);
assert!(matches!(err, Error::Io(_)), "{err:?}");
}
#[cfg(unix)]
#[skuld::test]
fn an_elevation_refused_for_its_shape_did_not_start() {
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(["/bin/sh", "-c", "true"]).elevate();
cmd.fd(3, crate::stdio::Stdio::null()).expect("fd 3");
let err = expect_not_started(cmd.spawn().expect_err("fd >= 3 is refused under elevation"));
assert!(matches!(err, Error::Unsupported { .. }), "{err:?}");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_handshake_that_cannot_open_did_not_start() {
let _armed = super::pidfd_handshake::fault::fail_done_fd(rustix::io::Errno::MFILE);
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
let err = expect_not_started(cmd.spawn().expect_err("a failed open fails the spawn"));
assert!(
matches!(err, Error::Io(ref e) if e.to_string() == format!("eventfd: {}", std::io::Error::from_raw_os_error(libc::EMFILE))),
"{err:?}"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_child_reaped_elsewhere_after_the_teardowns_kill_is_killed() {
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 pid = std::rc::Rc::new(std::cell::Cell::new(0));
let _noted = fault::set_at(fault::SpawnPoint::BeforeIdentity, {
let pid = std::rc::Rc::clone(&pid);
move || pid.set(fault::spawn_pid())
});
let _foreign_reap = crate::graceful_hooks::at(crate::graceful_hooks::HookPoint::AfterDropKill, move || {
let pid = pid.get();
assert_ne!(pid, 0, "the spawn noted the child's pid");
drop(writer);
crate::test_child::assert_zombie_sigkilled("the child", pid);
let mut status = 0;
let reaped = unsafe { libc::waitpid(pid as libc::pid_t, &mut status, 0) };
assert_eq!(reaped, pid as libc::pid_t, "{}", std::io::Error::last_os_error());
});
fault::set_force_identity_vanished(true);
let err = cmd.spawn().err();
fault::set_force_identity_vanished(false);
let (_err, fate) = expect_may_have_started_with(err.expect("the forced vanish fails the spawn"));
assert_eq!(fate, ChildFate::Killed);
}
#[skuld::test]
fn a_foreign_verdict_is_killed_after_a_delivered_kill_and_gone_otherwise() {
use crate::os_process::child::Foreign;
for foreign in [Foreign::Gone, Foreign::Other, Foreign::Orphaned] {
assert_eq!(foreign.fate(true), ChildFate::Killed, "{foreign:?}");
assert_eq!(foreign.fate(false), ChildFate::Gone, "{foreign:?}");
}
}
#[cfg(unix)]
#[skuld::test]
fn an_unfolded_diagnosis_is_logged_on_drop_but_not_while_unwinding() {
crate::log_capture::install();
let mark = crate::log_capture::mark();
drop(super::Diagnosis::of("diagnosis 4e1c, dropped quietly".to_owned()));
assert!(crate::log_capture::contains_since(
mark,
"diagnosis 4e1c, dropped quietly"
));
let mark = crate::log_capture::mark();
let unwound = std::panic::catch_unwind(|| {
let _owed = super::Diagnosis::of("diagnosis 9b7a, dropped unwinding".to_owned());
panic!("unwinding with a diagnosis owed");
});
assert!(unwound.is_err());
assert!(!crate::log_capture::contains_since(
mark,
"diagnosis 9b7a, dropped unwinding"
));
}
#[cfg(unix)]
#[skuld::test]
fn a_note_owed_after_a_keep_is_warned_and_the_kept_check_is_not() {
crate::log_capture::install();
let mark = crate::log_capture::mark();
let mut why = super::Diagnosis::of_failed_check(
"check 6d1f, kept".to_owned(),
std::io::Error::other("forced check failure"),
);
let _ = super::kept_without_identity(1, Default::default(), &mut why);
why.add("later note 2b9c");
drop(why);
let warns = crate::log_capture::warns_since(mark, "");
assert_eq!(warns.len(), 1, "{warns:?}");
assert!(
warns[0].contains("later note 2b9c") && !warns[0].contains("check 6d1f"),
"the later note is warned alone: {warns:?}"
);
assert_eq!(
crate::log_capture::levels_since(mark, "check 6d1f, kept"),
[log::Level::Debug],
"the kept check is logged once, at debug"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn resolve_identity_of_a_reaped_child_whose_pid_a_same_tick_reuser_holds_is_gone() {
use rustix::process::{pidfd_open, waitid, Pid, PidfdFlags, WaitId, WaitIdOptions};
use crate::identity::stat_parse::stat_fixture;
use crate::identity::{FakeKernel, HostKernel, Resolved};
use crate::wait::exit_only::Target;
#[allow(
clippy::zombie_processes,
reason = "reaped through its pidfd; waiting by its number could reach a reused pid"
)]
let mut child = crate::test_spawn::spawn(&mut crate::test_child::held_std_blocker(std::process::Stdio::null()))
.expect("spawn the child");
let pid = child.id();
let raw = Pid::from_raw(pid as i32).expect("a child's pid is nonzero");
let pidfd = pidfd_open(raw, PidfdFlags::empty()).expect("pidfd_open the child");
let id = crate::identity::ticks_id(pid);
drop(child.stdin.take());
crate::test_child::pid_reuse::wait_pollin(std::os::fd::AsFd::as_fd(&pidfd));
let reaped = waitid(WaitId::PidFd(std::os::fd::AsFd::as_fd(&pidfd)), WaitIdOptions::EXITED).expect("raw reap");
assert!(reaped.is_some(), "the raw reap must consume an exit record");
let look_alike = stat_fixture("S", id.key().ticks());
let kernel = FakeKernel::over(&HostKernel)
.live_without_pidfs(pid, pidfd.try_clone().expect("the pidfd duplicates"))
.same_view()
.on_read(&format!("{pid}/stat"), Ok(&look_alike));
let held = held_through(&kernel, pid);
let (read, _, _) = super::resolve_identity(&kernel, pid, &Target::PidFd(std::os::fd::AsFd::as_fd(&held)));
assert!(
matches!(read, Resolved::Gone),
"a look-alike with the child's token is not the child: {read:?}"
);
}
#[cfg(target_os = "linux")]
fn held_through(kernel: &crate::identity::FakeKernel<'_>, pid: u32) -> std::os::fd::OwnedFd {
use crate::identity::Kernel as _;
let target = rustix::process::Pid::from_raw(pid as i32).expect("a child's pid is nonzero");
kernel
.pidfd_open(target, rustix::process::PidfdFlags::empty())
.expect("the kernel's row hands out the pidfd")
}
#[cfg(target_os = "linux")]
fn live_child_with_pidfd() -> (std::process::Child, std::os::fd::OwnedFd) {
#[allow(clippy::zombie_processes, reason = "the test reaps it with `release`")]
let child = crate::test_spawn::spawn(&mut crate::test_child::held_std_blocker(std::process::Stdio::null()))
.expect("spawn the child");
let raw = rustix::process::Pid::from_raw(child.id() as i32).expect("a child's pid is nonzero");
let pidfd = rustix::process::pidfd_open(raw, rustix::process::PidfdFlags::empty()).expect("pidfd_open the child");
(child, pidfd)
}
#[cfg(target_os = "linux")]
fn release(mut child: std::process::Child) {
drop(child.stdin.take());
child.wait().expect("reap the child");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn resolve_identity_reads_the_held_pidfd_and_needs_no_second_open() {
use crate::identity::{FakeKernel, HostKernel, ProcessId, Resolved};
use crate::wait::exit_only::Target;
let (child, pidfd) = live_child_with_pidfd();
let pid = child.id();
let kernel = FakeKernel::over(&HostKernel).on_pidfd_open(pid, Err(rustix::io::Errno::MFILE));
let (read, _, why) = super::resolve_identity(&kernel, pid, &Target::PidFd(std::os::fd::AsFd::as_fd(&pidfd)));
let Resolved::Found(id) = read else {
panic!("the held pidfd answers whatever a second open would: {read:?}")
};
assert!(!why.is_owed(), "a held pidfd that answers owes no diagnosis");
assert_eq!(
ProcessId::of(pid).found(),
Some(id),
"the key read from the held pidfd is the one the by-pid read gives"
);
release(child);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn resolve_identity_with_a_failing_fstat_on_the_held_pidfd_is_unknown() {
use crate::identity::{FakeKernel, HostKernel, Resolved};
use crate::wait::exit_only::Target;
let (child, pidfd) = live_child_with_pidfd();
let pid = child.id();
let kernel = FakeKernel::over(&HostKernel)
.on_pidfd_open(pid, Ok(pidfd.try_clone().expect("the pidfd duplicates")))
.on_pidfs_ino(pid, Err(rustix::io::Errno::BADF));
let held = held_through(&kernel, pid);
let (read, _, _) = super::resolve_identity(&kernel, pid, &Target::PidFd(std::os::fd::AsFd::as_fd(&held)));
assert!(matches!(read, Resolved::Unknown), "{read:?}");
release(child);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn resolve_identity_with_a_held_pidfd_that_has_no_inode_reads_proc() {
use crate::identity::{FakeKernel, HostKernel, Resolved};
use crate::wait::exit_only::Target;
let (child, pidfd) = live_child_with_pidfd();
let pid = child.id();
let kernel =
FakeKernel::over(&HostKernel).live_without_pidfs(pid, pidfd.try_clone().expect("the pidfd duplicates"));
let held = held_through(&kernel, pid);
let (read, _, _) = super::resolve_identity(&kernel, pid, &Target::PidFd(std::os::fd::AsFd::as_fd(&held)));
match read {
Resolved::Found(id) => assert_eq!(id, crate::identity::ticks_id(pid)),
other => panic!("{other:?}"),
}
release(child);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn resolve_identity_of_a_reaped_child_is_gone() {
use rustix::process::{pidfd_open, waitid, Pid, PidfdFlags, WaitId, WaitIdOptions};
use crate::identity::{FakeKernel, HostKernel, Resolved};
use crate::wait::exit_only::Target;
#[allow(
clippy::zombie_processes,
reason = "reaped through its pidfd; waiting by its number could reach a reused pid"
)]
let mut child = crate::test_spawn::spawn(&mut crate::test_child::held_std_blocker(std::process::Stdio::null()))
.expect("spawn the child");
let pid = child.id();
let raw = Pid::from_raw(pid as i32).expect("a child's pid is nonzero");
let pidfd = pidfd_open(raw, PidfdFlags::empty()).expect("pidfd_open the child");
drop(child.stdin.take());
crate::test_child::pid_reuse::wait_pollin(std::os::fd::AsFd::as_fd(&pidfd));
let reaped = waitid(WaitId::PidFd(std::os::fd::AsFd::as_fd(&pidfd)), WaitIdOptions::EXITED).expect("raw reap");
assert!(reaped.is_some(), "the raw reap must consume an exit record");
let kernel = FakeKernel::over(&HostKernel)
.on_pidfd_open(pid, Ok(pidfd.try_clone().expect("the pidfd duplicates")))
.on_pidfs_ino(pid, Ok(Some(1)));
let held = held_through(&kernel, pid);
let (read, _, _) = super::resolve_identity(&kernel, pid, &Target::PidFd(std::os::fd::AsFd::as_fd(&held)));
assert!(matches!(read, Resolved::Gone), "a reaped child is gone: {read:?}");
}
#[cfg(windows)]
#[skuld::test]
fn every_pipe_a_spawn_makes_is_overlapped_in_the_parent_and_synchronous_in_the_child() {
use std::os::windows::io::{AsHandle as _, AsRawHandle as _, BorrowedHandle};
use crate::pipe::windows::is_overlapped;
use crate::stdio::{Direction, Fd, Stdio};
for dir in [Direction::In, Direction::Out] {
let (child_end, parent_end) = super::make_pipe(dir).expect("make the pipe");
let theirs = unsafe { BorrowedHandle::borrow_raw(child_end.as_raw_handle()) };
assert!(
!is_overlapped(theirs).expect("query the child's end"),
"{dir:?}: the child's end is overlapped"
);
assert!(
is_overlapped(crate::test_child::parent_handle(&parent_end)).expect("query the parent's end"),
"{dir:?}: the parent's end is synchronous"
);
}
type Row<'a> = (&'a str, &'a [(i32, Direction)], Option<(i32, i32)>);
let rows: [Row; 3] = [
(
"std slots",
&[(0, Direction::In), (1, Direction::Out), (2, Direction::Out)],
None,
),
("merge target", &[(1, Direction::Out)], Some((2, 1))),
("fd >= 3", &[(3, Direction::Out), (4, Direction::In)], None),
];
for (row, pipes, merge) in rows {
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(["cmd", "/C", "exit 0"]);
for &(slot, dir) in pipes {
cmd.fd(
slot,
match dir {
Direction::In => Stdio::pipe_in(),
Direction::Out => Stdio::pipe_out(),
},
)
.expect("set the pipe");
}
if let Some((slot, target)) = merge {
cmd.fd(slot, Stdio::merge(Fd::from(target))).expect("set the merge");
}
let mut child = cmd.spawn().expect("spawn");
for &(slot, dir) in pipes {
let slot = Fd::from(slot);
let mode = match dir {
Direction::In => child
.fd_write_end(slot)
.map(|w| is_overlapped(w.as_handle()).expect("query the mode")),
Direction::Out => child
.fd_read_end(slot)
.map(|r| is_overlapped(r.as_handle()).expect("query the mode")),
};
assert_eq!(mode, Some(true), "{row}: the parent's end for {slot} is not overlapped");
}
child.wait().expect("reap");
}
}
#[cfg(windows)]
#[skuld::test]
fn piping_one_childs_stdout_into_anothers_stdin_delivers_the_bytes() {
use std::io::Read as _;
let mut first = crate::test_child::command(Console::Hidden);
first.args(["cmd", "/C", "echo x-through-the-pipe"]);
first.stdout(crate::Stdio::pipe()).expect("set stdout pipe");
let mut first = first.spawn().expect("spawn the writer");
let stdout = first.stdout().expect("piped stdout");
let mut second = crate::test_spawn::spawn(
std::process::Command::new("findstr")
.arg("x")
.stdin(std::process::Stdio::from(stdout))
.stdout(std::process::Stdio::piped()),
)
.expect("spawn the reader");
let mut out = String::new();
second
.stdout
.take()
.expect("piped stdout")
.read_to_string(&mut out)
.expect("read the second child's output");
assert_eq!(out.trim(), "x-through-the-pipe");
assert!(second.wait().expect("reap the reader").success());
first.wait().expect("reap the writer");
}