use std::io::{BufRead as _, BufReader, Read as _, Write as _};
use std::os::unix::process::CommandExt as _;
use std::process::{ChildStdin, ChildStdout};
use crate::test_child::{fixture_command, fixture_path, is_marked_fixture_reexec};
const MARKER: &str = "COSCA_TEST_SHARED_FOREIGN_TRACER";
const PID_ENV: &str = "COSCA_TEST_SHARED_FOREIGN_TRACER_PID";
pub(crate) const STOP: u8 = b's';
pub(crate) const REAP: u8 = b'r';
pub(crate) const EXIT: u8 = b'x';
fn say(line: &str) {
writeln!(std::io::stdout(), "@@{line}@@").expect("write to the driver");
}
fn waitpid_status(pid: libc::pid_t) -> libc::c_int {
loop {
let mut status = 0;
let r = unsafe { libc::waitpid(pid, &mut status, libc::__WALL) };
if r != -1 {
return status;
}
let e = std::io::Error::last_os_error();
assert_eq!(e.raw_os_error(), Some(libc::EINTR), "waitpid: {e}");
}
}
#[skuld::test]
fn foreign_tracer_helper() {
if !is_marked_fixture_reexec(MARKER) {
return;
}
let pid: libc::pid_t = std::env::var(PID_ENV)
.expect("the tracee's pid")
.parse()
.expect("a pid");
let null = std::ptr::null_mut::<libc::c_void>;
let rc = unsafe { libc::ptrace(libc::PTRACE_SEIZE, pid, null(), null()) };
assert_eq!(rc, 0, "PTRACE_SEIZE: {}", std::io::Error::last_os_error());
say("seized");
loop {
let mut go = [0u8; 1];
std::io::stdin().read_exact(&mut go).expect("the driver's go byte");
match go[0] {
EXIT => return,
STOP => {
let rc = unsafe { libc::ptrace(libc::PTRACE_INTERRUPT, pid, null(), null()) };
assert_eq!(rc, 0, "PTRACE_INTERRUPT: {}", std::io::Error::last_os_error());
let status = waitpid_status(pid);
assert!(libc::WIFSTOPPED(status), "waitpid: not a stop: {status:#x}");
say("stopped");
}
REAP => {
let status = waitpid_status(pid);
assert!(
libc::WIFEXITED(status) || libc::WIFSIGNALED(status),
"waitpid: not an exit: {status:#x}"
);
say("reaped");
return;
}
other => panic!("an unknown go byte {other:#x}"),
}
}
}
pub(crate) fn allow_any_tracer(cmd: &mut std::process::Command) {
unsafe {
cmd.pre_exec(allow_any_tracer_now);
}
}
pub(crate) fn allow_any_tracer_now() -> std::io::Result<()> {
match rustix::process::set_ptracer(rustix::process::PTracer::Any) {
Ok(()) | Err(rustix::io::Errno::INVAL) => Ok(()),
Err(e) => Err(e.into()),
}
}
struct Helper(std::process::Child);
impl Drop for Helper {
fn drop(&mut self) {
_ = self.0.kill();
_ = self.0.wait();
}
}
pub(crate) struct Tracer {
helper: Helper,
go: Option<ChildStdin>,
lines: std::io::Lines<BufReader<ChildStdout>>,
}
pub(crate) fn spawn_helper(pid: u32) -> Tracer {
let mut cmd = fixture_command(fixture_path!(foreign_tracer_helper));
cmd.env(MARKER, std::process::id().to_string())
.env(PID_ENV, pid.to_string())
.env_remove("RUST_TEST_NOCAPTURE")
.stdin(std::process::Stdio::piped())
.stderr(std::process::Stdio::inherit());
let mut helper = Helper(crate::test_spawn::spawn(&mut cmd).expect("spawn the foreign tracer"));
let go = helper.0.stdin.take().expect("piped stdin");
let lines = BufReader::new(helper.0.stdout.take().expect("piped stdout")).lines();
let mut tracer = Tracer {
helper,
go: Some(go),
lines,
};
tracer.expect("seized");
tracer
}
impl Tracer {
pub(crate) fn send(&mut self, go_byte: u8) {
self.go
.as_mut()
.expect("the tracer is still driven")
.write_all(&[go_byte])
.expect("send the helper a go byte");
}
pub(crate) fn expect(&mut self, expected: &str) {
let want = format!("@@{expected}@@");
for line in &mut self.lines {
if line.expect("read the helper's stdout").ends_with(&want) {
return;
}
}
panic!("the helper ended without reporting {expected:?}");
}
pub(crate) fn finish(mut self) {
drop(self.go.take());
let status = self.helper.0.wait().expect("the helper exits");
assert!(status.success(), "{status:?}");
}
}