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 e.raw_os_error() == 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 e.raw_os_error() != Some(libc::ENOENT) => Err(WalkError::Watch(e.into_io())),
_ => Ok(()),
}
}
fn refused(pid: u32, errno: i32) -> WalkError {
WalkError::Identity(std::io::Error::new(
std::io::Error::from_raw_os_error(errno).kind(),
format!("tracer {pid}: its identity could not be read (errno {errno})"),
))
}
fn arm(kq: &Kqueue, pid: u32) -> Result<(), crate::error::Error> {
#[cfg(test)]
if let Some(errno) = seams::take_refused_registration() {
return Err(crate::error::Error::Io(std::io::Error::from_raw_os_error(errno)));
}
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()) };
static REFUSED_REGISTRATION: std::cell::Cell<Option<i32>> = const { std::cell::Cell::new(None) };
}
#[cfg(feature = "tokio")]
pub(crate) fn refuse_next_registration(errno: i32) -> RefusedRegistration {
REFUSED_REGISTRATION.with(|r| r.set(Some(errno)));
RefusedRegistration(())
}
#[cfg(feature = "tokio")]
#[must_use = "the refusal is cleared as soon as the guard is dropped"]
pub(crate) struct RefusedRegistration(());
#[cfg(feature = "tokio")]
impl Drop for RefusedRegistration {
fn drop(&mut self) {
REFUSED_REGISTRATION.with(|r| r.set(None));
}
}
pub(super) fn take_refused_registration() -> Option<i32> {
REFUSED_REGISTRATION.with(std::cell::Cell::take)
}
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;