use super::super::{RawPid, Resolved};
#[repr(C)]
pub(crate) struct kinfo_proc {
pub(crate) kp_proc: extern_proc,
kp_eproc: [u8; 352],
}
impl kinfo_proc {
const E_PPID_OFFSET: usize = 264;
pub(super) fn e_ppid(&self) -> libc::pid_t {
const LEN: usize = std::mem::size_of::<libc::pid_t>();
let bytes: [u8; LEN] = self.kp_eproc[kinfo_proc::E_PPID_OFFSET..kinfo_proc::E_PPID_OFFSET + LEN]
.try_into()
.expect("kp_eproc is 352 bytes; E_PPID_OFFSET + LEN fits with room to spare (see the tripwire below)");
libc::pid_t::from_ne_bytes(bytes)
}
}
#[cfg(test)]
impl kinfo_proc {
const E_JOBC_OFFSET: usize = 272;
pub(crate) fn e_jobc(&self) -> i16 {
let at = kinfo_proc::E_JOBC_OFFSET;
i16::from_ne_bytes(self.kp_eproc[at..at + 2].try_into().expect("2 bytes"))
}
fn set_e_ppid(&mut self, ppid: libc::pid_t) {
let at = kinfo_proc::E_PPID_OFFSET;
self.kp_eproc[at..at + std::mem::size_of::<libc::pid_t>()].copy_from_slice(&ppid.to_ne_bytes());
}
}
const _: () = assert!(kinfo_proc::E_PPID_OFFSET + std::mem::size_of::<libc::pid_t>() <= 352);
#[repr(C)]
pub(crate) struct extern_proc {
pub(crate) p_un: p_un,
p_vmspace: u64,
p_sigacts: u64,
pub(crate) p_flag: libc::c_int,
pub(crate) p_stat: libc::c_char,
pub(crate) p_pid: libc::pid_t,
pub(crate) p_oppid: libc::pid_t,
p_dupfd: libc::c_int,
user_stack: u64,
exit_thread: u64,
p_debugger: libc::c_int,
sigwait: libc::c_int, p_estcpu: libc::c_uint,
p_cpticks: libc::c_int,
p_pctcpu: u32, p_wchan: u64,
p_wmesg: u64,
p_swtime: libc::c_uint,
p_slptime: libc::c_uint,
p_realtimer: itimerval,
p_rtime: libc::timeval,
p_uticks: u64,
p_sticks: u64,
p_iticks: u64,
p_traceflag: libc::c_int,
p_tracep: u64,
p_siglist: libc::c_int,
p_textvp: u64,
p_holdcnt: libc::c_int,
p_sigmask: u32, p_sigignore: u32,
p_sigcatch: u32,
p_priority: u8,
p_usrpri: u8,
p_nice: libc::c_char,
p_comm: [libc::c_char; 17], p_pgrp: u64,
p_addr: u64,
p_xstat: u16,
p_acflag: u16,
p_ru: u64,
}
#[repr(C)]
pub(crate) union p_un {
p_st1: run_sleep_queue,
pub(crate) p_starttime: libc::timeval,
}
#[repr(C)]
#[derive(Clone, Copy)]
struct run_sleep_queue {
p_forw: u64,
p_back: u64,
}
#[repr(C)]
struct itimerval {
it_interval: libc::timeval,
it_value: libc::timeval,
}
const _: () = assert!(std::mem::size_of::<kinfo_proc>() == 648);
const _: () = assert!(std::mem::size_of::<extern_proc>() == 296);
pub(crate) const P_SYSTEM: libc::c_int = 0x00000200;
#[cfg(test)]
pub(crate) const P_WEXIT: libc::c_int = 0x0000_2000;
pub(crate) fn kinfo(pid: RawPid) -> Resolved<kinfo_proc> {
#[cfg(test)]
if fault::take_unreadable() {
return Resolved::Unknown;
}
#[cfg(test)]
if let Some(oppid) = fault::take_oppid() {
return match read_record(pid, libc::KERN_PROC_PID) {
Resolved::Found(mut info) => {
info.kp_proc.p_oppid = oppid;
Resolved::Found(info)
}
other => other,
};
}
#[cfg(test)]
if let Some((oppid, ppid)) = fault::forced_parents(pid) {
return match read_record(pid, libc::KERN_PROC_PID) {
Resolved::Found(mut info) => {
info.kp_proc.p_oppid = oppid;
info.set_e_ppid(ppid);
Resolved::Found(info)
}
other => other,
};
}
read_record(pid, libc::KERN_PROC_PID)
}
#[cfg(test)]
pub(crate) mod fault {
use std::cell::Cell;
thread_local! {
static OPPID: Cell<Option<libc::pid_t>> = const { Cell::new(None) };
static UNREADABLE: Cell<bool> = const { Cell::new(false) };
}
pub(crate) fn force_unreadable_once() {
UNREADABLE.with(|u| u.set(true));
}
pub(super) fn take_unreadable() -> bool {
UNREADABLE.with(Cell::take)
}
pub(crate) fn force_oppid_once(oppid: libc::pid_t) {
OPPID.with(|o| o.set(Some(oppid)));
}
pub(super) fn take_oppid() -> Option<libc::pid_t> {
OPPID.with(Cell::take)
}
type Parents = Box<dyn FnMut() -> (libc::pid_t, libc::pid_t)>;
thread_local! {
static PARENTS: std::cell::RefCell<Option<(crate::identity::RawPid, Parents)>> = const { std::cell::RefCell::new(None) };
}
pub(crate) fn force_parents(
pid: crate::identity::RawPid,
parents: impl FnMut() -> (libc::pid_t, libc::pid_t) + 'static,
) -> ForcedParents {
PARENTS.with(|p| *p.borrow_mut() = Some((pid, Box::new(parents))));
ForcedParents(())
}
#[must_use = "the reads are real again as soon as the guard is dropped"]
pub(crate) struct ForcedParents(());
impl Drop for ForcedParents {
fn drop(&mut self) {
PARENTS.with(|p| p.borrow_mut().take());
}
}
pub(super) fn forced_parents(pid: crate::identity::RawPid) -> Option<(libc::pid_t, libc::pid_t)> {
PARENTS.with(|p| match p.borrow_mut().as_mut() {
Some((forced, parents)) if *forced == pid => Some(parents()),
_ => None,
})
}
}
fn read_record(pid: RawPid, selector: libc::c_int) -> Resolved<kinfo_proc> {
let mut mib = [libc::CTL_KERN, libc::KERN_PROC, selector, pid as libc::c_int];
loop {
let mut info: kinfo_proc = unsafe { std::mem::zeroed() };
let mut size = std::mem::size_of::<kinfo_proc>();
let rc = unsafe {
libc::sysctl(
mib.as_mut_ptr(),
mib.len() as libc::c_uint,
&mut info as *mut _ as *mut libc::c_void,
&mut size,
std::ptr::null_mut(),
0,
)
};
if rc != 0 {
let e = std::io::Error::last_os_error();
return match e.raw_os_error() {
Some(libc::EINTR) => continue,
Some(libc::ESRCH) => Resolved::Gone,
Some(libc::EPERM) | Some(libc::EACCES) => {
log::debug!(
"sysctl(KERN_PROC selector {selector}, {pid}) refused: {report}",
report = crate::error::Report(&e)
);
Resolved::Unknown
}
_ => {
super::contract_violation(format_args!(
"sysctl(KERN_PROC selector {selector}, {pid}) failed: {report}",
report = crate::error::Report(&e)
));
Resolved::Unknown
}
};
}
if size == 0 {
return Resolved::Gone;
}
if size != std::mem::size_of::<kinfo_proc>() {
super::contract_violation(format_args!(
"sysctl(KERN_PROC selector {selector}, {pid}) wrote {size} bytes, expected {}",
std::mem::size_of::<kinfo_proc>()
));
return Resolved::Unknown;
}
return Resolved::Found(info);
}
}
#[cfg(test)]
#[path = "kinfo_tests.rs"]
mod kinfo_tests;