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, Kernel, ProcDir, ViewUnreadable, UNREADABLE_STATUS_REASON};
use crate::log_capture::warns_since;
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()), None)
.expect("a forced id"));
assert!(subtree(HIGH, true)
.reached_by(pid, Some(pidfd.as_fd()), None)
.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(err @ crate::error::Error::Unsupported { .. }) => {
let crate::error::Error::Unsupported { detail, .. } = &err else {
unreachable!()
};
assert!(detail.contains("hidepid"), "{detail}");
assert!(detail.contains("before anything is spawned"), "{detail}");
assert_eq!(crate::error::first_os_code(&err), Some(libc::ENOENT), "{err:?}");
let named = std::io::Error::from_raw_os_error(libc::ENOENT).to_string();
assert!(!detail.contains(&named), "{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}");
assert_eq!(
crate::error::first_os_code(&err),
Some(libc::ENOENT),
"{stat:?} {sub}: {err:?}"
);
}
}
#[skuld::test]
fn a_task_still_in_the_cgroup_it_was_seen_in_is_placed_without_a_walk() {
let (leaf, _dir) = stand_in_subtree(None);
let _id = fault::force_pidfd_cgroup_id(HIGH + 1);
let _hidden = fault::hide_proc();
let pidfd = own_pidfd();
let pid = std::process::id();
let (inside, by) = leaf
.holds_seen(pid, Some(pidfd.as_fd()), Some(HIGH + 1))
.expect("no walk and no /proc read");
assert!(inside);
assert_eq!(
by,
Some(HIGH + 1),
"the cgroup id that placed it is named, for a listing to keep"
);
assert!(leaf
.reached_by(pid, Some(pidfd.as_fd()), Some(HIGH + 1))
.expect("no walk and no /proc read"));
leaf.holds_seen(pid, Some(pidfd.as_fd()), Some(HIGH + 2))
.expect_err("a task that moved is placed by the walk, which cannot tell here");
leaf.holds_seen(pid, Some(pidfd.as_fd()), None)
.expect_err("a task not seen before is placed by the walk");
}
#[skuld::test]
fn a_task_still_in_the_cgroup_it_was_seen_in_is_placed_without_the_leafs_id() {
let leaf = Subtree::new(
None,
None,
Some("/stand-in-leaf".to_owned()),
crate::containment::cgroup::Swept::default(),
super::PlacedAtRemoval::default(),
kill_record(true),
);
let _id = fault::force_pidfd_cgroup_id(HIGH + 1);
let _hidden = fault::hide_proc();
let pidfd = own_pidfd();
let pid = std::process::id();
let (inside, by) = leaf
.holds_seen(pid, Some(pidfd.as_fd()), Some(HIGH + 1))
.expect("no walk and no /proc read");
assert!(inside);
assert_eq!(by, Some(HIGH + 1), "the id that placed it is named");
assert!(leaf
.reached_by(pid, Some(pidfd.as_fd()), Some(HIGH + 1))
.expect("no walk and no /proc read"));
leaf.holds_seen(pid, Some(pidfd.as_fd()), Some(HIGH + 2))
.expect_err("a task that moved is placed through the hidden /proc");
}
#[skuld::test]
fn an_unreadable_pidfd_id_places_a_seen_task_through_proc_without_the_leafs_id() {
let leaf = Subtree::new(
None,
None,
Some("/stand-in-leaf".to_owned()),
crate::containment::cgroup::Swept::default(),
super::PlacedAtRemoval::default(),
kill_record(true),
);
let _failing = fault::fail_pidfd_info();
let _hidden = fault::hide_proc();
let pidfd = own_pidfd();
let e = leaf
.holds_seen(std::process::id(), Some(pidfd.as_fd()), Some(HIGH))
.expect_err("the hidden /proc places nothing");
assert_eq!(
e.raw_os_error(),
Some(libc::ENOENT),
"/proc's error, not the id's EIO: {e}"
);
}
#[skuld::test]
fn an_exited_task_has_no_pidfd_id_and_is_not_placed_through_proc_without_the_leafs_id() {
let leaf = Subtree::new(
None,
None,
Some("/stand-in-leaf".to_owned()),
crate::containment::cgroup::Swept::default(),
super::PlacedAtRemoval::default(),
kill_record(true),
);
let _failing = fault::fail_pidfd_info_with(libc::ESRCH);
let _hidden = fault::hide_proc();
let pidfd = own_pidfd();
let e = leaf
.holds_seen(std::process::id(), Some(pidfd.as_fd()), Some(HIGH))
.expect_err("the task's exit is the answer");
assert_eq!(e.raw_os_error(), Some(libc::ESRCH), "the id's ESRCH, not /proc's: {e}");
}
#[skuld::test]
fn a_placement_by_the_leafs_own_id_names_it() {
let _id = fault::force_pidfd_cgroup_id(HIGH);
let pidfd = own_pidfd();
let (inside, by) = subtree(HIGH, true)
.holds_seen(std::process::id(), Some(pidfd.as_fd()), None)
.expect("the leaf's own id");
assert!(inside);
assert_eq!(by, Some(HIGH), "the leaf's own id placed it");
}
#[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(e @ crate::error::Error::Io(_)) => {
assert!(crate::error::said(&e).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(err @ crate::error::Error::Unsupported { .. }) => {
let crate::error::Error::Unsupported { detail, .. } = &err else {
unreachable!()
};
assert!(detail.contains("PIDFD_GET_INFO failed"), "{detail}");
assert_eq!(crate::error::first_os_code(&err), Some(libc::EIO), "{err:?}");
let named = std::io::Error::from_raw_os_error(libc::EIO).to_string();
assert!(!detail.contains(&named), "{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(err @ crate::error::Error::Unsupported { .. }) => {
let crate::error::Error::Unsupported { detail, .. } = &err else {
unreachable!()
};
let named = std::io::Error::from_raw_os_error(errno).to_string();
assert!(!detail.contains(&named), "{errno}: {detail}");
assert_eq!(crate::error::first_os_code(&err), Some(errno), "{err:?}");
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:?}"),
}
}
#[skuld::test]
fn a_task_read_through_an_unusable_view_has_the_views_error_as_its_cause() {
let why = crate::identity::ViewUnreadable::from_open_errno(rustix::io::Errno::MFILE);
let kind = std::io::Error::from_raw_os_error(libc::EMFILE).kind();
let err = super::view_unreadable(7, why);
assert_eq!(err.kind(), kind);
assert_eq!(crate::error::first_os_code(&err), Some(libc::EMFILE), "{err:?}");
assert!(err.to_string().contains("pid 7's cgroup cannot be read"), "{err}");
}
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(libc::SIGKILL),
ProbeStep::Reap(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_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(libc::SIGKILL),
ProbeStep::Reap(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(libc::SIGKILL),
ProbeStep::Reap(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(libc::SIGKILL),
ProbeStep::Reap(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(libc::SIGKILL), ProbeStep::Reap(ProbeEnd::Elsewhere)]
);
}
#[skuld::test]
fn a_probe_child_that_dies_early_with_sigchld_ignored_says_so() {
if !alone("containment::cgroup::reach::reach_tests::a_probe_child_that_dies_early_with_sigchld_ignored_says_so") {
return;
}
crate::log_capture::install();
let _ignored = ignore_sigchld();
let _missing = fault::miss_pidfd_info();
let _no_dir = fault::fail_probe_fd_dir();
fault::take_probe_steps();
let mark = crate::log_capture::mark();
let err = front_placement(&HostKernel, || Ok(HIGH)).expect_err("the probe's child is gone");
assert_eq!(
fault::take_probe_steps().last(),
Some(&ProbeStep::Reap(ProbeEnd::Elsewhere))
);
assert!(
crate::error::said(&err).contains("SIGCHLD"),
"the error names the ignored SIGCHLD: {err:?}"
);
let records = crate::log_capture::records_since_on_current_thread(mark, "was reaped by another reaper");
assert!(
records.iter().any(|(_, record)| record.contains("SIGCHLD")),
"the record names the ignored SIGCHLD: {records:?}"
);
}
struct ChildExitsAfterCgroupRead {
killed: std::sync::atomic::AtomicBool,
}
impl Kernel for ChildExitsAfterCgroupRead {
fn pidfd_open(
&self,
target: rustix::process::Pid,
flags: rustix::process::PidfdFlags,
) -> Result<OwnedFd, rustix::io::Errno> {
HostKernel.pidfd_open(target, flags)
}
fn pidfs_ino(&self, fd: std::os::fd::BorrowedFd<'_>) -> Result<Option<u64>, rustix::io::Errno> {
HostKernel.pidfs_ino(fd)
}
fn open_proc(&self) -> Result<ProcDir, ViewUnreadable> {
HostKernel.open_proc()
}
fn read(&self, dir: &ProcDir, path: &str) -> std::io::Result<Vec<u8>> {
let read = HostKernel.read(dir, path);
if let Some(pid) = path.strip_suffix("/cgroup").and_then(|pid| pid.parse().ok()) {
assert_eq!(unsafe { libc::kill(pid, libc::SIGKILL) }, 0, "kill the probe's child");
rustix::process::waitid(
rustix::process::WaitId::Pid(rustix::process::Pid::from_raw(pid).expect("a positive pid")),
rustix::process::WaitIdOptions::EXITED | rustix::process::WaitIdOptions::NOWAIT,
)
.expect("wait for the probe's child to exit");
self.killed.store(true, std::sync::atomic::Ordering::SeqCst);
}
read
}
fn pids(&self, dir: &ProcDir) -> std::io::Result<Vec<u32>> {
HostKernel.pids(dir)
}
fn signal_probe(&self, target: rustix::process::Pid) -> Result<(), rustix::io::Errno> {
HostKernel.signal_probe(target)
}
}
#[skuld::test]
fn a_probe_child_that_exits_before_the_read_is_confirmed_is_reported_gone() {
let _missing = fault::miss_pidfd_info();
let kernel = ChildExitsAfterCgroupRead {
killed: std::sync::atomic::AtomicBool::new(false),
};
fault::take_probe_steps();
let err = front_placement(&kernel, || Ok(HIGH)).expect_err("the probe's child is gone");
assert!(
kernel.killed.load(std::sync::atomic::Ordering::SeqCst),
"the kernel read the child's cgroup and killed the child"
);
assert!(
crate::error::said(&err).contains("had exited by the time its cgroup read was confirmed"),
"the probe reports its child gone: {err:?}"
);
assert_eq!(
fault::take_probe_steps().last(),
Some(&ProbeStep::Reap(ProbeEnd::Signal(libc::SIGKILL)))
);
}
#[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(libc::SIGKILL), ProbeStep::Reap(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(libc::SIGKILL),
ProbeStep::Reap(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(libc::SIGKILL),
ProbeStep::Reap(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(4);
}
#[skuld::test]
fn a_probe_with_no_descriptor_for_its_childs_pidfd_fails_with_the_clones_errno() {
if !alone(
"containment::cgroup::reach::reach_tests::a_probe_with_no_descriptor_for_its_childs_pidfd_fails_with_the_clones_errno",
) {
return;
}
let _missing = fault::miss_pidfd_info();
let _hidden = fault::hide_proc();
let _limit = limit_nofile(3);
let err = front_placement(&HostKernel, || Ok(HIGH)).expect_err("the probe cannot fork");
assert!(matches!(err, crate::error::Error::Io(_)), "{err:?}");
assert_eq!(crate::error::first_os_code(&err), Some(libc::EMFILE), "{err:?}");
}
#[skuld::test]
fn keep_only_own_needs_no_free_descriptor_number() {
use std::os::fd::AsRawFd as _;
use crate::os_process::linux::fork::{fork_with_pidfd, Fork};
const KEPT: i32 = 0;
const WALK_FAILED: i32 = 1;
const NOT_FULL: i32 = 2;
if !alone("containment::cgroup::reach::reach_tests::keep_only_own_needs_no_free_descriptor_number") {
return;
}
let proc = proc_dir();
let (parent_end, child_end) = std::os::unix::net::UnixStream::pair().expect("socketpair");
let ends = super::Ends {
child: child_end.as_raw_fd(),
parent: parent_end.as_raw_fd(),
};
let new = {
let _lock = crate::child::spawn::spawn_lock();
match unsafe { fork_with_pidfd() }.expect("fork") {
Fork::Child => unsafe {
let mut full: libc::c_int = 0;
while libc::fcntl(full, libc::F_GETFD) != -1 {
full += 1;
}
let limit = libc::rlimit {
rlim_cur: full as libc::rlim_t,
rlim_max: full as libc::rlim_t,
};
if ends.child >= full || ends.parent >= full || libc::setrlimit(libc::RLIMIT_NOFILE, &limit) != 0 {
libc::_exit(NOT_FULL);
}
libc::_exit(if super::keep_only_own(&proc, ends) {
KEPT
} else {
WALK_FAILED
});
},
Fork::Parent(new) => new,
}
};
let status = rustix::process::waitid(
rustix::process::WaitId::PidFd(new.pidfd.as_fd()),
rustix::process::WaitIdOptions::EXITED,
)
.expect("waitid on the child's pidfd")
.expect("a waitid without NOHANG returns a status");
assert_eq!(status.exit_status(), Some(KEPT), "{status:?}");
}
#[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(libc::SIGKILL),
ProbeStep::Reap(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(_)) && crate::error::said(&err).contains("ABANDONED"),
"the error names the child's status: {err:?}"
);
assert_eq!(
fault::take_probe_steps(),
[
ProbeStep::Kill(libc::SIGKILL),
ProbeStep::Reap(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_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());
}