use super::*;
use crate::identity::{FakeKernel, HostKernel};
#[skuld::test]
fn kernel_writes_exactly_our_kinfo_proc_size() {
let mut buf = [0u8; 2 * std::mem::size_of::<kinfo_proc>()];
let mut size = buf.len();
let mut mib = [
libc::CTL_KERN,
libc::KERN_PROC,
libc::KERN_PROC_PID,
std::process::id() as libc::c_int,
];
let rc = unsafe {
libc::sysctl(
mib.as_mut_ptr(),
mib.len() as libc::c_uint,
buf.as_mut_ptr() as *mut libc::c_void,
&mut size,
std::ptr::null_mut(),
0,
)
};
assert_eq!(rc, 0, "sysctl fetch failed: {}", std::io::Error::last_os_error());
assert_eq!(
size,
std::mem::size_of::<kinfo_proc>(),
"kernel kinfo_proc record size disagrees with our layout"
);
}
#[cfg_attr(debug_assertions, should_panic(expected = "synthetic"))]
#[skuld::test]
fn contract_violation_traces_then_trips() {
crate::log_capture::install();
let mark = crate::log_capture::mark();
super::super::contract_violation(format_args!("synthetic contract violation (test)"));
assert!(
crate::log_capture::contains_since(mark, "synthetic contract violation (test)"),
"the warn must have fired before the (compiled-out) tripwire"
);
}
#[skuld::test]
fn sysctl_token_matches_libproc_for_a_live_process() {
let pid = std::process::id() as libc::c_int;
let (crate::identity::Resolved::Found(ours), _) = HostKernel.kinfo(pid as super::super::RawPid) else {
panic!("self resolves via sysctl");
};
let ours = {
let t = unsafe { ours.kp_proc.p_un.p_starttime };
t.tv_sec as u64 * 1_000_000 + t.tv_usec as u64
};
let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
let size = std::mem::size_of::<libc::proc_bsdinfo>() as libc::c_int;
let n = unsafe {
libc::proc_pidinfo(
pid,
libc::PROC_PIDTBSDINFO,
0,
&mut info as *mut _ as *mut libc::c_void,
size,
)
};
assert_eq!(n, size, "proc_pidinfo oracle failed for self");
let theirs = info.pbi_start_tvsec * 1_000_000 + info.pbi_start_tvusec;
assert_eq!(ours, theirs, "sysctl and libproc disagree on self's start token");
}
#[skuld::test]
fn sysctl_e_ppid_matches_libproc_across_the_live_process_table() {
let mut cap = 1024usize;
let pids = loop {
let mut buf = vec![0i32; cap];
let bytes = (buf.len() * std::mem::size_of::<i32>()) as libc::c_int;
let written = unsafe { libc::proc_listallpids(buf.as_mut_ptr() as *mut libc::c_void, bytes) };
assert!(
written > 0,
"proc_listallpids failed: {}",
std::io::Error::last_os_error()
);
let written = written as usize;
if written < buf.len() {
buf.truncate(written);
break buf;
}
cap *= 2;
};
let (mut agreed, mut rescued, mut both_failed) = (0usize, 0usize, 0usize);
let (mut ambiguous_zero_libproc, mut ambiguous_zero_sysctl) = (0usize, 0usize);
for pid in pids {
if pid <= 0 {
continue; }
let pid_raw = pid as super::super::RawPid;
let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
let size = std::mem::size_of::<libc::proc_bsdinfo>() as libc::c_int;
let n = unsafe {
libc::proc_pidinfo(
pid,
libc::PROC_PIDTBSDINFO,
0,
&mut info as *mut _ as *mut libc::c_void,
size,
)
};
let libproc_ppid = (n == size).then_some(info.pbi_ppid);
let sysctl_ppid = match HostKernel.kinfo(pid_raw).0 {
crate::identity::Resolved::Found(k) => Some(k.e_ppid() as super::super::RawPid),
crate::identity::Resolved::Gone | crate::identity::Resolved::Unknown => None,
};
let libproc_untrusted = libproc_ppid.is_some_and(|raw| super::super::trusted_ppid(pid_raw, raw).is_none());
let sysctl_untrusted = sysctl_ppid.is_some_and(|raw| super::super::trusted_ppid(pid_raw, raw).is_none());
match (libproc_ppid, sysctl_ppid) {
_ if libproc_untrusted || sysctl_untrusted => {
if libproc_untrusted {
ambiguous_zero_libproc += 1;
}
if sysctl_untrusted {
ambiguous_zero_sysctl += 1;
}
}
(Some(a), Some(b)) => {
assert_eq!(a, b, "pid {pid}: libproc ppid {a} disagrees with sysctl ppid {b}");
agreed += 1;
}
(None, Some(_)) => rescued += 1,
(Some(_), None) => both_failed += 1,
(None, None) => both_failed += 1,
}
}
eprintln!(
"sysctl_e_ppid oracle over the live process table: agreed={agreed} rescued={rescued} \
both_failed={both_failed} ambiguous_zero_libproc={ambiguous_zero_libproc} \
ambiguous_zero_sysctl={ambiguous_zero_sysctl}"
);
assert!(
agreed > 0,
"must observe at least one libproc/sysctl agreement on a live host (self, if nothing else)"
);
}
#[skuld::test]
fn p_flag_system_bit_matches_a_second_sysctl_query_and_libproc_disagrees_for_non_system() {
const PROC_FLAG_SYSTEM: u32 = 1;
let (crate::identity::Resolved::Found(k), _) = HostKernel.kinfo(0) else {
panic!("pid 0 (kernproc) resolves via sysctl KERN_PROC_PID");
};
assert!(
k.kp_proc.p_flag & P_SYSTEM != 0,
"kernproc (pid 0) must be P_SYSTEM-flagged via KERN_PROC_PID"
);
let mut mib = [libc::CTL_KERN, libc::KERN_PROC, libc::KERN_PROC_ALL, 0];
let mut len: libc::size_t = 0;
let rc = unsafe {
libc::sysctl(
mib.as_mut_ptr(),
mib.len() as libc::c_uint,
std::ptr::null_mut(),
&mut len,
std::ptr::null_mut(),
0,
)
};
assert_eq!(
rc,
0,
"KERN_PROC_ALL sizing query failed: {}",
std::io::Error::last_os_error()
);
let record = std::mem::size_of::<kinfo_proc>();
let mut buf: Vec<kinfo_proc> = Vec::with_capacity(len / record + 8);
let mut got = buf.capacity() * record;
let rc = unsafe {
libc::sysctl(
mib.as_mut_ptr(),
mib.len() as libc::c_uint,
buf.as_mut_ptr().cast(),
&mut got,
std::ptr::null_mut(),
0,
)
};
assert_eq!(rc, 0, "KERN_PROC_ALL fetch failed: {}", std::io::Error::last_os_error());
unsafe { buf.set_len(got / record) };
let kernproc = buf
.iter()
.find(|k| k.kp_proc.p_pid == 0)
.expect("pid 0 (kernproc) present in a KERN_PROC_ALL scan");
assert!(
kernproc.kp_proc.p_flag & P_SYSTEM != 0,
"kernproc (pid 0) must be P_SYSTEM-flagged via the independent KERN_PROC_ALL scan too"
);
for pid in [1, std::process::id() as libc::c_int] {
let (crate::identity::Resolved::Found(k), _) = HostKernel.kinfo(pid as super::super::RawPid) else {
panic!("pid {pid} resolves via sysctl");
};
assert!(
k.kp_proc.p_flag & P_SYSTEM == 0,
"pid {pid} must not be P_SYSTEM-flagged via sysctl"
);
}
let me = std::process::id() as libc::c_int;
let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
let size = std::mem::size_of::<libc::proc_bsdinfo>() as libc::c_int;
let n = unsafe {
libc::proc_pidinfo(
me,
libc::PROC_PIDTBSDINFO,
0,
&mut info as *mut _ as *mut libc::c_void,
size,
)
};
assert_eq!(n, size, "proc_pidinfo oracle failed for self");
assert!(
info.pbi_flags & PROC_FLAG_SYSTEM == 0,
"this test process must not be PROC_FLAG_SYSTEM-flagged via proc_pidinfo"
);
}
#[skuld::test]
fn exit_begun_is_p_wexit_or_a_zombie_and_no_other_flag() {
let running = libc::SRUN as libc::c_char;
let zombie = libc::SZOMB as libc::c_char;
assert!(!exit_begun(running, 0));
assert!(!exit_begun(running, P_SYSTEM));
assert!(exit_begun(running, P_WEXIT));
assert!(exit_begun(zombie, 0));
assert_eq!(exit_state(running, 0), ExitState::Running);
assert_eq!(exit_state(running, P_WEXIT), ExitState::Exiting);
assert_eq!(exit_state(zombie, 0), ExitState::Zombie);
assert_eq!(exit_state(zombie, P_WEXIT), ExitState::Zombie);
let me = HostKernel
.kinfo(std::process::id())
.0
.found()
.expect("this process resolves");
assert!(
!exit_begun(me.kp_proc.p_stat, me.kp_proc.p_flag),
"this process is running"
);
}
#[skuld::test]
fn the_exit_read_of_an_identity_is_gone_for_another_token_and_unknown_when_refused() {
let me = crate::identity::ProcessId::of(std::process::id())
.found()
.expect("this process has an identity");
assert_eq!(
super::super::exit_begun(&HostKernel, me.pid(), me.key).0,
crate::identity::Resolved::Found(false),
"this process is running"
);
let other = crate::identity::Key::from_raw(me.key.raw() + 1);
assert_eq!(
super::super::exit_begun(&HostKernel, me.pid(), other).0,
crate::identity::Resolved::Gone,
"the pid holds another process than the token's"
);
let refused = FakeKernel::over(&HostKernel).on_kinfo_refused(me.pid(), libc::EPERM);
let (read, cause) = super::super::exit_begun(&refused, me.pid(), me.key);
assert_eq!(read, crate::identity::Resolved::Unknown);
let error = cause.into_error("pid 1").expect("the refusal is the cause");
assert!(error.to_string().contains("kinfo_proc could not be read"), "{error}");
}
#[skuld::test]
fn a_sysctl_result_is_classified_by_its_errno_and_size() {
let failed = |errno| std::io::Error::from_raw_os_error(errno);
let size = std::mem::size_of::<kinfo_proc>();
assert!(matches!(classify(7, Err(failed(libc::EINTR))), SysctlOutcome::Retry));
assert!(matches!(classify(7, Err(failed(libc::ESRCH))), SysctlOutcome::Gone));
assert!(matches!(classify(7, Ok(0)), SysctlOutcome::Gone));
assert!(matches!(classify(7, Ok(size)), SysctlOutcome::Record));
for errno in [libc::EPERM, libc::EACCES] {
match classify(7, Err(failed(errno))) {
SysctlOutcome::Refused(e) => assert_eq!(e.raw_os_error(), Some(errno)),
other => panic!("errno {errno} is a refusal, got {other:?}"),
}
}
for errno in [libc::ENOMEM, libc::EINVAL] {
match classify(7, Err(failed(errno))) {
SysctlOutcome::Violation { message, error } => {
assert!(message.contains("sysctl(KERN_PROC_PID, 7) failed"), "{message}");
assert_eq!(error.raw_os_error(), Some(errno), "the errno stays the read's cause");
}
other => panic!("errno {errno} is a contract violation, got {other:?}"),
}
}
for wrote in [size - 1, size + 1] {
match classify(7, Ok(wrote)) {
SysctlOutcome::Violation { message, error } => {
assert_eq!(
message,
format!("sysctl(KERN_PROC_PID, 7) wrote {wrote} bytes, expected {size}")
);
assert_eq!(error.to_string(), message);
}
other => panic!("{wrote} bytes is layout drift, got {other:?}"),
}
}
}