use std::os::fd::AsRawFd as _;
use super::{clone_with_pidfd, fails_with, fallback, fork_with_pidfd, Fork, ForkFn, NewChild, Path};
use crate::child::spawn::spawn_lock;
use crate::test_groups::{clone3, Group};
fn fork_exiting(fork: ForkFn, code: i32) -> Result<NewChild, i32> {
let _lock = spawn_lock();
match unsafe { fork() }? {
Fork::Child => unsafe { libc::_exit(code) },
Fork::Parent(child) => Ok(child),
}
}
fn reaped_through_pidfd(child: &NewChild) -> (libc::pid_t, i32) {
let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
let waited = unsafe {
libc::waitid(
libc::P_PIDFD,
child.pidfd.as_raw_fd() as libc::id_t,
&mut info,
libc::WEXITED,
)
};
assert_eq!(waited, 0, "waitid on the pidfd: {}", std::io::Error::last_os_error());
unsafe { (info.si_pid(), info.si_status()) }
}
fn assert_names_the_child_that_ran(entry: &str, hint: &str, fork: ForkFn, path: Path, code: i32) {
let child = fork_exiting(fork, code).unwrap_or_else(|errno| panic!("{entry} failed, errno {errno}{hint}"));
assert_eq!(
child.path, path,
"{entry} made the child by {:?}, not {path:?}{hint}",
child.path
);
let flags = unsafe { libc::fcntl(child.pidfd.as_raw_fd(), libc::F_GETFD) };
assert!(
flags >= 0 && flags & libc::FD_CLOEXEC != 0,
"the pidfd of {entry} is close-on-exec: {flags:#x}"
);
assert_eq!(reaped_through_pidfd(&child), (child.pid, code), "{entry}");
}
#[skuld::test]
fn the_pidfd_names_the_child_that_ran(#[fixture(clone3)] _group: &Group) {
assert_names_the_child_that_ran(
"fork_with_pidfd",
"; this row needs a host that allows clone3: set COSCA_TEST_CLONE3=0 to turn it off",
fork_with_pidfd,
Path::Clone3,
7,
);
}
#[skuld::test]
fn clone_makes_a_child_its_pidfd_names() {
assert_names_the_child_that_ran("clone_with_pidfd", "", clone_with_pidfd, Path::Clone, 9);
}
unsafe fn enosys_then_clone() -> Result<Fork, i32> {
unsafe { fallback(|| fails_with(libc::ENOSYS), clone_with_pidfd) }
}
unsafe fn eperm_then_clone() -> Result<Fork, i32> {
unsafe { fallback(|| fails_with(libc::EPERM), clone_with_pidfd) }
}
unsafe fn eagain_then_clone() -> Result<Fork, i32> {
unsafe { fallback(|| fails_with(libc::EAGAIN), clone_with_pidfd) }
}
#[skuld::test]
fn a_refused_first_clone_falls_back_to_clone() {
assert_names_the_child_that_ran("enosys then clone", "", enosys_then_clone, Path::Clone, 10);
assert_names_the_child_that_ran("eperm then clone", "", eperm_then_clone, Path::Clone, 11);
}
#[skuld::test]
fn another_errno_of_the_first_clone_does_not_fall_back() {
let answer = fork_exiting(eagain_then_clone, 12);
assert_eq!(answer.err(), Some(libc::EAGAIN));
}