use std::io;
use std::os::fd::{AsFd, BorrowedFd};
use std::sync::atomic::{AtomicI32, Ordering};
use mach2::message::audit_token_t;
use super::{Exit, OsProcess, WaitFor, OPEN_CONSEQUENCE};
use crate::error::{io_context, Error};
use crate::identity::{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: ExitWatch,
}
impl MacProcess {
pub(crate) fn open(id: ProcessId) -> Result<Option<Self>, Error> {
let pid = id.pid();
let read = || read_for_open(pid, "wait", OPEN_CONSEQUENCE);
let Some(first) = read()? else {
return Ok(None);
};
match id.exists() {
Existence::Present => {}
Existence::Gone => return Ok(None),
Existence::Unknown => {
log::warn!("wait: pid {pid} identity could not be confirmed; {OPEN_CONSEQUENCE}");
return Err(Error::Unassessable {
detail: format!("pid {pid} identity could not be confirmed; {OPEN_CONSEQUENCE}"),
source: None,
});
}
}
let watch = ExitWatch::proc_exit(pid)?;
let Some(second) = read()?.filter(|second| second.unique_id == first.unique_id) else {
return Ok(None);
};
Ok(Some(Self {
id,
unique: second.unique_id,
idversion: AtomicI32::new(second.id_version),
watch,
}))
}
}
pub(crate) fn read_for_open(pid: u32, caller: &str, 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) => {
log::warn!("{caller}: pid {pid} identity could not be read (errno {errno}); {consequence}");
Err(Error::Unassessable {
detail: format!("pid {pid} identity could not be read (errno {errno}); {consequence}"),
source: Some(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() {
log::warn!("wait: pid {pid} is not a single-process signal target - not signaled");
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 = &self.watch;
if watch.exited()? {
Ok(Exit::Exited)
} else {
Ok(Exit::Running(WaitFor::Readable(watch.as_fd())))
}
}
}
#[derive(Debug)]
pub(crate) struct ExitWatch {
kq: Kqueue,
exited: bool,
}
impl ExitWatch {
pub(super) fn new(kq: Kqueue) -> Self {
Self { kq, exited: false }
}
pub(crate) fn proc_exit(pid: u32) -> Result<Self, Error> {
let kq = Kqueue::new()?;
let exit = Subscription::Process {
pid,
signals: false,
reap: false,
};
match kq.subscribe(exit) {
Ok(()) => Ok(Self::new(kq)),
Err(e) if e.raw_os_error() == Some(libc::ESRCH) => Ok(Self { kq, exited: true }),
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 as_fd(&self) -> BorrowedFd<'_> {
self.kq.as_fd()
}
}
#[cfg(test)]
#[path = "macos_tests.rs"]
mod macos_tests;