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::kinfo::ExitState;
use crate::identity::{exit_state_of, has_exited, Existence, Kernel, ProcessId, Resolved, 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;
}
pub(crate) struct MacosProcess<K> {
kernel: K,
id: ProcessId,
unique: u64,
idversion: AtomicI32,
watch: OnceLock<ExitWatch>,
}
impl<K> std::fmt::Debug for MacosProcess<K> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("MacosProcess")
.field("id", &self.id)
.field("unique", &self.unique)
.field("idversion", &self.idversion)
.field("watch", &self.watch)
.finish_non_exhaustive()
}
}
impl<K: Kernel + Send> MacosProcess<K> {
pub(crate) fn open(kernel: K, id: ProcessId) -> Result<Option<Self>, Error> {
let pid = id.pid();
let Some(read) = read_for_open(&kernel, pid, OPEN_CONSEQUENCE)? else {
return Ok(None);
};
match id.exists_with(&kernel).0 {
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 {
kernel,
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(&self.kernel, pid)?;
Ok(match read_for_open(&self.kernel, pid, EXIT_CONSEQUENCE)? {
Some(now) if now.unique_id == self.unique => watch,
Some(_) | None => watch.exited_now(),
})
}
}
pub(crate) fn read_for_open(kernel: &dyn Kernel, pid: u32, consequence: &str) -> Result<Option<UniqInfo>, Error> {
match kernel.unique_info(pid) {
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,
Exiting,
Gone,
}
pub(crate) fn read_version(kernel: &dyn Kernel, pid: u32, unique: u64, sig: Sig) -> io::Result<Option<i32>> {
match kernel.unique_info(pid) {
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(
kernel: &dyn Kernel,
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(libc::EPERM) => {
return match exit_state_of(kernel, pid, unique) {
Resolved::Found(ExitState::Exiting) => {
log::debug!("{sig} to pid {pid}: refused with EPERM, its exit has begun");
Ok(SignalByTokenOutcome::Exiting)
}
Resolved::Found(ExitState::Zombie) => {
log::debug!("{sig} to pid {pid}: refused with EPERM, it has exited and is not reaped yet");
Ok(SignalByTokenOutcome::ExitedUnreaped)
}
Resolved::Gone => {
log::debug!(
"{sig} to pid {pid}: refused with EPERM, and it is gone, or its pid names another process"
);
Ok(SignalByTokenOutcome::Gone)
}
Resolved::Unknown => {
log::debug!("{sig} to pid {pid}: refused with EPERM, and its exit state could not be read");
Err(io::Error::from_raw_os_error(libc::EPERM))
}
Resolved::Found(ExitState::Running) => Err(io::Error::from_raw_os_error(libc::EPERM)),
};
}
Err(errno) => return Err(io::Error::from_raw_os_error(errno)),
}
match read_version(kernel, 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<K: Kernel + Send> OsProcess for MacosProcess<K> {
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(&self.kernel, pid, self.unique, &mut idversion, sig);
self.idversion.store(idversion, Ordering::Relaxed);
match outcome.map_err(Error::Io)? {
SignalByTokenOutcome::Delivered | SignalByTokenOutcome::Exiting => 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.kernel, 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 registration(pid: u32) -> Subscription {
Subscription::Process {
pid,
signals: false,
reap: false,
}
}
pub(crate) fn proc_exit(kernel: &dyn Kernel, pid: u32) -> Result<Self, Error> {
let kq = Kqueue::new()?;
match kernel.subscribe(&kq, Self::registration(pid)) {
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(Error::Io(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, kernel: &dyn Kernel, 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(kernel, pid, unique) {
Ok(true) => {
self.confirm();
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 confirm(&self) {
self.confirmed.store(true, Ordering::Relaxed);
}
pub(crate) fn as_fd(&self) -> BorrowedFd<'_> {
self.kq.as_fd()
}
}
#[cfg(test)]
#[path = "macos_tests.rs"]
mod macos_tests;