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::containment::cgroup::test_support::KillOnDrop;
use crate::test_child::{fixture_command, fixture_path, is_marked_fixture_reexec};
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);
}
}
#[cfg(feature = "tokio")]
pub(crate) fn blocker() -> std::process::Child {
let mut cmd = crate::test_child::held_std_blocker(std::process::Stdio::null());
allow_any_tracer(&mut cmd);
crate::test_spawn::spawn(&mut cmd).expect("spawn the tracee")
}
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: std::process::Child,
ends_helper: KillOnDrop,
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 = crate::test_spawn::spawn(&mut cmd).expect("spawn the foreign tracer");
let ends_helper = KillOnDrop::of(&helper);
let go = helper.stdin.take().expect("piped stdin");
let lines = BufReader::new(helper.stdout.take().expect("piped stdout")).lines();
Tracer {
helper,
ends_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");
_ = self.ends_helper.defuse();
assert!(status.success(), "{status:?}");
}
}
#[cfg(feature = "tokio")]
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Holder {
Blocked,
Warned,
Finished,
}
#[cfg(feature = "tokio")]
fn thread_state(tid: libc::pid_t) -> Option<Holder> {
let path = format!("/proc/self/task/{tid}/syscall");
match std::fs::read_to_string(&path) {
Ok(text) if text.trim() == "running" => None,
Ok(text) => {
let mut fields = text.split_whitespace();
let nr: libc::c_long = fields
.next()
.and_then(|n| n.parse().ok())
.unwrap_or_else(|| panic!("{path}: no syscall number in {text:?}"));
if nr != libc::SYS_waitid {
return None;
}
let options = fields
.nth(3)
.and_then(|o| u64::from_str_radix(o.trim_start_matches("0x"), 16).ok())
.unwrap_or_else(|| panic!("{path}: no waitid options in {text:?}"));
(options & libc::WNOHANG as u64 == 0).then_some(Holder::Blocked)
}
Err(e) if matches!(e.raw_os_error(), Some(libc::ENOENT | libc::ESRCH)) => Some(Holder::Finished),
Err(e) => panic!("read {path}: {e}"),
}
}
#[cfg(feature = "tokio")]
fn await_blocked_warned_or_finished(tid: libc::pid_t, mut warned: impl FnMut() -> bool) -> Holder {
let mut pause = std::time::Duration::from_micros(50);
loop {
match thread_state(tid) {
Some(holder) => return holder,
None if warned() => return Holder::Warned,
None => {}
}
std::thread::sleep(pause);
pause = (pause * 2).min(std::time::Duration::from_millis(5));
}
}
#[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,
Unknown,
}
#[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 {
crate::log_capture::install();
let mark = crate::log_capture::mark();
let (tid_tx, tid_rx) = std::sync::mpsc::channel();
let (pid, holder, warns, status, done) = std::thread::scope(|s| {
let thread = s.spawn(move || {
tid_tx
.send(rustix::thread::gettid().as_raw_nonzero().get())
.expect("report the tid");
let _warn = crate::tokio::warn_slow_teardowns();
teardown()
});
let tid = tid_rx.recv().expect("the teardown's tid");
let (pid, mut tracer) = seized();
let who = match names {
Names::Pid => format!("child {pid}"),
Names::Unknown => "pid unknown".to_owned(),
};
let said_waiting = || {
crate::log_capture::records_since(mark, &who)
.iter()
.any(|text| text.contains("still waiting"))
};
let holder = await_blocked_warned_or_finished(tid, said_waiting);
let warns: Vec<_> = crate::log_capture::records_since(mark, &who)
.into_iter()
.filter(|text| text.contains("still waiting"))
.collect();
tracer.send(REAP);
let status = tracer.expect_reaped();
(pid, holder, warns, status, thread.join().expect("the teardown"))
});
assert_ne!(
holder,
Holder::Finished,
"the teardown returned while the tracer still held child {pid}'s zombie"
);
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}"
);
assert_eq!(warns.len(), 1, "one warn before the blocking wait: {warns:?}");
assert_eq!(
crate::log_capture::levels_since(mark, "still waiting"),
[log::Level::Warn],
"exactly one warn, at warn"
);
done
}
#[cfg(feature = "tokio")]
pub(crate) fn assert_warns_once_after_seizing<R: Send>(
names: Names,
pid: u32,
teardown: impl FnOnce() -> R + Send,
) -> R {
let (seized_tx, seized_rx) = std::sync::mpsc::channel();
assert_warns_once_before_blocking(
names,
move || {
seized_rx.recv().expect("the tracer seized the child");
teardown()
},
move || {
let tracer = spawn_helper(pid);
seized_tx.send(()).expect("let the teardown go on");
(pid, tracer)
},
)
}
#[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:?}"
);
}
}