use std::time::Duration;
use nix::sys::event::{EvFlags, EventFilter, FilterFlag, KEvent};
use super::sys::{self, Stop};
use super::{Mode, Until};
use crate::os_process::macos::kqueue::{Event, Kqueue};
const FIRST_BACKOFF: Duration = Duration::from_millis(1);
const MAX_BACKOFF: Duration = Duration::from_millis(50);
pub(super) const MALFORMED_PID_LINE: i32 = 3;
pub(super) fn main() {
let marker = std::env::var("COSCA_UH_MARKER").expect("COSCA_UH_MARKER is set by the client");
let mode = match std::env::var("COSCA_UH_MODE").as_deref() {
Ok("auto") => Mode::Auto,
Ok("hold") => Mode::Hold,
other => panic!("COSCA_UH_MODE must be auto or hold, got {other:?}"),
};
let trace = std::env::var("COSCA_UH_TRACE").as_deref() == Ok("1");
let mut forces = Forces::parse(&std::env::var("COSCA_UH_FORCE").unwrap_or_default());
let note_exit_seen = match forces.take("seed").as_deref() {
None => false,
Some("NOTE_EXIT") => true,
Some(other) => panic!("seed takes only NOTE_EXIT, got {other:?}"),
};
match read_pid_line() {
PidLine::Pid(pid) => Machine {
pid,
mode,
marker,
trace,
forces: &mut forces,
note_exit_seen,
kept: None,
blocked: None,
eof_seen: false,
signal_pipe: SignalPipe::default(),
}
.run(),
PidLine::Eof => {}
PidLine::Malformed(line) => {
use std::io::Write as _;
let message = format!(
"tracer helper: malformed pid line {:?}\n",
String::from_utf8_lossy(&line)
);
std::io::stderr()
.lock()
.write_all(message.as_bytes())
.unwrap_or_default();
std::process::exit(MALFORMED_PID_LINE);
}
}
assert!(
forces.0.is_empty(),
"the run never used these COSCA_UH_FORCE entries: {:?}",
forces.0
);
}
enum PidLine {
Pid(u32),
Eof,
Malformed(Vec<u8>),
}
fn read_pid_line() -> PidLine {
let mut line = Vec::new();
loop {
match sys::read_byte(0) {
None if line.is_empty() => return PidLine::Eof,
None => return PidLine::Malformed(line),
Some(b'\n') => break,
Some(byte) => line.push(byte),
}
}
let pid = std::str::from_utf8(&line)
.ok()
.and_then(|line| line.strip_prefix("pid "))
.and_then(|pid| pid.parse::<libc::pid_t>().ok())
.filter(|&pid| pid > 0);
match pid {
Some(pid) => PidLine::Pid(pid as u32),
None => PidLine::Malformed(line),
}
}
struct Forces(Vec<(String, String)>);
const FORCE_TAGS: &[&str] = &[
"seed",
"gone",
"S0",
"S1",
"S1h",
"S1hstop",
"S2",
"S2b",
"S2stop",
"S2cont",
"S3",
"S3stop",
"S3cont",
"S3x",
"S4",
"S4b",
"S4stop",
"S4cont",
"S4sigstop",
"S4r",
"S5",
"S6",
];
impl Forces {
fn parse(raw: &str) -> Forces {
Forces(
raw.split(',')
.filter(|entry| !entry.is_empty())
.map(|entry| {
let (tag, directive) = entry
.split_once(':')
.unwrap_or_else(|| panic!("COSCA_UH_FORCE entry {entry:?} is not <tag>:<directive>"));
assert!(
FORCE_TAGS.contains(&tag),
"COSCA_UH_FORCE entry {entry:?} has an unknown tag; known: {FORCE_TAGS:?}"
);
(tag.to_string(), directive.to_string())
})
.collect(),
)
}
fn take(&mut self, tag: &str) -> Option<String> {
let at = self.0.iter().position(|(t, _)| t == tag)?;
Some(self.0.remove(at).1)
}
fn take_exact(&mut self, tag: &str, directive: &str) -> bool {
let Some(at) = self.0.iter().position(|(t, d)| t == tag && d == directive) else {
return false;
};
self.0.remove(at);
true
}
fn stop(&mut self, tag: &str) -> Option<Result<Stop, i32>> {
self.take(tag).map(|directive| match directive.as_str() {
"none" => Ok(Stop::Running),
"settling" => Ok(Stop::Settling),
"SIGTERM" => Ok(Stop::Stopped(libc::SIGTERM)),
"SIGTSTP" => Ok(Stop::Stopped(libc::SIGTSTP)),
name => Err(errno_named(name)),
})
}
fn result(&mut self, tag: &str) -> Option<Result<(), i32>> {
self.take(tag).map(|directive| match directive.as_str() {
"ok" => Ok(()),
name => Err(errno_named(name)),
})
}
}
fn errno_named(name: &str) -> i32 {
match name {
"EPERM" => libc::EPERM,
"ESRCH" => libc::ESRCH,
"EINTR" => libc::EINTR,
"ECHILD" => libc::ECHILD,
"EBUSY" => libc::EBUSY,
"EINVAL" => libc::EINVAL,
number => number
.parse()
.unwrap_or_else(|_| panic!("COSCA_UH_FORCE: unknown errno {number:?}")),
}
}
fn is_stop_signal(signal: i32) -> bool {
matches!(signal, libc::SIGSTOP | libc::SIGTSTP | libc::SIGTTIN | libc::SIGTTOU)
}
#[derive(Default)]
struct Batch {
note_exit: bool,
signal: bool,
eof: bool,
sigchld: bool,
}
impl Batch {
fn any(&self) -> bool {
self.note_exit || self.signal || self.eof
}
fn cause(&self) -> &'static str {
debug_assert!(self.any(), "cause() of a batch with no event");
match (self.note_exit, self.signal, self.eof) {
(true, _, _) => "NOTE_EXIT",
(false, true, _) => "SIGNAL",
(false, false, true) => "EOF",
(false, false, false) => unreachable!("cause() of a batch with no event"),
}
}
}
#[derive(Clone, Copy)]
enum State {
S0,
S1,
S1h,
S2,
S3,
S3x {
release: bool,
},
S4,
S5,
S6,
}
enum Next {
To(State),
Exit,
}
struct Gone;
enum Check {
Result(Result<(), i32>),
PeekFailed(i32),
}
type Step = Result<Next, Gone>;
fn to(state: State) -> Step {
Ok(Next::To(state))
}
const EXIT: Step = Ok(Next::Exit);
struct Machine<'f> {
pid: u32,
mode: Mode,
marker: String,
trace: bool,
forces: &'f mut Forces,
note_exit_seen: bool,
kept: Option<i32>,
blocked: Option<String>,
eof_seen: bool,
signal_pipe: SignalPipe,
}
impl Machine<'_> {
fn run(mut self) {
let kq = Kqueue::new().expect("create the helper's kqueue");
let mut state = State::S0;
while let Ok(Next::To(next)) = self.step(&kq, state) {
state = next;
}
self.done();
}
fn done(&mut self) {
loop {
if self.block("done", Until::Eof).is_err() || sys::read_byte(0).is_none() || self.enter("done").is_err() {
return;
}
}
}
fn step(&mut self, kq: &Kqueue, state: State) -> Step {
match state {
State::S0 => self.s0(kq),
State::S1 => self.s1(),
State::S1h => self.s1h(kq),
State::S2 => self.s2(kq),
State::S3 => self.s3(kq),
State::S3x { release } => self.s3x(kq, release),
State::S4 => self.s4(kq),
State::S5 => self.s5(),
State::S6 => self.s6(kq),
}
}
fn s0(&mut self, kq: &Kqueue) -> Step {
self.enter("S0")?;
let registered = match self.forces.result("S0") {
Some(forced) => forced,
None => sys::watch_signal_pipe(kq)
.and_then(|()| sys::watch_sigchld(kq))
.and_then(|()| sys::watch_exit(kq, self.pid)),
};
match registered {
Ok(()) => to(State::S1),
Err(e) => self.fail(e, "S0"),
}
}
fn s1(&mut self) -> Step {
self.enter("S1")?;
let hold = match self.forces.take("S1").as_deref() {
None => false,
Some("hold") => true,
Some(name) => return self.fail(errno_named(name), "S1"),
};
match sys::attach(self.pid) {
Ok(()) if hold => to(State::S1h),
Ok(()) => to(State::S2),
Err(e) => self.fail(e, "S1"),
}
}
fn s1h(&mut self, kq: &Kqueue) -> Step {
self.enter("S1h")?;
let mut backoff = Some(FIRST_BACKOFF);
loop {
let batch = self.wait(kq, "S1h", backoff)?;
if batch.note_exit {
return to(State::S5);
}
if batch.eof {
return EXIT;
}
if batch.signal {
return to(State::S2);
}
let Some(current) = backoff else {
continue;
};
match self.forces.stop("S1hstop").unwrap_or_else(|| sys::stop(self.pid)) {
Ok(Stop::Stopped(_)) => {
self.enter("S1hs")?;
backoff = None;
}
Ok(Stop::Running | Stop::Settling) => backoff = Some(next_backoff(current)),
Err(e) => return self.fail(e, "S1h"),
}
}
}
fn s2(&mut self, kq: &Kqueue) -> Step {
self.enter("S2")?;
let mut backoff = FIRST_BACKOFF;
loop {
let result = match self.forces.result("S2") {
Some(forced) => forced,
None => match self.act_once_stopped("S2", sys::resume)? {
Check::Result(result) => result,
Check::PeekFailed(e) => return self.fail(e, "S2"),
},
};
match result {
Ok(()) => return self.report_then("attached", to(State::S3)),
Err(libc::EBUSY) => {
self.enter("S2b")?;
let batch = self.wait(kq, "S2b", Some(backoff))?;
if batch.any() {
return self.fail(batch.cause(), "S2b");
}
backoff = next_backoff(backoff);
}
Err(e) => return self.fail(e, "S2"),
}
}
}
fn s3(&mut self, kq: &Kqueue) -> Step {
self.enter("S3")?;
let mut settling = None;
let batch = loop {
let batch = self.wait_with(kq, "S3", settling, true)?;
if batch.sigchld || settling.is_some() {
let stop = self.forces.stop("S3stop").unwrap_or_else(|| sys::stop(self.pid));
let previous = settling.take();
match stop {
Ok(Stop::Stopped(signal)) => match self.pass_on("S3", signal)? {
Ok(()) | Err(libc::ESRCH) => {}
Err(e) => return self.fail(e, "S3"),
},
Ok(Stop::Settling) => settling = Some(previous.map_or(FIRST_BACKOFF, next_backoff)),
Ok(Stop::Running) => {}
Err(e) => return self.fail(e, "S3"),
}
}
if batch.any() {
break batch;
}
};
let release = batch.signal || batch.eof;
match (self.mode, batch.note_exit) {
(Mode::Auto, true) => to(State::S5),
(Mode::Hold, true) => {
self.block("S3", Until::Exit)?;
match sys::await_zombie(self.pid) {
Ok(()) => self.report_then("exited", to(State::S3x { release })),
Err(e) => self.fail(e, "S3"),
}
}
(_, false) => to(State::S4),
}
}
fn s3x(&mut self, kq: &Kqueue, release: bool) -> Step {
self.enter("S3x")?;
if release {
return to(State::S5);
}
let batch = self.wait(kq, "S3x", None)?;
if batch.note_exit {
return self.fail("NOTE_EXIT", "S3x");
}
to(State::S5)
}
fn s4(&mut self, kq: &Kqueue) -> Step {
self.enter("S4")?;
let mut forced = self.forces.result("S4");
let stopped = match self.forces.take("S4sigstop").as_deref() {
None if forced.is_none() => sys::kill(self.pid, libc::SIGSTOP),
None | Some("0") => Ok(()),
Some("1") => sys::kill(self.pid, libc::SIGSTOP),
Some(name) => Err(errno_named(name)),
};
match stopped {
Ok(()) => {}
Err(libc::ESRCH) => return self.exiting(),
Err(e) => return self.fail(e, "S4"),
}
let mut backoff = FIRST_BACKOFF;
loop {
let result = match forced.take() {
Some(forced) => forced,
None => match self.act_once_stopped("S4", sys::detach)? {
Check::Result(result) => result,
Check::PeekFailed(e) => return self.fail(e, "S4"),
},
};
match result {
Ok(()) => return self.detached(),
Err(libc::ESRCH) => return self.exiting(),
Err(libc::EBUSY) => {
self.enter("S4b")?;
if self.wait(kq, "S4b", Some(backoff))?.note_exit {
return to(State::S5);
}
backoff = next_backoff(backoff);
forced = self.forces.result("S4");
}
Err(e) => return self.fail(e, "S4"),
}
}
}
fn detached(&mut self) -> Step {
if let Some(signal) = self.kept.take() {
let sent = self.forces.result("S4r").unwrap_or_else(|| sys::kill(self.pid, signal));
if let Err(e) = sent {
return self.fail(e, "S4");
}
self.enter("S4r")?;
}
self.report_then("detached", EXIT)
}
fn act_once_stopped(&mut self, tag: &str, act: fn(u32) -> Result<(), i32>) -> Result<Check, Gone> {
let stop = self
.forces
.stop(&format!("{tag}stop"))
.unwrap_or_else(|| sys::stop(self.pid));
Ok(match stop {
Err(e) => Check::PeekFailed(e),
Ok(Stop::Stopped(libc::SIGSTOP)) => Check::Result(act(self.pid)),
Ok(Stop::Stopped(signal)) => match self.pass_on(tag, signal)? {
Ok(()) => Check::Result(Err(libc::EBUSY)),
Err(e) => Check::Result(Err(e)),
},
Ok(Stop::Running | Stop::Settling) => Check::Result(Err(libc::EBUSY)),
})
}
fn pass_on(&mut self, tag: &str, signal: i32) -> Result<Result<(), i32>, Gone> {
let keep = is_stop_signal(signal);
let delivered = if keep { 0 } else { signal };
let result = self
.forces
.result(&format!("{tag}cont"))
.unwrap_or_else(|| sys::cont(self.pid, delivered));
if result.is_ok() {
if keep {
self.kept.get_or_insert(signal);
} else if signal == libc::SIGCONT {
self.kept = None;
}
self.enter(&format!("{tag}{}", if keep { "k" } else { "s" }))?;
}
Ok(result)
}
fn exiting(&self) -> Step {
to(if self.note_exit_seen { State::S5 } else { State::S6 })
}
fn s5(&mut self) -> Step {
self.enter("S5")?;
let mut result = self.forces.result("S5");
loop {
let reaped = match result.take() {
Some(forced) => forced,
None => {
self.block("S5", Until::Exit)?;
sys::reap(self.pid)
}
};
match reaped {
Ok(()) => return self.report_then("reaped", EXIT),
Err(libc::EINTR) => {}
Err(e) => return self.fail(e, "S5"),
}
}
}
fn s6(&mut self, kq: &Kqueue) -> Step {
self.enter("S6")?;
if self.wait(kq, "S6", None)?.note_exit {
to(State::S5)
} else {
to(State::S6)
}
}
fn wait(&mut self, kq: &Kqueue, tag: &str, timeout: Option<Duration>) -> Result<Batch, Gone> {
self.wait_with(kq, tag, timeout, false)
}
fn wait_with(&mut self, kq: &Kqueue, tag: &str, timeout: Option<Duration>, sigchld: bool) -> Result<Batch, Gone> {
loop {
let mut batch = match self.forces.take(tag) {
Some(directive) => injected(tag, &directive),
None => {
if timeout.is_none() {
let until = if tag == "S6" { Until::Exit } else { Until::Eof };
debug_assert!(
until == Until::Exit || !self.eof_seen,
"{tag} waits for an EOF that already came"
);
self.block(tag, until)?;
}
real_round(kq, &mut self.signal_pipe, timeout)
}
};
self.note_exit_seen |= batch.note_exit;
self.eof_seen |= batch.eof;
batch.sigchld &= sigchld;
if batch.any() || batch.sigchld || timeout.is_some() {
return Ok(batch);
}
}
}
fn enter(&mut self, state: &str) -> Result<(), Gone> {
if self.trace {
self.report(&format!("state {state}"))?;
}
Ok(())
}
fn block(&mut self, state: &str, until: Until) -> Result<(), Gone> {
let text = format!(
"blocking {state} {}",
match until {
Until::Eof => "eof",
Until::Exit => "exit",
}
);
if self.blocked.as_deref() != Some(text.as_str()) {
self.report(&text)?;
self.blocked = Some(text);
}
Ok(())
}
fn report(&mut self, text: &str) -> Result<(), Gone> {
self.blocked = None;
if !self.forces.take_exact("gone", text) && write_report(&self.marker, text) {
Ok(())
} else {
Err(Gone)
}
}
fn report_then(&mut self, text: &str, next: Step) -> Step {
self.report(text)?;
next
}
fn fail(&mut self, cause: impl std::fmt::Display, state: &str) -> Step {
self.report_then(&format!("error {cause} {state}"), EXIT)
}
}
fn injected(tag: &str, directive: &str) -> Batch {
let mut batch = Batch::default();
for event in directive.split('+') {
match event {
"NOTE_EXIT" => batch.note_exit = true,
"SIGNAL" => batch.signal = true,
"EOF" => batch.eof = true,
"SIGCHLD" => batch.sigchld = true,
other => panic!("{tag} takes NOTE_EXIT, SIGCHLD, SIGNAL or EOF, got {other:?}"),
}
}
batch
}
#[derive(Default)]
struct SignalPipe {
buffered: usize,
closed: bool,
}
enum Taken {
Nothing,
Byte,
Eof,
}
impl SignalPipe {
fn note(&mut self, buffered: usize, closed: bool) {
self.buffered = buffered;
self.closed |= closed;
}
fn pending(&self) -> bool {
self.buffered > 0 || self.closed
}
fn take(&mut self) -> Taken {
if self.buffered > 0 {
return match sys::read_byte(0) {
Some(_) => {
self.buffered -= 1;
Taken::Byte
}
None => self.eof(),
};
}
if self.closed {
return self.eof();
}
Taken::Nothing
}
fn eof(&mut self) -> Taken {
*self = SignalPipe::default();
Taken::Eof
}
}
fn real_round(kq: &Kqueue, pipe: &mut SignalPipe, timeout: Option<Duration>) -> Batch {
let timeout = if pipe.pending() { Some(Duration::ZERO) } else { timeout };
let timeout = timeout.map(crate::os_process::macos::kqueue::kevent_timeout);
let blank = || KEvent::new(0, EventFilter::EVFILT_PROC, EvFlags::empty(), FilterFlag::empty(), 0, 0);
let mut events = [blank(), blank(), blank()];
let n = loop {
match kq.native().kevent(&[], &mut events, timeout) {
Ok(n) => break n,
Err(nix::errno::Errno::EINTR) => continue,
Err(e) => panic!("kevent failed: {e}"),
}
};
let mut batch = Batch::default();
for raw in &events[..n] {
match Event::from_kevent(raw) {
Some(Event::Process { .. }) => batch.note_exit = true,
Some(Event::Signal { .. }) => batch.sigchld = true,
Some(Event::Readable { bytes, closed, .. }) => pipe.note(bytes, closed),
None => panic!("kevent returned an event of an unregistered filter: {:?}", raw.filter()),
}
}
match pipe.take() {
Taken::Nothing => {}
Taken::Byte => batch.signal = true,
Taken::Eof => {
sys::unwatch_signal_pipe(kq);
batch.eof = true;
}
}
batch
}
fn next_backoff(current: Duration) -> Duration {
(current * 2).min(MAX_BACKOFF)
}
#[must_use]
fn write_report(marker: &str, text: &str) -> bool {
use std::io::Write as _;
let line = format!("\n{marker} {text}\n");
let mut out = std::io::stdout().lock();
out.write_all(line.as_bytes()).and_then(|()| out.flush()).is_ok()
}
#[cfg(test)]
#[path = "machine_tests.rs"]
mod machine_tests;