use std::ffi::OsString;
use std::fs::File;
use std::io::{Read as _, Write as _};
use std::os::fd::{AsRawFd as _, FromRawFd as _, OwnedFd, RawFd};
use std::os::unix::process::{parent_id, CommandExt as _};
use std::process::{Child, Command, ExitStatus, Stdio};
pub(crate) type Spawn = fn(&mut Command) -> std::io::Result<Child>;
pub(crate) const ENV: &str = "COSCA_TEST_OWN_PROCESS";
const STARTED: &[u8] = b"started";
const RETURNED: &[u8] = b"returned";
#[allow(
unused_macros,
reason = "unused in the integration binaries that mount this file only for `tests/common`"
)]
macro_rules! test_path {
($name:ident) => {{
let _ = $name;
concat!(module_path!(), "::", stringify!($name))
}};
}
pub(crate) fn test_filter(path: &str) -> &str {
path.split_once("::")
.unwrap_or_else(|| panic!("{path:?} has no crate segment"))
.1
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Role {
Parent,
Child { token_fd: RawFd },
}
pub(crate) fn child_args(test: &str) -> [&str; 4] {
["--exact", test, "--test-threads=1", super::test_reexec::NOCAPTURE]
}
pub(crate) fn role(inherited: Option<&str>, parent_pid: u32, args: &[OsString], test: &str) -> Role {
let Some(inherited) = inherited else {
return Role::Parent;
};
let mut parts = inherited.splitn(3, ':');
let (Some(pid), Some(fd), Some(named)) = (parts.next(), parts.next(), parts.next()) else {
return Role::Parent;
};
let Ok(token_fd) = fd.parse::<RawFd>() else {
return Role::Parent;
};
let exact_argv = args
.iter()
.map(OsString::as_os_str)
.eq(child_args(test).iter().map(std::ffi::OsStr::new));
if pid == parent_pid.to_string() && named == test && exact_argv && token_fd > 2 {
Role::Child { token_fd }
} else {
Role::Parent
}
}
pub(crate) fn is_reexecution(inherited: Option<&str>, parent_pid: u32, test: &str) -> bool {
let mut parts = inherited.unwrap_or_default().splitn(3, ':');
matches!(
(parts.next(), parts.next(), parts.next()),
(Some(pid), Some(_), Some(named)) if pid == parent_pid.to_string() && named == test
)
}
#[must_use = "the body's completion is reported when this drops; bind it for the whole body"]
pub(crate) struct Completion(pub(crate) File);
impl Drop for Completion {
fn drop(&mut self) {
if !std::thread::panicking() {
self.0
.write_all(RETURNED)
.expect("report that the isolated body returned");
}
}
}
#[must_use = "`let Some(done) = own_process(..) else { return };`: without the witness the test is not isolated"]
pub(crate) fn own_process(path: &str, spawn: Spawn) -> Option<Completion> {
if let Some(done) = child_completion(path) {
return Some(done);
}
if let Err(failure) = run(test_filter(path), &[], spawn) {
panic!("{failure}");
}
None
}
#[must_use = "without the witness the test is not isolated"]
pub(crate) fn child_completion(path: &str) -> Option<Completion> {
let test = test_filter(path);
let args: Vec<OsString> = std::env::args_os().skip(1).collect();
match role(std::env::var(ENV).ok().as_deref(), parent_id(), &args, test) {
Role::Child { token_fd } => Some(accept(token_fd)),
Role::Parent => {
let inherited = std::env::var(ENV).ok();
assert!(
!is_reexecution(inherited.as_deref(), parent_id(), test),
"re-executed for {test} but not accepted as its own process: got {args:?} with {ENV}={inherited:?}, \
expected {:?}",
child_args(test)
);
None
}
}
}
fn accept(token_fd: RawFd) -> Completion {
let set = rustix::io::fcntl_setfd(
unsafe { rustix::fd::BorrowedFd::borrow_raw(token_fd) },
rustix::io::FdFlags::CLOEXEC,
);
if let Err(e) = set {
panic!("the token fd {token_fd} is not open: {e}");
}
let mut token = unsafe { File::from_raw_fd(token_fd) };
token.write_all(STARTED).expect("report that the isolated run started");
Completion(token)
}
#[derive(Debug)]
pub(crate) struct Failure {
pub(crate) kind: FailureKind,
report: String,
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum FailureKind {
Exited(ExitStatus),
NeverStarted,
DidNotReturn,
}
impl std::fmt::Display for Failure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.report)
}
}
pub(crate) fn drain(token_read: &mut std::io::PipeReader) -> std::io::Result<Vec<u8>> {
let flags = rustix::fs::fcntl_getfl(&*token_read).expect("read the token pipe's flags");
debug_assert!(
flags.contains(rustix::fs::OFlags::NONBLOCK),
"the token pipe's read end must be nonblocking"
);
let mut token = Vec::new();
let mut chunk = [0u8; 64];
loop {
match token_read.read(&mut chunk) {
Ok(0) => return Ok(token),
Ok(n) => token.extend_from_slice(&chunk[..n]),
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => return Ok(token),
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
Err(e) => return Err(e),
}
}
}
pub(crate) fn run(test: &str, env: &[(&str, &str)], spawn: Spawn) -> Result<(), Failure> {
let (mut token_read, token_write) = std::io::pipe().expect("create the completion pipe");
rustix::fs::fcntl_setfl(&token_read, rustix::fs::OFlags::NONBLOCK).expect("make the completion pipe non-blocking");
let token_write = OwnedFd::from(token_write);
let token_write = {
let high = token_write
.try_clone()
.expect("move the completion pipe above the stdio slots");
drop(token_write);
high
};
let token_fd = token_write.as_raw_fd();
let mut command = super::test_reexec::command(std::env::current_exe().expect("current_exe"));
command
.args(child_args(test))
.env(ENV, format!("{}:{token_fd}:{test}", std::process::id()))
.envs(env.iter().copied())
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
unsafe {
command.pre_exec(move || {
let fd = rustix::fd::BorrowedFd::borrow_raw(token_fd);
rustix::io::fcntl_setfd(fd, rustix::io::FdFlags::empty()).map_err(std::io::Error::from)
});
}
let child = spawn(&mut command).expect("re-execute the test binary");
drop(token_write);
let output = child.wait_with_output().expect("wait for the isolated run");
let token = drain(&mut token_read).expect("read the completion pipe");
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let (kind, why) = if !output.status.success() {
(
FailureKind::Exited(output.status),
format!("it exited with {:?}", output.status),
)
} else if !token.starts_with(STARTED) {
(FailureKind::NeverStarted, "the filter matched no test".to_string())
} else if &token[STARTED.len()..] != RETURNED {
(
FailureKind::DidNotReturn,
"the body exited the process without returning".to_string(),
)
} else {
return Ok(());
};
Err(Failure {
kind,
report: format!(
"test {test} did not pass in its own process: {why}\n--- stdout ---\n{stdout}\n--- stderr ---\n{stderr}"
),
})
}
pub(crate) use test_path;