use std::os::fd::OwnedFd;
use rustix::io::Errno;
use rustix::process::Pid;
use crate::error::Error;
use crate::identity::{FakeKernel, HostKernel, Kernel, Key, ProcessId};
use crate::test_child::{blocker_with, StdChild};
use crate::Recursive;
const ROOT: u32 = 4242;
const CHILD: u32 = 4243;
const ROOT_INO: u64 = 900;
const CHILD_INO: u64 = 5;
const ROOT_START: u64 = 1_000;
const CHILD_START: u64 = 2_000;
fn stand_in() -> OwnedFd {
OwnedFd::from(std::fs::File::open("/dev/null").expect("/dev/null opens"))
}
fn stat(pid: u32, ppid: u32, start: u64) -> Vec<u8> {
format!("{pid} (x) S {ppid} {ppid} 1 0 -1 0 0 0 0 0 0 0 0 0 20 0 1 0 {start} 0 0").into_bytes()
}
fn root() -> ProcessId {
ProcessId::from_parts_for_test(ROOT, Key::Pidfs(ROOT_INO))
}
fn child() -> ProcessId {
ProcessId::from_parts_for_test(CHILD, Key::Pidfs(CHILD_INO))
}
fn table() -> FakeKernel<'static> {
FakeKernel::over(&HostKernel)
.same_view()
.on_pids(Ok(&[ROOT, CHILD]))
.on_pidfd_open(ROOT, Ok(stand_in()))
.on_pidfs_ino(ROOT, Ok(Some(ROOT_INO)))
.on_pidfd_open(CHILD, Ok(stand_in()))
.on_pidfs_ino(CHILD, Ok(Some(CHILD_INO)))
.on_read(&format!("{ROOT}/stat"), Ok(&stat(ROOT, 1, ROOT_START)))
.on_read(&format!("{CHILD}/stat"), Ok(&stat(CHILD, ROOT, CHILD_START)))
}
const EDGES: [(u32, u32); 2] = [(ROOT, 1), (CHILD, ROOT)];
pub(super) fn descendants(kernel: &dyn Kernel, root: ProcessId, edges: &[(u32, u32)]) -> Result<Vec<ProcessId>, Error> {
Ok(super::walk_from(kernel, root, edges, Recursive::Yes)?
.unwrap_or_default()
.members)
}
pub(super) fn children_of(
kernel: &dyn Kernel,
parent: ProcessId,
edges: &[(u32, u32)],
) -> Result<Vec<ProcessId>, Error> {
Ok(super::walk_from(kernel, parent, edges, Recursive::No)?
.unwrap_or_default()
.members)
}
#[skuld::test]
fn resolve_or_drop_hands_out_a_pidfs_id_and_no_bound() {
assert_eq!(
super::resolve_or_drop(&table(), CHILD, root(), None).expect("the child reads"),
Some((child(), None))
);
}
#[skuld::test]
fn descendants_and_children_of_keep_the_child_of_a_pidfs_root() {
assert_eq!(
descendants(&table(), root(), &EDGES).expect("a readable root"),
vec![child()]
);
assert_eq!(
children_of(&table(), root(), &EDGES).expect("a readable root"),
vec![child()]
);
}
#[skuld::test]
fn a_child_that_started_before_a_pidfs_root_is_still_its_child() {
let kernel = table().on_read(&format!("{CHILD}/stat"), Ok(&stat(CHILD, ROOT, ROOT_START - 500)));
assert_eq!(descendants(&kernel, root(), &EDGES).unwrap(), vec![child()]);
assert_eq!(children_of(&kernel, root(), &EDGES).unwrap(), vec![child()]);
}
#[skuld::test]
fn a_pidfs_child_whose_stat_shows_no_start_time_is_a_member_of_a_complete_walk() {
let kernel = table().on_read(&format!("{CHILD}/stat"), Ok(format!("{CHILD} (x) S {ROOT}").as_bytes()));
for depth in [Recursive::Yes, Recursive::No] {
let walk = super::walk_from(&kernel, root(), &EDGES, depth)
.unwrap()
.expect("the root is live");
assert_eq!(walk.members, vec![child()], "{depth:?}");
assert!(walk.unassessed.is_empty(), "{:?}", walk.unassessed);
}
}
#[skuld::test]
fn the_walk_of_a_ticks_root_whose_stat_is_gone_is_empty() {
let kernel = ticks_table(ROOT_START)
.on_read(&format!("{ROOT}/stat"), Err(libc::ENOENT))
.on_signal_probe(Pid::from_raw(ROOT as i32).unwrap(), Err(Errno::SRCH));
assert!(descendants(&kernel, ticks_root(), &EDGES).unwrap().is_empty());
assert!(children_of(&kernel, ticks_root(), &EDGES).unwrap().is_empty());
}
#[skuld::test]
fn the_walk_of_a_ticks_root_whose_stat_cannot_be_read_is_unassessable() {
let kernel = ticks_table(ROOT_START)
.on_read(&format!("{ROOT}/stat"), Err(libc::EACCES))
.on_signal_probe(Pid::from_raw(ROOT as i32).unwrap(), Ok(()));
for result in [
descendants(&kernel, ticks_root(), &EDGES),
children_of(&kernel, ticks_root(), &EDGES),
] {
match result {
Err(Error::Unassessable { detail, .. }) => {
assert!(
detail.contains(&format!("pid {ROOT} exists but could not be queried")),
"{detail}"
);
}
other => panic!("expected Unassessable, got {other:?}"),
}
}
}
const GRAND: u32 = 4244;
const GRAND_INO: u64 = 7;
const GRAND_START: u64 = 3_000;
fn table_with_a_grandchild() -> FakeKernel<'static> {
table()
.on_pidfd_open(GRAND, Ok(stand_in()))
.on_pidfs_ino(GRAND, Ok(Some(GRAND_INO)))
.on_read(&format!("{GRAND}/stat"), Ok(&stat(GRAND, CHILD, GRAND_START)))
}
const EDGES_WITH_A_GRANDCHILD: [(u32, u32); 3] = [(ROOT, 1), (CHILD, ROOT), (GRAND, CHILD)];
#[skuld::test]
fn a_child_read_after_its_parents_number_changed_hands_is_dropped() {
let kernel = || table().on_pidfs_ino_after_read(ROOT, &format!("{CHILD}/stat"), Ok(Some(ROOT_INO + 1)));
assert!(descendants(&kernel(), root(), &EDGES).unwrap().is_empty());
assert!(children_of(&kernel(), root(), &EDGES).unwrap().is_empty());
}
#[skuld::test]
fn a_grandchild_read_after_its_accepted_parents_number_changed_hands_is_dropped() {
let kernel =
table_with_a_grandchild().on_pidfs_ino_after_read(CHILD, &format!("{GRAND}/stat"), Ok(Some(CHILD_INO + 1)));
assert_eq!(
descendants(&kernel, root(), &EDGES_WITH_A_GRANDCHILD).unwrap(),
vec![child()]
);
let kept = descendants(&table_with_a_grandchild(), root(), &EDGES_WITH_A_GRANDCHILD).unwrap();
assert_eq!(
kept.len(),
2,
"with the parent still holding its number the grandchild is kept"
);
}
#[skuld::test]
fn a_grandchild_that_started_before_its_listed_parent_is_kept_off_windows() {
let kernel = table_with_a_grandchild().on_read(
&format!("{GRAND}/stat"),
Ok(&stat(GRAND, CHILD, (ROOT_START + CHILD_START) / 2)),
);
let grand = ProcessId::from_parts_for_test(GRAND, Key::Pidfs(GRAND_INO));
assert_eq!(
descendants(&kernel, root(), &EDGES_WITH_A_GRANDCHILD).unwrap(),
vec![child(), grand]
);
}
#[skuld::test]
fn a_child_whose_parent_cannot_be_proved_again_is_dropped() {
let kernel = || table().on_pidfs_ino_after_read(ROOT, &format!("{CHILD}/stat"), Err(Errno::BADF));
assert!(descendants(&kernel(), root(), &EDGES).unwrap().is_empty());
assert!(children_of(&kernel(), root(), &EDGES).unwrap().is_empty());
}
#[skuld::test]
fn a_child_whose_parent_cannot_be_proved_again_is_unassessed_and_a_gone_child_is_not() {
let unproved = || table().on_pidfs_ino_after_read(ROOT, &format!("{CHILD}/stat"), Err(Errno::BADF));
let walk = |kernel: &FakeKernel, depth| {
super::walk_from(kernel, root(), &EDGES, depth)
.unwrap()
.expect("the root is live")
};
let found = walk(&unproved(), Recursive::Yes);
let [(pid, Error::Unassessable { detail, .. })] = &found.unassessed[..] else {
panic!("expected one Unassessable entry, got {:?}", found.unassessed);
};
assert_eq!(*pid, CHILD);
assert!(
detail.contains(&format!("ppid {ROOT} identity could not be read")),
"{detail}"
);
assert!(found.members.is_empty());
let children = walk(&unproved(), Recursive::No);
assert_eq!(children.unassessed.len(), 1, "{:?}", children.unassessed);
let gone = table()
.on_pidfd_open(CHILD, Err(Errno::SRCH))
.on_read(&format!("{CHILD}/stat"), Err(libc::ENOENT));
for depth in [Recursive::Yes, Recursive::No] {
let found = walk(&gone, depth);
assert!(found.members.is_empty() && found.unassessed.is_empty(), "{found:?}");
}
}
#[skuld::test]
fn a_child_whose_parent_cannot_be_proved_is_reported_by_an_error_naming_both() {
crate::log_capture::install();
let kernel = || table().on_pidfs_ino_after_read(ROOT, &format!("{CHILD}/stat"), Err(Errno::BADF));
let names_both = |detail: &str| {
detail.contains(&format!("ppid {ROOT} identity could not be read")) && detail.contains(&format!("pid {CHILD}"))
};
let mark = crate::log_capture::mark();
for depth in [Recursive::No, Recursive::Yes] {
let walked = super::walk_from(&kernel(), root(), &EDGES, depth)
.expect("the root reads")
.expect("the root is live");
let [(_, Error::Unassessable { detail, .. })] = &walked.unassessed[..] else {
panic!(
"{depth:?}: expected one Unassessable entry, got {:?}",
walked.unassessed
);
};
assert!(
detail.contains(&format!("ppid {ROOT} identity could not be read"))
&& detail.contains(&format!("reading pid {CHILD}")),
"{depth:?}: {detail}"
);
let err = walked.complete_members().expect_err("the list would be short");
let Error::Unassessable { detail, .. } = &err else {
panic!("{depth:?}: expected Unassessable, got {err:?}");
};
assert!(names_both(detail), "{depth:?}: {detail}");
}
assert_eq!(
crate::log_capture::records_since_on_current_thread(mark, ""),
[],
"a query logs nothing"
);
let walked = super::walk_from(&kernel(), root(), &EDGES, Recursive::Yes)
.expect("the root reads")
.expect("the root is live");
let mark = crate::log_capture::mark();
super::warn_unassessed(&walked.unassessed);
let warned = crate::log_capture::records_since_on_current_thread(mark, "");
assert_eq!(warned.len(), 1, "{warned:?}");
assert_eq!(warned[0].0, log::Level::Warn);
assert!(names_both(&warned[0].1), "{warned:?}");
}
fn ticks_table(root_start_now: u64) -> FakeKernel<'static> {
FakeKernel::over(&HostKernel)
.same_view()
.on_pidfd_open(CHILD, Ok(stand_in()))
.on_pidfs_ino(CHILD, Ok(None))
.on_read(&format!("{ROOT}/stat"), Ok(&stat(ROOT, 1, root_start_now)))
.on_read(&format!("{CHILD}/stat"), Ok(&stat(CHILD, ROOT, CHILD_START)))
}
fn ticks_root() -> ProcessId {
ProcessId::from_parts_for_test(ROOT, Key::Ticks(ROOT_START))
}
#[skuld::test]
fn on_a_ticks_host_a_child_is_kept_only_while_its_parent_shows_its_ticks() {
let kept = ticks_table(ROOT_START);
assert_eq!(descendants(&kept, ticks_root(), &EDGES).unwrap().len(), 1);
assert_eq!(children_of(&kept, ticks_root(), &EDGES).unwrap().len(), 1);
let changed_hands = ticks_table(ROOT_START + 1);
assert!(descendants(&changed_hands, ticks_root(), &EDGES).unwrap().is_empty());
assert!(children_of(&changed_hands, ticks_root(), &EDGES).unwrap().is_empty());
}
fn root_changed_hands() -> FakeKernel<'static> {
table().on_pidfs_ino(ROOT, Ok(Some(ROOT_INO + 1)))
}
fn root_proof_fails() -> FakeKernel<'static> {
table().on_pidfs_ino(ROOT, Err(Errno::BADF))
}
#[skuld::test]
fn a_root_whose_proof_finds_another_process_walks_nothing() {
let sends = crate::send_log::Capture::start();
let walks = super::fault::record_walks();
assert!(
matches!(
super::hard_kill(
&root_changed_hands(),
root(),
&super::ByIdentity::new(&root_changed_hands(), root())
)
.outcome(),
crate::containment::dispatch::TreeKillOutcome::NoRoot(..)
),
"a gone root has no tree to walk"
);
let termed = super::terminate(
&root_changed_hands(),
root(),
&super::ByIdentity::new(&root_changed_hands(), root()),
crate::containment::TreeStop::default(),
);
assert!(
matches!(termed, (super::SendOutcome::RootExited(_), None)),
"a gone root sends nothing"
);
for recursive in [Recursive::No, Recursive::Yes] {
let children = root().children_with(&root_changed_hands(), recursive);
assert_eq!(children.expect("a gone root is Ok"), vec![], "{recursive:?}");
}
assert_eq!(walks.walked(), Vec::<u32>::new(), "no walk began");
assert!(sends.by_identity().is_empty(), "{:?}", sends.by_identity());
}
#[skuld::test]
fn a_root_whose_proof_cannot_be_made_is_unassessable_and_signals_nothing() {
let sends = crate::send_log::Capture::start();
let walks = super::fault::record_walks();
let results = [
super::hard_kill(
&root_proof_fails(),
root(),
&super::ByIdentity::new(&root_proof_fails(), root()),
)
.outcome()
.into_result()
.map_err(crate::containment::dispatch::Unkilled::into_error),
match super::terminate(
&root_proof_fails(),
root(),
&super::ByIdentity::new(&root_proof_fails(), root()),
crate::containment::TreeStop::default(),
) {
(super::SendOutcome::NotSent(not_sent), _) => Err(not_sent),
_ => Ok(()),
},
root().children_with(&root_proof_fails(), Recursive::No).map(|_| ()),
root().children_with(&root_proof_fails(), Recursive::Yes).map(|_| ()),
];
for result in results {
match result {
Err(Error::Unassessable { detail, .. }) => {
assert!(detail.contains(&format!("pid {ROOT}")), "{detail}");
}
other => panic!("expected Unassessable, got {other:?}"),
}
}
assert_eq!(walks.walked(), Vec::<u32>::new(), "no walk began");
assert!(sends.by_identity().is_empty(), "{:?}", sends.by_identity());
}
const KILLED_INO: u64 = 77;
fn live_child_in_a_table() -> (StdChild, ProcessId, FakeKernel<'static>) {
let child = blocker_with(|cat| {
cat.stdout(std::process::Stdio::null());
});
let pid = child.id();
let kernel = FakeKernel::over(&HostKernel)
.on_pidfd_open(pid, Ok(crate::child::front_cgroup_tests::pidfd_of(pid)))
.on_pidfs_ino(pid, Ok(Some(KILLED_INO)));
(
child,
ProcessId::from_parts_for_test(pid, Key::Pidfs(KILLED_INO)),
kernel,
)
}
#[skuld::test]
fn a_kill_by_identity_is_sent_through_the_proved_pidfd() {
use std::os::unix::process::ExitStatusExt as _;
let (mut child, id, kernel) = live_child_in_a_table();
let sends = crate::send_log::Capture::start();
let outcome = super::kill_by_identity(&kernel, id, crate::signal::Sig::Graceful(crate::signal::Signal::Term));
assert!(matches!(outcome, super::KillOutcome::Terminated), "{outcome:?}");
assert_eq!(
sends.entries(),
[(
id.pid(),
crate::signal::Sig::Graceful(crate::signal::Signal::Term),
crate::send_log::Via::Pidfd
)]
);
assert_eq!(
child.wait().expect("the child exits").signal(),
Some(libc::SIGTERM),
"the signal reached the process the pidfd names"
);
}
#[skuld::test]
fn a_kill_by_identity_of_a_process_reaped_after_the_proof_is_already_gone() {
let (mut child, id, kernel) = live_child_in_a_table();
drop(child.stdin.take());
child.wait().expect("the child exits at EOF");
let outcome = super::kill_by_identity(&kernel, id, crate::signal::Sig::Graceful(crate::signal::Signal::Term));
assert!(matches!(outcome, super::KillOutcome::AlreadyGone), "{outcome:?}");
}