use super::{kill_group, term_group};
use crate::test_child::blocker_with;
use crate::test_groups::{stray_signal, Group};
use crate::test_support::stated_root::StatedRoot;
fn await_zombie(pid: u32) {
let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
loop {
let rc = unsafe { libc::waitid(libc::P_PID, pid as libc::id_t, &mut info, libc::WEXITED | libc::WNOWAIT) };
if rc == 0 {
return;
}
let err = std::io::Error::last_os_error();
if err.raw_os_error() == Some(libc::EINTR) {
continue;
}
panic!("waitid failed: {err}");
}
}
#[skuld::test]
fn kill_group_and_term_group_reject_non_positive_pgid(#[fixture(stray_signal)] _stray: &Group) {
for pgid in [0, -1, i32::MIN] {
let kill_err = kill_group(pgid, Some(&StatedRoot::unreaped()), &mut Vec::new())
.expect_err("kill_group(non-positive) must be Err");
assert!(
matches!(kill_err, crate::error::Error::Unassessable { .. }),
"got {kill_err:?}"
);
let term_err =
term_group(pgid, Some(&StatedRoot::unreaped())).expect_err("term_group(non-positive) must be Err");
assert!(
matches!(term_err, crate::error::Error::Unassessable { .. }),
"got {term_err:?}"
);
}
}
#[skuld::test]
fn term_group_tree_of_a_non_positive_pgid_says_nothing_was_sent(#[fixture(stray_signal)] _stray: &Group) {
for pgid in [0, -1, i32::MIN] {
match super::term_group_tree(
pgid,
Some(&StatedRoot::unreaped()),
crate::containment::TreeStop::default(),
) {
crate::containment::TerminateOutcome::NotSent(crate::error::Error::Unassessable {
source: None, ..
}) => {}
other => panic!("pgid {pgid}: expected NotSent(Unassessable), got {other:?}"),
}
}
}
#[skuld::test]
fn kill_group_on_owned_group_succeeds() {
use std::os::unix::process::CommandExt;
use std::os::unix::process::ExitStatusExt as _;
let mut child = blocker_with(|cat| {
cat.process_group(0);
});
let stdin = child.stdin.take().expect("piped stdin");
let pgid = child.id() as i32;
assert!(
kill_group(pgid, Some(&StatedRoot::unreaped()), &mut Vec::new()).is_ok(),
"kill_group on owned group must succeed"
);
drop(stdin);
let status = child.wait().expect("wait after kill_group");
assert_eq!(
status.signal(),
Some(libc::SIGKILL),
"kill_group must have actually killed the leader, got {status:?}"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn kill_group_dooms_the_group_before_it_is_listed() {
use std::io::BufRead as _;
use std::os::unix::process::CommandExt;
use std::os::unix::process::ExitStatusExt as _;
let mut child = crate::test_child::StdChild::spawn(
std::process::Command::new("sh")
.arg("-c")
.arg("while read x; do (echo spawned; exec cat) & done")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.process_group(0),
);
let mut stdin = child.stdin.take().expect("piped stdin");
let mut stdout = std::io::BufReader::new(child.stdout.take().expect("piped stdout"));
let pgid = child.id() as i32;
let seen = std::rc::Rc::new(std::cell::RefCell::new(None::<String>));
let record = seen.clone();
let _armed = super::group::fault::set_after_listing(move || {
crate::test_child::write_to_possibly_dead_stdin(&mut stdin, b"x\n");
let mut line = String::new();
stdout.read_line(&mut line).expect("read to a line or EOF");
*record.borrow_mut() = Some(line);
});
kill_group(pgid, Some(&StatedRoot::unreaped()), &mut Vec::new()).expect("kill_group on an owned group");
let status = child.wait().expect("reap the leader");
let line = seen.borrow_mut().take().expect("the hook ran in converge");
assert_eq!(
line, "",
"a member forked after the listing: the first killpg did not doom the group"
);
assert_eq!(status.signal(), Some(libc::SIGKILL), "got {status:?}");
}
#[skuld::test]
fn term_group_on_owned_group_succeeds() {
use std::os::unix::process::{CommandExt, ExitStatusExt as _};
let mut child = blocker_with(|cat| {
cat.process_group(0);
});
let stdin = child.stdin.take().expect("piped stdin");
let pgid = child.id() as i32;
assert!(
term_group(pgid, Some(&StatedRoot::unreaped())).is_ok(),
"term_group on owned group must succeed"
);
drop(stdin);
let status = child.wait().expect("wait after term_group");
assert_eq!(
status.signal(),
Some(libc::SIGTERM),
"term_group must have actually delivered SIGTERM and ended the leader, got {status:?}"
);
}
#[skuld::test]
fn kill_group_on_an_all_zombie_group_is_ok() {
use std::os::unix::process::CommandExt;
let child = crate::test_spawn::spawn(std::process::Command::new("true").process_group(0)).expect("spawn true");
let pid = child.id();
await_zombie(pid);
#[cfg(target_os = "macos")]
assert_eq!(
nix::sys::signal::killpg(nix::unistd::Pid::from_raw(pid as i32), None),
Err(nix::errno::Errno::EPERM),
"macOS reports EPERM for an all-zombie group; if this changed, the arm under test moved"
);
assert!(
kill_group(pid as i32, Some(&StatedRoot::unreaped()), &mut Vec::new()).is_ok(),
"a group holding only a zombie is already down"
);
let mut child = child;
child.wait().expect("reap");
}
#[skuld::test]
fn term_group_on_an_all_zombie_group_is_ok() {
use std::os::unix::process::CommandExt;
let child = crate::test_spawn::spawn(std::process::Command::new("true").process_group(0)).expect("spawn true");
let pid = child.id();
await_zombie(pid);
#[cfg(target_os = "macos")]
assert_eq!(
nix::sys::signal::killpg(
nix::unistd::Pid::from_raw(pid as i32),
nix::sys::signal::Signal::SIGTERM
),
Err(nix::errno::Errno::EPERM),
"macOS reports EPERM for an all-zombie group; if this changed, the arm under test moved"
);
#[cfg(target_os = "linux")]
assert_eq!(
nix::sys::signal::killpg(
nix::unistd::Pid::from_raw(pid as i32),
nix::sys::signal::Signal::SIGTERM
),
Ok(()),
"Linux reports Ok for an all-zombie group (no live member to refuse); if this changed, \
the arm under test moved"
);
assert!(
term_group(pid as i32, Some(&StatedRoot::unreaped())).is_ok(),
"a group holding only a zombie is already down"
);
let mut child = child;
child.wait().expect("reap");
}
mod group_kill_and_terminate {
use super::super::{fault, kill_group_tree, term_group_tree};
use crate::containment::dispatch::TreeKillOutcome;
use crate::containment::{Refusal, TerminateOutcome, Why};
use crate::signal::RootState;
use crate::test_support::stated_root::StatedRoot;
const PGID: i32 = 999_999;
#[derive(Clone, Copy, Debug)]
enum Root {
Unreaped,
ReapedElsewhere,
Unknown,
}
fn stated(root: Root) -> StatedRoot<'static> {
StatedRoot::with_state(PGID as u32, move || match root {
Root::Unreaped => RootState::Unreaped,
Root::ReapedElsewhere => RootState::Reaped,
Root::Unknown => RootState::Unknown(std::sync::Arc::new(std::io::Error::other("a failed peek"))),
})
}
fn assert_skip(skip: &crate::containment::Skip, verb: &str, root: Root) {
assert_eq!(
skip.action,
format!("{verb} its process group (pgid {PGID})"),
"{root:?}"
);
assert!(skip.holders.is_none(), "a group has no holders: {root:?}");
match (&skip.why, root) {
(Why::MayNameAnother(Refusal::ReapedElsewhere(_), _), Root::ReapedElsewhere) => {
assert!(!skip.root_alone, "{root:?}");
}
(Why::MayNameAnother(Refusal::Unsure(..), _), Root::Unknown) => {
assert_eq!(skip.root_alone, cfg!(target_os = "linux"), "{root:?}");
}
(Why::Untrusted { .. }, Root::Unknown) if cfg!(target_os = "macos") => {}
(why, _) => panic!("{root:?} was skipped for {why:?}"),
}
}
#[skuld::test]
fn a_group_kill_sends_or_skips_by_the_roots_state() {
for root in [Root::Unreaped, Root::ReapedElsewhere, Root::Unknown] {
let recorder = fault::record_kill_group();
let outcome = kill_group_tree(PGID, Some(&stated(root))).outcome();
let sent = recorder.killed();
match (root, outcome) {
(Root::Unreaped, TreeKillOutcome::Ran(Ok(()))) => assert_eq!(sent, [PGID], "{root:?}"),
(_, TreeKillOutcome::Skipped(skip)) => {
assert_eq!(sent, Vec::<i32>::new(), "{root:?}");
assert_skip(&skip, "kill", root);
}
(_, outcome) => panic!("{root:?} was answered {outcome:?}"),
}
}
}
#[skuld::test]
fn a_group_terminate_sends_or_skips_by_the_roots_state() {
for root in [Root::Unreaped, Root::ReapedElsewhere, Root::Unknown] {
let recorder = fault::record_term_group();
let outcome = term_group_tree(PGID, Some(&stated(root)), crate::containment::TreeStop::default());
let sent = recorder.termed();
match (root, outcome) {
(
Root::Unreaped,
TerminateOutcome::Sent {
result: Ok(()),
earlier: Some(ref earlier),
..
},
) if earlier == "the SIGTERM" => assert_eq!(sent, [PGID], "{root:?}"),
(Root::Unknown, TerminateOutcome::RootThroughPidfd(skip)) if cfg!(target_os = "linux") => {
assert_eq!(sent, Vec::<i32>::new(), "{root:?}");
assert_skip(&skip, "signal", root);
}
(_, TerminateOutcome::End(skip)) => {
assert_eq!(sent, Vec::<i32>::new(), "{root:?}");
assert_skip(&skip, "signal", root);
}
(_, outcome) => panic!("{root:?} was answered {outcome:?}"),
}
}
}
}
#[skuld::test]
fn a_send_refused_for_an_unsure_root_has_the_handles_error_as_its_source() {
use super::send_to_group;
use crate::error::Error;
use crate::signal::RootState;
let os_error = std::io::Error::from_raw_os_error(libc::EPERM).to_string();
let root = StatedRoot::with_state(999_999, || {
RootState::Unknown(std::sync::Arc::new(std::io::Error::from_raw_os_error(libc::EPERM)))
});
let refused = send_to_group(999_999, nix::sys::signal::Signal::SIGTERM, Some(&root))
.expect_err("a root that cannot say is no check that passes");
let Error::Unassessable { detail, .. } = &refused else {
panic!("got {refused:?}");
};
assert_eq!(crate::error::first_os_code(&refused), Some(libc::EPERM), "{refused:?}");
assert!(!detail.contains(&os_error), "{detail}");
}
#[skuld::test]
fn a_skip_over_an_untrusted_root_has_the_handles_error_as_its_source() {
use super::skipped_group;
use crate::containment::root::NumberLook;
use crate::containment::{SkipCall, Tree};
use crate::error::Error;
use crate::signal::RootState;
use crate::signal::Sig;
let os_error = std::io::Error::from_raw_os_error(libc::EPERM).to_string();
let call = SkipCall {
op: "skip_untrusted_probe_4c2",
pid: 999_999,
signal: Sig::Graceful(crate::signal::Signal::Term),
earlier: None,
};
let skip = skipped_group(
999_999,
"kill",
NumberLook::Untrusted(RootState::Unknown(std::sync::Arc::new(
std::io::Error::from_raw_os_error(libc::EPERM),
))),
);
let answer = call
.answer(&Tree::none(), skip, None)
.answer
.expect_err("a skipped call is no success");
let Error::Unassessable { detail, .. } = &answer else {
panic!("got {answer:?}");
};
assert_eq!(crate::error::first_os_code(&answer), Some(libc::EPERM), "{answer:?}");
assert!(!detail.contains(&os_error), "{detail}");
}
#[skuld::test]
fn a_skip_over_an_untrusted_root_with_a_context_error_keeps_its_os_code() {
use super::skipped_group;
use crate::containment::root::NumberLook;
use crate::containment::{SkipCall, Tree};
use crate::signal::RootState;
use crate::signal::Sig;
let call = SkipCall {
op: "skip_untrusted_context_probe",
pid: 999_999,
signal: Sig::Graceful(crate::signal::Signal::Term),
earlier: None,
};
let handle_error = crate::error::io_context(
"the root could not be peeked",
std::io::Error::from_raw_os_error(libc::EPERM),
);
let skip = skipped_group(
999_999,
"kill",
NumberLook::Untrusted(RootState::Unknown(std::sync::Arc::new(handle_error))),
);
let answer = call
.answer(&Tree::none(), skip, None)
.answer
.expect_err("a skipped call is no success");
assert_eq!(crate::error::first_os_code(&answer), Some(libc::EPERM), "{answer:?}");
}
fn member_cause(code: i32) -> crate::error::Error {
crate::error::Error::Io(std::io::Error::from_raw_os_error(code))
}
fn members_below(error: &crate::error::Error) -> Vec<(String, Option<i32>)> {
use std::error::Error as _;
let source = error.source().and_then(|s| s.downcast_ref::<crate::error::Error>());
let Some(crate::error::Error::Several(list)) = source else {
panic!("expected a Several below the variant: {error:?}");
};
list.iter()
.map(|member| (member.to_string(), crate::error::first_os_code(&**member)))
.collect()
}
#[skuld::test]
fn a_group_with_refusers_answers_containment_with_every_members_cause() {
use super::group::GroupState;
use crate::error::Error;
let answer = super::answer_of(
GroupState::Refused {
refused: vec![(7, member_cause(libc::EPERM)), (8, member_cause(libc::EACCES))],
unassessable: vec![(9, member_cause(libc::EIO))],
},
42,
nix::sys::signal::Signal::SIGKILL,
)
.expect_err("the group was not cleared");
let Error::Containment { detail, .. } = &answer else {
panic!("{answer:?}");
};
assert!(detail.contains("SIGKILL") && detail.contains("42"), "{detail}");
assert!(
!detail.contains(&std::io::Error::from_raw_os_error(libc::EPERM).to_string()),
"{detail}"
);
let members = members_below(&answer);
let codes: Vec<_> = members.iter().map(|(_, code)| *code).collect();
assert_eq!(codes, [Some(libc::EPERM), Some(libc::EACCES), Some(libc::EIO)]);
for ((said, _), pid) in members.iter().zip([7, 8, 9]) {
assert!(said.contains(&format!("pid {pid}")), "{said}");
}
}
#[skuld::test]
fn a_group_with_one_refuser_has_that_member_as_its_cause() {
use super::group::GroupState;
use crate::error::Error;
use std::error::Error as _;
let answer = super::answer_of(
GroupState::Refused {
refused: vec![(7, member_cause(libc::EPERM))],
unassessable: vec![],
},
42,
nix::sys::signal::Signal::SIGTERM,
)
.expect_err("the group was not cleared");
let source = answer.source().and_then(|s| s.downcast_ref::<Error>());
assert!(
matches!(source, Some(Error::Containment { detail, .. }) if detail.contains("pid 7")),
"{answer:?}"
);
assert_eq!(crate::error::first_os_code(&answer), Some(libc::EPERM));
}
#[skuld::test]
fn a_group_with_only_unassessable_members_answers_unassessable_with_every_cause() {
use super::group::GroupState;
use crate::error::Error;
let answer = super::answer_of(
GroupState::Unassessed {
members: vec![(5, member_cause(libc::EIO)), (6, member_cause(libc::EACCES))],
},
42,
nix::sys::signal::Signal::SIGKILL,
)
.expect_err("the group was not cleared");
let Error::Unassessable { detail, .. } = &answer else {
panic!("{answer:?}");
};
assert!(
!detail.contains(&std::io::Error::from_raw_os_error(libc::EIO).to_string()),
"{detail}"
);
let codes: Vec<_> = members_below(&answer).iter().map(|(_, code)| *code).collect();
assert_eq!(codes, [Some(libc::EIO), Some(libc::EACCES)]);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_group_whose_listing_is_refused_answers_unsupported() {
use rustix::io::Errno;
use super::group::{GroupState, ListingFailure};
use crate::error::Error;
let refusal = crate::identity::FailedCall::openat2(Errno::PERM)
.refusal()
.expect("an openat2 answering EPERM is a refusal");
let answer = super::answer_of(
GroupState::Unlistable {
detail: "process group 42 could not be listed".to_owned(),
source: ListingFailure::Unsupported(refusal.unsupported("listing process group 42")),
},
42,
nix::sys::signal::Signal::SIGKILL,
)
.expect_err("the group was not cleared");
let Error::Unsupported { op, detail, .. } = &answer else {
panic!("{answer:?}");
};
assert_eq!(op, "listing process group 42");
assert!(detail.contains("requires openat2"), "{detail}");
assert_eq!(crate::error::first_os_code(&answer), Some(libc::EPERM));
}
#[skuld::test]
fn a_group_whose_listing_failed_with_an_enosys_of_its_own_answers_unassessable() {
use super::group::{GroupState, ListingFailure};
use crate::error::Error;
let source = std::io::Error::from_raw_os_error(libc::ENOSYS);
assert_eq!(
source.kind(),
std::io::ErrorKind::Unsupported,
"std maps ENOSYS to Unsupported"
);
let answer = super::answer_of(
GroupState::Unlistable {
detail: "process group 42 could not be listed".to_owned(),
source: ListingFailure::Failed(source),
},
42,
nix::sys::signal::Signal::SIGKILL,
)
.expect_err("the group was not cleared");
assert!(matches!(answer, Error::Unassessable { .. }), "{answer:?}");
assert_eq!(crate::error::first_os_code(&answer), Some(libc::ENOSYS));
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_listing_that_fails_after_its_open_with_enosys_answers_unassessable() {
use crate::error::Error;
use crate::identity::{FakeKernel, HostKernel};
let kernel = FakeKernel::over(&HostKernel)
.same_view()
.on_pids_failing_after_open(libc::ENOSYS);
let signal = nix::sys::signal::Signal::SIGKILL;
let answer = super::answer_of(
super::group::state(&kernel, 42, signal, None, &mut Vec::new()),
42,
signal,
)
.expect_err("a group that cannot be listed is not cleared");
assert!(matches!(answer, Error::Unassessable { .. }), "{answer:?}");
assert_eq!(crate::error::first_os_code(&answer), Some(libc::ENOSYS), "{answer:?}");
}