use std::os::fd::{AsFd as _, OwnedFd};
use std::sync::Arc;
use super::ProbeEnd;
use super::{dying_in, front_placement, Subtree};
use crate::containment::cgroup::fault::{self, ProbeStep};
use crate::containment::cgroup::test_support::{alone, kill_record};
use crate::identity::{FakeKernel, HostKernel, UNREADABLE_STATUS_REASON};
use crate::log_capture::warns_since;
use crate::send_log::Via;
use crate::test_groups::{cgroup, Group};
const HIGH: u64 = 0x1_0000_0007;
fn own_pidfd() -> OwnedFd {
rustix::process::pidfd_open(rustix::process::getpid(), rustix::process::PidfdFlags::empty()).expect("pidfd_open")
}
fn subtree(leaf_id: u64, killed: bool) -> Subtree {
Subtree::new(
Some(leaf_id),
None,
None,
crate::containment::cgroup::Swept::default(),
super::PlacedAtRemoval::default(),
kill_record(killed),
)
}
fn stand_in_subtree(stat: Option<&str>) -> (Subtree, tempfile::TempDir) {
let dir = tempfile::tempdir().expect("tempdir");
std::fs::write(dir.path().join("cgroup.events"), "populated 0\n").expect("write the stand-in cgroup.events");
if let Some(stat) = stat {
std::fs::write(dir.path().join("cgroup.stat"), stat).expect("write the stand-in cgroup.stat");
}
let fd = rustix::fs::open(
dir.path(),
rustix::fs::OFlags::PATH | rustix::fs::OFlags::DIRECTORY | rustix::fs::OFlags::CLOEXEC,
rustix::fs::Mode::empty(),
)
.expect("open the stand-in leaf");
(subtree_of(fd, crate::containment::cgroup::Swept::default()), dir)
}
fn subtree_of(fd: OwnedFd, swept: crate::containment::cgroup::Swept) -> Subtree {
Subtree::new(
Some(HIGH),
Some(Arc::new(fd)),
Some("/stand-in-leaf".to_owned()),
swept,
super::PlacedAtRemoval::default(),
kill_record(true),
)
}
fn holds_hidden(leaf: &Subtree, id: u64) -> std::io::Result<bool> {
let _id = fault::force_pidfd_cgroup_id(id);
let _hidden = fault::hide_proc();
let pidfd = own_pidfd();
leaf.holds(std::process::id(), Some(pidfd.as_fd()))
}
#[skuld::test]
fn a_subtree_compares_all_64_bits_of_a_cgroup_id() {
let pidfd = own_pidfd();
let pid = std::process::id();
let leaf = subtree(HIGH, false);
{
let _id = fault::force_pidfd_cgroup_id(HIGH);
assert!(leaf.holds(pid, Some(pidfd.as_fd())).expect("a forced id"));
}
{
let _id = fault::force_pidfd_cgroup_id(HIGH & u64::from(u32::MAX));
assert!(
!leaf.holds(pid, Some(pidfd.as_fd())).expect("a forced id"),
"an id equal only in its low 32 bits is another cgroup"
);
}
let low = subtree(HIGH & u64::from(u32::MAX), false);
let _id = fault::force_pidfd_cgroup_id(HIGH);
assert!(!low.holds(pid, Some(pidfd.as_fd())).expect("a forced id"));
}
#[skuld::test]
fn a_subtree_reached_a_task_only_once_its_kill_landed() {
let pidfd = own_pidfd();
let pid = std::process::id();
let _id = fault::force_pidfd_cgroup_id(HIGH);
assert!(subtree(HIGH, false)
.holds(pid, Some(pidfd.as_fd()))
.expect("a forced id"));
assert!(!subtree(HIGH, false)
.reached_by(pid, Some(pidfd.as_fd()))
.expect("a forced id"));
assert!(subtree(HIGH, true)
.reached_by(pid, Some(pidfd.as_fd()))
.expect("a forced id"));
}
#[skuld::test]
fn with_pidfd_info_a_front_is_placeable_whatever_proc_hides() {
let _id = fault::force_pidfd_cgroup_id(HIGH);
let _hidden = fault::hide_proc();
front_placement(&HostKernel, || Ok(HIGH)).expect("placeable by a pidfd's cgroup id");
}
#[skuld::test]
fn cgroup_without_pidfd_info_a_proc_that_shows_untraceable_processes_places_fronts(#[fixture(cgroup)] _group: &Group) {
let _missing = fault::miss_pidfd_info();
front_placement(&HostKernel, || Ok(HIGH)).expect("the lane's /proc shows its root every process");
}
#[skuld::test]
fn without_pidfd_info_a_hidepid_proc_refuses_naming_hidepid() {
let _missing = fault::miss_pidfd_info();
let _hidden = fault::hide_proc();
match front_placement(&HostKernel, || Ok(HIGH)) {
Err(crate::error::Error::Unsupported { detail, .. }) => {
assert!(detail.contains("hidepid"), "{detail}");
assert!(detail.contains("before anything is spawned"), "{detail}");
}
other => panic!("expected Unsupported, got {other:?}"),
}
}
#[skuld::test]
fn without_pidfd_info_a_diverged_proc_view_refuses_naming_the_view() {
let _missing = fault::miss_pidfd_info();
let kernel = FakeKernel::over(&HostKernel).diverged_view();
match front_placement(&kernel, || Ok(HIGH)) {
Err(crate::error::Error::Unsupported { detail, .. }) => {
assert!(detail.contains("an outer pid namespace's"), "{detail}");
assert!(!detail.contains("hidepid"), "{detail}");
}
other => panic!("expected Unsupported, got {other:?}"),
}
}
#[skuld::test]
fn without_pidfd_info_an_unassessable_proc_view_refuses_naming_the_view() {
let _missing = fault::miss_pidfd_info();
let kernel = FakeKernel::over(&HostKernel).unreadable_view();
match front_placement(&kernel, || Ok(HIGH)) {
Err(crate::error::Error::Unsupported { detail, .. }) => {
assert!(
detail.contains(&format!("could not be established ({UNREADABLE_STATUS_REASON})")),
"{detail}"
);
assert!(!detail.contains("hidepid"), "{detail}");
}
other => panic!("expected Unsupported, got {other:?}"),
}
}
#[skuld::test]
fn cgroup_the_placement_probe_answers_with_fds_0_and_1_closed(#[fixture(cgroup)] _group: &Group) {
use crate::test_own_process::{own_process, test_path};
use crate::test_spawn::spawn;
use crate::test_stdio::RestoreStdio;
let Some(done) = own_process(
test_path!(cgroup_the_placement_probe_answers_with_fds_0_and_1_closed),
spawn,
) else {
return;
};
let _missing = fault::miss_pidfd_info();
let restore = RestoreStdio::close(&done, &[0, 1]);
let shown = front_placement(&HostKernel, || Ok(HIGH));
let hidden = {
let _hidden = fault::hide_proc();
front_placement(&HostKernel, || Ok(HIGH))
};
drop(restore);
shown.expect("this test's /proc hides nothing");
assert!(
matches!(hidden, Err(crate::error::Error::Unsupported { .. })),
"{hidden:?}"
);
}
#[skuld::test]
fn dying_cgroups_are_read_from_cgroup_stat() {
assert_eq!(dying_in("nr_descendants 0\nnr_dying_descendants 0\n"), Some(0));
assert_eq!(
dying_in("nr_descendants 2\nnr_dying_descendants 1\nnr_subsys_cpu 3\n"),
Some(1)
);
assert_eq!(dying_in("nr_descendants 0\n"), None);
assert_eq!(dying_in("nr_dying_descendants_x 0\n"), None);
}
#[skuld::test]
fn cgroup_a_task_in_a_nested_cgroup_is_found_by_the_walk(#[fixture(cgroup)] _group: &Group) {
use crate::containment::cgroup::dir_walk_tests::{id_at, Scratch};
let scratch = Scratch::new("reach-nested");
let nested = id_at(&scratch.make("a/b/c"));
scratch.make("d");
let leaf = subtree_of(scratch.fd(), crate::containment::cgroup::Swept::default());
assert!(holds_hidden(&leaf, nested).expect("no /proc read"));
}
#[skuld::test]
fn a_task_the_walk_finds_nowhere_is_outside() {
let (leaf, _dir) = stand_in_subtree(Some("nr_descendants 0\nnr_dying_descendants 0\n"));
assert!(!holds_hidden(&leaf, HIGH + 1).expect("no /proc read"));
}
#[skuld::test]
fn a_walk_that_finds_nothing_but_cannot_prove_it_says_why() {
crate::log_capture::install();
let says = "so it is not shown to be outside";
for (stat, cause) in [
(Some("nr_dying_descendants 2\n"), Some("2 are removed")),
(Some("nr_descendants 0\n"), Some("an unknown number")),
(None, Some("cgroup.stat cannot be read")),
(Some("nr_dying_descendants 0\n"), None),
] {
let (leaf, _dir) = stand_in_subtree(stat);
let mark = crate::log_capture::mark();
let held = holds_hidden(&leaf, HIGH + 1);
let logs = crate::log_capture::records_since_on_current_thread(mark, says);
match cause {
Some(cause) => {
held.expect_err("not shown outside, so placed through the hidden /proc");
assert_eq!(logs.len(), 1, "{stat:?}: {logs:?}");
assert_eq!(logs[0].0, log::Level::Debug, "{stat:?}");
assert!(logs[0].1.contains(cause), "{stat:?}: {logs:?}");
}
None => {
assert!(!held.expect("proven outside"));
assert_eq!(logs, [], "{stat:?}");
}
}
}
}
#[skuld::test]
fn cgroup_a_task_in_a_cgroup_the_sweep_removed_is_in_the_subtree(#[fixture(cgroup)] _group: &Group) {
use crate::containment::cgroup::dir_walk_tests::{id_at, Scratch};
let scratch = Scratch::new("reach-swept");
let sub = id_at(&scratch.make("sub"));
let leaf = crate::containment::cgroup::LeafDir::open_for_test(scratch.path());
assert_eq!(leaf.remove_children().expect("sweep"), 1);
leaf.rmdir().expect("remove the scratch leaf");
let subtree = Subtree::new(
Some(HIGH),
Some(leaf.shared()),
Some("/stand-in-leaf".to_owned()),
leaf.swept(),
super::PlacedAtRemoval::default(),
kill_record(true),
);
assert!(holds_hidden(&subtree, sub).expect("no /proc read"));
}
#[skuld::test]
fn a_task_the_walk_cannot_place_is_placed_through_proc() {
for (stat, sub) in [
(Some("nr_dying_descendants 1\n"), false),
(None, false),
(Some("nr_dying_descendants 0\n"), true),
] {
let (leaf, dir) = stand_in_subtree(stat);
if sub {
std::fs::create_dir(dir.path().join("sub")).expect("mkdir");
}
let err = holds_hidden(&leaf, HIGH + 1).expect_err("placed through the hidden /proc");
assert!(err.to_string().contains("maybe one under it"), "{stat:?} {sub}: {err}");
}
}
#[skuld::test]
fn a_removed_leaf_is_answered_by_the_place_recorded_before_its_removal() {
use super::names_leaf;
let unasked = || -> Option<bool> { panic!("not asked") };
let (leaf, deleted) = ("/a/leaf", "/a/leaf (deleted)");
assert!(names_leaf(leaf, leaf, false, unasked).expect("decided"));
assert!(names_leaf("/a/leaf/sub (deleted)", leaf, true, unasked).expect("decided"));
assert!(
names_leaf(deleted, leaf, false, || Some(true)).expect("decided"),
"recorded in the leaf"
);
assert!(
!names_leaf(deleted, leaf, false, || Some(false)).expect("decided"),
"recorded outside"
);
names_leaf(deleted, leaf, false, || None).expect_err("no record: the leaf or its namesake");
assert!(
!names_leaf(deleted, leaf, true, unasked).expect("decided"),
"another cgroup id"
);
assert!(!names_leaf("/a/leafx (deleted)", leaf, false, unasked).expect("decided"));
}
#[skuld::test]
fn a_recorded_place_answers_for_its_own_task_alone() {
let placed = super::PlacedAtRemoval::default();
assert_eq!(placed.of(7), None);
placed.record(7, true);
assert_eq!((placed.of(7), placed.of(8)), (Some(true), None));
placed.clear();
assert_eq!(placed.of(7), None);
}
#[skuld::test]
fn without_pidfd_info_a_hidepid_1_proc_refuses_naming_hidepid() {
let _missing = fault::miss_pidfd_info();
let _hidden = fault::hide_proc_as(libc::EPERM);
match front_placement(&HostKernel, || Ok(HIGH)) {
Err(crate::error::Error::Unsupported { detail, .. }) => assert!(detail.contains("hidepid"), "{detail}"),
other => panic!("expected Unsupported, got {other:?}"),
}
}
#[skuld::test]
fn a_probe_child_that_stays_dumpable_fails_the_probe() {
let _missing = fault::miss_pidfd_info();
let _dumpable = fault::keep_probe_dumpable();
match front_placement(&HostKernel, || Ok(HIGH)) {
Err(crate::error::Error::Io(e)) => assert!(e.to_string().contains("non-dumpable"), "{e}"),
other => panic!("expected Io, got {other:?}"),
}
}
#[skuld::test]
fn a_refused_pidfd_info_refuses_naming_it() {
let _failing = fault::fail_pidfd_info();
match front_placement(&HostKernel, || Ok(HIGH)) {
Err(crate::error::Error::Unsupported { detail, .. }) => {
assert!(detail.contains("PIDFD_GET_INFO failed"), "{detail}");
}
other => panic!("expected Unsupported, got {other:?}"),
}
}
#[skuld::test]
fn a_host_that_gives_no_cgroup_id_refuses_naming_the_errno() {
for errno in [libc::ENOSYS, libc::EOPNOTSUPP, libc::EPERM] {
match front_placement(&HostKernel, || Err(std::io::Error::from_raw_os_error(errno))) {
Err(crate::error::Error::Unsupported { detail, .. }) => {
let named = std::io::Error::from_raw_os_error(errno).to_string();
assert!(detail.contains(&named), "{errno}: {detail}");
assert!(detail.contains("before anything is spawned"), "{errno}: {detail}");
}
other => panic!("{errno}: expected Unsupported, got {other:?}"),
}
}
}
#[skuld::test]
fn any_other_failure_to_read_the_leaf_id_is_an_io_error() {
match front_placement(&HostKernel, || Err(std::io::Error::from_raw_os_error(libc::ENOMEM))) {
Err(crate::error::Error::Io(e)) => assert!(e.to_string().contains("leaf"), "{e}"),
other => panic!("expected Io, got {other:?}"),
}
}
struct ProbeGuard(OwnedFd);
impl Drop for ProbeGuard {
fn drop(&mut self) {
if rustix::process::pidfd_send_signal(self.0.as_fd(), rustix::process::Signal::KILL).is_ok() {
_ = rustix::process::waitid(
rustix::process::WaitId::PidFd(self.0.as_fd()),
rustix::process::WaitIdOptions::EXITED,
);
}
}
}
impl ProbeGuard {
fn of(pid: libc::pid_t) -> ProbeGuard {
ProbeGuard(
rustix::process::pidfd_open(
rustix::process::Pid::from_raw(pid).expect("a positive pid"),
rustix::process::PidfdFlags::empty(),
)
.expect("pidfd_open the probe"),
)
}
}
fn proc_dir() -> crate::identity::ProcDir {
match crate::identity::proc_view_with(&crate::identity::HostKernel) {
crate::identity::ProcView::Same(dir) => dir,
_ => panic!("precondition: this test's /proc is its own pid namespace's"),
}
}
#[skuld::test]
fn the_probe_child_dies_with_the_thread_that_forked_it() {
use std::io::Read as _;
let (ready_tx, ready_rx) = std::sync::mpsc::channel();
let (go_tx, go_rx) = std::sync::mpsc::channel::<()>();
std::thread::scope(move |scope| {
scope.spawn(move || {
let parent = rustix::process::getpid().as_raw_nonzero().get();
let probe = super::fork_probe(&proc_dir(), parent, false).expect("fork the probe");
let mut report = [0u8; 2];
probe.channel().read_exact(&mut report).expect("the probe reports");
ready_tx.send((probe, report)).expect("report the probe");
_ = go_rx.recv();
});
let (probe, report) = ready_rx.recv().expect("the probe");
let pidfd = ProbeGuard::of(probe.pid);
assert_eq!(
report,
[0, libc::SIGKILL as u8],
"non-dumpable, and killed with its parent"
);
go_tx.send(()).expect("let the forking thread end");
let status = rustix::process::waitid(
rustix::process::WaitId::PidFd(pidfd.0.as_fd()),
rustix::process::WaitIdOptions::EXITED,
)
.expect("the probe ends with its forking thread")
.expect("a blocking waitid returns a status");
assert_eq!(status.terminating_signal(), Some(libc::SIGKILL));
});
}
#[skuld::test]
fn a_probe_whose_parent_is_gone_exits_without_reporting() {
use std::io::Read as _;
let not_the_parent = rustix::process::getpid().as_raw_nonzero().get() + 1;
let probe = super::fork_probe(&proc_dir(), not_the_parent, false).expect("fork the probe");
let pidfd = ProbeGuard::of(probe.pid);
let mut reported = [0u8; 2];
let read = probe.channel().read(&mut reported).expect("read the probe's report");
assert_eq!(read, 0, "the probe reported {reported:?}");
let status = rustix::process::waitid(
rustix::process::WaitId::PidFd(pidfd.0.as_fd()),
rustix::process::WaitIdOptions::EXITED,
)
.expect("reap the probe")
.expect("a blocking waitid returns a status");
assert_eq!(status.exit_status(), Some(super::ABANDONED));
}
fn descriptors_of(pid: libc::pid_t) -> std::collections::BTreeMap<i32, String> {
std::fs::read_dir(format!("/proc/{pid}/fd"))
.expect("list the probe child's descriptors")
.map(|entry| {
let entry = entry.expect("a descriptor entry");
let fd = entry
.file_name()
.to_str()
.and_then(|n| n.parse().ok())
.expect("a numbered entry");
let target = std::fs::read_link(entry.path()).expect("read what the descriptor names");
(fd, target.to_string_lossy().into_owned())
})
.collect()
}
fn own_descriptor(fd: &impl std::os::fd::AsRawFd) -> String {
let target = std::fs::read_link(format!("/proc/self/fd/{}", fd.as_raw_fd())).expect("read an own descriptor");
target.to_string_lossy().into_owned()
}
fn assert_two_probes_hold_only_their_own() {
use std::io::Read as _;
let proc = proc_dir();
let parent = rustix::process::getpid().as_raw_nonzero().get();
let first = super::fork_probe(&proc, parent, true).expect("fork the first probe");
let second = super::fork_probe(&proc, parent, true).expect("fork the second probe");
let mut report = [0u8; 2];
first
.channel()
.read_exact(&mut report)
.expect("the first probe reports");
second
.channel()
.read_exact(&mut report)
.expect("the second probe reports");
for (name, probe) in [("first", &first), ("second", &second)] {
let held: Vec<_> = descriptors_of(probe.pid).into_values().collect();
assert!(
matches!(held.as_slice(), [one] if one.starts_with("socket:")),
"the {name} probe's child holds only its end of the socket: {held:?}"
);
assert_ne!(
held[0],
own_descriptor(probe.channel()),
"the {name} probe's child holds its parent's end"
);
}
let first_parent_end = own_descriptor(first.channel());
assert!(
!descriptors_of(second.pid)
.values()
.any(|target| *target == first_parent_end),
"the second probe's child holds the first's parent end"
);
}
#[skuld::test]
fn concurrent_probes_children_each_hold_only_their_own_descriptors() {
assert_two_probes_hold_only_their_own();
}
#[skuld::test]
fn probes_children_hold_only_their_own_descriptors_without_close_range() {
let _refused = fault::refuse_probe_close_range();
assert_two_probes_hold_only_their_own();
}
#[skuld::test]
fn probes_children_hold_only_their_own_descriptors_when_a_later_close_range_is_refused() {
let _refused = fault::refuse_probe_close_range_after(1);
assert_two_probes_hold_only_their_own();
}
#[skuld::test]
fn the_probe_child_is_killed_through_its_pidfd() {
let _missing = fault::miss_pidfd_info();
let _hidden = fault::hide_proc();
fault::take_probe_steps();
front_placement(&HostKernel, || Ok(HIGH)).expect_err("a hidden /proc refuses");
assert_eq!(
fault::take_probe_steps(),
[
ProbeStep::Kill(Via::Pidfd, libc::SIGKILL),
ProbeStep::Reap(Via::Pidfd, ProbeEnd::Signal(libc::SIGKILL))
]
);
}
fn no_child_holds(pid: libc::pid_t) -> Result<bool, rustix::io::Errno> {
use rustix::process::{waitid, Pid, WaitId, WaitIdOptions};
let pid = Pid::from_raw(pid).expect("a positive pid");
match waitid(
WaitId::Pid(pid),
WaitIdOptions::EXITED | WaitIdOptions::NOHANG | WaitIdOptions::NOWAIT,
) {
Err(rustix::io::Errno::CHILD) => Ok(true),
Err(e) => Err(e),
Ok(_) => Ok(false),
}
}
#[skuld::test]
fn a_probe_child_no_pidfd_can_pin_is_killed_and_reaped_by_its_number() {
let _missing = fault::miss_pidfd_info();
let _hidden = fault::hide_proc();
let forked = std::rc::Rc::new(std::cell::Cell::new(None));
let _unpinned = fault::set_before_probe_pin({
let forked = forked.clone();
move |pid| {
forked.set(Some(pid));
Some(libc::EMFILE)
}
});
fault::take_probe_steps();
front_placement(&HostKernel, || Ok(HIGH)).expect_err("a hidden /proc refuses");
let pid = forked.get().expect("the probe forked");
assert_eq!(
fault::take_probe_steps(),
[
ProbeStep::Kill(Via::Pid, libc::SIGKILL),
ProbeStep::Reap(Via::Pid, ProbeEnd::Signal(libc::SIGKILL))
]
);
assert_eq!(no_child_holds(pid), Ok(true), "the probe's child {pid} is left");
}
#[skuld::test]
fn a_probe_child_reaped_elsewhere_before_its_pin_is_sent_nothing() {
let _missing = fault::miss_pidfd_info();
let _reaped = fault::set_before_probe_pin(|pid| {
assert_eq!(unsafe { libc::kill(pid, libc::SIGKILL) }, 0, "kill the probe's child");
crate::test_child::reaped_elsewhere::reap_behind(pid as u32);
None
});
fault::take_probe_steps();
let err = front_placement(&HostKernel, || Ok(HIGH)).expect_err("the probe has no child left");
assert_eq!(fault::take_probe_steps(), [], "nothing was sent");
assert!(matches!(err, crate::error::Error::Io(_)), "{err:?}");
}
#[skuld::test]
fn a_probe_child_whose_pidfd_kill_fails_is_released_and_reaped_through_its_pidfd() {
crate::log_capture::install();
let _missing = fault::miss_pidfd_info();
let _hidden = fault::hide_proc();
let forked = std::rc::Rc::new(std::cell::Cell::new(None));
let _failed = fault::set_before_probe_kill({
let forked = forked.clone();
move |pid| {
forked.set(Some(pid));
Some(libc::EPERM)
}
});
fault::take_probe_steps();
let mark = crate::log_capture::mark();
front_placement(&HostKernel, || Ok(HIGH)).expect_err("a hidden /proc refuses");
let pid = forked.get().expect("the probe's child was to be killed");
assert_eq!(
fault::take_probe_steps(),
[
ProbeStep::Kill(Via::Pidfd, libc::SIGKILL),
ProbeStep::Reap(Via::Pidfd, ProbeEnd::Exit(super::RELEASED))
]
);
let warns = warns_since(mark, "");
assert!(
warns.iter().any(|w| w.contains(&format!("child {pid}"))),
"a warn names the probe's child {pid}: {warns:?}"
);
assert_eq!(no_child_holds(pid), Ok(true), "the probe's child {pid} is left");
}
#[skuld::test]
fn a_probe_child_whose_kill_by_number_fails_is_released_and_warned() {
crate::log_capture::install();
let _missing = fault::miss_pidfd_info();
let _hidden = fault::hide_proc();
let forked = std::rc::Rc::new(std::cell::Cell::new(None));
let _unpinned = fault::set_before_probe_pin({
let forked = forked.clone();
move |pid| {
forked.set(Some(pid));
Some(libc::EMFILE)
}
});
let _failed = fault::set_before_probe_kill(|_| Some(libc::EPERM));
fault::take_probe_steps();
let mark = crate::log_capture::mark();
front_placement(&HostKernel, || Ok(HIGH)).expect_err("a hidden /proc refuses");
let pid = forked.get().expect("the probe forked");
assert_eq!(
fault::take_probe_steps(),
[
ProbeStep::Kill(Via::Pid, libc::SIGKILL),
ProbeStep::Reap(Via::Pid, ProbeEnd::Exit(super::RELEASED))
]
);
let warns = warns_since(mark, "");
assert!(
warns.iter().any(|w| w.contains(&format!("child {pid}"))),
"a warn names the probe's child {pid}: {warns:?}"
);
assert_eq!(no_child_holds(pid), Ok(true), "the probe's child {pid} is left");
}
#[skuld::test]
fn a_failed_kill_of_one_probe_is_not_stalled_by_another_probes_child() {
let _missing = fault::miss_pidfd_info();
let _hidden = fault::hide_proc();
let second = std::rc::Rc::new(std::cell::RefCell::new(None));
let _failed = fault::set_before_probe_kill({
let second = second.clone();
move |_| {
use std::io::Read as _;
let parent = rustix::process::getpid().as_raw_nonzero().get();
let probe = super::fork_probe(&proc_dir(), parent, false).expect("fork the second probe");
let mut report = [0u8; 2];
probe
.channel()
.read_exact(&mut report)
.expect("the second probe reports");
*second.borrow_mut() = Some(probe);
Some(libc::EPERM)
}
});
fault::take_probe_steps();
front_placement(&HostKernel, || Ok(HIGH)).expect_err("a hidden /proc refuses");
assert_eq!(
fault::take_probe_steps(),
[
ProbeStep::Kill(Via::Pidfd, libc::SIGKILL),
ProbeStep::Reap(Via::Pidfd, ProbeEnd::Exit(super::RELEASED))
]
);
let second = second.borrow_mut().take().expect("the second probe forked");
let pid = second.pid;
assert_eq!(
no_child_holds(pid),
Ok(false),
"the second probe's child {pid} still runs"
);
second.end().expect("end the second probe");
assert_eq!(
fault::take_probe_steps(),
[
ProbeStep::Kill(Via::Pidfd, libc::SIGKILL),
ProbeStep::Reap(Via::Pidfd, ProbeEnd::Signal(libc::SIGKILL))
]
);
}
struct SigchldIgnored(nix::sys::signal::SigAction);
fn ignore_sigchld() -> SigchldIgnored {
use nix::sys::signal::{sigaction, SaFlags, SigAction, SigHandler, SigSet, Signal};
let ignore = SigAction::new(SigHandler::SigIgn, SaFlags::empty(), SigSet::empty());
SigchldIgnored(unsafe { sigaction(Signal::SIGCHLD, &ignore) }.expect("ignore SIGCHLD"))
}
impl Drop for SigchldIgnored {
fn drop(&mut self) {
_ = unsafe { nix::sys::signal::sigaction(nix::sys::signal::Signal::SIGCHLD, &self.0) };
}
}
#[skuld::test]
fn a_probe_child_reaped_by_an_ignored_sigchld_keeps_the_verdict() {
if !alone("containment::cgroup::reach::reach_tests::a_probe_child_reaped_by_an_ignored_sigchld_keeps_the_verdict") {
return;
}
let _ignored = ignore_sigchld();
let _missing = fault::miss_pidfd_info();
let _hidden = fault::hide_proc();
fault::take_probe_steps();
let err = front_placement(&HostKernel, || Ok(HIGH)).expect_err("a hidden /proc refuses");
assert!(matches!(err, crate::error::Error::Unsupported { .. }), "{err:?}");
assert_eq!(
fault::take_probe_steps(),
[
ProbeStep::Kill(Via::Pidfd, libc::SIGKILL),
ProbeStep::Reap(Via::Pidfd, ProbeEnd::Elsewhere)
]
);
}
#[skuld::test]
fn a_probe_child_no_pidfd_pins_reaped_by_an_ignored_sigchld_keeps_the_verdict() {
if !alone(
"containment::cgroup::reach::reach_tests::a_probe_child_no_pidfd_pins_reaped_by_an_ignored_sigchld_keeps_the_verdict",
) {
return;
}
let _ignored = ignore_sigchld();
let _missing = fault::miss_pidfd_info();
let _hidden = fault::hide_proc();
let _unpinned = fault::set_before_probe_pin(|_| Some(libc::EMFILE));
fault::take_probe_steps();
let err = front_placement(&HostKernel, || Ok(HIGH)).expect_err("a hidden /proc refuses");
assert!(matches!(err, crate::error::Error::Unsupported { .. }), "{err:?}");
assert_eq!(
fault::take_probe_steps(),
[
ProbeStep::Kill(Via::Pid, libc::SIGKILL),
ProbeStep::Reap(Via::Pid, ProbeEnd::Elsewhere)
]
);
}
#[skuld::test]
fn a_probe_child_reaped_by_another_waiter_keeps_the_verdict() {
let _missing = fault::miss_pidfd_info();
let _hidden = fault::hide_proc();
let _reaped = fault::set_before_probe_kill(|pid| {
assert_eq!(unsafe { libc::kill(pid, libc::SIGKILL) }, 0, "kill the probe's child");
crate::test_child::reaped_elsewhere::reap_behind(pid as u32);
None
});
fault::take_probe_steps();
let err = front_placement(&HostKernel, || Ok(HIGH)).expect_err("a hidden /proc refuses");
assert!(matches!(err, crate::error::Error::Unsupported { .. }), "{err:?}");
assert_eq!(
fault::take_probe_steps(),
[
ProbeStep::Kill(Via::Pidfd, libc::SIGKILL),
ProbeStep::Reap(Via::Pidfd, ProbeEnd::Elsewhere)
]
);
}
#[skuld::test]
fn a_probe_child_already_dead_at_its_pidfd_send_is_reaped_through_the_pidfd() {
let _missing = fault::miss_pidfd_info();
let _hidden = fault::hide_proc();
let forked = std::rc::Rc::new(std::cell::Cell::new(None));
let _dead = fault::set_before_probe_kill({
let forked = forked.clone();
move |pid| {
forked.set(Some(pid));
assert_eq!(unsafe { libc::kill(pid, libc::SIGKILL) }, 0, "kill the probe's child");
Some(libc::ESRCH)
}
});
fault::take_probe_steps();
front_placement(&HostKernel, || Ok(HIGH)).expect_err("a hidden /proc refuses");
let pid = forked.get().expect("the probe's child was to be killed");
assert_eq!(
fault::take_probe_steps(),
[
ProbeStep::Kill(Via::Pidfd, libc::SIGKILL),
ProbeStep::Reap(Via::Pidfd, ProbeEnd::Signal(libc::SIGKILL))
]
);
assert_eq!(no_child_holds(pid), Ok(true), "the probe's child {pid} is left");
}
struct NofileLimit(libc::rlimit);
fn limit_nofile(spare: usize) -> NofileLimit {
let open: std::collections::BTreeSet<i32> = descriptors_of(std::process::id() as libc::pid_t)
.into_iter()
.filter(|(_, target)| !target.ends_with("/fd"))
.map(|(fd, _)| fd)
.collect();
let last_free = (0..)
.filter(|fd| !open.contains(fd))
.nth(spare - 1)
.expect("a free descriptor number");
let mut before = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
assert_eq!(
unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut before) },
0,
"getrlimit"
);
let lowered = libc::rlimit {
rlim_cur: last_free as libc::rlim_t + 1,
rlim_max: before.rlim_max,
};
assert_eq!(
unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &lowered) },
0,
"setrlimit"
);
NofileLimit(before)
}
impl Drop for NofileLimit {
fn drop(&mut self) {
unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &self.0) };
}
}
fn assert_probe_answers_with_spare_descriptors(spare: usize) {
crate::log_capture::install();
let _missing = fault::miss_pidfd_info();
let _hidden = fault::hide_proc();
let _limit = limit_nofile(spare);
fault::take_probe_steps();
let mark = crate::log_capture::mark();
let err = front_placement(&HostKernel, || Ok(HIGH)).expect_err("a hidden /proc refuses");
assert!(
matches!(&err, crate::error::Error::Unsupported { detail, .. } if detail.contains("hides the cgroup")),
"the refusal is the hidden /proc's: {err:?}"
);
assert_eq!(
fault::take_probe_steps(),
[
ProbeStep::Kill(Via::Pidfd, libc::SIGKILL),
ProbeStep::Reap(Via::Pidfd, ProbeEnd::Signal(libc::SIGKILL))
]
);
assert_eq!(warns_since(mark, ""), Vec::<String>::new());
}
#[skuld::test]
fn the_probe_answers_with_the_fewest_descriptors_its_parent_needs() {
if !alone("containment::cgroup::reach::reach_tests::the_probe_answers_with_the_fewest_descriptors_its_parent_needs")
{
return;
}
assert_probe_answers_with_spare_descriptors(3);
}
#[skuld::test]
fn a_probe_child_that_exits_early_with_sigchld_ignored_says_so() {
if !alone("containment::cgroup::reach::reach_tests::a_probe_child_that_exits_early_with_sigchld_ignored_says_so") {
return;
}
let _ignored = ignore_sigchld();
let _missing = fault::miss_pidfd_info();
let _exits = fault::set_before_probe_pin(|pid| {
assert_eq!(unsafe { libc::kill(pid, libc::SIGKILL) }, 0, "kill the probe's child");
let waited = rustix::process::waitid(
rustix::process::WaitId::Pid(rustix::process::Pid::from_raw(pid).expect("a positive pid")),
rustix::process::WaitIdOptions::EXITED,
);
assert_eq!(
waited.expect_err("the kernel reaps the child"),
rustix::io::Errno::CHILD
);
None
});
let err = front_placement(&HostKernel, || Ok(HIGH)).expect_err("the probe has no child left");
assert!(
err.to_string().contains("SIGCHLD"),
"the error names the ignored SIGCHLD: {err}"
);
}
#[skuld::test]
fn a_probe_dropped_unended_is_killed_and_reaped() {
fault::take_probe_steps();
let parent = rustix::process::getpid().as_raw_nonzero().get();
let pid = {
let probe = super::fork_probe(&proc_dir(), parent, false).expect("fork the probe");
probe.pid
};
assert_eq!(
fault::take_probe_steps(),
[
ProbeStep::Kill(Via::Pidfd, libc::SIGKILL),
ProbeStep::Reap(Via::Pidfd, ProbeEnd::Signal(libc::SIGKILL))
]
);
assert_eq!(no_child_holds(pid), Ok(true), "the probe's child {pid} is left");
}
#[skuld::test]
fn a_probe_child_that_cannot_close_its_descriptors_is_reported_abandoned() {
crate::log_capture::install();
let _missing = fault::miss_pidfd_info();
let _no_dir = fault::fail_probe_fd_dir();
let forked = std::rc::Rc::new(std::cell::Cell::new(None));
let _seen = fault::set_before_probe_kill({
let forked = forked.clone();
move |pid| {
forked.set(Some(pid));
None
}
});
fault::take_probe_steps();
let mark = crate::log_capture::mark();
let err = front_placement(&HostKernel, || Ok(HIGH)).expect_err("the probe fails");
let pid = forked.get().expect("the probe's child was to be killed");
assert!(
matches!(&err, crate::error::Error::Io(e) if e.to_string().contains("ABANDONED")),
"the error names the child's status: {err:?}"
);
assert_eq!(
fault::take_probe_steps(),
[
ProbeStep::Kill(Via::Pidfd, libc::SIGKILL),
ProbeStep::Reap(Via::Pidfd, ProbeEnd::Exit(super::ABANDONED))
]
);
let warns = warns_since(mark, "");
assert!(
warns
.iter()
.any(|w| w.contains(&format!("child {pid}")) && w.contains("ABANDONED")),
"a warn names the probe's child {pid} and its status: {warns:?}"
);
}
#[skuld::test]
fn the_walk_closes_the_lowest_descriptors_with_fds_0_and_1_closed() {
use crate::test_own_process::{own_process, test_path};
use crate::test_spawn::spawn;
use crate::test_stdio::RestoreStdio;
use std::io::Read as _;
let Some(done) = own_process(
test_path!(the_walk_closes_the_lowest_descriptors_with_fds_0_and_1_closed),
spawn,
) else {
return;
};
let _refused = fault::refuse_probe_close_range();
let restore = RestoreStdio::close(&done, &[0, 1]);
let proc = proc_dir();
let parent = rustix::process::getpid().as_raw_nonzero().get();
let probe = super::fork_probe(&proc, parent, true).expect("fork the probe");
let mut report = [0u8; 2];
probe.channel().read_exact(&mut report).expect("the probe reports");
let held: Vec<_> = descriptors_of(probe.pid).into_values().collect();
drop(probe);
drop(proc);
drop(restore);
assert!(
matches!(held.as_slice(), [one] if one.starts_with("socket:")),
"the probe's child holds only its end of the socket: {held:?}"
);
}
#[skuld::test]
fn the_walk_closes_a_listing_longer_than_one_batch() {
use std::io::Read as _;
if !alone("containment::cgroup::reach::reach_tests::the_walk_closes_a_listing_longer_than_one_batch") {
return;
}
let mut files: Vec<_> = (0..100)
.map(|_| std::fs::File::open("/dev/null").expect("open /dev/null"))
.collect();
drop(files.drain(10..12));
let _refused = fault::refuse_probe_close_range();
let parent = rustix::process::getpid().as_raw_nonzero().get();
let probe = super::fork_probe(&proc_dir(), parent, true).expect("fork the probe");
let mut report = [0u8; 2];
probe.channel().read_exact(&mut report).expect("the probe reports");
let held: Vec<_> = descriptors_of(probe.pid).into_values().collect();
assert!(
matches!(held.as_slice(), [one] if one.starts_with("socket:")),
"the probe's child holds only its end of the socket: {held:?}"
);
}
#[skuld::test]
fn a_release_that_cannot_be_sent_is_a_warn_naming_the_child() {
crate::log_capture::install();
let not_a_socket =
std::os::unix::net::UnixStream::from(OwnedFd::from(std::fs::File::open("/dev/null").expect("open /dev/null")));
let mark = crate::log_capture::mark();
super::release_probe(4242, not_a_socket);
let warns = warns_since(mark, "");
assert!(
warns.iter().any(|w| w.contains("child 4242")),
"a warn names the probe's child: {warns:?}"
);
}
#[skuld::test]
fn the_ranges_around_two_descriptors_cover_every_other_number() {
use super::ranges_around;
const MAX: u32 = u32::MAX;
assert_eq!(ranges_around(0, 1), [None, None, Some((2, MAX))]);
assert_eq!(ranges_around(1, 0), [None, None, Some((2, MAX))]);
assert_eq!(ranges_around(5, 2), [Some((0, 1)), Some((3, 4)), Some((6, MAX))]);
assert_eq!(ranges_around(2, 5), [Some((0, 1)), Some((3, 4)), Some((6, MAX))]);
assert_eq!(ranges_around(0, 3), [None, Some((1, 2)), Some((4, MAX))]);
assert_eq!(ranges_around(MAX, 0), [None, Some((1, MAX - 1)), None]);
}
#[skuld::test]
fn a_pidfd_naming_no_child_of_this_process_leaves_the_probe_child_gone() {
let own = std::process::id() as libc::pid_t;
match super::own_child_pidfd(own) {
Err(super::Unpinned::Gone(e)) => assert!(e.to_string().contains(&format!("child {own}")), "{e}"),
Err(super::Unpinned::Failed(e)) => panic!("expected Gone, got Failed({e})"),
Ok(_) => panic!("expected Gone, got a pidfd"),
}
}
#[skuld::test]
fn a_descriptor_that_is_no_pidfd_fails_the_pin() {
let not_a_pidfd = OwnedFd::from(std::fs::File::open("/dev/null").expect("open /dev/null"));
match super::confirm_child(4242, not_a_pidfd) {
Err(super::Unpinned::Failed(e)) => assert_eq!(e.raw_os_error(), Some(libc::EBADF), "{e}"),
Err(super::Unpinned::Gone(e)) => panic!("expected Failed, got Gone({e})"),
Ok(_) => panic!("expected Failed, got a pidfd"),
}
}
#[skuld::test]
fn a_subtree_asked_about_a_pidless_child_cannot_place_it() {
use crate::child::owned::teardown::Reach;
let child = crate::child::owned::OwnedChild::new(Box::new(crate::os_process::fake::FakeProcess::new([])));
assert!(subtree(HIGH, true).reached(&child).is_err());
}