use std::io::Write as _;
use crate::test_child::Console;
const ROLE_ENV: &str = "COSCA_UH_ROLE";
const MODE_ENV: &str = "COSCA_UH_MODE";
const FORCE_ENV: &str = "COSCA_UH_FORCE";
const TRACE_ENV: &str = "COSCA_UH_TRACE";
const MARKER_ENV: &str = "COSCA_UH_MARKER";
const KIND_ENV: &str = "COSCA_UH_KIND";
mod attach;
mod machine;
mod sys;
pub(crate) use attach::{attach_settled, settled_stop, AttachError};
const DEFAULT_MARKER: &str = "@@cosca-uh@@";
thread_local! {
static UNREAPED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
fn unreaped_helpers() -> usize {
UNREAPED.get()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Mode {
Auto,
Hold,
}
impl Mode {
fn as_env(self) -> &'static str {
match self {
Mode::Auto => "auto",
Mode::Hold => "hold",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Until {
Eof,
Exit,
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Report {
Attached,
Exited,
Reaped,
Detached,
Error { cause: Cause, state: String },
State(String),
Blocking { state: String, until: Until },
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Cause {
Errno(i32),
Event(String),
}
impl Report {
fn parse(text: &str) -> Report {
match text {
"attached" => Report::Attached,
"exited" => Report::Exited,
"reaped" => Report::Reaped,
"detached" => Report::Detached,
_ => {
if let Some(rest) = text.strip_prefix("error ") {
let (cause, state) = rest
.split_once(' ')
.unwrap_or_else(|| panic!("malformed tracer helper error report: {text:?}"));
let cause = match cause.parse() {
Ok(errno) => Cause::Errno(errno),
Err(_) => Cause::Event(cause.to_string()),
};
Report::Error {
cause,
state: state.to_string(),
}
} else if let Some(name) = text.strip_prefix("state ") {
Report::State(name.to_string())
} else if let Some(rest) = text.strip_prefix("blocking ") {
let until = match rest.rsplit_once(' ') {
Some((state, "eof")) => (state, Until::Eof),
Some((state, "exit")) => (state, Until::Exit),
_ => panic!("malformed tracer helper blocking report: {text:?}"),
};
Report::Blocking {
state: until.0.to_string(),
until: until.1,
}
} else {
panic!("unrecognized tracer helper report: {text:?}")
}
}
}
}
}
struct Reports {
rx: std::io::BufReader<std::process::ChildStdout>,
marker: String,
}
impl Reports {
fn next(&mut self) -> Option<Report> {
use std::io::BufRead as _;
loop {
let mut line = String::new();
if self
.rx
.read_line(&mut line)
.expect("read the tracer helper's report pipe")
== 0
{
return None;
}
if let Some(text) = self.echo(&line) {
return Some(Report::parse(text.trim()));
}
}
}
fn discard_rest(&mut self) {
use std::io::BufRead as _;
let mut line = String::new();
while self.rx.read_line(&mut line).is_ok_and(|n| n > 0) {
self.echo(&line);
line.clear();
}
}
fn echo<'l>(&self, line: &'l str) -> Option<&'l str> {
let Some(idx) = line.find(self.marker.as_str()) else {
if !line.trim().is_empty() {
let echo = format!("tracer helper stdout: {line}");
eprint!("{echo}");
}
return None;
};
let text = &line[idx + self.marker.len()..];
let echo = format!("tracer helper report: {}\n", text.trim());
eprint!("{echo}");
Some(text)
}
}
struct Session {
helper: std::process::Child,
signal_tx: Option<std::process::ChildStdin>,
reports: Option<Reports>,
awaits_exit: Option<String>,
finished: bool,
_exe_dir: tempfile::TempDir,
_thread: std::marker::PhantomData<*const ()>,
}
impl Session {
fn signal_tx(&mut self) -> &mut std::process::ChildStdin {
self.signal_tx.as_mut().expect("the signal pipe is already closed")
}
fn next_report(&mut self) -> Option<Report> {
let report = self.reports.as_mut().expect("the report pipe is already closed").next();
self.awaits_exit = match &report {
Some(Report::Blocking {
state,
until: Until::Exit,
}) => Some(state.clone()),
_ => None,
};
report
}
fn finish(&mut self) -> std::process::ExitStatus {
debug_assert!(!self.finished, "the tracer helper is already torn down");
self.finished = true;
let panicking = std::thread::panicking();
let stuck = self.awaits_exit.take();
if panicking || stuck.is_some() {
if let Err(e) = self.helper.kill() {
eprintln!("could not kill the tracer helper: {e}");
}
}
drop(self.signal_tx.take());
if let Some(reports) = &mut self.reports {
if panicking || stuck.is_some() {
reports.discard_rest();
} else {
while reports.next().is_some() {}
}
}
let status = self.helper.wait().expect("reap the tracer helper");
debug_assert!(
UNREAPED.get() > 0,
"the tracer helper was reaped on a thread that did not launch it"
);
UNREAPED.set(UNREAPED.get() - 1);
if let Some(state) = stuck {
if !panicking {
panic!(
"the test dropped the tracer helper while it waited in {state} for the tracee's \
exit, which EOF does not end; it was killed instead. Read its reports through \
the terminal one first"
);
}
}
status
}
}
impl Drop for Session {
fn drop(&mut self) {
if self.finished {
return;
}
let status = self.finish();
if self.reports.is_some() && !std::thread::panicking() {
assert!(
status.success(),
"the tracer helper failed ({status}); its output is above"
);
}
}
}
pub(crate) struct Pending {
session: Session,
}
pub(crate) fn start(mode: Mode) -> Pending {
launch(mode, None)
}
pub(crate) fn start_forced(mode: Mode, force: &str) -> Pending {
launch(mode, Some(force))
}
fn launch(mode: Mode, force: Option<&str>) -> Pending {
let exe_dir = tempfile::tempdir().expect("create a directory for the signed helper");
let exe = debugger_signed_copy(exe_dir.path());
let marker = DEFAULT_MARKER.to_string();
let mut cmd = crate::test_reexec::command(exe);
cmd.args(crate::test_reexec::fixture_args(crate::test_child::fixture_path!(
uh_helper_entry
)))
.env(ROLE_ENV, "helper")
.env(MODE_ENV, mode.as_env())
.env(MARKER_ENV, &marker)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::inherit());
match force {
Some(force) => cmd.env(TRACE_ENV, "1").env(FORCE_ENV, force),
None => cmd.env_remove(TRACE_ENV).env_remove(FORCE_ENV),
};
let mut helper = crate::test_spawn::spawn(&mut cmd).expect("spawn the tracer helper");
UNREAPED.set(UNREAPED.get() + 1);
let signal_tx = helper.stdin.take().expect("the helper's stdin is piped");
let rx = std::io::BufReader::new(helper.stdout.take().expect("the helper's stdout is piped"));
Pending {
session: Session {
helper,
signal_tx: Some(signal_tx),
reports: Some(Reports { rx, marker }),
awaits_exit: None,
finished: false,
_exe_dir: exe_dir,
_thread: std::marker::PhantomData,
},
}
}
pub(crate) fn debugger_signed_copy(dir: &std::path::Path) -> std::path::PathBuf {
const ENTITLEMENTS: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict><key>com.apple.security.cs.debugger</key><true/></dict></plist>
"#;
let exe = dir.join("tracer-helper");
let plist = dir.join("entitlements.plist");
let codesign = {
let _guard = crate::child::spawn::spawn_lock();
std::fs::copy(std::env::current_exe().expect("current_exe"), &exe).expect("copy the test binary");
std::fs::write(&plist, ENTITLEMENTS).expect("write the entitlements plist");
let mut cmd = std::process::Command::new("/usr/bin/codesign");
cmd.args(["--sign", "-", "--force", "--entitlements"])
.arg(&plist)
.arg(&exe)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped());
#[allow(
clippy::disallowed_methods,
reason = "`_guard` is spawn_lock, held over the copy and the fork"
)]
cmd.spawn().expect("spawn codesign")
};
let out = codesign.wait_with_output().expect("wait for codesign");
assert!(
out.status.success(),
"codesign of the tracer helper failed ({}): {}{}",
out.status,
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr),
);
exe
}
impl Pending {
pub(crate) fn attach(self, tracee: &mut crate::Child) -> TracerHelper<'_> {
self.attach_pid(tracee)
}
pub(crate) fn attach_shared(self, tracee: &crate::Child) -> TracerHelper<'_> {
self.attach_pid(tracee)
}
#[cfg(target_os = "macos")]
pub(crate) fn attach_unheld(self, pid: u32) -> TracerHelper<'static> {
self.attach_pid_number(pid)
}
fn attach_pid(self, tracee: &crate::Child) -> TracerHelper<'_> {
self.attach_pid_number(tracee.pid())
}
fn attach_pid_number<'a>(mut self, pid: u32) -> TracerHelper<'a> {
if let Err(e) = sys::peek_child(pid) {
panic!(
"attach: the tracee {pid} is not this process's unreaped child (waitid: errno {e}), \
so its pid may name another process"
);
}
let tx = self.session.signal_tx();
writeln!(tx, "pid {pid}").expect("send the pid line to the tracer helper");
tx.flush().expect("flush the pid line");
TracerHelper {
session: self.session,
_tracee: std::marker::PhantomData,
}
}
}
pub(crate) struct TracerHelper<'a> {
session: Session,
_tracee: std::marker::PhantomData<&'a ()>,
}
impl TracerHelper<'_> {
pub(crate) fn recv(&mut self) -> Report {
loop {
match self.session.next_report() {
Some(Report::Blocking { .. }) => {}
Some(report) => return report,
None => panic!("the tracer helper exited before the report this test waits for"),
}
}
}
#[cfg(target_os = "macos")]
pub(crate) fn helper_pid(&self) -> u32 {
self.session.helper.id()
}
pub(crate) fn signal(&mut self) {
let tx = self.session.signal_tx();
tx.write_all(b"x").expect("write a signal byte");
tx.flush().expect("flush the signal byte");
}
#[cfg(target_os = "macos")]
pub(crate) fn close_signal_pipe(&mut self) {
drop(
self.session
.signal_tx
.take()
.expect("the signal pipe is already closed"),
);
}
}
pub(crate) const SIGTERM_EXIT: i32 = 15;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Tracee {
Plain,
OwnGroup,
CatchSigterm,
UnstartedThread,
IgnoreSigtstp,
BlockSigtstp,
OwnSession,
}
const TRACEE_READY: &str = "uh-tracee-ready";
#[derive(Debug)]
pub(crate) struct Ready {
pub(crate) blocked: u32,
pub(crate) pgrp: libc::pid_t,
pub(crate) caught: u32,
pub(crate) ignored: u32,
}
impl Ready {
fn parse(fields: &str) -> Option<Ready> {
let mut values = [None; 4];
for field in fields.split_whitespace() {
let (key, value) = field.split_once('=')?;
let at = ["blocked", "pgrp", "caught", "ignored"]
.iter()
.position(|k| *k == key)?;
values[at] = Some(value.parse::<i64>().ok()?);
}
let [Some(blocked), Some(pgrp), Some(caught), Some(ignored)] = values else {
return None;
};
Some(Ready {
blocked: u32::try_from(blocked).ok()?,
pgrp: libc::pid_t::try_from(pgrp).ok()?,
caught: u32::try_from(caught).ok()?,
ignored: u32::try_from(ignored).ok()?,
})
}
}
pub(crate) fn spawn_tracee(kind: Tracee) -> (crate::Child, Ready) {
spawn_tracee_over(kind, crate::identity::HostKernel)
}
pub(crate) fn spawn_tracee_over(
kind: Tracee,
kernel: impl crate::identity::Kernel + Send + 'static,
) -> (crate::Child, Ready) {
let exe = std::env::current_exe().expect("current_exe");
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.executable(&exe)
.args(crate::test_child::fixture_argv(crate::test_child::fixture_path!(
uh_tracee_fixture
)))
.env(ROLE_ENV, "tracee")
.env(KIND_ENV, format!("{kind:?}"));
crate::test_reexec::scrub_env(|var| _ = cmd.env_remove(var));
cmd.stdin(crate::Stdio::pipe()).expect("stdin pipe");
cmd.stdout(crate::Stdio::pipe()).expect("stdout pipe");
cmd.stderr(crate::Stdio::null()).expect("stderr null");
let mut tracee = crate::child::spawn::spawn_with(&mut cmd, kernel)
.map_err(crate::error::Error::from)
.expect("spawn the tracee fixture");
let ready = await_ready(&mut tracee);
(tracee, ready)
}
fn await_ready(tracee: &mut crate::Child) -> Ready {
use std::io::BufRead as _;
let mut stdout = std::io::BufReader::new(tracee.stdout().expect("the tracee's stdout is piped"));
loop {
let mut line = String::new();
let n = stdout.read_line(&mut line).expect("read the tracee's stdout");
assert!(n > 0, "the tracee exited before it was ready");
if let Some(fields) = line.trim().strip_prefix(TRACEE_READY) {
return Ready::parse(fields).unwrap_or_else(|| panic!("malformed tracee ready line: {line:?}"));
}
}
}
#[skuld::test]
fn uh_tracee_fixture() {
if std::env::var(ROLE_ENV).as_deref() != Ok("tracee") {
return;
}
extern "C" fn exit_on_sigterm(_: libc::c_int) {
unsafe { libc::_exit(SIGTERM_EXIT) }
}
let own_group = || {
nix::unistd::setpgid(nix::unistd::Pid::from_raw(0), nix::unistd::Pid::from_raw(0)).expect("setpgid");
};
let kind = std::env::var(KIND_ENV).unwrap_or_else(|_| panic!("{KIND_ENV} is set by spawn_tracee"));
match kind.as_str() {
"Plain" => {}
"OwnGroup" => own_group(),
"CatchSigterm" => {
let previous = unsafe { libc::signal(libc::SIGTERM, exit_on_sigterm as *const () as libc::sighandler_t) };
assert_ne!(previous, libc::SIG_ERR, "install the SIGTERM handler");
}
"UnstartedThread" => {
unsafe extern "C" {
fn pthread_create_suspended_np(
thread: *mut libc::pthread_t,
attr: *const libc::pthread_attr_t,
start: extern "C" fn(*mut libc::c_void) -> *mut libc::c_void,
arg: *mut libc::c_void,
) -> libc::c_int;
}
extern "C" fn never_runs(_: *mut libc::c_void) -> *mut libc::c_void {
std::ptr::null_mut()
}
let mut thread: libc::pthread_t = 0;
let rc =
unsafe { pthread_create_suspended_np(&mut thread, std::ptr::null(), never_runs, std::ptr::null_mut()) };
assert_eq!(rc, 0, "pthread_create_suspended_np");
}
"IgnoreSigtstp" => {
own_group();
let previous = unsafe { libc::signal(libc::SIGTSTP, libc::SIG_IGN) };
assert_ne!(previous, libc::SIG_ERR, "ignore SIGTSTP");
}
"BlockSigtstp" => {
let mut set = nix::sys::signal::SigSet::empty();
set.add(nix::sys::signal::Signal::SIGTSTP);
set.thread_block().expect("block SIGTSTP");
reexec_as("BlockedSigtstp");
}
"BlockedSigtstp" => own_group(),
"OwnSession" => {
nix::unistd::setsid().expect("setsid");
}
other => panic!("unknown {KIND_ENV} {other:?}"),
}
let blocked = nix::sys::signal::SigSet::thread_get_mask().expect("read the signal mask");
let blocked: libc::sigset_t = *blocked.as_ref();
let pgrp = unsafe { libc::getpgrp() };
let (mut caught, mut ignored) = (0u32, 0u32);
for signal in (1..32).filter(|&s| s != libc::SIGKILL && s != libc::SIGSTOP) {
let mut old: libc::sigaction = unsafe { std::mem::zeroed() };
let rc = unsafe { libc::sigaction(signal, std::ptr::null(), &mut old) };
assert_eq!(rc, 0, "read the action of signal {signal}");
match old.sa_sigaction {
libc::SIG_DFL => {}
libc::SIG_IGN => ignored |= 1 << (signal - 1),
_ => caught |= 1 << (signal - 1),
}
}
let line = format!("\n{TRACEE_READY} blocked={blocked} pgrp={pgrp} caught={caught} ignored={ignored}\n");
let mut out = std::io::stdout().lock();
out.write_all(line.as_bytes())
.and_then(|()| out.flush())
.expect("report readiness");
let null = std::fs::File::options()
.write(true)
.open("/dev/null")
.expect("open /dev/null");
nix::unistd::dup2_stdout(&null).expect("point stdout at /dev/null");
drop(out);
let _ = sys::read_byte(0);
}
fn reexec_as(kind: &str) -> ! {
use std::os::unix::ffi::OsStrExt as _;
let c = |bytes: &[u8]| std::ffi::CString::new(bytes).expect("no NUL in argv or the environment");
let exe = c(std::env::current_exe().expect("current_exe").as_os_str().as_bytes());
let argv: Vec<_> = std::env::args_os().map(|arg| c(arg.as_bytes())).collect();
let env: Vec<_> = std::env::vars_os()
.filter(|(key, _)| key != KIND_ENV)
.map(|(key, value)| c(&[key.as_bytes(), b"=", value.as_bytes()].concat()))
.chain([c(format!("{KIND_ENV}={kind}").as_bytes())])
.collect();
let e = nix::unistd::execve(&exe, &argv, &env).unwrap_err();
panic!("re-execute the tracee fixture: {e}")
}
#[skuld::test]
fn uh_helper_entry() {
if std::env::var(ROLE_ENV).as_deref() != Ok("helper") {
return;
}
machine::main();
}
#[cfg(test)]
#[path = "tracer_tests.rs"]
mod tracer_tests;