use std::cell::Cell;
use std::io::{BufRead as _, BufReader, Read as _, Write as _};
use std::os::fd::AsRawFd as _;
use std::os::unix::process::{CommandExt as _, ExitStatusExt as _};
use std::rc::Rc;
use std::sync::mpsc;
use std::sync::Arc;
use super::fixtures::Blocker;
use crate::test_groups::{tracer_group, Group};
use crate::wait::exit_only::seams::{self as exit_seams, HolderStep};
use crate::wait::exit_only::Target;
const MARKER: &str = "COSCA_TEST_SHARED_FOREIGN_TRACER";
const PID_ENV: &str = "COSCA_TEST_SHARED_FOREIGN_TRACER_PID";
const STOP: u8 = b's';
const REAP: u8 = b'r';
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 !crate::test_child::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}"),
}
}
}
struct Helper(std::process::Child);
impl Drop for Helper {
fn drop(&mut self) {
_ = self.0.kill();
_ = self.0.wait();
}
}
enum Msg {
AtBlockingWaitid(libc::pid_t),
AtBackoff,
Spun(String),
Done(std::io::Result<Option<std::process::ExitStatus>>, Vec<HolderStep>),
}
fn expect_line(lines: &mut impl Iterator<Item = std::io::Result<String>>, expected: &str) {
let want = format!("@@{expected}@@");
for line in lines {
if line.expect("read the helper's stdout").ends_with(&want) {
return;
}
}
panic!("the helper ended without reporting {expected:?}");
}
#[derive(Debug, PartialEq, Eq)]
enum Holder {
Blocked,
Finished,
}
fn await_blocked_or_finished(tid: libc::pid_t) -> Holder {
let path = format!("/proc/self/task/{tid}/syscall");
let mut pause = std::time::Duration::from_micros(50);
loop {
match std::fs::read_to_string(&path) {
Ok(text) if text.trim() == "running" => {}
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 {
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:?}"));
if options & libc::WNOHANG as u64 == 0 {
return Holder::Blocked;
}
}
}
Err(e) if matches!(e.raw_os_error(), Some(libc::ENOENT | libc::ESRCH)) => return Holder::Finished,
Err(e) => panic!("read {path}: {e}"),
}
std::thread::sleep(pause);
pause = (pause * 2).min(std::time::Duration::from_millis(5));
}
}
#[derive(Clone, Copy)]
enum Wait {
Unbounded,
Deadline,
}
#[skuld::test]
fn a_zombie_held_by_a_foreign_tracer_is_handed_back_to_a_blocked_wait(#[fixture(tracer_group)] _group: &Group) {
hand_back(REAP, Wait::Unbounded, false);
}
#[skuld::test]
fn a_zombie_held_by_a_foreign_tracer_that_exits_is_handed_back_to_a_blocked_wait(
#[fixture(tracer_group)] _group: &Group,
) {
hand_back(EXIT, Wait::Unbounded, false);
}
#[skuld::test]
fn a_tracee_stopped_by_a_foreign_tracer_is_not_an_exit(#[fixture(tracer_group)] _group: &Group) {
hand_back(REAP, Wait::Unbounded, true);
}
#[skuld::test]
fn a_deadline_wait_on_a_zombie_held_by_a_foreign_tracer_is_handed_back(#[fixture(tracer_group)] _group: &Group) {
hand_back(REAP, Wait::Deadline, false);
}
fn hand_back(go_byte: u8, wait: Wait, stop_first: bool) {
let b = Blocker::spawn_with(|cmd| {
unsafe {
cmd.pre_exec(|| match rustix::process::set_ptracer(rustix::process::PTracer::Any) {
Ok(()) | Err(rustix::io::Errno::INVAL) => Ok(()),
Err(e) => Err(e.into()),
});
}
});
let pid = b.shared.id();
let mut cmd = crate::test_child::fixture_command(crate::test_child::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 mut go = helper.0.stdin.take().expect("piped stdin");
let mut lines = BufReader::new(helper.0.stdout.take().expect("piped stdout")).lines();
expect_line(&mut lines, "seized");
if stop_first {
go.write_all(&[STOP]).expect("tell the helper to stop the tracee");
expect_line(&mut lines, "stopped");
assert_eq!(b.shared.try_wait().expect("try_wait"), None, "a stop is no exit");
exit_seams::holder_steps();
let _no_reap = exit_seams::on_holder_step(HolderStep::Reap, || {
panic!("the holder went to reap a tracee that is only stopped")
});
let soon = std::time::Instant::now() + std::time::Duration::from_millis(20);
assert_eq!(
b.shared.wait_deadline(soon).expect("wait_deadline"),
None,
"a stop is no exit"
);
}
b.shared.kill().expect("kill");
let Some(Target::PidFd(fd)) = b.shared.target() else {
panic!("a pidfd");
};
let mut fds = [libc::pollfd {
fd: fd.as_raw_fd(),
events: libc::POLLIN,
revents: 0,
}];
loop {
let r = unsafe { libc::poll(fds.as_mut_ptr(), 1, -1) };
if r == 1 {
break;
}
let e = std::io::Error::last_os_error();
assert!(r == -1 && e.raw_os_error() == Some(libc::EINTR), "poll: {e}");
}
assert_eq!(
b.shared.try_wait().expect("try_wait"),
None,
"the tracer still holds it"
);
let (tx, rx) = mpsc::channel();
let waiter = std::thread::spawn({
let shared = Arc::clone(&b.shared);
move || {
exit_seams::holder_steps();
let waiting = Rc::new(Cell::new(false));
let spin = |step| {
let spun = tx.clone();
let waiting = Rc::clone(&waiting);
move || {
if !waiting.get() {
_ = spun.send(Msg::Spun(format!("a second {step:?}")));
}
}
};
let reaped = Rc::new(Cell::new(false));
let first_reap = Rc::clone(&reaped);
let _first_poll = exit_seams::on_holder_step(HolderStep::Poll, || {});
let _first_reap = exit_seams::on_holder_step(HolderStep::Reap, move || first_reap.set(true));
let _second_poll = exit_seams::on_holder_step(HolderStep::Poll, spin(HolderStep::Poll));
let _second_reap = exit_seams::on_holder_step(HolderStep::Reap, spin(HolderStep::Reap));
let peeks = Cell::new(0u32);
let waited = Cell::new(false);
let (seen, armed, spun) = (Rc::clone(&reaped), Rc::clone(&waiting), tx.clone());
let _observer = matches!(wait, Wait::Unbounded).then(|| {
exit_seams::observe_waitid(move |options| {
if armed.get() {
if !waited.replace(true) {
assert_eq!(
options & libc::WNOHANG as u32,
0,
"the visible-exit wait made a WNOHANG waitid ({options:#x}) instead of blocking in its first"
);
}
} else if seen.get() {
peeks.set(peeks.get() + 1);
if peeks.get() > 1 {
_ = spun.send(Msg::Spun("a second non-blocking waitid before blocking".into()));
}
}
})
});
let _first_backoff = exit_seams::on_holder_step(HolderStep::Backoff, || {});
let at = tx.clone();
let _hook = match wait {
Wait::Unbounded => exit_seams::on_holder_step(HolderStep::BlockingWaitid, move || {
waiting.set(true);
_ = at.send(Msg::AtBlockingWaitid(rustix::thread::gettid().as_raw_nonzero().get()));
}),
Wait::Deadline => exit_seams::on_holder_step(HolderStep::Backoff, move || {
waiting.set(true);
_ = at.send(Msg::AtBackoff);
}),
};
let result = match wait {
Wait::Unbounded => shared.wait().map(Some),
Wait::Deadline => {
shared.wait_deadline(std::time::Instant::now() + std::time::Duration::from_secs(3600))
}
};
_ = tx.send(Msg::Done(result, exit_seams::holder_steps()));
}
});
match rx.recv().expect("the waiter reports") {
Msg::AtBlockingWaitid(tid) => {
if await_blocked_or_finished(tid) == Holder::Finished {
match waiter.join() {
Err(panic) => std::panic::resume_unwind(panic),
Ok(()) => panic!("the holder finished while the tracer still held the zombie"),
}
}
let printed = format!("{:?}", b.shared);
assert!(printed.contains("W {"), "the holder is in W: {printed}");
}
Msg::AtBackoff => {}
Msg::Spun(what) => panic!("the holder polled instead of waiting: {what}"),
Msg::Done(result, steps) => {
panic!("wait returned {result:?} ({steps:?}) while the tracer still held the zombie")
}
}
go.write_all(&[go_byte])
.expect("tell the helper to hand the zombie back");
if go_byte == REAP {
expect_line(&mut lines, "reaped");
}
let Msg::Done(result, steps) = rx.recv().expect("the waiter reports") else {
panic!("the waiter reported a step twice");
};
waiter.join().expect("the waiter");
let status = result.expect("wait").expect("the exit");
assert_eq!(status.signal(), Some(libc::SIGKILL));
match wait {
Wait::Unbounded => assert_eq!(
steps,
[
HolderStep::Poll,
HolderStep::Reap,
HolderStep::BlockingWaitid,
HolderStep::Reap
]
),
Wait::Deadline => {
let (first, rest) = steps.split_at(2);
assert_eq!(first, [HolderStep::Poll, HolderStep::Reap]);
let (last, backoffs) = rest.split_last().expect("the final reap");
assert_eq!(*last, HolderStep::Reap, "{steps:?}");
assert!(
!backoffs.is_empty() && backoffs.iter().all(|s| *s == HolderStep::Backoff),
"{steps:?}"
);
}
}
assert_eq!(
b.shared.try_wait().expect("try_wait").and_then(|s| s.signal()),
Some(libc::SIGKILL)
);
drop(go);
let status = helper.0.wait().expect("the helper exits");
assert!(status.success(), "{status:?}");
}