use super::{descendants_with, Resolution, Walk};
use crate::error::Error;
use crate::identity::{Key, OrderKey, ProcessId, RawPid, UnknownCause};
#[cfg(unix)]
use crate::test_groups::setuid;
use std::collections::HashMap;
const ROOT_PID: RawPid = 100;
const ROOT_TOKEN: u64 = 1_000;
#[cfg(any(unix, windows))]
#[skuld::test]
fn a_tree_call_given_no_owner_sends_the_roots_kill_by_identity() {
let (child, stdin) = crate::test_child::held_uncontained_blocker(false);
let id = child.id().expect(crate::test_child::IDENTITY_READ);
super::kill_tree(id, None)
.outcome()
.into_result()
.expect("the walk found the root and killed it");
let status = child.wait().expect("the killed root is reaped");
assert!(!status.success(), "the kill ended the root, not its stdin: {status:?}");
drop(stdin);
}
#[cfg(unix)]
#[skuld::test]
fn a_tree_call_given_no_owner_sends_the_roots_term_by_identity() {
use std::os::unix::process::ExitStatusExt as _;
let (child, stdin) = crate::test_child::held_uncontained_blocker(false);
let id = child.id().expect(crate::test_child::IDENTITY_READ);
match super::terminate_tree(&crate::identity::HostKernel, id, None) {
crate::containment::TerminateOutcome::Sent { result: Ok(()), .. } => {}
other => panic!("the walk found the root and signalled it: {other:?}"),
}
let status = child.wait().expect("the signalled root is reaped");
assert_eq!(status.signal(), Some(libc::SIGTERM), "{status:?}");
drop(stdin);
}
#[cfg(debug_assertions)]
#[skuld::test]
fn an_unverified_send_is_a_contract_breach() {
assert!(
std::panic::catch_unwind(|| super::KillOutcome::of(Ok(crate::signal::Sent::Unverified))).is_err(),
"the breach did not assert"
);
}
#[cfg(not(debug_assertions))]
#[skuld::test]
fn an_unverified_send_is_not_attempted_in_release() {
match super::KillOutcome::of(Ok(crate::signal::Sent::Unverified)) {
super::KillOutcome::NotAttempted(Error::Unassessable { .. }) => {}
other => panic!("an unverified send is not attempted, Unassessable: {other:?}"),
}
}
#[skuld::test]
fn a_sends_answer_is_one_outcome_whoever_sent() {
use super::KillOutcome;
use crate::signal::Sent;
assert!(matches!(KillOutcome::of(Ok(Sent::Delivered)), KillOutcome::Terminated));
assert!(matches!(KillOutcome::of(Ok(Sent::Gone)), KillOutcome::AlreadyGone));
match KillOutcome::of(Err(Error::Io(std::io::Error::from(
std::io::ErrorKind::PermissionDenied,
)))) {
KillOutcome::NotAttempted(Error::Io(refused)) => {
assert_eq!(refused.kind(), std::io::ErrorKind::PermissionDenied);
}
other => panic!("a refusal is not attempted, with the OS's own error: {other:?}"),
}
}
fn id(pid: RawPid, token: u64) -> ProcessId {
ProcessId::from_parts_for_test(pid, Key::for_test(token))
}
fn bound_of(token: u64) -> Option<OrderKey> {
Some(OrderKey::for_test(token))
}
fn resolved(pid: RawPid, token: u64) -> (ProcessId, Option<OrderKey>) {
(id(pid, token), bound_of(token))
}
fn resolver(tokens: &HashMap<RawPid, u64>) -> impl Fn(RawPid, ProcessId, Option<OrderKey>) -> Resolution + '_ {
move |pid, _parent, _bound| Ok(tokens.get(&pid).map(|&t| resolved(pid, t)))
}
fn unreadable(pid: RawPid) -> Error {
crate::identity::unqueryable_read("pid", pid, UnknownCause::default())
}
fn pids(walk: Walk) -> Vec<RawPid> {
let mut v = walk.members;
v.sort_by_key(|i| i.pid());
v.into_iter().map(|i| i.pid()).collect()
}
fn unassessed(walk: &Walk) -> Vec<RawPid> {
let mut v: Vec<RawPid> = walk.unassessed.iter().map(|&(pid, _)| pid).collect();
v.sort_unstable();
v
}
fn root() -> ProcessId {
id(ROOT_PID, ROOT_TOKEN)
}
fn root_bound() -> Option<OrderKey> {
bound_of(ROOT_TOKEN)
}
#[skuld::test]
fn recurses_into_deep_tree() {
let parents = [(200, ROOT_PID), (300, 200), (400, 300)];
let tokens = HashMap::from([
(200u32, ROOT_TOKEN + 1),
(300u32, ROOT_TOKEN + 2),
(400u32, ROOT_TOKEN + 3),
]);
let got = descendants_with(root(), root_bound(), &parents, resolver(&tokens));
assert_eq!(pids(got), [200, 300, 400]);
}
#[skuld::test]
fn reparented_orphan_is_missed() {
let parents = [(300, 1)];
let tokens = HashMap::from([(300u32, ROOT_TOKEN + 9)]);
let got = descendants_with(root(), root_bound(), &parents, resolver(&tokens));
assert!(
got.members.is_empty(),
"reparented orphan is honestly missed (documented)"
);
}
#[skuld::test]
fn root_is_never_included() {
let parents = [(ROOT_PID, ROOT_PID), (200, ROOT_PID)];
let tokens = HashMap::from([(ROOT_PID, ROOT_TOKEN), (200u32, ROOT_TOKEN + 1)]);
let got = descendants_with(root(), root_bound(), &parents, resolver(&tokens));
assert_eq!(pids(got), [200], "root excluded; genuine child kept");
}
#[skuld::test]
fn duplicate_edge_yields_pid_once() {
let parents = [(200, ROOT_PID), (200, ROOT_PID)];
let tokens = HashMap::from([(200u32, ROOT_TOKEN + 1)]);
let got = descendants_with(root(), root_bound(), &parents, resolver(&tokens));
assert_eq!(pids(got), [200], "duplicate edge collapses to a single result");
}
#[skuld::test]
fn unresolvable_candidate_is_skipped() {
let parents = [(200, ROOT_PID), (300, 200)];
let tokens = HashMap::from([(300u32, ROOT_TOKEN + 5)]); let got = descendants_with(root(), root_bound(), &parents, resolver(&tokens));
assert!(got.members.is_empty(), "gone candidate and its subtree are skipped");
assert!(got.unassessed.is_empty(), "a gone candidate is not unassessed");
}
#[skuld::test]
fn an_unreadable_candidate_and_its_subtree_are_out_of_the_walk_and_it_is_unassessed() {
let parents = [(200, ROOT_PID), (300, 200), (400, ROOT_PID)];
let tokens = HashMap::from([(300u32, ROOT_TOKEN + 5), (400u32, ROOT_TOKEN + 6)]);
let read = resolver(&tokens);
let got = descendants_with(root(), root_bound(), &parents, |pid, parent, bound| {
if pid == 200 {
Err(unreadable(200))
} else {
read(pid, parent, bound)
}
});
assert_eq!(unassessed(&got), [200]);
assert!(matches!(&got.unassessed[0].1, Error::Unassessable { detail, .. } if detail.contains("pid 200")));
assert_eq!(pids(got), [400]);
}
#[skuld::test]
fn complete_members_keeps_every_unassessed_candidate_as_a_cause_in_order() {
let parents = [(200, ROOT_PID), (300, ROOT_PID), (400, ROOT_PID)];
let os_code = |pid: RawPid| match pid {
200 => 2,
300 => 3,
_ => 5,
};
let got = descendants_with(root(), root_bound(), &parents, |pid, _, _| {
Err(Error::Unassessable {
detail: format!("cause of {pid}"),
source: Some(Error::io_cause(std::io::Error::from_raw_os_error(os_code(pid)))),
})
});
let order: Vec<RawPid> = got.unassessed.iter().map(|(pid, _)| *pid).collect();
let error = got.complete_members().expect_err("three candidates were not assessed");
let Error::Unassessable {
detail,
source: Some(source),
} = &error
else {
panic!("the first's variant is kept: {error:?}");
};
assert_eq!(*detail, format!("cause of {}", order[0]));
let Error::Several(list) = &**source else {
panic!("expected Several, got {source:?}");
};
let codes: Vec<_> = list
.iter()
.map(|member| crate::error::first_os_code(&**member))
.collect();
assert_eq!(codes, order.iter().map(|pid| Some(os_code(*pid))).collect::<Vec<_>>());
for other in &order[1..] {
let member = list
.iter()
.nth(order.iter().position(|pid| pid == other).expect("listed"))
.expect("a member");
assert!(
matches!(&**member, Error::Unassessable { detail, .. } if *detail == format!("cause of {other}")),
"{member:?}"
);
}
}
#[skuld::test]
fn complete_members_keeps_every_candidate_below_an_unassessable_when_the_first_is_an_io_error() {
let parents = [(200, ROOT_PID), (300, ROOT_PID)];
let got = descendants_with(root(), root_bound(), &parents, |pid, _, _| {
let code = if pid == 200 { 2 } else { 3 };
Err(if pid == 200 {
Error::Io(std::io::Error::from_raw_os_error(code))
} else {
Error::Unassessable {
detail: "the second".to_owned(),
source: Some(Error::io_cause(std::io::Error::from_raw_os_error(code))),
}
})
});
let order: Vec<RawPid> = got.unassessed.iter().map(|(pid, _)| *pid).collect();
assert_eq!(order, [200, 300]);
let error = got.complete_members().expect_err("two candidates were not assessed");
let Error::Unassessable {
source: Some(source), ..
} = &error
else {
panic!("expected Unassessable, got {error:?}");
};
let Error::Several(list) = &**source else {
panic!("expected Several, got {source:?}");
};
let codes: Vec<_> = list
.iter()
.map(|member| crate::error::first_os_code(&**member))
.collect();
assert_eq!(codes, [Some(2), Some(3)]);
}
#[skuld::test]
fn a_duplicate_edge_to_an_unreadable_candidate_is_one_unassessed_entry() {
let parents = [(200, ROOT_PID), (200, ROOT_PID)];
let got = descendants_with(root(), root_bound(), &parents, |pid, _, _| Err(unreadable(pid)));
assert_eq!(unassessed(&got), [200]);
assert!(got.members.is_empty());
}
#[skuld::test]
fn only_a_gone_candidate_is_logged_as_gone_or_an_impostor() {
use super::children_of_with;
const UNREADABLE: RawPid = 61_001;
const GONE: RawPid = 61_002;
crate::log_capture::install();
let parents = [(UNREADABLE, ROOT_PID), (GONE, ROOT_PID)];
let resolve = |pid: RawPid, _parent: ProcessId, _bound: Option<OrderKey>| -> Resolution {
if pid == UNREADABLE {
Err(unreadable(pid))
} else {
Ok(None)
}
};
let mark = crate::log_capture::mark();
descendants_with(root(), root_bound(), &parents, resolve);
children_of_with(root(), root_bound(), &parents, resolve);
assert!(crate::log_capture::contains_since(
mark,
&format!("pid {GONE} gone, or an impostor")
));
assert!(!crate::log_capture::contains_since(
mark,
&format!("pid {UNREADABLE} gone, or an impostor")
));
}
#[skuld::test]
fn an_unreadable_direct_child_is_unassessed_in_the_one_level_filter_too() {
use super::children_of_with;
let parents = [(200, ROOT_PID), (200, ROOT_PID), (300, ROOT_PID), (400, 200)];
let tokens = HashMap::from([(300u32, ROOT_TOKEN + 5)]);
let read = resolver(&tokens);
let got = children_of_with(root(), root_bound(), &parents, |pid, parent, bound| {
if pid == 200 {
Err(unreadable(200))
} else {
read(pid, parent, bound)
}
});
assert_eq!(unassessed(&got), [200]);
assert_eq!(pids(got), [300]);
}
#[skuld::test]
fn a_duplicate_edge_is_resolved_once_in_both_filters() {
use super::children_of_with;
use std::cell::Cell;
let parents = [(200, ROOT_PID), (200, ROOT_PID)];
let reads = Cell::new(0);
let first_reads_second_does_not = |pid: RawPid, _parent: ProcessId, _bound: Option<OrderKey>| {
reads.set(reads.get() + 1);
if reads.get() == 1 {
Ok(Some(resolved(pid, ROOT_TOKEN + 5)))
} else {
Err(unreadable(pid))
}
};
let got = children_of_with(root(), root_bound(), &parents, first_reads_second_does_not);
assert_eq!((pids(got), reads.get()), (vec![200], 1), "one level");
reads.set(0);
let got = descendants_with(root(), root_bound(), &parents, first_reads_second_does_not);
assert!(got.unassessed.is_empty(), "{:?}", got.unassessed);
assert_eq!((pids(got), reads.get()), (vec![200], 1), "whole subtree");
}
#[skuld::test]
fn children_of_keeps_one_level_genuine_children_only() {
use super::children_of_with;
let root = id(100, 50);
let parents = [(101, 100), (102, 101), (103, 100)];
let tokens = HashMap::from([(101u32, 60), (102u32, 70)]);
let got = children_of_with(root, bound_of(50), &parents, resolver(&tokens));
assert!(got.unassessed.is_empty());
assert_eq!(pids(got), [101]);
}
#[skuld::test]
fn children_of_duplicate_edge_yields_pid_once() {
use super::children_of_with;
let root = id(100, ROOT_TOKEN);
let parents = [(101, 100), (101, 100)];
let tokens = HashMap::from([(101u32, ROOT_TOKEN + 1)]);
assert_eq!(
pids(children_of_with(root, root_bound(), &parents, resolver(&tokens))),
[101],
"duplicate edge collapses to a single child"
);
}
#[skuld::test]
fn the_resolver_is_asked_for_each_candidates_accepted_parent() {
use std::cell::RefCell;
use super::children_of_with;
let asked = RefCell::new(Vec::new());
let resolve = |pid: u32, parent: ProcessId, bound: Option<OrderKey>| -> Resolution {
asked.borrow_mut().push((pid, parent, bound));
Ok(Some(resolved(pid, ROOT_TOKEN + 1)))
};
let parents = [(200, ROOT_PID), (300, 200)];
descendants_with(root(), root_bound(), &parents, resolve);
assert_eq!(
asked.take(),
[
(200, root(), root_bound()),
(300, id(200, ROOT_TOKEN + 1), bound_of(ROOT_TOKEN + 1))
]
);
children_of_with(root(), root_bound(), &parents, resolve);
assert_eq!(asked.take(), [(200, root(), root_bound())]);
}
#[skuld::test]
fn the_bound_is_the_roots_bound_not_its_id_token() {
use std::cell::RefCell;
use super::children_of_with;
let parents = [(200, ROOT_PID)];
let asked = RefCell::new(Vec::new());
let resolve = |pid: u32, _parent: ProcessId, bound: Option<OrderKey>| -> Resolution {
asked.borrow_mut().push((pid, bound));
Ok(None)
};
for bound in [bound_of(ROOT_TOKEN - 500), None] {
descendants_with(root(), bound, &parents, resolve);
assert_eq!(asked.take(), [(200, bound)], "descendants_with");
children_of_with(root(), bound, &parents, resolve);
assert_eq!(asked.take(), [(200, bound)], "children_of_with");
}
}
#[skuld::test]
fn the_anchor_hands_out_a_bound_only_on_windows() {
let proof = super::anchor(&crate::identity::HostKernel, ProcessId::current())
.expect("this process reads")
.expect("this process is live");
assert_eq!(proof.bound.is_some(), crate::identity::ORDER_AFTER_PARENT);
}
#[cfg(windows)]
#[skuld::test]
fn resolve_or_drop_drops_an_access_denied_pid_as_an_error() {
let Some(done) = crate::test_own_process::own_process(
crate::test_own_process::test_path!(resolve_or_drop_drops_an_access_denied_pid_as_an_error),
crate::test_spawn::spawn,
) else {
return;
};
use windows::Win32::System::Threading::PROCESS_SYNCHRONIZE;
crate::log_capture::install();
let denied = crate::identity::windows_fixture::spawn_restricted(&done, PROCESS_SYNCHRONIZE.0);
assert!(denied.is_running(), "precondition: the subject must be live");
let mark = crate::log_capture::mark();
let Err(Error::Unassessable { detail, .. }) =
super::resolve_or_drop(&crate::identity::HostKernel, denied.pid(), ProcessId::current(), None)
else {
panic!("the walk cannot keep what it cannot verify, and an unread pid is not a gone one");
};
assert!(
detail.contains(&format!("pid {} exists but could not be queried", denied.pid())),
"{detail}"
);
assert!(
!crate::log_capture::contains_since(mark, &format!("treewalk: pid {}", denied.pid())),
"the walk's caller reports it, not the walk"
);
assert!(denied.is_running(), "and dropping it must not have touched it");
}
#[cfg(windows)]
#[skuld::test]
fn a_refused_creator_query_is_worded_with_its_status_in_the_walks_warn_on_windows() {
let refused = windows::Win32::Foundation::NTSTATUS(0xC000_0004_u32 as i32);
let cause = crate::identity::UnknownCause::default().with_creator_status(refused);
let error = crate::identity::unqueryable_read("pid", 7, cause);
let crate::error::Error::Unassessable { detail, .. } = &error else {
panic!("a refused creator query is Unassessable");
};
assert_eq!(detail, "pid 7 exists but its creator process id query failed");
assert_eq!(
crate::error::first_os_code(&error),
Some(windows::Win32::Foundation::ERROR_BAD_LENGTH.0 as i32)
);
}
#[cfg(windows)]
#[skuld::test]
fn a_real_candidate_is_dropped_under_a_parent_that_is_not_its_creator_on_windows() {
use crate::identity::HostKernel;
use crate::test_child::{live_findstr_blocker, release_findstr_unterminated};
use crate::Recursive;
let root = ProcessId::current();
let (x_child, x) = live_findstr_blocker();
let (y_child, y) = live_findstr_blocker();
let stale_creator = [(x.pid(), root.pid()), (y.pid(), x.pid())];
let dropped = super::walk_from(&HostKernel, root, &stale_creator, Recursive::Yes)
.expect("the root reads")
.expect("the root is live");
let genuine = [(x.pid(), root.pid()), (y.pid(), root.pid())];
let kept = super::walk_from(&HostKernel, root, &genuine, Recursive::Yes)
.expect("the root reads")
.expect("the root is live");
release_findstr_unterminated(x_child);
release_findstr_unterminated(y_child);
assert!(dropped.unassessed.is_empty() && kept.unassessed.is_empty());
assert_eq!(dropped.members, vec![x]);
assert_eq!(kept.members, vec![x, y]);
}
#[cfg(windows)]
#[skuld::test]
fn a_root_that_exited_while_its_handle_is_held_is_walked_and_its_child_killed() {
use std::process::Stdio;
use windows::Win32::Foundation::WAIT_OBJECT_0;
use windows::Win32::System::Threading::{
GetExitCodeProcess, WaitForSingleObject, INFINITE, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE,
};
use crate::identity::{windows_close, windows_open_classified, HostKernel, Opened};
use crate::Recursive;
let more = crate::test_child::windows_more();
let mut shell = crate::test_spawn::spawn(
std::process::Command::new("cmd.exe")
.arg("/c")
.arg(&more)
.stdin(Stdio::piped())
.stdout(Stdio::piped()),
)
.expect("spawn the root");
let root = ProcessId::of(shell.id()).found().expect("the live root resolves");
let mut stdin = shell.stdin.take().expect("piped stdin");
std::io::Write::write_all(&mut stdin, b"x\r\n").expect("feed the child a line");
let mut first = [0u8; 1];
let read = std::io::Read::read(shell.stdout.as_mut().expect("piped stdout"), &mut first).expect("read the echo");
assert_eq!(read, 1, "the root closed its output before its child echoed");
let children = root.children(Recursive::No).expect("the root's children");
let held = children
.into_iter()
.find(|id| crate::identity::windows_fixture::is_more_com(id.pid()))
.expect("the root has a `more` child")
.pid();
let Opened::Found(held_handle) =
windows_open_classified(held, PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION)
else {
panic!("the child is ours and openable");
};
shell.kill().expect("terminate the root");
shell.wait().expect("the root's exit is recorded");
let parents = crate::test_child::parents_once_unlisted(root.pid());
assert!(
parents.iter().any(|&(pid, ppid)| pid == held && ppid == root.pid()),
"precondition: the running child must still name the exited root as its creator"
);
let children = root.children(Recursive::No).expect("the exited root's children");
assert!(
children.iter().any(|id| id.pid() == held),
"{held} not among {children:?}"
);
super::hard_kill(&HostKernel, root, &super::ByIdentity::new(&HostKernel, root))
.outcome()
.into_result()
.expect("an exited root whose handle is held is walked completely");
drop(stdin);
let waited = unsafe { WaitForSingleObject(held_handle, INFINITE) };
assert_eq!(waited, WAIT_OBJECT_0, "the wait on the child returned {waited:?}");
let mut code = 0u32;
unsafe { GetExitCodeProcess(held_handle, &mut code) }.expect("the child's exit code");
windows_close(held_handle);
assert_eq!(
code,
crate::identity::WINDOWS_TERMINATE_EXIT_CODE,
"the walk must have terminated the child"
);
}
#[cfg(windows)]
#[skuld::test]
fn a_walk_members_handle_can_be_waited_on_after_its_kill() {
let (_child, _stdin, id) = crate::test_child::live_blocker();
let os = super::open_by_identity(&crate::identity::HostKernel, id)
.expect("a live member opens")
.expect("a live member is not gone");
assert!(
matches!(os.exited(), Ok(crate::os_process::Exit::Running(_))),
"a live member's handle is waited on, not refused"
);
let outcome = super::KillOutcome::of(os.signal(crate::signal::Sig::Kill));
assert!(matches!(outcome, super::KillOutcome::Terminated), "{outcome:?}");
assert!(
crate::os_process::drive::exited_held(&*os, None).expect("the member's handle can be waited on"),
"the wait ended on the member's exit"
);
}
#[cfg(windows)]
#[skuld::test]
fn kill_by_identity_reports_not_attempted_when_the_open_is_denied() {
let Some(done) = crate::test_own_process::own_process(
crate::test_own_process::test_path!(kill_by_identity_reports_not_attempted_when_the_open_is_denied),
crate::test_spawn::spawn,
) else {
return;
};
let child = crate::identity::windows_fixture::spawn_unkillable(&done);
let id = crate::identity::windows_identity_from_handle_result(child.handle(), child.pid())
.expect("the owned handle always yields an identity");
assert!(child.is_running(), "precondition: the subject must be live");
let outcome = super::kill_by_identity(id);
assert!(matches!(outcome, super::KillOutcome::NotAttempted(_)), "{outcome:?}");
assert!(child.is_running(), "a denied open must leave the process running");
}
#[cfg(windows)]
#[skuld::test]
fn hard_kill_of_a_root_it_may_read_but_not_terminate_is_an_error_naming_it() {
let Some(done) = crate::test_own_process::own_process(
crate::test_own_process::test_path!(hard_kill_of_a_root_it_may_read_but_not_terminate_is_an_error_naming_it),
crate::test_spawn::spawn,
) else {
return;
};
let child = crate::identity::windows_fixture::spawn_query_only(&done);
let id = crate::identity::windows_identity_from_handle_result(child.handle(), child.pid())
.expect("the owned handle always yields an identity");
assert!(child.is_running(), "precondition: the subject must be live");
let kernel = crate::identity::HostKernel;
match super::hard_kill(&kernel, id, &super::ByIdentity::new(&kernel, id))
.outcome()
.into_result()
{
Err(super::Unkilled {
members,
root: Some(root),
..
}) if members.is_empty() => {
let crate::error::Error::MemberNotKilled { pid, source, .. } = *root else {
panic!("expected MemberNotKilled for the root, got {root:?}");
};
assert_eq!(pid, child.pid());
assert!(
matches!(*source, crate::error::Error::Io(_)),
"a refused kill is the OS's error: {source:?}"
);
assert_eq!(
crate::error::first_os_code(&*source),
Some(windows::Win32::Foundation::ERROR_ACCESS_DENIED.0 as i32),
"{source:?}"
);
}
other => panic!("expected MemberNotKilled for the root, got {other:?}"),
}
assert!(child.is_running(), "a refused kill must leave the process running");
}
#[cfg(unix)]
#[skuld::test]
fn hard_kill_of_a_root_that_refuses_the_signal_is_an_error_carrying_the_errno(
#[fixture(setuid)] _group: &crate::test_groups::Group,
) {
let (child, stdin) = crate::test_privilege::spawn_setuid_blocker();
let id = child.id().expect(crate::test_child::IDENTITY_READ);
let kernel = crate::identity::HostKernel;
let left = super::hard_kill(&kernel, id, &super::ByIdentity::new(&kernel, id))
.outcome()
.into_result()
.expect_err("the kill is refused");
assert!(left.members.is_empty(), "the root is the only member the walk left");
let err = left.root.expect("the root was left");
let os = std::io::Error::from_raw_os_error(libc::EPERM);
assert_eq!(err.to_string(), format!("pid {} was not killed", child.pid()));
assert_eq!(
crate::error::said(&err),
format!("pid {} was not killed: {}", child.pid(), crate::error::io_said(&os))
);
match *err {
crate::error::Error::MemberNotKilled { pid, source, .. } => {
assert_eq!(pid, child.pid());
assert!(
matches!(*source, crate::error::Error::Io(ref e) if e.raw_os_error() == Some(libc::EPERM)),
"{source:?}"
);
}
other => panic!("expected MemberNotKilled, got {other:?}"),
}
drop(stdin);
assert!(child.wait().expect("the helper exits on EOF").success());
}
#[cfg(unix)]
#[skuld::test]
fn hard_kill_of_a_descendant_that_refuses_the_signal_is_an_error_naming_it_with_the_errno(
#[fixture(setuid)] _group: &crate::test_groups::Group,
) {
let (child, stdin) = crate::test_privilege::root_over_setuid_blockers(1, |_| {});
let id = child.id().expect(crate::test_child::IDENTITY_READ);
let kernel = crate::identity::HostKernel;
let left = super::hard_kill(&kernel, id, &super::ByIdentity::new(&kernel, id))
.outcome()
.into_result()
.expect_err("the helper refuses the kill");
assert!(left.root.is_none(), "the root was killed: {:?}", left.root);
assert_eq!(left.members.len(), 1, "{:?}", left.members);
match &left.members[0] {
crate::error::Error::MemberNotKilled { pid, source, .. } => {
assert_ne!(*pid, child.pid(), "the helper, not the root");
assert!(
matches!(**source, crate::error::Error::Io(ref e) if e.raw_os_error() == Some(libc::EPERM)),
"{source:?}"
);
}
other => panic!("expected MemberNotKilled, got {other:?}"),
}
drop(stdin);
crate::test_child::assert_killed("the root", child.wait().expect("reap the root"));
}
#[cfg(unix)]
#[skuld::test]
fn process_kill_tree_of_a_root_that_refuses_the_signal_names_the_root(
#[fixture(setuid)] _group: &crate::test_groups::Group,
) {
let (child, stdin) = crate::test_privilege::spawn_setuid_blocker();
let process = crate::Process::open_pid(child.pid()).expect("open").expect("running");
let err = process.kill_tree().expect_err("the root refuses the kill");
let crate::error::Error::MembersLeft { members, .. } = &err else {
panic!("expected MembersLeft, got {err:?}");
};
let [member] = &members.iter().collect::<Vec<_>>()[..] else {
panic!("the root is the one member left: {members:?}");
};
match &***member {
crate::error::Error::MemberNotKilled { pid, source, .. } => {
assert_eq!(*pid, child.pid());
assert!(
matches!(&**source, crate::error::Error::Io(e) if e.raw_os_error() == Some(libc::EPERM)),
"{source:?}"
);
}
other => panic!("expected MemberNotKilled, got {other:?}"),
}
drop(stdin);
assert!(child.wait().expect("the helper exits on EOF").success());
}
#[cfg(unix)]
#[skuld::test]
fn process_kill_tree_returns_every_refusing_member_and_warns_of_none(
#[fixture(setuid)] _group: &crate::test_groups::Group,
) {
crate::log_capture::install();
let (child, stdin) = crate::test_privilege::root_over_setuid_blockers(2, |_| {});
let process = crate::Process::open_pid(child.pid()).expect("open").expect("running");
let mark = crate::log_capture::mark();
let err = process.kill_tree().expect_err("two members refuse the kill");
let crate::error::Error::MembersLeft { members, .. } = &err else {
panic!("expected MembersLeft, got {err:?}");
};
let mut pids = Vec::new();
for member in members.iter() {
let crate::error::Error::MemberNotKilled { pid, .. } = &**member else {
panic!("expected MemberNotKilled, got {member:?}");
};
assert_eq!(crate::error::first_os_code(&**member), Some(libc::EPERM), "{member:?}");
pids.push(*pid);
}
pids.sort_unstable();
pids.dedup();
assert_eq!(pids.len(), 2, "each refusing member is named once: {members:?}");
let warned = crate::log_capture::warns_since(mark, "was not killed");
assert!(warned.is_empty(), "the members are in the error: {warned:?}");
drop(stdin);
crate::test_child::assert_killed("the root", child.wait().expect("reap the root"));
}
#[cfg(unix)]
#[skuld::test]
fn terminate_warns_once_of_a_member_that_refuses_the_signal(#[fixture(setuid)] _group: &crate::test_groups::Group) {
crate::log_capture::install();
let (child, stdin) = crate::test_privilege::root_over_setuid_blockers(1, |_| {});
let mark = crate::log_capture::mark();
let id = child.id().expect(crate::test_child::IDENTITY_READ);
let kernel = crate::identity::HostKernel;
super::terminate(&kernel, id, &super::ByIdentity::new(&kernel, id)).expect("best effort");
let os = std::io::Error::from_raw_os_error(libc::EPERM);
let warned = crate::log_capture::warns_since(mark, "was sent no SIGTERM");
assert_eq!(warned.len(), 1, "{warned:?}");
assert!(warned[0].starts_with("treewalk: pid "), "{warned:?}");
assert!(warned[0].contains(&os.to_string()), "{warned:?}");
drop(stdin);
child.wait().expect("reap the root");
}
#[cfg(windows)]
#[skuld::test]
fn kill_by_identity_spares_a_stale_identity_and_kills_a_matching_one() {
let Some(done) = crate::test_own_process::own_process(
crate::test_own_process::test_path!(kill_by_identity_spares_a_stale_identity_and_kills_a_matching_one),
crate::test_spawn::spawn,
) else {
return;
};
use windows::Win32::System::Threading::PROCESS_QUERY_LIMITED_INFORMATION;
let (child, stdin) =
crate::identity::windows_fixture::spawn_restricted_releasable(&done, PROCESS_QUERY_LIMITED_INFORMATION.0);
let real = crate::identity::windows_identity_from_handle_result(child.handle(), child.pid())
.expect("the owned handle always yields an identity");
let stale = real.with_other_value();
let outcome = super::kill_by_identity(stale);
assert!(
matches!(outcome, super::KillOutcome::AlreadyGone),
"a stale identity names a process that is gone - nothing to terminate: {outcome:?}"
);
assert!(
child.is_running(),
"a stale identity must never terminate the pid-s occupant"
);
let outcome = super::kill_by_identity(real);
assert!(
matches!(outcome, super::KillOutcome::Terminated),
"a matching identity must reach TerminateProcess: {outcome:?}"
);
drop(stdin);
child.await_exit();
assert_eq!(
child.exit_code(),
1,
"a matching identity must terminate the process, not leave it to exit when released"
);
}
#[cfg(windows)]
#[skuld::test]
fn kill_by_identity_reports_a_member_that_exits_before_the_terminate_as_gone() {
let Some(done) = crate::test_own_process::own_process(
crate::test_own_process::test_path!(kill_by_identity_reports_a_member_that_exits_before_the_terminate_as_gone),
crate::test_spawn::spawn,
) else {
return;
};
use windows::Win32::System::Threading::PROCESS_QUERY_LIMITED_INFORMATION;
let _watch = crate::log_capture::warn_watch();
let (child, _stdin) =
crate::identity::windows_fixture::spawn_restricted_releasable(&done, PROCESS_QUERY_LIMITED_INFORMATION.0);
let child = std::rc::Rc::new(child);
let id = crate::identity::windows_identity_from_handle_result(child.handle(), child.pid())
.expect("the owned handle always yields an identity");
let exiter = std::rc::Rc::clone(&child);
super::fault::set_before_terminate(move || exiter.terminate());
let outcome = super::kill_by_identity(id);
assert!(
matches!(outcome, super::KillOutcome::AlreadyGone),
"a member that exited before the terminate has nothing left to kill: {outcome:?}"
);
assert!(!child.is_running(), "precondition: the hook ended the member");
}
#[cfg(windows)]
#[skuld::test]
fn kill_by_identity_reports_a_member_that_is_exiting_but_not_signalled_as_gone() {
use std::os::windows::io::AsRawHandle;
let mut child = crate::test_spawn::spawn(
std::process::Command::new("cmd")
.args(["/C", "more"])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null()),
)
.expect("spawn cmd /C more");
let id = crate::identity::windows_identity_from_handle_result(
windows::Win32::Foundation::HANDLE(child.as_raw_handle()),
child.id(),
)
.expect("the owned handle always yields an identity");
let _refusal = crate::identity::windows_fault::refuse_next_terminate_as_exiting();
let outcome = super::kill_by_identity(id);
child.kill().expect("end the fixture");
child.wait().expect("reap the fixture");
assert!(matches!(outcome, super::KillOutcome::AlreadyGone), "{outcome:?}");
}
#[cfg(unix)]
#[skuld::test]
fn a_walk_is_skipped_by_the_roots_state_only_on_macos() {
use crate::containment::dispatch::TreeKillOutcome;
use crate::containment::TerminateOutcome;
use crate::signal::RootState;
use crate::test_support::stated_root::StatedRoot;
type Case = (&'static str, fn() -> RootState, bool);
let states: [Case; 5] = [
("unreaped", || RootState::Unreaped, false),
("reaped, own", || RootState::Reaped { own: true }, false),
("reaped elsewhere", || RootState::Reaped { own: false }, false),
(
"unknown",
|| RootState::Unknown(std::sync::Arc::new(std::io::Error::other("forced"))),
true,
),
("unpinned", || RootState::Unpinned, true),
];
for (name, state, untrusted) in states {
let skipped = untrusted && cfg!(target_os = "macos");
let root = StatedRoot::with_state(ROOT_PID, state);
let killed = super::kill_tree(self::root(), Some(&root)).outcome();
assert_eq!(
matches!(killed, TreeKillOutcome::Skipped(_)),
skipped,
"kill, {name}: {killed:?}"
);
if !skipped {
assert!(matches!(killed, TreeKillOutcome::NoRoot), "kill, {name}: {killed:?}");
}
let termed = super::terminate_tree(&crate::identity::HostKernel, self::root(), Some(&root));
assert_eq!(
matches!(termed, TerminateOutcome::End(_)),
skipped,
"terminate, {name}: {termed:?}"
);
}
}
#[skuld::test]
fn a_member_never_read_is_held_with_its_own_cause() {
use super::{not_killed, Left};
use crate::containment::dispatch::Unkilled;
let code = if cfg!(windows) { 5 } else { 13 };
let Error::MemberNotKilled { pid, source, .. } = not_killed(
7,
Error::Unassessable {
detail: "pid 7 identity could not be confirmed".into(),
source: Some(std::sync::Arc::new(Error::Containment {
detail: "the middle layer".into(),
source: Some(Error::io_cause(std::io::Error::from_raw_os_error(code))),
})),
},
) else {
unreachable!("`not_killed` builds a `MemberNotKilled`");
};
let member = Error::MemberNotKilled {
pid,
source: std::sync::Arc::clone(&source),
};
let first = Unkilled {
members: vec![member],
root: None,
resolved: Vec::new(),
};
let held = Left::of(&first);
let [Left::Unread { pid: 7, source: held }] = held.as_slice() else {
panic!("never read: {held:?}");
};
assert!(
std::sync::Arc::ptr_eq(held, &source),
"the held source is the member's own"
);
assert_eq!(crate::error::first_os_code(&**held), Some(code), "{held:?}");
}
#[skuld::test]
fn a_member_never_read_is_reported_the_same_over_every_round() {
use super::{not_killed, with_earlier, Left};
use crate::containment::dispatch::Unkilled;
let code = if cfg!(windows) { 5 } else { 13 };
let bare = || std::io::Error::from_raw_os_error(code);
let layered = || Error::Containment {
detail: "the middle layer".into(),
source: Some(Error::io_cause(crate::error::io_context("w", bare()))),
};
for (what, below) in [
("a bare OS error", Error::Io(bare())),
("layers over an OS error", layered()),
] {
let Error::MemberNotKilled { pid, source, .. } = not_killed(
7,
Error::Unassessable {
detail: "pid 7 identity could not be confirmed".into(),
source: Some(std::sync::Arc::new(below)),
},
) else {
unreachable!("`not_killed` builds a `MemberNotKilled`");
};
let mut round = Unkilled {
members: vec![Error::MemberNotKilled {
pid,
source: std::sync::Arc::clone(&source),
}],
root: None,
resolved: Vec::new(),
};
let first = crate::error::said(&round.members[0]);
for n in 2..=3 {
let held = Left::of(&round);
round = with_earlier(&crate::identity::HostKernel, held, Ok(()))
.0
.expect_err("never read, so never shown killed");
assert_eq!(crate::error::said(&round.members[0]), first, "{what}, round {n}");
let Error::MemberNotKilled { source: again, .. } = &round.members[0] else {
panic!("{round:?}");
};
assert!(
std::sync::Arc::ptr_eq(again, &source),
"{what}, round {n}: the first round's source"
);
}
assert_eq!(crate::error::first_os_code(&round.members[0]), Some(code), "{what}");
let Error::MemberNotKilled { source, .. } = &round.members[0] else {
panic!("{round:?}");
};
let Error::Unassessable {
source: Some(cause), ..
} = &**source
else {
panic!("{source:?}");
};
if what == "a bare OS error" {
assert!(
matches!(&**cause, Error::Io(e) if e.raw_os_error() == Some(code)),
"{cause:?}"
);
}
}
}
#[skuld::test]
fn a_member_never_read_is_reported_again_as_the_variant_it_was() {
use super::{not_killed, with_earlier, Left};
use crate::containment::dispatch::Unkilled;
let first = Unkilled {
members: vec![not_killed(
7,
Error::Unsupported {
op: "process open".into(),
platform: "linux",
detail: "pidfd_open was refused".into(),
source: None,
},
)],
root: None,
resolved: Vec::new(),
};
let held = Left::of(&first);
let again = with_earlier(&crate::identity::HostKernel, held, Ok(()))
.0
.expect_err("never read, so never shown killed");
let Error::MemberNotKilled { pid, source, .. } = &again.members[0] else {
panic!("{again:?}");
};
assert_eq!(*pid, 7);
assert!(
matches!(&**source, Error::Unsupported { op, platform: "linux", detail, .. }
if op == "process open" && detail == "pidfd_open was refused"),
"{source:?}"
);
}