use std::io::{BufRead as _, BufReader, Read as _, Write as _};
#[cfg(feature = "tokio")]
use crate::test_child::Console;
use std::os::unix::process::CommandExt as _;
use std::process::{ChildStdin, ChildStdout};
use crate::test_child::{fixture_command, fixture_path, is_marked_fixture_reexec, StdChild};
const MARKER: &str = "COSCA_TESTCFG_SHARED_FOREIGN_TRACER";
const PID_ENV: &str = "COSCA_TESTCFG_SHARED_FOREIGN_TRACER_PID";
const HOLD_EXIT_ENV: &str = "COSCA_TESTCFG_SHARED_FOREIGN_TRACER_HOLD_EXIT";
pub(crate) const STOP: u8 = b's';
pub(crate) const LET_EXIT: u8 = b'c';
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 = match std::env::var(PID_ENV) {
Ok(pid) => pid,
Err(_) => {
let mut line = String::new();
std::io::stdin().read_line(&mut line).expect("the tracee's pid");
line
}
}
.trim()
.parse()
.expect("a pid");
let null = std::ptr::null_mut::<libc::c_void>;
let options = if std::env::var_os(HOLD_EXIT_ENV).is_some() {
libc::PTRACE_O_TRACEEXIT
} else {
0
};
let rc = unsafe { libc::ptrace(libc::PTRACE_SEIZE, pid, null(), options as usize as *mut libc::c_void) };
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");
}
LET_EXIT => {
let status = waitpid_status(pid);
assert!(
libc::WIFSTOPPED(status) && status >> 16 == libc::PTRACE_EVENT_EXIT,
"waitpid: not the exit stop: {status:#x}"
);
let rc = unsafe { libc::ptrace(libc::PTRACE_CONT, pid, null(), null()) };
assert_eq!(rc, 0, "PTRACE_CONT: {}", std::io::Error::last_os_error());
say("continued");
}
REAP => {
let status = loop {
let status = waitpid_status(pid);
if libc::WIFEXITED(status) || libc::WIFSIGNALED(status) {
break status;
}
assert!(
libc::WIFSTOPPED(status),
"waitpid: neither a stop nor an exit: {status:#x}"
);
let signal = if status >> 16 == 0 { libc::WSTOPSIG(status) } else { 0 };
let rc =
unsafe { libc::ptrace(libc::PTRACE_CONT, pid, null(), signal as usize as *mut libc::c_void) };
assert_eq!(rc, 0, "PTRACE_CONT: {}", std::io::Error::last_os_error());
};
say(&format!("exit {status}"));
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()),
}
}
pub(crate) struct Tracer {
helper: StdChild,
go: Option<ChildStdin>,
lines: std::io::Lines<BufReader<ChildStdout>>,
}
pub(crate) fn spawn_helper(pid: u32) -> Tracer {
let mut tracer = start_helper(Some(pid), false);
tracer.expect("seized");
tracer
}
#[cfg(feature = "tokio")]
pub(crate) fn spawn_helper_holding_exit(pid: u32) -> Tracer {
let mut tracer = start_helper(Some(pid), true);
tracer.expect("seized");
tracer
}
#[cfg_attr(
not(feature = "tokio"),
allow(dead_code, reason = "only the tokio spawn's tracer test uses it")
)]
pub(crate) fn spawn_unseized_helper() -> Tracer {
start_helper(None, false)
}
fn start_helper(pid: Option<u32>, hold_exit: bool) -> Tracer {
let mut cmd = fixture_command(fixture_path!(foreign_tracer_helper));
if let Some(pid) = pid {
cmd.env(PID_ENV, pid.to_string());
}
cmd.env(MARKER, std::process::id().to_string())
.env_remove(HOLD_EXIT_ENV)
.env_remove("RUST_TEST_NOCAPTURE")
.stdin(std::process::Stdio::piped())
.stderr(std::process::Stdio::inherit());
if hold_exit {
cmd.env(HOLD_EXIT_ENV, "1");
}
let mut helper = StdChild::spawn(&mut cmd);
let go = helper.stdin.take().expect("piped stdin");
let lines = BufReader::new(helper.stdout.take().expect("piped stdout")).lines();
Tracer {
helper,
go: Some(go),
lines,
}
}
impl Tracer {
#[cfg_attr(
not(feature = "tokio"),
allow(dead_code, reason = "only the tokio spawn's tracer test uses it")
)]
pub(crate) fn seize(&mut self, pid: u32) {
writeln!(self.go.as_mut().expect("the tracer is still driven"), "{pid}").expect("send the helper the pid");
self.expect("seized");
}
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:?}");
}
#[cfg(feature = "tokio")]
pub(crate) fn expect_reaped(&mut self) -> libc::c_int {
let mut status = None;
for line in &mut self.lines {
let line = line.expect("read the helper's stdout");
if let Some((_, rest)) = line.split_once("@@exit ") {
status = Some(rest.trim_end_matches("@@").parse().expect("the helper's wait status"));
} else if line.ends_with("@@reaped@@") {
return status.expect("the helper reports the status before it reaps");
}
}
panic!("the helper ended without reporting \"reaped\"");
}
pub(crate) fn finish(mut self) {
drop(self.go.take());
let status = self.helper.wait().expect("the helper exits");
assert!(status.success(), "{status:?}");
}
}
#[cfg(feature = "tokio")]
const TRACEE_MARKER: &str = "COSCA_TESTCFG_FOREIGN_TRACER_TOKIO_TRACEE";
#[cfg(feature = "tokio")]
#[skuld::test]
fn tokio_tracee() {
let driver = std::env::var(TRACEE_MARKER).ok();
if driver != Some(std::os::unix::process::parent_id().to_string()) {
return;
}
allow_any_tracer_now().expect("allow any tracer");
say("allowed");
std::io::copy(&mut std::io::stdin(), &mut std::io::sink()).expect("read stdin to EOF");
}
#[cfg(feature = "tokio")]
pub(crate) fn tokio_tracee_command() -> crate::tokio::Command {
let mut cmd = crate::test_child::tokio_command(Console::Hidden);
cmd.executable(std::env::current_exe().expect("current_exe"))
.args(crate::test_child::fixture_argv(fixture_path!(tokio_tracee)));
crate::test_reexec::scrub_env(|var| _ = cmd.env_remove(var));
cmd.env(TRACEE_MARKER, std::process::id().to_string());
cmd
}
#[cfg(feature = "tokio")]
pub(crate) async fn spawn_tokio_tracee() -> (crate::tokio::Child, crate::tokio::ChildStdin) {
use ::tokio::io::AsyncBufReadExt as _;
let mut cmd = tokio_tracee_command();
cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
cmd.stdout(crate::Stdio::pipe()).expect("set stdout pipe");
let mut child = cmd.spawn().await.expect("spawn the tracee");
let stdin = child.stdin().expect("piped stdin");
let mut lines = ::tokio::io::BufReader::new(child.stdout().expect("piped stdout")).lines();
loop {
let line = lines.next_line().await.expect("read the tracee's stdout");
match line {
Some(line) if line.ends_with("@@allowed@@") => return (child, stdin),
Some(_) => {}
None => panic!("the tracee ended without reporting \"allowed\""),
}
}
}
#[cfg(feature = "tokio")]
#[derive(Clone, Copy)]
pub(crate) enum Names {
Pid,
}
#[cfg(feature = "tokio")]
const WAITING_FOR_EXIT: &str = "still waiting for it to exit";
#[cfg(feature = "tokio")]
enum TeardownLook {
Held { warned: bool },
Returned,
}
#[cfg(feature = "tokio")]
#[derive(Clone, Copy)]
enum Threshold {
Zero,
Frozen(std::time::Duration),
}
#[cfg(feature = "tokio")]
thread_local! {
static BLOCKS_IGNORED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
#[cfg(feature = "tokio")]
#[must_use = "the watch hears blocks again as soon as the guard is dropped"]
pub(crate) struct BlocksIgnored(());
#[cfg(feature = "tokio")]
impl Drop for BlocksIgnored {
fn drop(&mut self) {
BLOCKS_IGNORED.with(|i| i.set(false));
}
}
#[cfg(feature = "tokio")]
pub(crate) fn ignore_blocks_until() -> BlocksIgnored {
BLOCKS_IGNORED.with(|i| i.set(true));
BlocksIgnored(())
}
#[cfg(feature = "tokio")]
struct Held<R> {
pid: u32,
look: TeardownLook,
warns: Vec<String>,
levels: Vec<log::Level>,
status: i32,
done: R,
}
#[cfg(feature = "tokio")]
fn hold_teardown<R: Send>(
threshold: Threshold,
teardown: impl FnOnce() -> R + Send,
seized: impl FnOnce() -> (u32, Tracer),
) -> Held<R> {
use crate::wait::block_probe::{is_drain_wait, on_each_block, on_pause};
crate::log_capture::install();
let mark = crate::log_capture::mark();
let (look_tx, look_rx) = std::sync::mpsc::channel::<bool>();
std::thread::scope(|s| {
let thread = s.spawn(move || {
let (_clock, _zero, _warn);
match threshold {
Threshold::Zero => _warn = crate::tokio::warn_slow_teardowns_after(std::time::Duration::ZERO),
Threshold::Frozen(after) => {
_clock = crate::wait::test_clock::FrozenClockGuard::install();
_zero = crate::wait::test_clock::ZeroElapsedGuard::install();
_warn = crate::tokio::warn_slow_teardowns_after(after);
}
}
let report = |tx: std::sync::mpsc::Sender<bool>| {
move || {
let warned =
!crate::log_capture::records_since_on_current_thread(mark, WAITING_FOR_EXIT).is_empty();
_ = tx.send(warned);
}
};
let at_block = report(look_tx.clone());
let at_pause = report(look_tx);
let _block = on_each_block(move |block| {
if !is_drain_wait(block) && !BLOCKS_IGNORED.with(std::cell::Cell::get) {
at_block();
}
});
let _pause = on_pause(at_pause);
teardown()
});
let (pid, mut tracer) = seized();
let look = match look_rx.recv() {
Ok(warned) => TeardownLook::Held { warned },
Err(_) => TeardownLook::Returned,
};
tracer.send(REAP);
let status = tracer.expect_reaped();
let done = thread.join().unwrap_or_else(|panic| std::panic::resume_unwind(panic));
Held {
pid,
look,
warns: crate::log_capture::records_since(mark, WAITING_FOR_EXIT),
levels: crate::log_capture::levels_since(mark, WAITING_FOR_EXIT),
status,
done,
}
})
}
#[cfg(feature = "tokio")]
fn assert_killed(pid: u32, status: i32) {
assert!(
libc::WIFSIGNALED(status) && libc::WTERMSIG(status) == libc::SIGKILL,
"the teardown's kill must end child {pid}, not its own exit once its stdin was released: {status:#x}"
);
}
#[cfg(feature = "tokio")]
pub(crate) fn assert_warns_once_before_blocking<R: Send>(
names: Names,
teardown: impl FnOnce() -> R + Send,
seized: impl FnOnce() -> (u32, Tracer),
) -> R {
let Held {
pid,
look,
warns,
levels,
status,
done,
} = hold_teardown(Threshold::Zero, teardown, seized);
match look {
TeardownLook::Held { warned: true } => {}
TeardownLook::Held { warned: false } => {
panic!("the teardown blocked or paused before it warned that it was still waiting for child {pid}")
}
TeardownLook::Returned => panic!("the teardown returned while the tracer still held child {pid}'s zombie"),
}
assert_killed(pid, status);
let who = match names {
Names::Pid => format!("child {pid}"),
};
let named: Vec<_> = warns.iter().filter(|text| text.contains(&who)).collect();
assert_eq!(named.len(), 1, "one warn before the blocking wait: {warns:?}");
assert_eq!(levels, [log::Level::Warn], "exactly one warn, at warn");
done
}
#[cfg(feature = "tokio")]
pub(crate) fn assert_no_warn_before_the_threshold<R: Send>(
after: std::time::Duration,
teardown: impl FnOnce() -> R + Send,
seized: impl FnOnce() -> (u32, Tracer),
) -> R {
let Held {
pid,
look,
warns,
status,
done,
..
} = hold_teardown(Threshold::Frozen(after), teardown, seized);
if matches!(look, TeardownLook::Returned) {
panic!("the teardown returned while the tracer still held child {pid}'s zombie");
}
assert_killed(pid, status);
assert!(warns.is_empty(), "no warn before the threshold passed: {warns:?}");
done
}
#[cfg(feature = "tokio")]
#[track_caller]
pub(crate) fn assert_reaped_by_sigkill(reaps: &[(u32, std::process::ExitStatus)]) {
use std::os::unix::process::ExitStatusExt as _;
assert!(!reaps.is_empty(), "the teardown must have reaped the child");
for (pid, status) in reaps {
assert_eq!(
status.signal(),
Some(libc::SIGKILL),
"pid {pid} must be SIGKILLed by its teardown kill, not exit once its stdin was released: {status:?}"
);
}
}