skuld::default_labels!(crate::test_harness::ROOT);
#[cfg(target_os = "linux")]
pub(crate) mod namespaces;
#[cfg(target_os = "linux")]
pub(crate) mod pid_reuse;
#[cfg(windows)]
pub(crate) mod ctrl_break;
#[cfg(windows)]
pub(crate) fn parent_handle(end: &crate::pipe::ParentEnd) -> std::os::windows::io::BorrowedHandle<'_> {
use std::os::windows::io::AsHandle;
match end {
crate::pipe::ParentEnd::Reader(r) => r.as_handle(),
crate::pipe::ParentEnd::Writer(w) => w.as_handle(),
}
}
#[cfg(windows)]
pub(crate) mod unwaitable;
#[cfg(unix)]
pub(crate) mod blocked_tree_root;
#[cfg(target_os = "linux")]
pub(crate) mod zombie_leader_root;
#[cfg(unix)]
pub(crate) mod foreign;
#[cfg(unix)]
pub(crate) mod reaped_elsewhere;
#[cfg(target_os = "linux")]
pub(crate) mod member;
pub(crate) mod over_fake;
#[cfg(any(target_os = "linux", all(windows, feature = "tokio")))]
mod parked;
#[cfg(any(target_os = "linux", all(windows, feature = "tokio")))]
pub(crate) use parked::Parked;
#[cfg(target_os = "macos")]
use crate::test_own_process;
#[cfg(target_os = "macos")]
#[path = "../tests/common/kevent_eintr.rs"]
mod kevent_eintr;
pub(crate) use crate::test_spawn::console_flags::Console;
pub(crate) fn command(console: Console) -> crate::Command {
let mut cmd = crate::Command::new();
if console.hides_window() {
cmd.no_window();
}
cmd
}
#[cfg(feature = "tokio")]
pub(crate) fn tokio_command(console: Console) -> crate::tokio::Command {
let mut cmd = crate::tokio::Command::new();
if console.hides_window() {
cmd.no_window();
}
cmd
}
#[cfg(windows)]
pub(crate) fn testbin(name: &str) -> std::path::PathBuf {
let exe = std::env::current_exe().expect("current_exe");
let path = exe
.parent()
.and_then(std::path::Path::parent)
.expect("the test binary lives in <target>/<profile>/deps")
.join(format!("{name}{}", std::env::consts::EXE_SUFFIX));
assert!(
path.is_file(),
"{} is missing: build the package's bin targets (`cargo nextest run` does; `--lib` does not)",
path.display()
);
path
}
mod std_child;
#[cfg(windows)]
pub(crate) use std_child::blocker_with_flags;
pub(crate) use std_child::StdChild;
pub(crate) use std_child::{blocker, blocker_with};
pub(crate) static BLOCKER_ARGV: std::sync::LazyLock<&'static [&'static str]> = std::sync::LazyLock::new(|| {
#[cfg(windows)]
{
let more: &'static str = Box::leak(
windows_more()
.into_os_string()
.into_string()
.expect("a UTF-8 System32 path")
.into_boxed_str(),
);
Box::leak(Box::new([more]))
}
#[cfg(not(windows))]
&["cat"]
});
#[cfg(unix)]
pub(crate) struct ClosedStdio {
saved: [std::os::fd::OwnedFd; 3],
}
#[cfg(unix)]
pub(crate) fn exhaust_fds(alone: &crate::test_own_process::Completion) -> RestoreNofile {
let lowest_free = unsafe {
let lowest_free = libc::dup(0);
assert!(lowest_free >= 0, "dup(0)");
libc::close(lowest_free);
lowest_free
};
lower_fd_limit(alone, lowest_free as libc::rlim_t)
}
#[cfg(unix)]
pub(crate) fn lower_fd_limit(_alone: &crate::test_own_process::Completion, soft: libc::rlim_t) -> RestoreNofile {
unsafe {
let mut limit: libc::rlimit = std::mem::zeroed();
assert_eq!(libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit), 0);
let before = limit;
limit.rlim_cur = soft;
assert_eq!(libc::setrlimit(libc::RLIMIT_NOFILE, &limit), 0);
RestoreNofile(before)
}
}
#[cfg(unix)]
#[must_use = "the limit stays lowered only while this lives"]
pub(crate) struct RestoreNofile(libc::rlimit);
#[cfg(unix)]
impl Drop for RestoreNofile {
fn drop(&mut self) {
let restored = unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &self.0) };
debug_assert_eq!(restored, 0, "restoring the descriptor limit");
}
}
#[cfg(unix)]
pub(crate) fn close_stdio_keeping_a_copy() -> ClosedStdio {
use std::os::fd::BorrowedFd;
let copy = |fd: i32| {
let stdio = unsafe { BorrowedFd::borrow_raw(fd) };
rustix::io::fcntl_dupfd_cloexec(stdio, 10).expect("copy a stdio descriptor")
};
let saved = [copy(0), copy(1), copy(2)];
for fd in 0..3 {
assert_eq!(unsafe { libc::close(fd) }, 0);
}
ClosedStdio { saved }
}
#[cfg(unix)]
impl Drop for ClosedStdio {
fn drop(&mut self) {
use std::os::fd::AsRawFd;
for (fd, saved) in self.saved.iter().enumerate() {
unsafe { libc::dup2(saved.as_raw_fd(), fd as i32) };
}
}
}
pub(crate) fn held_writer_stdin() -> (crate::stdio::Stdio, crate::PipeWriter) {
let (reader, writer) = std::io::pipe().expect("pipe");
#[cfg(unix)]
let file = std::fs::File::from(std::os::fd::OwnedFd::from(reader));
#[cfg(windows)]
let file = std::fs::File::from(std::os::windows::io::OwnedHandle::from(reader));
(crate::stdio::Stdio::from_file(file), writer.into())
}
#[cfg(unix)]
pub(crate) fn contain_without_cgroup(cmd: &mut crate::Command) -> &mut crate::Command {
#[cfg(target_os = "linux")]
return cmd.contain_with(crate::ContainMode::Session);
#[cfg(not(target_os = "linux"))]
cmd.contain()
}
#[path = "../tests/common/contain_gives.rs"]
mod contain_gives;
#[cfg(unix)]
pub(crate) use contain_gives::{contain_without_cgroup_gives, session_gives};
pub(crate) use contain_gives::{drainable_gives, tree_walk_gives};
#[cfg(all(unix, feature = "tokio"))]
pub(crate) fn contain_without_cgroup_async(cmd: &mut crate::tokio::Command) -> &mut crate::tokio::Command {
#[cfg(target_os = "linux")]
return cmd.contain_with(crate::ContainMode::Session);
#[cfg(not(target_os = "linux"))]
cmd.contain()
}
pub(crate) const IDENTITY_READ: &str = "the spawn read the child's identity";
pub(crate) fn held_contained_blocker(stdout: crate::Stdio) -> (crate::Child, crate::PipeWriter) {
held_blocker(stdout, Console::Hidden, |cmd| _ = cmd.contain())
}
pub(crate) fn held_contained_blocker_on_console(stdout: crate::Stdio) -> (crate::Child, crate::PipeWriter) {
held_blocker(stdout, Console::Asked, |cmd| _ = cmd.contain())
}
#[cfg(windows)]
pub(crate) fn live_blocker() -> (crate::Child, crate::PipeWriter, crate::identity::ProcessId) {
let (child, stdin) = held_contained_blocker(crate::Stdio::null());
let id = child.id().expect(IDENTITY_READ);
(child, stdin, id)
}
#[cfg(windows)]
pub(crate) fn spawn_more_blocker() -> StdChild {
StdChild::spawn(
std::process::Command::new("cmd")
.args(["/C", "more"])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null()),
)
}
#[cfg(windows)]
pub(crate) fn spawn_job_member() -> (StdChild, crate::containment::windows::JobHandle) {
use std::os::windows::io::AsRawHandle as _;
let child = spawn_more_blocker();
let job = crate::containment::windows::assign_to_kill_on_close_job(child.as_raw_handle()).expect("assign to job");
(child, job)
}
#[cfg(all(windows, feature = "tokio"))]
pub(crate) struct GuiMember {
_child: StdChild,
_sock: std::net::TcpStream,
}
#[cfg(all(windows, feature = "tokio"))]
pub(crate) fn spawn_job_gui_member() -> (GuiMember, crate::containment::windows::JobHandle) {
use std::os::windows::io::AsRawHandle as _;
let (listener, addr) = registration_rendezvous();
let mut cmd = std::process::Command::new(testbin("cosca_testbin_gui"));
cmd.arg(&addr)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
crate::test_reexec::scrub_env(|var| _ = cmd.env_remove(var));
cmd.env(ack::ACK_ENV, "1");
let child = StdChild::spawn(&mut cmd);
let job = crate::containment::windows::assign_to_kill_on_close_job(child.as_raw_handle()).expect("assign to job");
let id = crate::identity::ProcessId::of(child.id())
.found()
.expect("the member's identity");
let sock = ctrl_break::accept_tagged(&listener, id, b'G');
(
GuiMember {
_child: child,
_sock: sock,
},
job,
)
}
#[cfg(windows)]
pub(crate) fn spawn_job_with_members(count: usize) -> (Vec<StdChild>, crate::containment::windows::JobHandle) {
use std::os::windows::io::AsRawHandle as _;
let (first, job) = spawn_job_member();
let mut members = vec![first];
for _ in 1..count {
let member = spawn_more_blocker();
job.assign_for_test(member.as_raw_handle())
.expect("assign a member to the job");
members.push(member);
}
(members, job)
}
#[cfg(windows)]
pub(crate) fn spawn_job_with_two_members() -> (StdChild, StdChild, crate::containment::windows::JobHandle) {
let (mut members, job) = spawn_job_with_members(2);
let second = members.pop().expect("two members");
let first = members.pop().expect("two members");
(first, second, job)
}
#[cfg(windows)]
pub(crate) fn let_member_exit(mut child: StdChild) {
drop(child.stdin.take());
child.wait().expect("wait for cmd /C more to exit");
}
#[cfg(unix)]
pub(crate) fn held_contained_blocker_without_cgroup(stdout: crate::Stdio) -> (crate::Child, crate::PipeWriter) {
held_blocker(stdout, Console::Hidden, |cmd| _ = contain_without_cgroup(cmd))
}
#[cfg(target_os = "linux")]
pub(crate) fn held_treewalk_blocker() -> (crate::Child, crate::PipeWriter) {
held_blocker(crate::Stdio::null(), Console::Hidden, |cmd| {
cmd.contain_with(crate::ContainMode::TreeWalk);
})
}
#[cfg(target_os = "linux")]
pub(crate) fn held_treewalk_blocker_leaving(
left: crate::containment::treewalk::fault::LeftBehind,
) -> (crate::Child, crate::PipeWriter) {
let blocker = held_treewalk_blocker();
crate::containment::treewalk::fault::force_incomplete_once(left);
blocker
}
pub(crate) fn held_uncontained_blocker(kill_on_drop: bool) -> (crate::Child, crate::PipeWriter) {
held_uncontained_blocker_reporting(kill_on_drop, None)
}
pub(crate) fn held_uncontained_blocker_reporting(
kill_on_drop: bool,
report: Option<crate::elevation::ElevationReport>,
) -> (crate::Child, crate::PipeWriter) {
let (stdin, writer) = held_writer_stdin();
let mut cmd = command(Console::Hidden);
cmd.args(BLOCKER_ARGV.iter().copied());
cmd.stdin(stdin).expect("set stdin");
cmd.kill_on_drop(kill_on_drop);
cmd.set_elevation_report(report);
(cmd.spawn().expect("spawn"), writer)
}
pub(crate) struct HandedBack<R> {
release: R,
unreaped: Option<crate::Unreaped>,
}
impl<R> HandedBack<R> {
fn new(release: R, unreaped: Option<crate::Unreaped>) -> HandedBack<R> {
HandedBack { release, unreaped }
}
pub(crate) fn is_none(&self) -> bool {
self.unreaped.is_none()
}
#[track_caller]
pub(crate) fn unreaped(&self) -> &crate::Unreaped {
self.unreaped.as_ref().expect("the teardown handed the child back")
}
#[track_caller]
pub(crate) fn wait(self) -> std::process::ExitStatus {
let HandedBack { release, unreaped } = self;
drop(release);
unreaped
.expect("the teardown handed the child back")
.wait()
.expect("the handed-back child exits once released")
}
}
pub(crate) fn tear_down_holding<R>(
child: crate::Child,
release: R,
disposition: crate::child::owned::teardown::Disposition,
) -> (crate::error::ChildFate, HandedBack<R>) {
let (fate, _, handed_back) = tear_down_holding_failures(child, release, disposition);
(fate, handed_back)
}
pub(crate) fn tear_down_holding_failures<R>(
child: crate::Child,
release: R,
disposition: crate::child::owned::teardown::Disposition,
) -> (crate::error::ChildFate, Option<crate::error::Failures>, HandedBack<R>) {
let crate::child::drop_teardown::Torn {
fate,
unreaped,
cleanup,
} = child.tear_down_or_hand_back(disposition);
(fate, cleanup, HandedBack::new(release, unreaped))
}
#[track_caller]
pub(crate) fn expect_may_have_started_parts<R>(
error: crate::error::Error,
release: R,
) -> (crate::error::Error, crate::error::ChildFate, HandedBack<R>) {
let (cause, fate, unreaped) = crate::child::spawn::failure::error_parts(error);
(cause, fate, HandedBack::new(release, unreaped))
}
#[cfg(unix)]
#[track_caller]
pub(crate) fn cleanup_of(error: &crate::error::Error) -> crate::error::Failures {
let crate::error::Error::MayHaveStarted { cleanup, .. } = error else {
panic!("expected MayHaveStarted, got {error:?}");
};
cleanup
.clone()
.unwrap_or_else(|| panic!("the teardown's failures are in the cleanup: {error:?}"))
}
#[cfg(unix)]
#[track_caller]
pub(crate) fn detail_of(error: &crate::error::Error) -> String {
let crate::error::Error::MayHaveStarted { detail, .. } = error else {
panic!("expected MayHaveStarted, got {error:?}");
};
detail
.clone()
.unwrap_or_else(|| panic!("the spawn says what it did with its child: {error:?}"))
}
#[cfg(unix)]
#[track_caller]
pub(crate) fn expect_handed_back<R>(
error: crate::error::Error,
release: R,
) -> (crate::error::Error, crate::error::ChildFate, HandedBack<R>) {
let (cause, fate, handed_back) = expect_may_have_started_parts(error, release);
assert!(
!handed_back.is_none(),
"the spawn handed no child back ({fate:?}): {cause:?}"
);
(cause, fate, handed_back)
}
#[cfg(target_os = "linux")]
pub(crate) fn tear_down_held_holding<R>(
child: crate::child::owned::OwnedChild,
id: Option<crate::identity::ProcessId>,
subtree: Option<&crate::containment::cgroup::Subtree>,
why: &mut crate::child::spawn::Diagnosis,
release: R,
) -> (Option<String>, crate::error::ChildFate, HandedBack<R>) {
let how = crate::child::spawn::held_teardown::HeldTeardown {
id,
reach: subtree.map(|subtree| subtree as &dyn crate::child::owned::teardown::Reach),
disposition: crate::child::owned::teardown::Disposition::HandBack,
policy: crate::child::spawn::policy::SpawnPolicy::SYNC,
};
let (detail, torn) = crate::child::spawn::held_teardown::tear_down_held(child, how, why);
(detail, torn.fate, HandedBack::new(release, torn.unreaped))
}
#[cfg(unix)]
impl crate::child::spawn::SpawnFailure {
#[track_caller]
pub(crate) fn expect_may_have_started_parts<R>(
self,
release: R,
) -> (crate::error::Error, crate::error::ChildFate, HandedBack<R>) {
let (cause, fate, unreaped) = self.parts();
(cause, fate, HandedBack::new(release, unreaped))
}
}
fn held_blocker(
stdout: crate::Stdio,
console: Console,
contain: impl FnOnce(&mut crate::Command),
) -> (crate::Child, crate::PipeWriter) {
let mut cmd = command(console);
cmd.args(BLOCKER_ARGV.iter().copied());
cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
cmd.stdout(stdout).expect("set stdout");
contain(&mut cmd);
let mut child = cmd.spawn().expect("spawn");
let stdin = child.stdin().expect("piped stdin");
(child, stdin)
}
#[cfg(feature = "tokio")]
pub(crate) async fn held_contained_blocker_async(
stdout: crate::Stdio,
) -> (crate::tokio::Child, crate::tokio::ChildStdin) {
held_blocker_async(stdout, Console::Hidden, |cmd| _ = cmd.contain()).await
}
#[cfg(all(unix, feature = "tokio"))]
pub(crate) async fn held_contained_blocker_without_cgroup_async(
stdout: crate::Stdio,
) -> (crate::tokio::Child, crate::tokio::ChildStdin) {
held_blocker_async(stdout, Console::Hidden, |cmd| _ = contain_without_cgroup_async(cmd)).await
}
#[cfg(feature = "tokio")]
pub(crate) async fn held_blocker_async(
stdout: crate::Stdio,
console: Console,
contain: impl FnOnce(&mut crate::tokio::Command),
) -> (crate::tokio::Child, crate::tokio::ChildStdin) {
let mut cmd = tokio_command(console);
cmd.args(BLOCKER_ARGV.iter().copied());
cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
cmd.stdout(stdout).expect("set stdout");
contain(&mut cmd);
let mut child = cmd.spawn().await.expect("spawn");
let stdin = child.stdin().expect("piped stdin");
(child, stdin)
}
#[cfg(unix)]
pub(crate) fn member_command(pgid: i32) -> std::process::Command {
use std::os::unix::process::CommandExt;
let mut cmd = std::process::Command::new("/bin/sh");
cmd.arg("-c")
.arg("echo $$; read _ignored")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.process_group(pgid);
cmd
}
#[cfg(unix)]
pub(crate) fn await_member_ready(child: &mut std::process::Child) {
use std::io::BufRead;
let mut out = std::io::BufReader::new(child.stdout.take().expect("piped stdout"));
let mut line = String::new();
out.read_line(&mut line).expect("read the member's announcement");
let announced: crate::identity::RawPid = line.trim().parse().expect("the announcement carries a pid");
assert_eq!(
announced,
child.id(),
"the announcement must come from the member itself"
);
child.stdout = Some(out.into_inner());
}
#[cfg(unix)]
pub(crate) fn exiting_member_command() -> std::process::Command {
let mut cmd = std::process::Command::new("/bin/sh");
cmd.arg("-c")
.arg("echo $$; read _ignored; exit 0")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped());
cmd
}
pub(crate) fn open_live(id: crate::identity::ProcessId) -> crate::Process {
crate::Process::open(id)
.expect("open the live process")
.expect("the live process is not gone")
}
#[cfg(unix)]
pub(crate) fn live_exiting_member() -> (StdChild, crate::identity::ProcessId) {
let mut child = StdChild::spawn(&mut exiting_member_command());
await_member_ready(&mut child);
let id = crate::identity::ProcessId::of(child.id())
.found()
.expect("the live member resolves");
(child, id)
}
#[cfg(unix)]
pub(crate) fn release_unsignalled(mut child: StdChild) {
use std::os::unix::process::ExitStatusExt;
drop(child.stdin.take());
let status = child.wait().expect("reap the member");
assert_eq!(status.signal(), None, "the member must not have been signalled");
assert_eq!(status.code(), Some(0), "the member must exit by itself");
}
#[cfg(target_os = "linux")]
pub(crate) fn stat_of_a_new_owner(pid: u32) -> Vec<u8> {
let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).expect("the live pid's stat");
let (head, tail) = stat.rsplit_once(')').expect("stat names its command in parentheses");
let mut fields: Vec<String> = tail.split_whitespace().map(str::to_owned).collect();
let start: u64 = fields[19].parse().expect("the start time");
fields[19] = (start + 1).to_string();
format!("{head}) {}\n", fields.join(" ")).into_bytes()
}
#[cfg(windows)]
pub(crate) fn live_findstr_blocker() -> (StdChild, crate::identity::ProcessId) {
let child = StdChild::spawn(
std::process::Command::new("findstr")
.arg("x")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped()),
);
let id = crate::identity::ProcessId::of(child.id())
.found()
.expect("the live blocker resolves");
(child, id)
}
#[cfg(windows)]
pub(crate) fn release_findstr_unterminated(mut child: StdChild) {
use std::io::{Read as _, Write as _};
let mut stdin = child.stdin.take().expect("piped stdin");
stdin.write_all(b"x\r\n").expect("write to the blocker");
drop(stdin);
let mut output = Vec::new();
child
.stdout
.take()
.expect("piped stdout")
.read_to_end(&mut output)
.expect("read stdout to EOF");
let status = child.wait().expect("reap the blocker");
assert!(status.success(), "the blocker must exit by itself, got {status:?}");
assert!(
output.contains(&b'x'),
"the blocker must echo its match, got {output:?}"
);
}
#[cfg(unix)]
pub(crate) fn assert_echoes(stdin: &mut impl std::io::Write, stdout: &mut impl std::io::Read) {
stdin.write_all(b"x").expect("write to the blocker");
let mut echo = [0u8; 1];
stdout
.read_exact(&mut echo)
.expect("the blocker must still be alive to echo");
assert_eq!(&echo, b"x");
}
#[cfg(unix)]
pub(crate) fn wait_until_zombie(pid: u32) {
let _ = zombie_record(pid);
}
#[cfg(unix)]
pub(crate) fn assert_zombie_sigkilled(who: &str, pid: u32) {
let info = zombie_record(pid);
#[cfg(target_os = "linux")]
let status = unsafe { info.si_status() };
#[cfg(target_os = "macos")]
let status = info.si_status;
assert_eq!(
(info.si_code, status),
(libc::CLD_KILLED, libc::SIGKILL),
"{who} must be SIGKILLed, not exit on its own"
);
}
#[cfg(unix)]
fn zombie_record(pid: u32) -> libc::siginfo_t {
loop {
let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
let rc = unsafe { libc::waitid(libc::P_PID, pid as libc::id_t, &mut info, libc::WEXITED | libc::WNOWAIT) };
if rc == 0 {
return info;
}
let e = std::io::Error::last_os_error();
assert_eq!(e.raw_os_error(), Some(libc::EINTR), "waitid: {e}");
}
}
#[cfg(unix)]
pub(crate) fn assert_no_child_of_this_thread(what: &str) {
#[cfg(target_os = "linux")]
let own_thread = libc::__WNOTHREAD;
#[cfg(not(target_os = "linux"))]
let own_thread = 0;
let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
let rc = unsafe {
libc::waitid(
libc::P_ALL,
0,
&mut info,
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT | own_thread,
)
};
let err = std::io::Error::last_os_error();
assert!(
rc == -1 && err.raw_os_error() == Some(libc::ECHILD),
"{what}: this thread must have no child, got rc {rc} ({err})"
);
}
#[cfg(unix)]
pub(crate) fn is_unreaped_child(pid: u32) -> bool {
let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
let rc = unsafe {
libc::waitid(
libc::P_PID,
pid as libc::id_t,
&mut info,
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
)
};
if rc == 0 {
return true;
}
let e = std::io::Error::last_os_error();
assert_eq!(e.raw_os_error(), Some(libc::ECHILD), "waitid: {e}");
false
}
#[cfg(unix)]
pub(crate) fn has_not_exited(pid: u32) -> bool {
let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
let rc = unsafe {
libc::waitid(
libc::P_PID,
pid as libc::id_t,
&mut info,
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
)
};
assert_eq!(rc, 0, "waitid: {}", std::io::Error::last_os_error());
#[cfg(target_os = "linux")]
let waited = unsafe { info.si_pid() };
#[cfg(not(target_os = "linux"))]
let waited = info.si_pid;
waited == 0
}
pub(crate) fn write_to_possibly_dead_stdin(stdin: &mut impl std::io::Write, bytes: &[u8]) {
match stdin.write_all(bytes) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => {}
Err(e) => panic!("writing to the held stdin failed for a reason other than a dead reader: {e}"),
}
}
#[cfg(test)]
mod write_to_possibly_dead_stdin_tests {
use super::write_to_possibly_dead_stdin;
struct FailsWith(std::io::ErrorKind);
impl std::io::Write for FailsWith {
fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
Err(self.0.into())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[skuld::test]
fn a_dead_reader_is_expected() {
write_to_possibly_dead_stdin(&mut FailsWith(std::io::ErrorKind::BrokenPipe), b"x");
}
#[skuld::test]
fn a_live_reader_is_expected() {
write_to_possibly_dead_stdin(&mut Vec::new(), b"x");
}
#[skuld::test]
#[should_panic(expected = "other than a dead reader")]
fn any_other_error_panics() {
write_to_possibly_dead_stdin(&mut FailsWith(std::io::ErrorKind::PermissionDenied), b"x");
}
}
#[cfg(unix)]
#[cfg_attr(
not(target_os = "macos"),
allow(dead_code, unused_imports, reason = "only the macOS tracer fixtures use it so far")
)]
mod bounded;
#[cfg(unix)]
#[cfg_attr(
not(target_os = "macos"),
allow(unused_imports, reason = "only the macOS tracer fixtures use it so far")
)]
pub(crate) use bounded::{run_fixture_output_within, step, watchdog};
#[cfg(unix)]
mod scratch;
#[cfg(unix)]
pub(crate) use scratch::fixture_scratch_tempdir;
#[cfg(unix)]
mod db_dir;
#[cfg(unix)]
pub(crate) use db_dir::FixtureDirs;
#[path = "../testbin/ack.rs"]
pub(crate) mod ack;
#[path = "../tests/common/accept/shared.rs"]
pub(crate) mod shared;
pub(crate) fn accept_or_die(
listener: &std::net::TcpListener,
target: crate::identity::ProcessId,
) -> std::net::TcpStream {
#[cfg(target_os = "linux")]
let event = watch_linux(listener, target);
#[cfg(target_os = "macos")]
let event = watch_macos(listener, target);
#[cfg(windows)]
let event = watch_windows(listener, target);
match event {
WatchEvent::Connection => shared::accept_and_ack(listener),
WatchEvent::Died => panic!("the control target (pid {}) died before it connected", target.pid()),
}
}
enum WatchEvent {
Connection,
Died,
}
#[cfg(windows)]
pub(crate) struct DrainSignal {
event: std::os::windows::io::OwnedHandle,
outcome: shared::DrainOutcome,
}
#[cfg(windows)]
impl DrainSignal {
pub(crate) fn new() -> Self {
Self {
event: crate::os_process::windows::test_event::new_test_event().expect("create the drain event"),
outcome: shared::DrainOutcome::default(),
}
}
pub(crate) fn is_signalled(&self) -> bool {
use std::os::windows::io::AsRawHandle as _;
use windows::Win32::Foundation::{HANDLE, WAIT_OBJECT_0};
use windows::Win32::System::Threading::WaitForSingleObject;
unsafe { WaitForSingleObject(HANDLE(self.event.as_raw_handle()), 0) == WAIT_OBJECT_0 }
}
pub(crate) fn record<T: std::fmt::Debug, E: std::fmt::Display>(&self, result: Result<T, E>) {
self.outcome.store(result);
crate::os_process::windows::test_event::signal_test_event(&self.event);
}
pub(crate) fn watch<T: std::fmt::Debug, E: std::fmt::Display>(&self, wait: impl FnOnce() -> Result<T, E>) {
shared::run_watcher(
&self.outcome,
|| crate::os_process::windows::test_event::signal_test_event(&self.event),
wait,
);
}
}
#[cfg(windows)]
pub(crate) fn accept_or_signalled(listener: &std::net::TcpListener, drained: &DrainSignal) -> std::net::TcpStream {
use std::os::windows::io::{AsRawHandle, AsRawSocket};
use windows::Win32::Foundation::{HANDLE, WAIT_FAILED, WAIT_OBJECT_0};
use windows::Win32::Networking::WinSock::{WSAEventSelect, FD_ACCEPT, SOCKET, WSAEVENT};
use windows::Win32::System::Threading::{WaitForMultipleObjects, INFINITE};
let accept_event = crate::os_process::windows::test_event::new_test_event()
.expect("create an event for the listener's accept-readiness watch");
let sock = SOCKET(listener.as_raw_socket() as usize);
let rc = unsafe {
WSAEventSelect(
sock,
Some(WSAEVENT(accept_event.as_raw_handle() as _)),
FD_ACCEPT as i32,
)
};
assert_eq!(
rc,
0,
"WSAEventSelect(FD_ACCEPT) on the control listener: {}",
std::io::Error::last_os_error()
);
let handles = [
HANDLE(drained.event.as_raw_handle()),
HANDLE(accept_event.as_raw_handle()),
];
let woken = unsafe { WaitForMultipleObjects(&handles, false, INFINITE) };
let wait_error = std::io::Error::last_os_error();
let cancel_rc = unsafe { WSAEventSelect(sock, None, 0) };
assert_eq!(
cancel_rc,
0,
"WSAEventSelect(0) to cancel the accept-readiness association: {}",
std::io::Error::last_os_error()
);
listener
.set_nonblocking(false)
.expect("restore the control listener to blocking mode");
assert_ne!(
woken, WAIT_FAILED,
"WaitForMultipleObjects while waiting for a control connection: {wait_error}"
);
let drain = woken == WAIT_OBJECT_0;
let connection = woken.0 == WAIT_OBJECT_0.0 + 1;
assert!(
drain || connection,
"WaitForMultipleObjects returned {woken:?} for two handles"
);
match shared::first_ready(drain, connection) {
Some(shared::Ready::Exit) => drained.outcome.fail("tree"),
Some(shared::Ready::Source) => shared::accept_and_ack(listener),
None => unreachable!("one of the two handles signalled"),
}
}
#[cfg(target_os = "linux")]
fn watch_linux(listener: &std::net::TcpListener, target: crate::identity::ProcessId) -> WatchEvent {
use std::os::fd::AsFd;
use rustix::event::{PollFd, PollFlags};
let Some(pidfd) = crate::os_process::linux::open::open_verified_with(&crate::identity::HostKernel, target)
.expect("open a pidfd to watch the target")
else {
return WatchEvent::Died;
};
let listener_fd = listener.as_fd();
let mut fds = [
PollFd::new(&pidfd, PollFlags::IN),
PollFd::new(&listener_fd, PollFlags::IN),
];
loop {
if let Err(e) = crate::wait::poll_ready(&mut fds) {
panic!(
"poll while waiting for a control connection: {}",
std::io::Error::from(e)
);
}
let (pidfd_revents, listener_revents) = (fds[0].revents(), fds[1].revents());
assert!(
!pidfd_revents.contains(PollFlags::NVAL),
"the pidfd went invalid mid-wait"
);
assert!(
!listener_revents.contains(PollFlags::NVAL),
"the control listener's fd went invalid mid-wait"
);
if listener_revents.contains(PollFlags::ERR) || listener_revents.contains(PollFlags::HUP) {
panic!("the control listener reported an error while waiting for a connection: {listener_revents:?}");
}
if pidfd_revents.contains(PollFlags::ERR) {
panic!("pidfd poll returned POLLERR while watching pid {}", target.pid());
}
match shared::first_ready(
pidfd_revents.contains(PollFlags::IN),
listener_revents.contains(PollFlags::IN),
) {
Some(shared::Ready::Exit) => return WatchEvent::Died,
Some(shared::Ready::Source) => return WatchEvent::Connection,
None => {}
}
}
}
#[cfg(target_os = "macos")]
fn watch_macos(listener: &std::net::TcpListener, target: crate::identity::ProcessId) -> WatchEvent {
use std::os::fd::AsRawFd;
use nix::sys::event::{EvFlags, EventFilter, FilterFlag, KEvent};
use crate::os_process::macos::kqueue::{Event, Subscription};
let Some(kq) =
crate::os_process::macos::kqueue::arm_proc_exit(target).expect("arm a kqueue exit-watch for the target")
else {
return WatchEvent::Died;
};
let listener = Subscription::Readable {
fd: listener.as_raw_fd(),
low_water: 1,
};
kq.subscribe(listener).expect("watch the control listener");
let placeholder = KEvent::new(0, EventFilter::EVFILT_PROC, EvFlags::empty(), FilterFlag::empty(), 0, 0);
let mut events = [placeholder; 2];
loop {
let n = match kq.native().kevent(&[], &mut events, None) {
Ok(n) => n,
Err(nix::errno::Errno::EINTR) => {
kevent_eintr::count_retry();
continue;
}
Err(e) => panic!("kevent while waiting for a control connection: {e}"),
};
let read: Vec<Event> = events[..n].iter().filter_map(Event::from_kevent).collect();
let exited = read.iter().any(|ev| matches!(ev, Event::Process { .. }));
let connection = read.iter().any(|ev| matches!(ev, Event::Readable { .. }));
match shared::first_ready(exited, connection) {
Some(shared::Ready::Exit) => return WatchEvent::Died,
Some(shared::Ready::Source) => return WatchEvent::Connection,
None => {}
}
}
}
#[cfg(windows)]
fn watch_windows(listener: &std::net::TcpListener, target: crate::identity::ProcessId) -> WatchEvent {
use std::os::windows::io::{AsRawHandle, AsRawSocket, FromRawHandle, OwnedHandle};
use windows::Win32::Foundation::{HANDLE, WAIT_FAILED, WAIT_OBJECT_0};
use windows::Win32::Networking::WinSock::{WSAEventSelect, FD_ACCEPT, SOCKET, WSAEVENT};
use windows::Win32::System::Threading::{WaitForMultipleObjects, INFINITE};
let Some((process, _granted)) =
crate::os_process::windows::open_verified(target).expect("open a handle to watch the target")
else {
return WatchEvent::Died;
};
let process = unsafe { OwnedHandle::from_raw_handle(process.0 as _) };
let accept_event = crate::os_process::windows::test_event::new_test_event()
.expect("create an event for the listener's accept-readiness watch");
let sock = SOCKET(listener.as_raw_socket() as usize);
let wsa_event = WSAEVENT(accept_event.as_raw_handle() as _);
let rc = unsafe { WSAEventSelect(sock, Some(wsa_event), FD_ACCEPT as i32) };
assert_eq!(
rc,
0,
"WSAEventSelect(FD_ACCEPT) on the control listener: {}",
std::io::Error::last_os_error()
);
let handles = [HANDLE(process.as_raw_handle()), HANDLE(accept_event.as_raw_handle())];
let woken = unsafe { WaitForMultipleObjects(&handles, false, INFINITE) };
let wait_error = std::io::Error::last_os_error();
let cancel_rc = unsafe { WSAEventSelect(sock, None, 0) };
assert_eq!(
cancel_rc,
0,
"WSAEventSelect(0) to cancel the accept-readiness association: {}",
std::io::Error::last_os_error()
);
listener
.set_nonblocking(false)
.expect("restore the control listener to blocking mode");
assert_ne!(
woken, WAIT_FAILED,
"WaitForMultipleObjects while waiting for a control connection: {wait_error}"
);
let exited = woken == WAIT_OBJECT_0;
let connection = woken.0 == WAIT_OBJECT_0.0 + 1;
assert!(
exited || connection,
"WaitForMultipleObjects returned {woken:?} for two handles"
);
match shared::first_ready(exited, connection) {
Some(shared::Ready::Exit) => WatchEvent::Died,
_ => WatchEvent::Connection,
}
}
pub(crate) fn run_fixture_with_cwd(fixture: &str, cwd: &std::path::Path, marker_env: &str) {
let mut cmd = fixture_command(fixture);
cmd.env(marker_env, cwd).current_dir(cwd);
run_fixture_command(fixture, cmd);
}
#[cfg(unix)]
pub(crate) fn run_fixture(fixture: &str) {
let scratch = tempfile::tempdir().expect("tempdir for fixture scratch root");
let (mut cmd, _dirs) = fixture_command_without_dac_bypass(fixture);
crate::test_reexec::with_json_events(&mut cmd);
#[cfg(target_os = "linux")]
{
use std::os::unix::process::CommandExt as _;
let guard = crate::child::spawn::spawn_lock();
let fd = scratch::open_scratch_fd(scratch.path());
let raw = fd.0;
cmd.env(scratch::FIXTURE_SCRATCH_FD_ENV, raw.to_string());
unsafe {
cmd.pre_exec(move || {
let fd = rustix::fd::BorrowedFd::borrow_raw(raw);
rustix::io::fcntl_setfd(fd, rustix::io::FdFlags::empty()).map_err(std::io::Error::from)
});
}
#[allow(
clippy::disallowed_methods,
reason = "spawn_lock is held by `guard`, taken earlier in this fn"
)]
let child = cmd.spawn().expect("spawn fixture child");
drop(fd);
drop(guard);
finish_fixture_command(fixture, child);
}
#[cfg(not(target_os = "linux"))]
{
if unsafe { libc::geteuid() } == 0 {
use std::os::unix::ffi::OsStrExt as _;
let path = std::ffi::CString::new(scratch.path().as_os_str().as_bytes())
.expect("scratch root path has no interior NUL");
let rc = unsafe {
libc::chown(
path.as_ptr(),
crate::test_privilege::UNPRIVILEGED,
crate::test_privilege::UNPRIVILEGED,
)
};
assert!(
rc == 0,
"chown scratch root to the fixture's post-drop identity: {}",
std::io::Error::last_os_error()
);
}
cmd.env(scratch::FIXTURE_SCRATCH_ROOT_ENV, scratch.path());
let child = crate::test_spawn::spawn(&mut cmd).expect("spawn fixture child");
finish_fixture_command(fixture, child);
}
}
#[cfg(unix)]
pub(crate) fn fixture_command_without_dac_bypass(fixture: &str) -> (std::process::Command, FixtureDirs) {
#[cfg(target_os = "linux")]
let (mut cmd, exe_copy) = (fixture_command(fixture), None);
#[cfg(not(target_os = "linux"))]
let (mut cmd, exe_copy) = if unsafe { libc::geteuid() } == 0 {
scratch::assert_dropped_identity_can_traverse_tmpdir();
let (dir, exe) = scratch::copy_exe_to_traversable_scratch();
let mut cmd = crate::test_reexec::command(exe);
configure_fixture_command(&mut cmd, fixture);
(cmd, Some(dir))
} else {
(fixture_command(fixture), None)
};
crate::test_privilege::drop_dac_bypass_before_exec(&mut cmd);
let db_dir = db_dir::fixture_db_dir();
cmd.env(db_dir::SKULD_DB_DIR_ENV, db_dir.path());
(cmd, FixtureDirs::new(exe_copy, db_dir))
}
#[cfg(unix)]
pub(crate) struct RestoreMode {
path: std::path::PathBuf,
mode: u32,
}
#[cfg(unix)]
impl RestoreMode {
pub(crate) fn new(path: impl Into<std::path::PathBuf>, mode: u32) -> Self {
Self {
path: path.into(),
mode,
}
}
}
#[cfg(unix)]
impl Drop for RestoreMode {
fn drop(&mut self) {
use std::os::unix::fs::PermissionsExt as _;
if let Err(e) = std::fs::set_permissions(&self.path, std::fs::Permissions::from_mode(self.mode)) {
log::warn!(
"could not restore mode {:o} on {:?}: {}",
self.mode,
self.path,
crate::error::Report(&e)
);
}
}
}
pub(crate) fn fixture_command(fixture: &str) -> std::process::Command {
#[cfg(target_os = "linux")]
let program = std::path::PathBuf::from("/proc/self/exe");
#[cfg(not(target_os = "linux"))]
let program = std::env::current_exe().expect("current_exe");
let mut cmd = crate::test_reexec::command(program);
configure_fixture_command(&mut cmd, fixture);
cmd
}
pub(crate) fn configure_fixture_command(cmd: &mut std::process::Command, fixture: &str) {
cmd.args(crate::test_reexec::fixture_args(fixture))
.env(FIXTURE_PARENT_PID_ENV, std::process::id().to_string())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped());
}
const FIXTURE_PARENT_PID_ENV: &str = "COSCA_FIXTURE_PARENT_PID";
#[cfg(unix)]
pub(crate) fn is_fixture_reexec() -> bool {
let reexec = parent_pid_matches();
if reexec {
write_gate_passed();
}
reexec
}
#[cfg(unix)]
fn parent_pid_matches() -> bool {
std::env::var(FIXTURE_PARENT_PID_ENV)
.ok()
.and_then(|s| s.parse::<u32>().ok())
.is_some_and(|pid| pid == std::os::unix::process::parent_id())
}
pub(crate) const FIXTURE_GATE_PASSED_LINE: &str = "COSCA_FIXTURE_GATE_PASSED";
fn write_gate_passed() {
use std::io::Write;
writeln!(std::io::stderr(), "{FIXTURE_GATE_PASSED_LINE}").expect("write the gate line to stderr");
}
pub(crate) fn run_fixture_command(fixture: &str, mut cmd: std::process::Command) {
crate::test_reexec::with_json_events(&mut cmd);
let child = crate::test_spawn::spawn(&mut cmd).expect("spawn fixture child");
finish_fixture_command(fixture, child);
}
fn finish_fixture_command(fixture: &str, child: std::process::Child) {
let output = child.wait_with_output().expect("wait for fixture child");
assert_fixture_passed(fixture, &output);
}
pub(crate) fn assert_fixture_passed(fixture: &str, output: &std::process::Output) {
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
if let Err(why) = crate::test_reexec::suite_passed_exactly_one(output) {
panic!(
"fixture {fixture} did not run and pass exactly one test: {why}\n--- stdout \
---\n{stdout}\n--- stderr ---\n{stderr}"
);
}
assert!(
stderr.contains(FIXTURE_GATE_PASSED_LINE),
"fixture {fixture} passed but never wrote {FIXTURE_GATE_PASSED_LINE:?}: its re-exec gate \
returned early without running its body:\n--- stdout ---\n{stdout}\n--- stderr ---\n{stderr}",
);
}
pub(crate) fn is_marked_fixture_reexec(marker_env: &str) -> bool {
let marker = std::env::var(marker_env).ok();
let driver = std::env::var(FIXTURE_PARENT_PID_ENV).ok();
let marked = marker.is_some() && marker == driver;
if marked {
write_gate_passed();
}
marked
}
pub(crate) fn run_fixture_output(fixture: &str, marker_env: &str) -> std::process::Output {
let mut cmd = fixture_command(fixture);
cmd.env(marker_env, std::process::id().to_string());
let child = crate::test_spawn::spawn(&mut cmd).expect("spawn fixture child");
child.wait_with_output().expect("wait for fixture child")
}
#[cfg(unix)]
pub(crate) fn run_fixture_case(fixture: &str, marker_env: &str, case_env: &str, case: &str) {
let mut cmd = fixture_command(fixture);
cmd.env(marker_env, std::process::id().to_string()).env(case_env, case);
crate::test_reexec::with_json_events(&mut cmd);
let child = crate::test_spawn::spawn(&mut cmd).expect("spawn fixture child");
let output = child.wait_with_output().expect("wait for fixture child");
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
if let Err(why) = crate::test_reexec::suite_passed_exactly_one(&output) {
panic!(
"fixture {fixture} case {case:?} did not run and pass exactly one test: {why}\n--- stdout \
---\n{stdout}\n--- stderr ---\n{stderr}"
);
}
assert!(
stderr.contains(FIXTURE_GATE_PASSED_LINE),
"fixture {fixture} case {case:?} never wrote {FIXTURE_GATE_PASSED_LINE:?}:\n{stderr}",
);
}
#[cfg(target_os = "macos")]
pub(crate) fn set_signal_ignored(signo: libc::c_int, ignore: bool) {
let handler = if ignore { libc::SIG_IGN } else { libc::SIG_DFL };
let previous = unsafe { libc::signal(signo, handler) };
assert_ne!(
previous,
libc::SIG_ERR,
"signal({signo}): {}",
std::io::Error::last_os_error()
);
}
#[cfg(target_os = "macos")]
#[must_use = "the limit is restored as soon as the guard drops"]
pub(crate) struct RefusedDescriptors {
saved: libc::rlimit,
pub(crate) limit: libc::c_int,
}
#[cfg(target_os = "macos")]
pub(crate) fn refuse_new_descriptors() -> RefusedDescriptors {
unsafe {
let probe = libc::dup(0);
assert!(probe > 0, "dup: {}", std::io::Error::last_os_error());
let mut saved = std::mem::zeroed::<libc::rlimit>();
assert_eq!(libc::getrlimit(libc::RLIMIT_NOFILE, &mut saved), 0);
let lowered = libc::rlimit {
rlim_cur: probe as libc::rlim_t,
rlim_max: saved.rlim_max,
};
assert_eq!(libc::close(probe), 0);
assert_eq!(libc::setrlimit(libc::RLIMIT_NOFILE, &lowered), 0);
RefusedDescriptors { saved, limit: probe }
}
}
#[cfg(target_os = "macos")]
impl Drop for RefusedDescriptors {
fn drop(&mut self) {
let restored = unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &self.saved) };
assert!(
restored == 0 || std::thread::panicking(),
"setrlimit: {}",
std::io::Error::last_os_error()
);
}
}
pub(crate) fn expected_cwd(marker_env: &str) -> Option<std::path::PathBuf> {
#[cfg(unix)]
if !parent_pid_matches() {
return None;
}
let expected = std::path::PathBuf::from(std::env::var_os(marker_env)?);
let actual = std::env::current_dir().expect("current_dir");
assert_eq!(
actual.canonicalize().expect("canonicalize actual cwd"),
expected.canonicalize().expect("canonicalize expected cwd"),
"this fixture's OS-level cwd must be the directory run_fixture_with_cwd's caller prepared",
);
write_gate_passed();
Some(expected)
}
macro_rules! fixture_path {
($name:ident) => {{
crate::test_child::assert_fn_item($name);
crate::test_child::strip_crate_prefix(concat!(module_path!(), "::", stringify!($name)))
}};
($name:ident, $group:ty) => {{
crate::test_child::assert_fn_item_taking::<$group, _>($name);
crate::test_child::strip_crate_prefix(concat!(module_path!(), "::", stringify!($name)))
}};
}
pub(crate) use fixture_path;
pub(crate) fn assert_fn_item<R>(_: impl Fn() -> R) {}
#[cfg(target_os = "macos")]
pub(crate) fn assert_fn_item_taking<A: ?Sized, R>(_: impl Fn(&A) -> R) {}
pub(crate) fn strip_crate_prefix(path: &'static str) -> &'static str {
let prefix = concat!(env!("CARGO_PKG_NAME"), "::");
path.strip_prefix(prefix)
.unwrap_or_else(|| panic!("{path:?} does not start with {prefix:?} — module_path!()'s contract changed"))
}
pub(crate) fn spawn_a_process_that_exits() -> std::process::Child {
crate::test_spawn::spawn(
crate::test_reexec::command(std::env::current_exe().expect("current_exe"))
.args(["--exact", "__cosca_no_such_test__"])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null()),
)
.expect("spawn")
}
#[cfg(windows)]
pub(crate) fn system32(name: &str) -> std::path::PathBuf {
std::path::Path::new(&std::env::var_os("SystemRoot").expect("SystemRoot is set on Windows"))
.join("System32")
.join(name)
}
#[cfg(windows)]
pub(crate) fn windows_more() -> std::path::PathBuf {
system32("more.com")
}
#[cfg(unix)]
pub(crate) const TERM_IGNORING_BLOCKER_ARGV: &[&str] = &["sh", "-c", "trap '' TERM; echo r; exec cat"];
#[cfg(unix)]
pub(crate) const CAT_TREE_ARGV: &[&str] = &[
"sh",
"-c",
"exec 3<&0; { cat <&3 3<&- && echo eof; } & echo r; exec cat",
];
#[cfg(unix)]
pub(crate) const TERM_IGNORING_TREE_ARGV: &[&str] = &[
"sh",
"-c",
"trap '' TERM; exec 3<&0; { sh -c 'echo r; read -r _; echo leaf' <&3 3<&- && echo eof; } & exec cat",
];
#[cfg(unix)]
pub(crate) const TERM_SURVIVOR_TREE_ARGV: &[&str] = &[
"sh",
"-c",
"exec 3<&0; { trap '' TERM; sh -c 'echo r; read -r _; echo leaf' <&3 3<&- & read -r _ <&3; echo sub; wait; } & exec cat",
];
#[cfg(unix)]
pub(crate) const ROOT_OUTLIVING_THE_GRACE_ARGV: &[&str] = &[
"sh",
"-c",
"trap '' TERM; exec 3<&0; ( trap - TERM; ( trap '' TERM; echo r; exec cat <&3 3<&- ) & wait ) & wait; exec cat",
];
#[cfg(unix)]
pub(crate) fn wait_for_the_middle_to_exit_after_the_term(
root: crate::identity::ProcessId,
) -> crate::oneshot_hook::Armed {
let middle = root
.children(crate::Recursive::No)
.expect("the root's children")
.pop()
.expect("the root's child");
let middle = crate::Process::open(middle)
.expect("open the middle")
.expect("the middle runs");
crate::graceful_hooks::at(crate::graceful_hooks::HookPoint::AfterTerminate, move || {
middle.wait().expect("the middle exits on the SIGTERM");
})
}
#[cfg(unix)]
pub(crate) fn term_ignoring_blocker() -> (crate::Child, crate::PipeWriter) {
use std::io::Read as _;
let mut cmd = command(Console::Hidden);
cmd.args(TERM_IGNORING_BLOCKER_ARGV.iter().copied());
cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
cmd.stdout(crate::Stdio::pipe()).expect("set stdout pipe");
cmd.contain();
let mut child = cmd.spawn().expect("spawn");
let stdin = child.stdin().expect("piped stdin");
let mut readiness = [0u8; 1];
child
.stdout()
.expect("piped stdout")
.read_exact(&mut readiness)
.expect("readiness byte");
(child, stdin)
}
pub(crate) fn assert_killed(who: &str, status: std::process::ExitStatus) {
#[cfg(unix)]
{
use std::os::unix::process::ExitStatusExt as _;
assert_eq!(
status.signal(),
Some(libc::SIGKILL),
"{who} must be SIGKILLed, not exit on its own: {status:?}"
);
}
#[cfg(windows)]
assert_eq!(
status.code(),
Some(1),
"{who} must be killed (exit code 1), not exit on its own: {status:?}"
);
}
#[cfg(any(windows, target_os = "macos", feature = "tokio"))]
pub(crate) fn fixture_argv(test: &str) -> [&str; 5] {
let [threads, exact, test, nocapture] = crate::test_reexec::fixture_args(test);
["cosca_unit_tests", threads, exact, test, nocapture]
}
#[cfg(windows)]
pub(crate) const FIXTURE_SURVIVES_GROUP_SIGNAL_TEST: &str = "test_child::fixture_survives_group_signal";
#[cfg(windows)]
pub(crate) const FIXTURE_SURVIVES_GROUP_SIGNAL_ADDR_ENV: &str = "COSCA_FIXTURE_SURVIVES_GROUP_SIGNAL_ADDR";
#[cfg(windows)]
#[skuld::test]
fn fixture_survives_group_signal() {
let Some(addr) = std::env::var_os(FIXTURE_SURVIVES_GROUP_SIGNAL_ADDR_ENV) else {
return; };
const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
#[allow(
clippy::zombie_processes,
reason = "the grandchild must outlive us; containment kills it"
)]
let _survivor = crate::test_spawn::spawn_with(
crate::test_reexec::command(std::env::current_exe().expect("current_exe"))
.args(&fixture_argv(FIXTURE_REGISTERS_THEN_BLOCKS_TEST)[1..])
.env(FIXTURE_REGISTERS_THEN_BLOCKS_ADDR_ENV, &addr)
.stdout(std::process::Stdio::null()),
CREATE_NEW_PROCESS_GROUP,
Console::Asked,
)
.expect("spawn a grandchild the group signal cannot reach");
}
#[cfg(windows)]
pub(crate) const FIXTURE_REGISTERS_THEN_BLOCKS_TEST: &str = "test_child::fixture_registers_then_blocks";
pub(crate) const FIXTURE_REGISTERS_THEN_BLOCKS_ADDR_ENV: &str = "COSCA_FIXTURE_REGISTERS_THEN_BLOCKS_ADDR";
#[cfg(windows)]
pub(crate) fn registration_rendezvous() -> (std::net::TcpListener, String) {
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind rendezvous listener");
let addr = listener.local_addr().expect("local_addr").to_string();
(listener, addr)
}
#[skuld::test]
fn fixture_registers_then_blocks() {
let Some(addr) = std::env::var_os(FIXTURE_REGISTERS_THEN_BLOCKS_ADDR_ENV) else {
return; };
use std::io::{Read, Write};
let mut sock = ack::connect_control(addr.to_str().expect("utf8 addr")).expect("connect rendezvous socket");
sock.write_all(b"R").expect("write registration tag");
sock.flush().expect("flush registration tag");
let mut sink = [0u8; 1];
_ = sock.read(&mut sink);
}
const FIXTURE_CONNECTS_AND_EXITS_TEST: &str = "test_child::fixture_connects_and_exits";
const FIXTURE_CONNECTS_AND_EXITS_ADDR_ENV: &str = "COSCA_FIXTURE_CONNECTS_AND_EXITS_ADDR";
#[skuld::test]
fn fixture_connects_and_exits() {
let Some(addr) = std::env::var_os(FIXTURE_CONNECTS_AND_EXITS_ADDR_ENV) else {
return; };
use std::io::Write;
let mut sock = ack::connect_control(addr.to_str().expect("utf8 addr")).expect("connect rendezvous socket");
sock.write_all(b"R").expect("write registration tag");
sock.flush().expect("flush registration tag");
}
fn spawn_connects_and_exits(
listener: &std::net::TcpListener,
acked: bool,
) -> (std::process::Child, crate::identity::ProcessId) {
let addr = listener.local_addr().expect("local_addr").to_string();
let mut cmd = std::process::Command::new(std::env::current_exe().expect("current_exe"));
cmd.args(["--test-threads=1", "--exact", FIXTURE_CONNECTS_AND_EXITS_TEST])
.env(FIXTURE_CONNECTS_AND_EXITS_ADDR_ENV, &addr)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
if acked {
cmd.env(ack::ACK_ENV, "1");
}
let child = crate::test_spawn::spawn(&mut cmd).expect("spawn the connects-and-exits fixture");
let target = crate::identity::ProcessId::of(child.id())
.found()
.expect("resolve the freshly spawned fixture's pid");
(child, target)
}
#[cfg(unix)]
fn wait_unreaped(pid: u32) {
loop {
let mut si: libc::siginfo_t = unsafe { std::mem::zeroed() };
let rc = unsafe { libc::waitid(libc::P_PID, pid as libc::id_t, &mut si, libc::WEXITED | libc::WNOWAIT) };
if rc == 0 {
return;
}
let e = std::io::Error::last_os_error();
assert_eq!(e.raw_os_error(), Some(libc::EINTR), "waitid: {e}");
}
}
#[skuld::test]
fn death_watch_accept_or_die_reports_a_target_that_connected_and_exited_without_the_ack_as_dead() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind rendezvous listener");
let (mut child, target) = spawn_connects_and_exits(&listener, false);
#[cfg(unix)]
wait_unreaped(child.id());
#[cfg(windows)]
child.wait().expect("wait for the fixture to exit");
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| accept_or_die(&listener, target)));
let payload = result.expect_err("accept_or_die must panic for an exited target");
let message = payload
.downcast_ref::<String>()
.cloned()
.or_else(|| payload.downcast_ref::<&str>().map(|s| s.to_string()))
.expect("string panic payload");
assert_eq!(
message,
format!("the control target (pid {}) died before it connected", target.pid())
);
child.wait().expect("reap the fixture");
}
#[skuld::test]
fn death_watch_accept_or_die_returns_the_connection_of_an_acked_target_that_exits_at_once() {
use std::io::Read;
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind rendezvous listener");
let (mut child, target) = spawn_connects_and_exits(&listener, true);
let mut sock = accept_or_die(&listener, target);
let mut tag = [0u8; 1];
sock.read_exact(&mut tag).expect("read the fixture's tag");
assert_eq!(&tag, b"R");
child.wait().expect("reap the fixture");
}
#[cfg(unix)]
pub(crate) const CWD_TOOL_EXIT: i32 = 11;
#[cfg(unix)]
pub(crate) const PATH_TOOL_EXIT: i32 = 22;
#[cfg(unix)]
pub(crate) fn cwd_and_path_tools() -> (tempfile::TempDir, tempfile::TempDir) {
use std::os::unix::fs::PermissionsExt;
let dirs = (
tempfile::tempdir().expect("tempdir"),
tempfile::tempdir().expect("tempdir"),
);
for (dir, code) in [(&dirs.0, CWD_TOOL_EXIT), (&dirs.1, PATH_TOOL_EXIT)] {
let tool = dir.path().join("tool");
let _guard = crate::child::spawn::spawn_lock();
std::fs::write(&tool, format!("#!/bin/sh\nexit {code}\n")).expect("write tool");
std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).expect("chmod tool");
}
dirs
}
#[cfg(test)]
#[path = "test_child_tests.rs"]
mod test_child_tests;
#[cfg(any(target_os = "linux", windows))]
pub(crate) fn exited_through_open(
id: crate::identity::ProcessId,
timeout: Option<std::time::Duration>,
) -> Result<bool, crate::error::Error> {
match crate::Process::open(id)? {
None => Ok(true),
Some(process) => match timeout {
None => process.wait().map(|()| true),
Some(timeout) => process.wait_timeout(timeout),
},
}
}
#[cfg(windows)]
pub(crate) fn parents_once_unlisted(
pid: crate::identity::RawPid,
) -> Vec<(crate::identity::RawPid, crate::identity::RawPid)> {
loop {
let parents =
crate::containment::enumerate::process_parents(&crate::identity::HostKernel).expect("the process snapshot");
if !parents.iter().any(|&(listed, _)| listed == pid) {
return parents;
}
std::thread::yield_now();
}
}