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::{ExitStatus, Stdio};
use super::test_own_process_gate::{child_args, child_role, env_value, gate, ENV};
pub(crate) use super::test_own_process_gate::{test_filter, test_path, Completion, Spawn};
const STARTED: &[u8] = b"started";
const RETURNED: &[u8] = b"returned";
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Role {
Parent,
Child { token_fd: RawFd },
}
pub(crate) fn role(inherited: Option<&str>, parent_pid: u32, args: &[OsString], test: &str) -> Role {
match gate(inherited, parent_pid, args, test)
.and_then(|fd| fd.parse::<RawFd>().ok())
.filter(|&token_fd| token_fd > 2)
{
Some(token_fd) => Role::Child { token_fd },
None => Role::Parent,
}
}
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> {
child_role(
test_filter(path),
parent_id(),
|inherited, parent_pid, args, test| match role(inherited, parent_pid, args, test) {
Role::Child { token_fd } => Some(token_fd),
Role::Parent => None,
},
)
.map(accept)
}
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, env_value(&token_fd.to_string(), test))
.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}"
),
})
}