use std::time::{Duration, Instant};
use nix::sys::event::{EvFlags, EventFilter, FilterFlag, KEvent, Kqueue};
use crate::error::Error;
use crate::identity::ProcessId;
const KEVENT_MAX_SECS: u64 = i32::MAX as u64;
fn kevent_cap() -> Duration {
#[cfg(test)]
if let Some(lowered) = test_hooks::clamp_override() {
return lowered;
}
Duration::from_secs(KEVENT_MAX_SECS)
}
fn assert_kevent_timespec(ts: &libc::timespec) {
debug_assert!(
ts.tv_sec >= 0 && ts.tv_sec as u64 <= KEVENT_MAX_SECS,
"kevent tv_sec {} exceeds XNU's INT32_MAX limit",
ts.tv_sec
);
}
pub(crate) fn kevent_timeout(d: Duration) -> libc::timespec {
let d = d.min(kevent_cap());
let ts = libc::timespec {
tv_sec: d.as_secs() as libc::time_t,
tv_nsec: d.subsec_nanos() as libc::c_long,
};
assert_kevent_timespec(&ts);
ts
}
#[derive(Debug, PartialEq, Eq)]
enum ZeroReturn {
Rearm,
Anomaly,
}
fn classify_zero_return(armed: Option<Duration>) -> ZeroReturn {
if armed == Some(kevent_cap()) {
ZeroReturn::Rearm
} else {
ZeroReturn::Anomaly
}
}
fn placeholder() -> KEvent {
KEvent::new(0, EventFilter::EVFILT_PROC, EvFlags::empty(), FilterFlag::empty(), 0, 0)
}
pub(crate) fn add_with_receipt(kq: &Kqueue, change: KEvent) -> Result<i64, Error> {
let mut receipt = [placeholder()];
let n = kq
.kevent(&[change], &mut receipt, None)
.map_err(|e| Error::Io(e.into()))?;
if n != 1 {
return Err(Error::Io(std::io::Error::other(
"kqueue EV_RECEIPT returned no receipt event",
)));
}
Ok(receipt[0].data() as i64)
}
pub(crate) fn arm_note_exit_on(kq: &Kqueue, pid: u32) -> Result<Option<()>, Error> {
let change = KEvent::new(
pid as usize,
EventFilter::EVFILT_PROC,
EvFlags::EV_ADD | EvFlags::EV_RECEIPT,
FilterFlag::NOTE_EXIT,
0,
0,
);
let add_result = add_with_receipt(kq, change)?;
if add_result == libc::ESRCH as i64 {
return Ok(None); }
if add_result != 0 {
return Err(Error::Io(std::io::Error::from_raw_os_error(add_result as i32)));
}
Ok(Some(()))
}
#[cfg_attr(
not(feature = "tokio"),
allow(dead_code, reason = "the only consumer is tokio::wait's watch")
)]
pub(crate) fn arm_proc_exit_for(pid: u32, unique: u64) -> Result<Option<Kqueue>, Error> {
use crate::identity::{uniq_info, ReadPurpose, UniqRead};
let kq = Kqueue::new().map_err(|e| Error::Io(e.into()))?;
if arm_note_exit_on(&kq, pid)?.is_none() {
return Ok(None);
}
match uniq_info(pid, ReadPurpose::Arm) {
UniqRead::Found(info) if info.unique_id == unique => Ok(Some(kq)),
UniqRead::Found(_) | UniqRead::Gone | UniqRead::Refused(_) => Ok(None),
}
}
pub(crate) fn arm_proc_exit(id: ProcessId) -> Result<Option<Kqueue>, Error> {
let kq = Kqueue::new().map_err(|e| Error::Io(e.into()))?;
if arm_note_exit_on(&kq, id.pid())?.is_none() {
return Ok(None); }
match id.exists() {
crate::identity::Existence::Present => Ok(Some(kq)),
crate::identity::Existence::Gone => Ok(None), crate::identity::Existence::Unknown => {
log::warn!(
"wait: pid {} identity could not be confirmed; its exit cannot be observed",
id.pid()
);
Err(Error::Unassessable {
detail: format!(
"pid {} identity could not be confirmed; its exit cannot be observed",
id.pid()
),
source: None,
})
}
}
}
#[cfg_attr(
not(feature = "tokio"),
allow(dead_code, reason = "non-test consumer is tokio::wait's watch loop")
)]
pub(crate) fn drain_proc_exit(kq: &Kqueue) -> Result<Option<()>, Error> {
let zero = libc::timespec { tv_sec: 0, tv_nsec: 0 };
let mut events = [placeholder()];
loop {
match kq.kevent(&[], &mut events, Some(zero)) {
Ok(0) => return Ok(None), Ok(_) => {
if events[0].flags().contains(EvFlags::EV_ERROR) {
return Err(Error::Io(std::io::Error::from_raw_os_error(events[0].data() as i32)));
}
return Ok(Some(())); }
Err(nix::errno::Errno::EINTR) => continue,
Err(e) => return Err(Error::Io(e.into())),
}
}
}
pub(crate) fn block_until_exit(id: ProcessId, deadline: Option<Option<Instant>>) -> Result<bool, Error> {
let Some(kq) = arm_proc_exit(id)? else {
return Ok(true);
};
block_on_kqueue(&kq, deadline, false, |event, _already_elapsed| {
if event.flags().contains(EvFlags::EV_ERROR) {
return Err(Error::Io(std::io::Error::from_raw_os_error(event.data() as i32)));
}
Ok(Some(true)) })
}
pub(crate) fn block_on_kqueue<T: Copy>(
kq: &Kqueue,
deadline: Option<Option<Instant>>,
on_timeout: T,
mut interpret: impl FnMut(&KEvent, bool) -> Result<Option<T>, Error>,
) -> Result<T, Error> {
let mut events = [placeholder()];
#[cfg(test)]
let mut round: u32 = 0;
#[cfg(test)]
let mut check = crate::wait::test_clock::RoundCheck::new("block_on_kqueue");
loop {
#[cfg(test)]
check.round();
#[cfg(test)]
test_hooks::fire_round_hook(round, kq);
#[cfg(test)]
let call_start = Instant::now();
let (already_elapsed, timeout, outcome) = loop {
let remaining = crate::wait::remaining(deadline);
let already_elapsed = remaining == Some(Duration::ZERO);
#[allow(unused_mut, reason = "mutated only under #[cfg(test)] below")]
let mut timeout = remaining.map(kevent_timeout);
#[cfg(test)]
if let Some(forced) = test_hooks::take_timeout_override() {
let forced = libc::timespec {
tv_sec: forced.as_secs() as libc::time_t,
tv_nsec: forced.subsec_nanos() as libc::c_long,
};
assert_kevent_timespec(&forced);
timeout = Some(forced);
}
match kq.kevent(&[], &mut events, timeout) {
Err(nix::errno::Errno::EINTR) => continue,
outcome => break (already_elapsed, timeout, outcome),
}
};
#[cfg(test)]
crate::wait::test_clock::advance_by_elapsed_if_frozen(call_start.elapsed());
#[cfg(test)]
test_hooks::record_kevent_call(as_duration(timeout));
#[cfg(test)]
let this_round = round;
#[cfg(test)]
{
round += 1;
}
match outcome {
Ok(0) => {
if crate::wait::remaining(deadline) == Some(Duration::ZERO) {
return Ok(on_timeout);
}
match classify_zero_return(as_duration(timeout)) {
ZeroReturn::Rearm => log::debug!("wait: kevent reached its timeout cap with time left; re-arming"),
ZeroReturn::Anomaly => log::warn!(
"wait: kevent returned 0 after a timeout below the cap ({:?}) with time left; re-arming",
as_duration(timeout)
),
}
continue; }
Ok(_) => {
#[cfg(test)]
test_hooks::record_event_data(events[0].data());
#[cfg(test)]
test_hooks::fire_post_event_hook(this_round);
let elapsed = already_elapsed || crate::wait::remaining(deadline) == Some(Duration::ZERO);
if let Some(verdict) = interpret(&events[0], elapsed)? {
return Ok(verdict);
}
if elapsed {
return Ok(on_timeout);
}
}
Err(nix::errno::Errno::EINTR) => {
debug_assert!(false, "EINTR must be retried in the inner loop above, never reach here");
continue;
}
Err(e) => return Err(Error::Io(e.into())),
}
}
}
fn as_duration(timeout: Option<libc::timespec>) -> Option<Duration> {
timeout.map(|ts| {
debug_assert!(
ts.tv_sec >= 0 && ts.tv_nsec >= 0,
"a kevent timeout must never be negative"
);
Duration::new(ts.tv_sec as u64, ts.tv_nsec as u32)
})
}
#[cfg(test)]
#[path = "macos/test_hooks.rs"]
pub(crate) mod test_hooks;
#[path = "macos/await_reapable.rs"]
mod await_reapable;
#[cfg(test)]
pub(crate) use await_reapable::await_reapable_on;
pub(crate) use await_reapable::{await_reapable, Waited};
pub(crate) fn kill(id: ProcessId) -> Result<(), Error> {
use nix::sys::signal::{kill as nix_kill, Signal};
use nix::unistd::Pid;
match ProcessId::of(id.pid()) {
crate::identity::Resolved::Found(live) if live == id => {}
crate::identity::Resolved::Found(_) | crate::identity::Resolved::Gone => return Ok(()),
crate::identity::Resolved::Unknown => {
log::warn!(
"wait: pid {} identity could not be confirmed - no signal was sent",
id.pid()
);
return Err(Error::Unassessable {
detail: format!("pid {} identity could not be confirmed; no signal was sent", id.pid()),
source: None,
});
}
}
let Some(target) = crate::identity::probe::signal_target(id.pid()) else {
log::warn!(
"wait: pid {} is not a single-process signal target - not signaled",
id.pid()
);
return Err(Error::Unassessable {
detail: format!("pid {} is not a signalable single-process target", id.pid()),
source: None,
});
};
#[cfg(test)]
crate::send_log::record_by_identity(id.pid(), Signal::SIGKILL as i32);
match nix_kill(Pid::from_raw(target), Signal::SIGKILL) {
Ok(()) => Ok(()),
Err(nix::errno::Errno::ESRCH) => Ok(()), Err(e) => Err(Error::Io(e.into())), }
}
pub(crate) fn terminate(id: ProcessId) -> Result<(), Error> {
use nix::sys::signal::{kill as nix_kill, Signal};
use nix::unistd::Pid;
match ProcessId::of(id.pid()) {
crate::identity::Resolved::Found(live) if live == id => {}
crate::identity::Resolved::Found(_) | crate::identity::Resolved::Gone => return Ok(()),
crate::identity::Resolved::Unknown => {
log::warn!(
"wait: pid {} identity could not be confirmed - no signal was sent",
id.pid()
);
return Err(Error::Unassessable {
detail: format!("pid {} identity could not be confirmed; no signal was sent", id.pid()),
source: None,
});
}
}
let Some(target) = crate::identity::probe::signal_target(id.pid()) else {
log::warn!(
"wait: pid {} is not a single-process signal target - not signaled",
id.pid()
);
return Err(Error::Unassessable {
detail: format!("pid {} is not a signalable single-process target", id.pid()),
source: None,
});
};
#[cfg(test)]
crate::send_log::record_by_identity(id.pid(), Signal::SIGTERM as i32);
match nix_kill(Pid::from_raw(target), Signal::SIGTERM) {
Ok(()) => Ok(()),
Err(nix::errno::Errno::ESRCH) => Ok(()),
Err(e) => Err(Error::Io(e.into())),
}
}
#[cfg(test)]
#[path = "macos_tests.rs"]
mod macos_tests;