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(target_os = "macos")]
#[path = "../tests/common/kevent_eintr.rs"]
mod kevent_eintr;
pub(crate) const BLOCKER_ARGV: &[&str] = if cfg!(windows) { &["findstr", "x"] } else { &["cat"] };
pub(crate) fn leaked_writer_stdin() -> crate::stdio::Stdio {
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));
std::mem::forget(writer);
crate::stdio::Stdio::from_file(file)
}
#[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 {
unsafe {
let lowest_free = libc::dup(0);
assert!(lowest_free >= 0, "dup(0)");
libc::close(lowest_free);
let mut limit: libc::rlimit = std::mem::zeroed();
assert_eq!(libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit), 0);
let before = limit;
limit.rlim_cur = lowest_free as libc::rlim_t;
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) };
}
}
}
#[cfg(unix)]
pub(crate) fn held_writer_stdin() -> (crate::stdio::Stdio, std::io::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)
}
pub(crate) fn held_std_blocker(stdout: std::process::Stdio) -> std::process::Command {
let mut cmd = std::process::Command::new(BLOCKER_ARGV[0]);
cmd.args(&BLOCKER_ARGV[1..])
.stdin(std::process::Stdio::piped())
.stdout(stdout);
cmd
}
pub(crate) fn held_contained_blocker(stdout: crate::Stdio) -> (crate::Child, std::io::PipeWriter) {
let mut cmd = crate::Command::new();
cmd.args(BLOCKER_ARGV.iter().copied());
cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
cmd.stdout(stdout).expect("set stdout");
cmd.contain();
let mut child = cmd.spawn().expect("spawn");
let stdin = child.stdin().expect("piped stdin");
(child, stdin)
}
#[cfg(feature = "tokio")]
pub(crate) fn held_contained_blocker_async(stdout: crate::Stdio) -> (crate::tokio::Child, crate::tokio::ChildStdin) {
let mut cmd = crate::tokio::Command::new();
cmd.args(BLOCKER_ARGV.iter().copied());
cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
cmd.stdout(stdout).expect("set stdout");
cmd.contain();
let mut child = cmd.spawn().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
}
#[cfg(unix)]
pub(crate) fn live_exiting_member() -> (std::process::Child, crate::identity::ProcessId) {
let mut child = crate::test_spawn::spawn(&mut exiting_member_command()).expect("spawn the member");
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: std::process::Child) {
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(windows)]
pub(crate) fn live_findstr_blocker() -> (std::process::Child, crate::identity::ProcessId) {
let child =
crate::test_spawn::spawn(&mut held_std_blocker(std::process::Stdio::piped())).expect("spawn the blocker");
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: std::process::Child) {
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 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) };
assert_eq!(rc, 0, "waitid: {}", std::io::Error::last_os_error());
}
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::wait::backend::new_cancel_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::wait::backend::signal_cancel(&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::wait::backend::signal_cancel(&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::wait::backend::new_cancel_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::{poll, PollFd, PollFlags};
let Some(pidfd) = crate::wait::backend::open_verified(target, crate::wait::backend::PidfdOp::Wait)
.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 {
match poll(&mut fds, None) {
Ok(_) => {}
Err(rustix::io::Errno::INTR) => continue,
Err(e) => 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};
let Some(kq) = crate::wait::backend::arm_proc_exit(target).expect("arm a kqueue exit-watch for the target") else {
return WatchEvent::Died;
};
let listener_change = KEvent::new(
listener.as_raw_fd() as usize,
EventFilter::EVFILT_READ,
EvFlags::EV_ADD | EvFlags::EV_RECEIPT,
FilterFlag::empty(),
0,
0,
);
let listener_errno =
crate::wait::backend::add_with_receipt(&kq, listener_change).expect("kevent(EV_ADD) to arm the listener watch");
assert_eq!(
listener_errno, 0,
"kevent(EV_ADD) for EVFILT_READ on the control listener reported errno {listener_errno}"
);
let placeholder = KEvent::new(0, EventFilter::EVFILT_PROC, EvFlags::empty(), FilterFlag::empty(), 0, 0);
let mut events = [placeholder; 2];
loop {
let n = match kq.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}"),
};
for ev in &events[..n] {
debug_assert!(
!ev.flags().contains(EvFlags::EV_ERROR),
"an armed kevent reported EV_ERROR: {ev:?}"
);
}
let exited = events[..n].iter().any(|ev| ev.filter() == Ok(EventFilter::EVFILT_PROC));
let connection = events[..n].iter().any(|ev| ev.filter() == Ok(EventFilter::EVFILT_READ));
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) = crate::wait::backend::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::wait::backend::new_cancel_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 {:?}: {e}", self.mode, self.path);
}
}
}
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_sigchld_ignored(ignore: bool) {
let handler = if ignore { libc::SIG_IGN } else { libc::SIG_DFL };
let previous = unsafe { libc::signal(libc::SIGCHLD, handler) };
assert_ne!(
previous,
libc::SIG_ERR,
"signal(SIGCHLD): {}",
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 windows_more() -> std::path::PathBuf {
std::path::Path::new(&std::env::var_os("SystemRoot").expect("SystemRoot is set on Windows"))
.join("System32")
.join("more.com")
}
#[cfg(windows)]
pub(crate) fn windows_blocker() -> (crate::Child, std::io::PipeWriter) {
let mut cmd = crate::Command::new();
cmd.args([windows_more()]);
cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
cmd.stdout(crate::Stdio::null()).expect("set stdout null");
cmd.contain();
let mut child = cmd.spawn().expect("spawn");
let stdin = child.stdin().expect("piped stdin");
(child, stdin)
}
#[cfg(all(windows, feature = "tokio"))]
pub(crate) fn windows_blocker_async(
configure: impl FnOnce(&mut crate::tokio::Command),
) -> (crate::tokio::Child, crate::tokio::ChildStdin) {
let mut cmd = crate::tokio::Command::new();
cmd.args([windows_more()]);
cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
cmd.stdout(crate::Stdio::null()).expect("set stdout null");
configure(&mut cmd);
let mut child = cmd.spawn().expect("spawn");
let stdin = child.stdin().expect("piped stdin");
(child, stdin)
}
#[cfg(unix)]
const TERM_IGNORING_BLOCKER_ARGV: &[&str] = &["sh", "-c", "trap '' TERM; echo r; exec cat"];
#[cfg(unix)]
pub(crate) fn term_ignoring_blocker() -> (crate::Child, std::io::PipeWriter) {
use std::io::Read as _;
let mut cmd = crate::Command::new();
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)
}
#[cfg(all(unix, feature = "tokio"))]
pub(crate) async fn term_ignoring_blocker_async() -> (crate::tokio::Child, crate::tokio::ChildStdin) {
use ::tokio::io::AsyncReadExt as _;
let mut cmd = crate::tokio::Command::new();
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)
.await
.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!(
!status.success(),
"{who} must be killed, not exit on its own: {status:?}"
);
}
#[cfg(any(windows, target_os = "macos"))]
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; };
use std::os::windows::process::CommandExt;
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(
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)
.creation_flags(CREATE_NEW_PROCESS_GROUP)
.stdout(std::process::Stdio::null()),
)
.expect("spawn a grandchild the group signal cannot reach");
}
#[cfg(any(windows, feature = "tokio"))]
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(any(windows, feature = "tokio"))]
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::Process::from_pid(child.id())
.found()
.expect("resolve the freshly spawned fixture's pid")
.id();
(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;