use std::time::{Duration, SystemTime};
use super::{Key, Liveness, OrderedRead, ParentRead, RawPid, Resolved, UnknownCause};
use kernel::Kernel;
#[path = "macos/kernel.rs"]
pub(crate) mod kernel;
#[path = "macos/kinfo.rs"]
pub(crate) mod kinfo;
pub(super) fn contract_violation(what: std::fmt::Arguments<'_>) {
log::warn!("{what}");
debug_assert!(false, "{what}");
}
fn token_of_bsd(info: &libc::proc_bsdinfo) -> Key {
Key::from_raw(info.pbi_start_tvsec * 1_000_000 + info.pbi_start_tvusec)
}
fn token_of_kinfo(info: &kinfo::kinfo_proc) -> Key {
let start = unsafe { info.kp_proc.p_un.p_starttime };
Key::from_raw(start.tv_sec as u64 * 1_000_000 + start.tv_usec as u64)
}
pub(crate) const LAUNCHD: RawPid = 1;
const PROC_PIDUNIQIDENTIFIERINFO: libc::c_int = 17;
#[repr(C)]
#[derive(Clone, Copy)]
struct ProcUniqIdentifierInfo {
p_uuid: [u8; 16],
p_uniqueid: u64,
p_puniqueid: u64,
p_idversion: i32,
p_orig_ppidversion: i32,
p_reserve2: u64,
p_reserve3: u64,
}
const _: () = assert!(std::mem::size_of::<ProcUniqIdentifierInfo>() == 56);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct UniqInfo {
pub(crate) unique_id: u64,
pub(crate) id_version: i32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum UniqRead {
Found(UniqInfo),
Gone,
Refused(i32),
}
fn pidinfo<T>(pid: RawPid, flavor: libc::c_int, buf: &mut T) -> Result<(), ReadErr> {
let size = std::mem::size_of::<T>() as libc::c_int;
let n = unsafe { libc::proc_pidinfo(pid as libc::c_int, flavor, 1, buf as *mut T as *mut libc::c_void, size) };
if n == size {
return Ok(());
}
if n <= 0 {
let errno = std::io::Error::last_os_error().raw_os_error().unwrap_or(libc::EIO);
return Err(if errno == libc::ESRCH {
ReadErr::Gone
} else {
ReadErr::Refused(errno)
});
}
Err(ReadErr::Partial {
wrote: n,
expected: size,
})
}
fn warn_partial(pid: RawPid, flavor: libc::c_int, err: &ReadErr) {
if let ReadErr::Partial { wrote, expected } = err {
log::warn!("proc_pidinfo({pid}, {flavor}) wrote {wrote} bytes, expected {expected}");
}
}
pub(crate) fn own_unique_id() -> Result<u64, i32> {
let mut info: ProcUniqIdentifierInfo = unsafe { std::mem::zeroed() };
let size = std::mem::size_of::<ProcUniqIdentifierInfo>() as libc::c_int;
let n = unsafe {
libc::proc_pidinfo(
libc::getpid(),
PROC_PIDUNIQIDENTIFIERINFO,
1,
(&mut info as *mut ProcUniqIdentifierInfo).cast(),
size,
)
};
if n == size {
Ok(info.p_uniqueid)
} else if n <= 0 {
Err(std::io::Error::last_os_error().raw_os_error().unwrap_or(libc::EIO))
} else {
Err(libc::EIO)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Held {
Parent(u32),
Other,
Gone,
Refused(i32),
}
pub(crate) fn held_by(kernel: &dyn Kernel, pid: RawPid, expected: u64) -> Held {
match short_read(kernel, pid, expected, |pid| short_ppid(kernel, pid)) {
Ok(ppid) => Held::Parent(ppid),
Err(Mismatch::Other) => Held::Other,
Err(Mismatch::Gone) => Held::Gone,
Err(Mismatch::Refused(errno)) => Held::Refused(errno),
}
}
pub(crate) fn has_exited(kernel: &dyn Kernel, pid: RawPid, expected: u64) -> Result<bool, i32> {
match short_read(kernel, pid, expected, |pid| short_status(kernel, pid)) {
Ok(status) => Ok(status == libc::SZOMB),
Err(Mismatch::Other | Mismatch::Gone) => Ok(true),
Err(Mismatch::Refused(errno)) => Err(errno),
}
}
pub(crate) fn exit_state_of(kernel: &dyn Kernel, pid: RawPid, expected: u64) -> Resolved<kinfo::ExitState> {
let read = short_read(kernel, pid, expected, |pid| {
Ok(match kernel.kinfo(pid).0 {
Resolved::Found(info) => Resolved::Found(kinfo::exit_state(info.kp_proc.p_stat, info.kp_proc.p_flag)),
Resolved::Gone => {
debug_assert!(false, "pid {pid}: kinfo said gone between two matching id reads");
Resolved::Unknown
}
Resolved::Unknown => Resolved::Unknown,
})
});
match read {
Ok(state) => state,
Err(Mismatch::Other | Mismatch::Gone) => Resolved::Gone,
Err(Mismatch::Refused(_)) => Resolved::Unknown,
}
}
enum Mismatch {
Other,
Gone,
Refused(i32),
}
fn short_read<T>(
kernel: &dyn Kernel,
pid: RawPid,
expected: u64,
read: impl FnOnce(RawPid) -> Result<T, ReadErr>,
) -> Result<T, Mismatch> {
let same = |read: UniqRead| match read {
UniqRead::Found(info) if info.unique_id == expected => Ok(()),
UniqRead::Found(_) => Err(Mismatch::Other),
UniqRead::Gone => Err(Mismatch::Gone),
UniqRead::Refused(errno) => Err(Mismatch::Refused(errno)),
};
same(kernel.unique_info(pid))?;
let read = read(pid);
same(kernel.unique_info(pid))?;
match read {
Ok(read) => Ok(read),
Err(ReadErr::Gone) => {
debug_assert!(false, "pid {pid}: a read said ESRCH between two matching id reads");
Err(Mismatch::Gone)
}
Err(ReadErr::Refused(errno)) => Err(Mismatch::Refused(errno)),
Err(ReadErr::Partial { .. }) => Err(Mismatch::Refused(libc::EIO)),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Origin {
Ours { parent: RawPid },
NotOurs,
Gone,
Refused(i32),
Unreadable,
}
pub(crate) fn origin(kernel: &dyn Kernel, pid: RawPid) -> Origin {
let own = match own_unique_id() {
Ok(own) => own,
Err(errno) => return Origin::Refused(errno),
};
let unique = match kernel.unique_info(pid) {
UniqRead::Found(info) => info.unique_id,
UniqRead::Gone => return Origin::Gone,
UniqRead::Refused(errno) => return Origin::Refused(errno),
};
let info = match kernel.kinfo(pid).0 {
Resolved::Found(info) => info,
Resolved::Gone => return Origin::Gone,
Resolved::Unknown => return Origin::Unreadable,
};
match kernel.unique_info(pid) {
UniqRead::Found(again) if again.unique_id == unique => {}
UniqRead::Found(_) => return Origin::NotOurs,
UniqRead::Gone => return Origin::Gone,
UniqRead::Refused(errno) => return Origin::Refused(errno),
}
let me = std::process::id() as libc::pid_t;
if unique > own && (info.kp_proc.p_oppid == me || info.e_ppid() == me) {
Origin::Ours {
parent: info.e_ppid() as RawPid,
}
} else {
Origin::NotOurs
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Link {
Found {
unique: u64,
parent: RawPid,
at_attach: RawPid,
},
Gone,
Refused(i32),
Unreadable,
}
pub(crate) fn link(kernel: &dyn Kernel, pid: RawPid) -> Link {
let unique = match kernel.unique_info(pid) {
UniqRead::Found(info) => info.unique_id,
UniqRead::Gone => return Link::Gone,
UniqRead::Refused(errno) => return Link::Refused(errno),
};
let info = match kernel.kinfo(pid).0 {
Resolved::Found(info) => info,
Resolved::Gone => return Link::Gone,
Resolved::Unknown => return Link::Unreadable,
};
match kernel.unique_info(pid) {
UniqRead::Found(again) if again.unique_id == unique => Link::Found {
unique,
parent: info.e_ppid() as RawPid,
at_attach: info.kp_proc.p_oppid as RawPid,
},
UniqRead::Found(_) | UniqRead::Gone => Link::Gone,
UniqRead::Refused(errno) => Link::Refused(errno),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ReadErr {
Gone,
Refused(i32),
Partial {
wrote: i32,
expected: i32,
},
}
fn short_ppid(kernel: &dyn Kernel, pid: RawPid) -> Result<u32, ReadErr> {
kernel.short_bsd(pid).map(|info| info.pbsi_ppid)
}
fn short_status(kernel: &dyn Kernel, pid: RawPid) -> Result<u32, ReadErr> {
kernel.short_bsd(pid).map(|info| info.pbsi_status)
}
struct Record {
key: Key,
raw_ppid: RawPid,
}
impl Record {
fn ppid(&self, pid: RawPid) -> Option<RawPid> {
trusted_ppid(pid, self.raw_ppid)
}
}
fn libproc_record(kernel: &dyn Kernel, pid: RawPid) -> Option<libc::proc_bsdinfo> {
match kernel.bsd_info(pid) {
Ok(info) => Some(info),
Err(ReadErr::Gone | ReadErr::Refused(libc::EPERM)) => None,
Err(ReadErr::Partial { wrote, expected }) => {
contract_violation(format_args!(
"proc_pidinfo({pid}) wrote {wrote} bytes, expected {expected}"
));
None
}
Err(ReadErr::Refused(errno)) => {
contract_violation(format_args!(
"proc_pidinfo({pid}) failed: {report}",
report = crate::error::Report(&std::io::Error::from_raw_os_error(errno))
));
None
}
}
}
fn read_record(kernel: &dyn Kernel, pid: RawPid) -> Resolved<Record> {
if let Some(info) = libproc_record(kernel, pid) {
return Resolved::Found(Record {
key: token_of_bsd(&info),
raw_ppid: info.pbi_ppid,
});
}
kernel.kinfo(pid).0.map(|info| Record {
key: token_of_kinfo(&info),
raw_ppid: info.e_ppid() as RawPid,
})
}
pub(super) fn start_token(kernel: &dyn Kernel, pid: RawPid) -> Resolved<Key> {
read_record(kernel, pid).map(|record| record.key)
}
pub(super) fn ordered_read(kernel: &dyn Kernel, pid: RawPid, expected: Option<Key>, ask_parent: bool) -> OrderedRead {
let read = if ask_parent {
ppid_and_key(kernel, pid).map(|(ppid, key)| (key, ParentRead::Is(ppid)))
} else {
read_record(kernel, pid).map(|record| (record.key, ParentRead::NotAsked))
};
match read {
Resolved::Found((key, parent)) => OrderedRead {
read: Resolved::Found((key, None)),
parent,
cause: UnknownCause::default(),
}
.against(expected),
Resolved::Gone => OrderedRead::missing(Resolved::Gone, UnknownCause::default(), ask_parent),
Resolved::Unknown => OrderedRead::missing(Resolved::Unknown, UnknownCause::default(), ask_parent),
}
}
fn trusted_ppid(pid: RawPid, raw: RawPid) -> Option<RawPid> {
if raw == 0 && pid > 1 {
log::debug!(
"pid {pid}'s process-info record reported ppid == 0 for a process other than pid 0 and 1 - a \
fork()-in-progress record, not a resolvable ppid"
);
None
} else {
Some(raw)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PpidRead {
Found(RawPid, Key),
Forking,
Gone,
Refused,
}
fn read_ppid_once(kernel: &dyn Kernel, pid: RawPid) -> PpidRead {
match read_record(kernel, pid) {
Resolved::Found(record) => match record.ppid(pid) {
Some(ppid) => PpidRead::Found(ppid, record.key),
None => PpidRead::Forking,
},
Resolved::Gone => PpidRead::Gone,
Resolved::Unknown => PpidRead::Refused,
}
}
fn resolve_ppid(mut read: impl FnMut() -> PpidRead, mut pause: impl FnMut(u32)) -> Resolved<(RawPid, Key)> {
let mut attempt = 0;
loop {
match read() {
PpidRead::Found(ppid, key) => return Resolved::Found((ppid, key)),
PpidRead::Gone => return Resolved::Gone,
PpidRead::Refused => return Resolved::Unknown,
PpidRead::Forking => {
pause(attempt);
attempt = attempt.saturating_add(1);
}
}
}
}
pub(crate) fn ppid_of(kernel: &dyn Kernel, pid: RawPid) -> Resolved<RawPid> {
ppid_and_key(kernel, pid).map(|(ppid, _)| ppid)
}
pub(super) fn ppid_and_key(kernel: &dyn Kernel, pid: RawPid) -> Resolved<(RawPid, Key)> {
resolve_ppid(|| read_ppid_once(kernel, pid), fork_pause)
}
fn fork_pause(attempt: u32) {
if attempt == 0 {
std::thread::yield_now();
} else {
std::thread::sleep(Duration::from_micros(1 << attempt.min(10)));
}
}
pub(super) fn current_token() -> Resolved<Key> {
start_token(&kernel::HostKernel, std::process::id())
}
pub(super) fn is_running(kernel: &dyn Kernel, pid: RawPid, start: Key) -> Liveness {
if let Some(info) = libproc_record(kernel, pid) {
if token_of_bsd(&info) != start {
return Liveness::Dead; }
return if info.pbi_status == libc::SZOMB {
Liveness::Dead
} else {
Liveness::Alive
};
}
match kernel.kinfo(pid).0 {
Resolved::Found(info) => {
if token_of_kinfo(&info) != start || info.kp_proc.p_stat as u32 == libc::SZOMB {
Liveness::Dead
} else {
Liveness::Alive
}
}
Resolved::Gone => Liveness::Dead,
Resolved::Unknown => Liveness::Unknown,
}
}
pub(super) fn exit_begun(kernel: &dyn Kernel, pid: RawPid, start: Key) -> (Resolved<bool>, super::UnknownCause) {
let (read, failure) = kernel.kinfo(pid);
let begun = match read {
Resolved::Found(info) if token_of_kinfo(&info) != start => Resolved::Gone,
Resolved::Found(info) => Resolved::Found(kinfo::exit_begun(info.kp_proc.p_stat, info.kp_proc.p_flag)),
Resolved::Gone => Resolved::Gone,
Resolved::Unknown => Resolved::Unknown,
};
(begun, super::UnknownCause::of_kinfo(failure))
}
pub(super) fn created_at(start: Key) -> Option<SystemTime> {
Some(SystemTime::UNIX_EPOCH + Duration::from_micros(start.raw()))
}
pub(super) fn session_scope() -> Result<super::persist::Scope, super::persist::ScopeReadError> {
Ok(super::persist::Scope::none())
}
#[cfg(test)]
#[path = "macos/ppid_tests.rs"]
mod ppid_tests;
#[cfg(test)]
#[path = "macos/origin_tests.rs"]
mod origin_tests;