use std::time::Duration;
#[cfg(not(test))]
use crate::identity::link;
use crate::identity::{uniq_info, Link, ReadPurpose, 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, 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(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 arm(kq, 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.into_io())),
}
match uniq_info(at, ReadPurpose::Link) {
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),
))
}
fn arm(kq: &Kqueue, pid: u32) -> Result<(), crate::error::Error> {
kq.subscribe(watched(pid))
}
#[cfg(test)]
fn link(pid: u32) -> Link {
seams::take_link().unwrap_or_else(|| crate::identity::link(pid))
}
#[cfg(test)]
pub(crate) mod seams {
use std::cell::RefCell;
use std::collections::VecDeque;
use crate::identity::Link;
thread_local! {
static LINKS: RefCell<VecDeque<Link>> = const { RefCell::new(VecDeque::new()) };
}
pub(crate) fn force_links(links: impl IntoIterator<Item = Link>) -> ForcedLinks {
LINKS.with(|l| *l.borrow_mut() = links.into_iter().collect());
ForcedLinks(())
}
#[must_use = "the reads are real again as soon as the guard is dropped"]
pub(crate) struct ForcedLinks(());
impl ForcedLinks {
pub(crate) fn left(&self) -> usize {
LINKS.with(|l| l.borrow().len())
}
pub(crate) fn then(&self, links: impl IntoIterator<Item = Link>) {
LINKS.with(|l| l.borrow_mut().extend(links));
}
}
impl Drop for ForcedLinks {
fn drop(&mut self) {
LINKS.with(|l| l.borrow_mut().clear());
}
}
pub(super) fn take_link() -> Option<Link> {
LINKS.with(|l| l.borrow_mut().pop_front())
}
}
#[cfg(test)]
#[path = "tracer_watch_tests.rs"]
mod tracer_watch_tests;