use std::time::Duration;
use crate::identity::{link, Kernel, Link, UniqRead, LAUNCHD};
use crate::os_process::macos::kqueue::{Event, Kqueue, Subscription};
const GONE_START: Duration = Duration::from_millis(1);
const GONE_CAP: Duration = Duration::from_millis(50);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum OnTracer {
Block,
Recheck(Duration),
}
#[derive(Debug)]
pub(crate) enum WalkError {
Identity(std::io::Error),
Watch(std::io::Error),
}
impl From<WalkError> for std::io::Error {
fn from(e: WalkError) -> std::io::Error {
match e {
WalkError::Identity(e) | WalkError::Watch(e) => e,
}
}
}
#[derive(Debug, Default)]
pub(crate) struct TracerWatch {
armed: Vec<(u32, u64)>,
gone: Option<Duration>,
}
impl TracerWatch {
pub(crate) fn held_by(&mut self, kernel: &dyn Kernel, kq: &Kqueue, tracer: u32) -> Result<OnTracer, WalkError> {
let me = std::process::id();
let mut walked = Vec::new();
let mut fresh = false;
let mut at = tracer;
while !walked.contains(&at) {
walked.push(at);
let (unique, parent, at_attach) = match link(kernel, at) {
Link::Found {
unique,
parent,
at_attach,
} => (unique, parent, at_attach),
Link::Gone => {
self.disarm(kq, at)?;
return Ok(self.gone());
}
Link::Refused(errno) => return Err(refused(at, errno)),
Link::Unreadable => {
return Err(WalkError::Identity(std::io::Error::other(format!(
"tracer {at}: who holds it could not be read (kinfo_proc refused)"
))))
}
};
if !self.armed.contains(&(at, unique)) {
self.disarm(kq, at)?;
match kernel.subscribe(kq, watched(at)) {
Ok(()) => {}
Err(e) if crate::error::first_os_code(&e) == Some(libc::ESRCH) => return Ok(self.gone()),
Err(e) => return Err(WalkError::Watch(e)),
}
match kernel.unique_info(at) {
UniqRead::Found(info) if info.unique_id == unique => {}
UniqRead::Found(_) | UniqRead::Gone => {
delete(kq, at)?;
return Ok(self.gone());
}
UniqRead::Refused(errno) => return Err(refused(at, errno)),
}
self.armed.push((at, unique));
fresh = true;
}
if at_attach == 0 || parent == me {
break;
}
if parent == LAUNCHD {
return Ok(self.gone());
}
at = parent;
}
self.gone = None;
Ok(if fresh {
OnTracer::Recheck(Duration::ZERO)
} else {
OnTracer::Block
})
}
fn disarm(&mut self, kq: &Kqueue, pid: u32) -> Result<(), WalkError> {
if self.armed.iter().any(|&(armed, _)| armed == pid) {
delete(kq, pid)?;
self.armed.retain(|&(armed, _)| armed != pid);
}
Ok(())
}
fn gone(&mut self) -> OnTracer {
let wait = self
.gone
.map_or(Duration::ZERO, |wait| (wait * 2).clamp(GONE_START, GONE_CAP));
self.gone = Some(wait);
OnTracer::Recheck(wait)
}
pub(crate) fn fired(&mut self, event: &Event, child: u32) -> bool {
let &Event::Process { pid, exited, .. } = event else {
return false;
};
let fired = pid != child;
if fired && exited {
self.armed.retain(|&(armed, _)| armed != pid);
}
fired
}
}
fn watched(pid: u32) -> Subscription {
Subscription::Process {
pid,
signals: true,
reap: false,
}
}
fn delete(kq: &Kqueue, pid: u32) -> Result<(), WalkError> {
match kq.unsubscribe(watched(pid)) {
Err(e) if crate::error::first_os_code(&e) != Some(libc::ENOENT) => Err(WalkError::Watch(e.into_io())),
_ => Ok(()),
}
}
fn refused(pid: u32, errno: i32) -> WalkError {
WalkError::Identity(crate::error::io_context(
format!("tracer {pid}: its identity could not be read"),
std::io::Error::from_raw_os_error(errno),
))
}
#[cfg(test)]
#[path = "tracer_watch_tests.rs"]
mod tracer_watch_tests;