use crate::error::Error;
use crate::identity::{Kernel, RawPid, Resolved};
const HEADROOM: usize = 16;
const DENIED_SAMPLE_CAP: usize = 5;
fn ppid_of(pid: libc::c_int) -> Resolved<RawPid> {
#[cfg(test)]
if fault::is_denied(pid) {
return Resolved::Unknown;
}
crate::identity::macos_ppid_of(pid as RawPid)
}
fn capacity_for(needed: usize) -> usize {
needed.saturating_add(HEADROOM)
}
fn size_argument_for(pid_count: usize) -> std::io::Result<libc::c_int> {
let bytes = pid_count
.checked_mul(std::mem::size_of::<libc::c_int>())
.and_then(|bytes| libc::c_int::try_from(bytes).ok())
.ok_or_else(|| {
std::io::Error::other(format!(
"a {pid_count}-pid buffer cannot be described in proc_listallpids' int size argument"
))
})?;
debug_assert!(
bytes >= 0,
"size_argument_for must never return a negative buffersize, got {bytes}"
);
Ok(bytes)
}
#[derive(Debug)]
struct Filled {
pids: Vec<libc::c_int>,
#[cfg_attr(
not(test),
allow(dead_code, reason = "read only by macos_tests' grow_loop/live_pid_list assertions")
)]
rounds: usize,
}
fn interpret_written(written: libc::c_int) -> std::io::Result<usize> {
if written <= 0 {
return Err(std::io::Error::last_os_error());
}
Ok(written as usize)
}
fn fill_from_kernel(pids: &mut [libc::c_int]) -> std::io::Result<usize> {
let buf_bytes = size_argument_for(pids.len())?;
let written = unsafe { libc::proc_listallpids(pids.as_mut_ptr() as *mut libc::c_void, buf_bytes) };
interpret_written(written)
}
fn collect_pids(
mut cap: usize,
mut fill: impl FnMut(&mut [libc::c_int]) -> std::io::Result<usize>,
mut allocate: impl FnMut(usize) -> std::io::Result<Vec<libc::c_int>>,
) -> std::io::Result<Filled> {
if cap == 0 {
return Err(std::io::Error::other(
"collect_pids requires a nonzero starting capacity",
));
}
let mut rounds = 0;
let mut prev = 0;
loop {
rounds += 1;
let mut pids = allocate(cap)?;
let n = pids.len();
if n <= prev {
return Err(std::io::Error::other(
"collect_pids's allocate step did not grow the buffer for a larger capacity",
));
}
prev = n;
let written = fill(&mut pids)?;
if written > n {
return Err(std::io::Error::other(
"collect_pids's fill step reported more pids than the buffer holds",
));
}
if written < n {
pids.truncate(written);
return Ok(Filled { pids, rounds });
}
cap = n * 2;
}
}
fn allocate_pids(cap: usize) -> std::io::Result<Vec<libc::c_int>> {
size_argument_for(cap)?;
let mut pids: Vec<libc::c_int> = Vec::new();
pids.try_reserve_exact(cap).map_err(|e| {
crate::error::io_context(
format!("a {cap}-pid buffer could not be allocated"),
std::io::Error::from(e),
)
})?;
pids.resize(cap, 0);
Ok(pids)
}
fn fill_all() -> std::io::Result<Filled> {
let needed = unsafe { libc::proc_listallpids(std::ptr::null_mut(), 0) };
let needed = interpret_written(needed)?;
collect_pids(capacity_for(needed), fill_from_kernel, allocate_pids)
}
fn try_all_pids() -> std::io::Result<Vec<libc::c_int>> {
#[cfg(test)]
if FORCE_BLIND.with(|c| {
let armed = c.get();
c.set(armed.saturating_sub(1));
armed > 0
}) {
log::warn!(
"proc_listallpids sizing call returned 0 (test fault injected); every containment \
teardown channel that reads the process table is blind this round"
);
return Err(std::io::Error::other(
"proc_listallpids sizing call returned 0 (test fault injected)",
));
}
fill_all().map(|filled| filled.pids)
}
fn all_pids_or_empty(pids: std::io::Result<Vec<libc::c_int>>) -> Vec<libc::c_int> {
pids.unwrap_or_else(|e| {
log::warn!(
"enumerate: pid snapshot failed ({report}) - callers see an EMPTY process table, \
so a tree walk over it finds no descendants",
report = crate::error::Report(&e)
);
Vec::new()
})
}
fn all_pids() -> Vec<libc::c_int> {
all_pids_or_empty(try_all_pids())
}
#[cfg(test)]
thread_local! {
static FORCE_BLIND: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
#[cfg(test)]
pub(crate) fn force_blind_snapshots(count: usize) {
FORCE_BLIND.with(|c| c.set(count));
}
fn push_denied_sample(sample: &mut Vec<libc::c_int>, pid: libc::c_int) {
if sample.len() < DENIED_SAMPLE_CAP {
sample.push(pid);
}
}
type Joined = (Vec<(RawPid, RawPid)>, usize, Vec<libc::c_int>);
fn join_edges(pids: &[libc::c_int]) -> std::io::Result<Joined> {
#[cfg(test)]
if fault::join_alloc_fails() {
return Err(std::io::Error::other(
"an edge buffer could not be allocated (test fault injected)",
));
}
let mut edges = Vec::new();
edges.try_reserve_exact(pids.len()).map_err(|e| {
crate::error::io_context(
format!("an edge buffer for {} pids could not be allocated", pids.len()),
std::io::Error::from(e),
)
})?;
let mut denied = 0usize;
let mut sample = Vec::new();
for &pid in pids {
if pid <= 0 {
continue; }
match ppid_of(pid) {
Resolved::Found(ppid) => edges.push((pid as RawPid, ppid)),
Resolved::Gone => {}
Resolved::Unknown => {
denied += 1;
push_denied_sample(&mut sample, pid);
}
}
}
Ok((edges, denied, sample))
}
pub(crate) fn process_parents(_kernel: &dyn Kernel) -> Result<Vec<(RawPid, RawPid)>, Error> {
let raw = try_all_pids().map_err(|e| {
let error = Error::Unassessable {
detail: "the process snapshot could not be taken: proc_listallpids failed".to_owned(),
source: Some(Error::io_cause(e)),
};
log::warn!("enumerate::process_parents: {}", crate::error::Report(&error));
error
})?;
let (edges, denied, sample) = join_edges(&raw).map_err(|e| {
let error = Error::Unassessable {
detail: "the process snapshot could not be taken".to_owned(),
source: Some(Error::io_cause(e)),
};
log::warn!("enumerate::process_parents: {}", crate::error::Report(&error));
error
})?;
if denied > 0 {
let detail = format!(
"the process snapshot could not be taken: {denied} of {} pids denied a ppid read, so their \
subtrees are missing from it; sample: {sample:?}",
raw.len()
);
log::warn!("enumerate::process_parents: {detail}");
return Err(Error::Unassessable { detail, source: None });
}
Ok(edges)
}
fn log_denied(denied: usize, total: usize, sample: &[libc::c_int]) {
if denied > 0 {
log::debug!(
"containment snapshot: {denied} of {total} pids denied a ppid read; their subtrees are \
invisible to the ppid-walk channel this round; sample: {sample:?}"
);
}
}
pub(crate) fn snapshot() -> (Vec<RawPid>, Vec<(RawPid, RawPid)>, usize) {
let raw = all_pids();
let (edges, denied, sample) = match join_edges(&raw) {
Ok(joined) => joined,
Err(e) => {
log::warn!(
"enumerate: pid snapshot failed ({report}) - callers see an EMPTY process table",
report = crate::error::Report(&e)
);
return (Vec::new(), Vec::new(), 0);
}
};
log_denied(denied, raw.len(), &sample);
let pids = raw.into_iter().filter(|&p| p > 0).map(|p| p as RawPid).collect();
(pids, edges, denied)
}
#[cfg(test)]
pub(crate) mod fault {
use std::cell::{Cell, RefCell};
thread_local! {
static DENIED: RefCell<Vec<libc::c_int>> = const { RefCell::new(Vec::new()) };
static JOIN_ALLOC_FAILS: Cell<bool> = const { Cell::new(false) };
}
#[must_use = "dropping this immediately disarms the forced faults"]
pub(crate) struct Forced(());
impl Drop for Forced {
fn drop(&mut self) {
DENIED.with(|d| d.borrow_mut().clear());
JOIN_ALLOC_FAILS.with(|f| f.set(false));
super::FORCE_BLIND.with(|c| c.set(0));
}
}
pub(crate) fn force_blind_snapshot() -> Forced {
super::force_blind_snapshots(1);
Forced(())
}
pub(crate) fn force_denied(pids: &[libc::c_int]) -> Forced {
DENIED.with(|d| d.borrow_mut().extend_from_slice(pids));
Forced(())
}
pub(crate) fn force_join_alloc_failure() -> Forced {
JOIN_ALLOC_FAILS.with(|f| f.set(true));
Forced(())
}
pub(super) fn is_denied(pid: libc::c_int) -> bool {
DENIED.with(|d| d.borrow().contains(&pid))
}
pub(super) fn join_alloc_fails() -> bool {
JOIN_ALLOC_FAILS.with(|f| f.get())
}
}
#[cfg(test)]
#[path = "macos_tests.rs"]
mod macos_tests;