use std::io;
use std::os::fd::{AsFd, BorrowedFd};
use std::sync::atomic::{AtomicBool, AtomicI32, Ordering};
use std::sync::OnceLock;
use mach2::message::audit_token_t;
use super::{Exit, OsProcess, WaitFor, EXIT_CONSEQUENCE, OPEN_CONSEQUENCE};
use crate::error::{io_context, Error};
use crate::identity::{has_exited, uniq_info, Existence, ProcessId, ReadPurpose, UniqInfo, UniqRead};
use crate::signal::{Sent, Sig};
use kqueue::{Kqueue, Subscription};
pub(crate) mod child;
pub(crate) mod kqueue;
extern "C" {
fn proc_signal_with_audittoken(audittoken: *mut audit_token_t, sig: libc::c_int) -> libc::c_int;
}
#[derive(Debug)]
pub(crate) struct MacProcess {
id: ProcessId,
unique: u64,
idversion: AtomicI32,
watch: OnceLock<ExitWatch>,
}
impl MacProcess {
pub(crate) fn open(id: ProcessId) -> Result<Option<Self>, Error> {
let pid = id.pid();
let Some(read) = read_for_open(pid, OPEN_CONSEQUENCE)? else {
return Ok(None);
};
match id.exists() {
Existence::Present => {}
Existence::Gone => return Ok(None),
Existence::Unknown => {
return Err(Error::Unassessable {
detail: format!("pid {pid} identity could not be confirmed; {OPEN_CONSEQUENCE}"),
source: None,
});
}
}
Ok(Some(Self {
id,
unique: read.unique_id,
idversion: AtomicI32::new(read.id_version),
watch: OnceLock::new(),
}))
}
fn arm(&self) -> Result<ExitWatch, Error> {
let pid = self.id.pid();
let watch = ExitWatch::proc_exit(pid)?;
Ok(match read_for_open(pid, EXIT_CONSEQUENCE)? {
Some(now) if now.unique_id == self.unique => watch,
Some(_) | None => watch.exited_now(),
})
}
}
pub(crate) fn read_for_open(pid: u32, consequence: &str) -> Result<Option<UniqInfo>, Error> {
match uniq_info(pid, ReadPurpose::Open) {
UniqRead::Found(info) => Ok(Some(info)),
UniqRead::Gone => Ok(None),
UniqRead::Refused(errno) => Err(Error::Unassessable {
detail: format!("pid {pid} identity could not be read; {consequence}"),
source: Some(Error::io_cause(std::io::Error::from_raw_os_error(errno))),
}),
}
}
fn audit_token(pid: u32, id_version: i32) -> audit_token_t {
let mut token = audit_token_t::default();
token.val[5] = pid;
token.val[7] = id_version as u32;
token
}
fn send_with_token(pid: u32, id_version: i32, sig: Sig) -> Result<(), i32> {
#[cfg(test)]
let seam = crate::signal::seams::kills_refused();
#[cfg(not(test))]
let seam: Option<i32> = None;
let sent = match seam {
Some(errno) => Err(errno),
None => {
let mut token = audit_token(pid, id_version);
match unsafe { proc_signal_with_audittoken(&mut token, sig.as_libc()) } {
0 => Ok(()),
errno => Err(errno),
}
}
};
#[cfg(test)]
crate::send_log::record_by_identity(pid, sig.as_libc());
sent
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SignalByTokenOutcome {
Delivered,
ExitedUnreaped,
Gone,
}
pub(crate) fn read_version(pid: u32, unique: u64, sig: Sig) -> io::Result<Option<i32>> {
match uniq_info(pid, ReadPurpose::Kill) {
UniqRead::Found(now) if now.unique_id == unique => Ok(Some(now.id_version)),
UniqRead::Found(_) | UniqRead::Gone => Ok(None),
UniqRead::Refused(errno) => Err(io_context(
format!("pid {pid}: its identity could not be read; {sig:?} not sent"),
io::Error::from_raw_os_error(errno),
)),
}
}
pub(crate) fn signal_by_token(
pid: u32,
unique: u64,
idversion: &mut i32,
sig: Sig,
) -> io::Result<SignalByTokenOutcome> {
loop {
match send_with_token(pid, *idversion, sig) {
Ok(()) => return Ok(SignalByTokenOutcome::Delivered),
Err(libc::ESRCH) => {}
Err(errno) => return Err(io::Error::from_raw_os_error(errno)),
}
match read_version(pid, unique, sig)? {
Some(now) if now == *idversion => {
log::debug!("{sig:?} to pid {pid}: it has exited and is not reaped yet");
return Ok(SignalByTokenOutcome::ExitedUnreaped);
}
Some(now) => *idversion = now,
None => {
log::debug!("{sig:?} to pid {pid}: it is gone, or its pid names another process");
return Ok(SignalByTokenOutcome::Gone);
}
}
}
}
impl OsProcess for MacProcess {
fn signal(&self, sig: Sig) -> Result<Sent, Error> {
let pid = self.id.pid();
if crate::identity::probe::signal_target(pid).is_none() {
return Err(Error::Unassessable {
detail: format!("pid {pid} is not a signalable single-process target"),
source: None,
});
}
let mut idversion = self.idversion.load(Ordering::Relaxed);
let outcome = signal_by_token(pid, self.unique, &mut idversion, sig);
self.idversion.store(idversion, Ordering::Relaxed);
match outcome.map_err(Error::Io)? {
SignalByTokenOutcome::Delivered => Ok(Sent::Delivered),
SignalByTokenOutcome::ExitedUnreaped | SignalByTokenOutcome::Gone => Ok(Sent::Gone),
}
}
fn exited(&self) -> Result<Exit<'_>, Error> {
let watch = match self.watch.get() {
Some(watch) => watch,
None => {
let armed = self.arm()?;
self.watch.get_or_init(|| armed)
}
};
watch.look(self.id.pid(), self.unique)
}
}
pub(crate) fn exit_read_refused(pid: u32, errno: i32, situation: &str) -> Error {
Error::Unassessable {
detail: format!("pid {pid}: {situation}"),
source: Some(Error::io_cause(io::Error::from_raw_os_error(errno))),
}
}
#[derive(Debug)]
pub(crate) struct ExitWatch {
kq: Kqueue,
exited: bool,
confirmed: AtomicBool,
}
impl ExitWatch {
pub(super) fn new(kq: Kqueue) -> Self {
Self {
kq,
exited: false,
confirmed: AtomicBool::new(false),
}
}
fn exited_now(mut self) -> Self {
self.exited = true;
self
}
pub(crate) fn proc_exit(pid: u32) -> Result<Self, Error> {
let kq = Kqueue::new()?;
let exit = Subscription::Process {
pid,
signals: false,
reap: false,
};
#[cfg(test)]
let forced = kqueue::test_hooks::take_forced_esrch_registration(kqueue::test_hooks::Registration::ExitWatch);
#[cfg(not(test))]
let forced = false;
let subscribed = if forced {
Err(Error::Io(io::Error::from_raw_os_error(libc::ESRCH)))
} else {
kq.subscribe(exit)
};
match subscribed {
Ok(()) => Ok(Self::new(kq)),
Err(e) if crate::error::first_os_code(&e) == Some(libc::ESRCH) => Ok(Self::new(kq).exited_now()),
Err(e) => Err(e),
}
}
pub(crate) fn exited(&self) -> Result<bool, Error> {
if self.exited {
return Ok(true);
}
crate::os_process::poll::is_readable(self.kq.as_fd()).map_err(Error::Io)
}
pub(crate) fn look(&self, pid: u32, unique: u64) -> Result<Exit<'_>, Error> {
if self.confirmed.load(Ordering::Relaxed) {
return Ok(Exit::Exited);
}
if !self.exited()? {
return Ok(Exit::Running(WaitFor::Readable(self.as_fd())));
}
match has_exited(pid, unique, ReadPurpose::Exit) {
Ok(true) => {
self.confirmed.store(true, Ordering::Relaxed);
Ok(Exit::Exited)
}
Ok(false) => Ok(Exit::Recheck),
Err(errno) => Err(exit_read_refused(
pid,
errno,
"its exit watch fired, but whether it has exited could not be read",
)),
}
}
pub(crate) fn as_fd(&self) -> BorrowedFd<'_> {
self.kq.as_fd()
}
}
#[cfg(test)]
#[path = "macos_tests.rs"]
mod macos_tests;