use crate::error::Error;
use crate::os_process::macos::kqueue::{Kqueue, Subscription};
fn errno() -> i32 {
std::io::Error::last_os_error()
.raw_os_error()
.expect("a failed syscall sets errno")
}
const ATTACH: libc::c_int = libc::PT_ATTACH;
fn ptrace(request: libc::c_int, pid: u32, data: i32) -> Result<(), i32> {
let rc = unsafe {
libc::ptrace(
request,
pid as libc::pid_t,
std::ptr::dangling_mut::<libc::c_char>(),
data,
)
};
if rc == 0 {
Ok(())
} else {
Err(errno())
}
}
pub(super) fn attach(pid: u32) -> Result<(), i32> {
ptrace(ATTACH, pid, 0)
}
pub(super) fn cont(pid: u32, signal: i32) -> Result<(), i32> {
ptrace(libc::PT_CONTINUE, pid, signal)
}
pub(super) fn resume(pid: u32) -> Result<(), i32> {
cont(pid, 0)
}
pub(super) fn detach(pid: u32) -> Result<(), i32> {
ptrace(libc::PT_DETACH, pid, 0)
}
pub(super) fn kill(pid: u32, signal: i32) -> Result<(), i32> {
if unsafe { libc::kill(pid as libc::pid_t, signal) } == 0 {
Ok(())
} else {
Err(errno())
}
}
pub(super) fn reap(pid: u32) -> Result<(), i32> {
let mut status = 0;
let rc = unsafe { libc::wait4(pid as libc::pid_t, &mut status, 0, std::ptr::null_mut()) };
if rc != pid as libc::pid_t {
Err(errno())
} else if libc::WIFEXITED(status) || libc::WIFSIGNALED(status) {
Ok(())
} else {
Err(libc::EINVAL)
}
}
pub(super) fn await_zombie(pid: u32) -> Result<(), i32> {
let info = peek(pid, libc::WEXITED)?;
if matches!(info.si_code, 1..=3) {
Ok(())
} else {
Err(libc::EINVAL)
}
}
pub(super) fn pbi_status(pid: u32) -> Result<u32, i32> {
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 as libc::c_int,
libc::PROC_PIDTBSDINFO,
0,
(&raw mut info).cast(),
size,
)
};
if n == size {
Ok(info.pbi_status)
} else {
Err(errno())
}
}
#[derive(Clone, Copy, Debug)]
pub(super) struct ProcState {
pub(super) p_stat: u32,
pub(super) p_flag: libc::c_int,
}
pub(super) fn proc_state(pid: u32) -> ProcState {
match crate::identity::Kernel::kinfo(&crate::identity::HostKernel, pid as _).0 {
crate::identity::Resolved::Found(info) => ProcState {
p_stat: info.kp_proc.p_stat as u32,
p_flag: info.kp_proc.p_flag,
},
crate::identity::Resolved::Gone => panic!("the unreaped tracee {pid} is gone"),
crate::identity::Resolved::Unknown => panic!("kinfo refused to read the tracee {pid}"),
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Stop {
Running,
Settling,
Stopped(i32),
}
pub(super) fn stop(pid: u32) -> Result<Stop, i32> {
verdict(&peek(pid, libc::WSTOPPED | libc::WNOHANG)?, || threads(pid))
}
fn verdict(peeked: &libc::siginfo_t, threads: impl FnOnce() -> Result<Vec<Thread>, i32>) -> Result<Stop, i32> {
if peeked.si_pid == 0 {
return Ok(Stop::Running);
}
match threads() {
Ok(threads) if all_parked(&threads) => Ok(Stop::Stopped(peeked.si_status)),
Ok(_) => Ok(Stop::Settling),
Err(libc::ESRCH) => Ok(Stop::Running),
Err(e) => Err(e),
}
}
const PROC_PIDLISTTHREADIDS: libc::c_int = 28;
const PROC_PIDTHREADID64INFO: libc::c_int = 15;
fn pidinfo<T>(pid: u32, flavor: libc::c_int, arg: u64, buf: &mut [T]) -> Result<usize, i32> {
let size = std::mem::size_of_val(buf) as libc::c_int;
let n = unsafe { libc::proc_pidinfo(pid as libc::c_int, flavor, arg, buf.as_mut_ptr().cast(), size) };
if n > 0 {
Ok(n as usize)
} else {
Err(errno())
}
}
fn all_parked(threads: &[Thread]) -> bool {
threads
.iter()
.all(|(_, info)| info.is_some_and(|info| parked(info.pth_run_state, info.pth_flags)))
}
pub(super) type Thread = (u64, Option<libc::proc_threadinfo>);
pub(super) fn threads(pid: u32) -> Result<Vec<Thread>, i32> {
threads_with(
|| thread_ids(pid),
|id| {
let mut thread: [libc::proc_threadinfo; 1] = unsafe { std::mem::zeroed() };
pidinfo(pid, PROC_PIDTHREADID64INFO, id, &mut thread).map(|_| thread[0])
},
)
}
fn threads_with<T>(
list: impl FnOnce() -> Result<Vec<u64>, i32>,
read: impl Fn(u64) -> Result<T, i32>,
) -> Result<Vec<(u64, Option<T>)>, i32> {
list()?
.into_iter()
.map(|id| match read(id) {
Ok(thread) => Ok((id, Some(thread))),
Err(libc::ESRCH) => Ok((id, None)),
Err(e) => Err(e),
})
.collect()
}
fn thread_ids(pid: u32) -> Result<Vec<u64>, i32> {
let mut task: [libc::proc_taskinfo; 1] = unsafe { std::mem::zeroed() };
pidinfo(pid, libc::PROC_PIDTASKINFO, 0, &mut task)?;
let mut ids = vec![0u64; task[0].pti_threadnum.max(1) as usize];
loop {
let n = pidinfo(pid, PROC_PIDLISTTHREADIDS, 0, &mut ids)? / std::mem::size_of::<u64>();
if n < ids.len() {
ids.truncate(n);
return Ok(ids);
}
ids.resize(ids.len() * 2, 0);
}
}
fn parked(run_state: i32, flags: i32) -> bool {
match run_state {
libc::TH_STATE_RUNNING => false,
libc::TH_STATE_UNINTERRUPTIBLE => flags & libc::TH_FLAGS_SWAPPED != 0,
libc::TH_STATE_WAITING | libc::TH_STATE_STOPPED | libc::TH_STATE_HALTED => true,
other => panic!("pth_run_state {other} is no TH_STATE_*"),
}
}
pub(super) fn peek_child(pid: u32) -> Result<(), i32> {
peek(pid, libc::WEXITED | libc::WSTOPPED | libc::WNOHANG).map(drop)
}
pub(super) fn peek(pid: u32, flags: libc::c_int) -> Result<libc::siginfo_t, i32> {
loop {
let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
if unsafe { libc::waitid(libc::P_PID, pid, &mut info, flags | libc::WNOWAIT) } == 0 {
return Ok(info);
}
match errno() {
libc::EINTR => continue,
e => return Err(e),
}
}
}
pub(super) fn read_byte(fd: i32) -> Option<u8> {
let mut byte = 0u8;
loop {
match unsafe { libc::read(fd, (&raw mut byte).cast(), 1) } {
1 => return Some(byte),
0 => return None,
_ => match errno() {
libc::EINTR => continue,
e => panic!("read from fd {fd} failed: errno {e}"),
},
}
}
}
fn subscribe(kq: &Kqueue, s: Subscription) -> Result<(), i32> {
match kq.subscribe(s) {
Ok(()) => Ok(()),
Err(Error::Io(e)) => Err(e.raw_os_error().expect("a refused registration names its errno")),
Err(e) => panic!("kevent registration failed outright: {e}"),
}
}
pub(super) fn watch_exit(kq: &Kqueue, pid: u32) -> Result<(), i32> {
subscribe(
kq,
Subscription::Process {
pid,
signals: false,
reap: false,
},
)
}
const SIGNAL_PIPE: Subscription = Subscription::Readable { fd: 0, low_water: 1 };
pub(super) fn watch_signal_pipe(kq: &Kqueue) -> Result<(), i32> {
subscribe(kq, SIGNAL_PIPE)
}
pub(super) fn watch_sigchld(kq: &Kqueue) -> Result<(), i32> {
subscribe(kq, Subscription::Signal(libc::SIGCHLD))
}
pub(super) fn unwatch_signal_pipe(kq: &Kqueue) {
kq.unsubscribe(SIGNAL_PIPE)
.unwrap_or_else(|e| panic!("removing the signal pipe's registration failed: {e}"));
}
#[cfg(test)]
#[path = "sys_tests.rs"]
mod sys_tests;