use std::cell::RefCell;
use std::io;
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
use std::sync::atomic::{AtomicI32, Ordering};
const MAX_PIDS: usize = 128;
const LIST_MAX: usize = 1024;
const SCAN_NS: libc::c_long = 2_000_000;
#[cfg(target_os = "linux")]
const EMPTY_CHILD_POLLS: u32 = 4;
#[cfg(target_os = "macos")]
const IDENTITY_POLLS: usize = 4096;
static STOP: AtomicI32 = AtomicI32::new(0);
static mut MISSED: u8 = 0;
pub(super) struct ReportPipe {
read: Option<OwnedFd>,
write: Option<OwnedFd>,
pub(super) armed: bool,
}
thread_local! {
static STASHED: RefCell<Option<ReportPipe>> = const { RefCell::new(None) };
}
#[derive(Clone, Copy)]
struct Row {
pid: libc::pid_t,
#[cfg(target_os = "macos")]
sec: u64,
#[cfg(target_os = "macos")]
usec: u64,
}
struct Table {
n: usize,
rows: [Row; MAX_PIDS],
}
static mut TABLE: Table = Table {
n: 0,
rows: [Row {
pid: 0,
#[cfg(target_os = "macos")]
sec: 0,
#[cfg(target_os = "macos")]
usec: 0,
}; MAX_PIDS],
};
#[cfg(target_os = "macos")]
struct Overflow {
n: usize,
rows: [Row; LIST_MAX],
}
#[cfg(target_os = "macos")]
static mut OVERFLOW: Overflow = Overflow {
n: 0,
rows: [Row {
pid: 0,
sec: 0,
usec: 0,
}; LIST_MAX],
};
#[cfg(target_os = "macos")]
struct PidSet {
n: usize,
pids: [libc::pid_t; MAX_PIDS + 1],
}
#[cfg(target_os = "macos")]
static mut CMD_PID: libc::pid_t = 0;
#[cfg(target_os = "macos")]
#[derive(Clone, Copy)]
struct Identity {
ready: u8,
comm: [u8; 16],
uid: u32,
sec: u64,
usec: u64,
}
#[cfg(target_os = "macos")]
static mut IDENT: Identity = Identity {
ready: 0,
comm: [0; 16],
uid: 0,
sec: 0,
usec: 0,
};
#[cfg(target_os = "macos")]
static mut REAPER_COMM: [u8; 16] = [0; 16];
#[cfg(target_os = "macos")]
static mut REAPER_COMM_READY: u8 = 0;
#[cfg(target_os = "macos")]
static mut SEEN: PidSet = PidSet {
n: 0,
pids: [0; MAX_PIDS + 1],
};
#[derive(Clone, Copy, PartialEq, Eq)]
enum Remember {
Stored,
Already,
Full,
}
impl ReportPipe {
pub(super) fn write_raw(&self) -> i32 {
self.write.as_ref().map(AsRawFd::as_raw_fd).unwrap_or(-1)
}
fn close_write(&mut self) {
self.write.take();
}
pub(super) fn tracked(mut self, timed_out: bool) -> bool {
if !self.armed {
return true;
}
let read = self.read.take();
drop(self.write.take());
if timed_out {
drop(read);
return true;
}
let Some(read) = read else {
return false;
};
let fd = read.as_raw_fd();
let mut buf = [0u8; 1];
let n = loop {
let n = unsafe { libc::read(fd, buf.as_mut_ptr().cast(), 1) };
if n < 0 && errno() == libc::EINTR {
continue;
}
break n;
};
drop(read);
n == 1 && buf[0] == 0
}
}
impl Drop for ReportPipe {
fn drop(&mut self) {
self.write.take();
self.read.take();
}
}
pub(super) fn open_report() -> ReportPipe {
let mut fds = [0; 2];
if unsafe { libc::pipe(fds.as_mut_ptr()) } != 0 {
return ReportPipe {
read: None,
write: None,
armed: true,
};
}
set_cloexec(fds[0]);
set_cloexec(fds[1]);
set_nonblock(fds[0]);
let read = unsafe { OwnedFd::from_raw_fd(fds[0]) };
let write = unsafe { OwnedFd::from_raw_fd(fds[1]) };
ReportPipe {
read: Some(read),
write: Some(write),
armed: true,
}
}
pub(super) fn unarmed_report() -> ReportPipe {
ReportPipe {
read: None,
write: None,
armed: false,
}
}
pub(super) fn stash_report(report: ReportPipe) {
let prev = STASHED.with(|slot| slot.borrow_mut().replace(report));
drop(prev);
}
pub(super) fn close_parent_report_write() {
STASHED.with(|slot| {
if let Some(report) = slot.borrow_mut().as_mut() {
report.close_write();
}
});
}
pub(super) fn discard_report() {
let prev = STASHED.with(|slot| slot.borrow_mut().take());
drop(prev);
}
pub(super) fn take_descendant_report(timed_out: bool) -> bool {
match STASHED.with(|slot| slot.borrow_mut().take()) {
Some(report) => report.tracked(timed_out),
None => timed_out,
}
}
pub(super) fn supervise_or_continue(report_fd: i32) -> io::Result<()> {
#[cfg(target_os = "linux")]
if unsafe { libc::prctl(libc::PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) } != 0 {
return Err(io::Error::last_os_error());
}
let pid = unsafe { libc::fork() };
if pid < 0 {
return Err(io::Error::last_os_error());
}
if pid == 0 {
#[cfg(target_os = "macos")]
unsafe {
libc::raise(libc::SIGSTOP);
}
return Ok(());
}
reaper_main(pid, report_fd);
}
fn reaper_main(cmd: libc::pid_t, report_fd: i32) -> ! {
unsafe {
libc::setpgid(0, 0);
}
reset_tracking();
#[cfg(target_os = "macos")]
unsafe {
std::ptr::addr_of_mut!(CMD_PID).write(cmd);
}
install_stop_handler();
detach_stdio();
let (kq, saw_stop) = watch_command(cmd, report_fd);
close_extra_fds(report_fd, kq);
#[cfg(target_os = "macos")]
{
if saw_stop {
unsafe { libc::kill(cmd, libc::SIGCONT) };
}
cache_command_identity(cmd, kq);
}
#[cfg(not(target_os = "macos"))]
{
let _ = saw_stop;
}
drain_proc_events(kq);
let mut status = 0;
loop {
if STOP.load(Ordering::Relaxed) != 0 {
stop_for_signal(cmd, report_fd, kq);
}
drain_proc_events(kq);
remember_tree(cmd, kq);
#[cfg(target_os = "macos")]
{
continue_stopped_preexec(cmd);
remember_identity(cmd);
}
let waited = unsafe { libc::waitpid(cmd, &mut status, libc::WNOHANG) };
if waited == cmd {
finish(cmd, status, report_fd, kq);
}
if waited < 0 && errno() == libc::ECHILD {
kill_recorded();
kill_adopted();
drain_zombies();
write_report(report_fd);
close_kq(kq);
unsafe { libc::_exit(1) }
}
block_until_scan(kq);
}
}
fn stop_for_signal(cmd: libc::pid_t, report_fd: i32, kq: i32) -> ! {
drain_proc_events(kq);
remember_tree(cmd, kq);
kill_recorded();
unsafe {
libc::kill(cmd, libc::SIGKILL);
}
let mut status = 0;
for _ in 0..20 {
let waited = unsafe { libc::waitpid(cmd, &mut status, libc::WNOHANG) };
if waited == cmd {
break;
}
block_until_scan(kq);
drain_proc_events(kq);
remember_tree(cmd, kq);
}
kill_adopted();
drain_zombies();
write_report(report_fd);
close_kq(kq);
unsafe { libc::_exit(128 + libc::SIGTERM) }
}
fn finish(cmd: libc::pid_t, status: libc::c_int, report_fd: i32, kq: i32) -> ! {
drain_proc_events(kq);
remember_tree(cmd, kq);
kill_recorded();
kill_adopted();
drain_zombies();
write_report(report_fd);
close_kq(kq);
exit_like_command(status);
}
fn exit_like_command(status: libc::c_int) -> ! {
if libc::WIFEXITED(status) {
unsafe { libc::_exit(libc::WEXITSTATUS(status)) }
}
if libc::WIFSIGNALED(status) {
let sig = libc::WTERMSIG(status);
unsafe {
libc::signal(sig, libc::SIG_DFL);
libc::raise(sig);
libc::_exit(128 + sig);
}
}
unsafe { libc::_exit(1) }
}
fn watch_command(cmd: libc::pid_t, report_fd: i32) -> (i32, bool) {
#[cfg(target_os = "macos")]
{
watch_command_macos(cmd, report_fd)
}
#[cfg(not(target_os = "macos"))]
{
let _ = (cmd, report_fd);
(-1, false)
}
}
#[cfg(target_os = "macos")]
fn watch_command_macos(cmd: libc::pid_t, report_fd: i32) -> (i32, bool) {
let Some(status) = wait_until_stopped(cmd) else {
mark_missed();
if STOP.load(Ordering::Relaxed) != 0 {
stop_for_signal(cmd, report_fd, -1);
}
return (-1, false);
};
if !libc::WIFSTOPPED(status) {
finish(cmd, status, report_fd, -1);
}
let kq = unsafe { libc::kqueue() };
if kq < 0 || !arm_knote_macos(kq, cmd) {
mark_missed();
if kq >= 0 {
unsafe { libc::close(kq) };
}
return (-1, true);
}
(kq, true)
}
#[cfg(target_os = "macos")]
fn wait_until_stopped(cmd: libc::pid_t) -> Option<libc::c_int> {
#[cfg(test)]
if test_misses_stop() {
return None;
}
let mut status = 0;
loop {
if STOP.load(Ordering::Relaxed) != 0 {
return None;
}
let waited = unsafe { libc::waitpid(cmd, &mut status, libc::WUNTRACED) };
if waited == cmd {
return Some(status);
}
if waited < 0 && errno() == libc::EINTR {
continue;
}
return None;
}
}
#[cfg(all(test, target_os = "macos"))]
thread_local! {
static MISS_STOP: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
#[cfg(all(test, target_os = "macos"))]
fn test_misses_stop() -> bool {
MISS_STOP.with(|flag| flag.get())
}
#[cfg(all(test, target_os = "macos"))]
fn arm_missed_stop() -> MissedStopGuard {
MISS_STOP.with(|flag| flag.set(true));
MissedStopGuard
}
#[cfg(all(test, target_os = "macos"))]
struct MissedStopGuard;
#[cfg(all(test, target_os = "macos"))]
impl Drop for MissedStopGuard {
fn drop(&mut self) {
MISS_STOP.with(|flag| flag.set(false));
}
}
pub(super) fn leader_pid(reaper: libc::pid_t) -> Option<libc::pid_t> {
for _ in 0..50 {
if let Some(pid) = first_child(reaper) {
let pg = unsafe { libc::getpgid(pid) };
if pg == pid {
return Some(pid);
}
}
sleep_scan();
}
None
}
pub(super) fn is_group_leader(pid: libc::pid_t) -> bool {
let pg = unsafe { libc::getpgid(pid) };
pg == pid
}
fn first_child(pid: libc::pid_t) -> Option<libc::pid_t> {
let mut kids = [0; 8];
let (n, _) = direct_children(pid, &mut kids);
if n == 0 { None } else { Some(kids[0]) }
}
fn install_stop_handler() {
unsafe {
let mut action: libc::sigaction = std::mem::zeroed();
action.sa_sigaction = on_stop as *const () as libc::sighandler_t;
libc::sigemptyset(&mut action.sa_mask);
libc::sigaction(libc::SIGTERM, &action, std::ptr::null_mut());
}
}
unsafe extern "C" fn on_stop(_sig: libc::c_int) {
STOP.store(1, Ordering::Relaxed);
}
pub(super) fn inherited_fd_scan_end(rlim_cur: libc::rlim_t) -> libc::c_int {
if rlim_cur <= 3 {
return 3;
}
if rlim_cur > libc::c_int::MAX as libc::rlim_t {
return libc::c_int::MAX;
}
libc::c_int::try_from(rlim_cur).unwrap_or(libc::c_int::MAX)
}
fn numeric_scan_end(rlim_cur: libc::rlim_t) -> Option<libc::c_int> {
if rlim_cur > libc::c_int::MAX as libc::rlim_t {
None
} else {
Some(inherited_fd_scan_end(rlim_cur))
}
}
fn soft_nofile() -> libc::rlim_t {
let mut limit = libc::rlimit {
rlim_cur: 1024,
rlim_max: 1024,
};
unsafe {
libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit);
}
limit.rlim_cur
}
#[cfg(any(test, target_os = "linux"))]
fn close_ranges(first: i32, keep_a: i32, keep_b: i32) -> ([(u32, u32); 3], usize) {
let mut ranges = [(0u32, 0u32); 3];
let mut n = 0usize;
if first < 0 {
return (ranges, 0);
}
let mut keeps = [keep_a, keep_b];
keeps.sort_unstable();
let mut cursor = first;
for keep in keeps {
if keep < cursor {
continue;
}
if keep > cursor {
let Ok(start) = u32::try_from(cursor) else {
return (ranges, n);
};
let Ok(last) = u32::try_from(keep - 1) else {
return (ranges, n);
};
ranges[n] = (start, last);
n += 1;
}
cursor = match keep.checked_add(1) {
Some(next) => next,
None => return (ranges, n),
};
}
if n < ranges.len()
&& let Ok(start) = u32::try_from(cursor)
{
ranges[n] = (start, u32::MAX);
n += 1;
}
(ranges, n)
}
#[cfg(target_os = "linux")]
fn linux_close_range(first: u32, last: u32, flags: libc::c_int) -> bool {
#[cfg(target_env = "gnu")]
let rc = unsafe { libc::close_range(first, last, flags) };
#[cfg(not(target_env = "gnu"))]
let rc = unsafe { libc::syscall(libc::SYS_close_range, first, last, flags) as libc::c_int };
rc == 0
}
#[cfg(target_os = "linux")]
fn linux_cloexec_from(first: i32) -> bool {
let Ok(start) = u32::try_from(first) else {
return false;
};
linux_close_range(start, u32::MAX, libc::CLOSE_RANGE_CLOEXEC as libc::c_int)
}
#[cfg(target_os = "linux")]
fn linux_close_from_except(first: i32, keep_a: i32, keep_b: i32) -> bool {
let (ranges, n) = close_ranges(first, keep_a, keep_b);
ranges
.iter()
.take(n)
.all(|&(start, last)| linux_close_range(start, last, 0))
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn parse_fd_name(name: &[u8]) -> Option<i32> {
if name.is_empty() {
return None;
}
let mut n: i32 = 0;
for byte in name {
if !byte.is_ascii_digit() {
return None;
}
n = n.checked_mul(10)?.checked_add(i32::from(byte - b'0'))?;
}
Some(n)
}
#[cfg(target_os = "macos")]
unsafe extern "C" {
fn getdirentries(
fd: libc::c_int,
buf: *mut libc::c_char,
nbytes: libc::c_int,
basep: *mut libc::c_long,
) -> libc::ssize_t;
}
#[cfg(target_os = "macos")]
fn macos_dirent_name(buf: &[u8], off: usize) -> Option<(usize, &[u8])> {
if off + 8 > buf.len() {
return None;
}
let reclen = usize::from(u16::from_le_bytes([buf[off + 4], buf[off + 5]]));
if reclen < 8 || off + reclen > buf.len() {
return None;
}
let namlen = usize::from(buf[off + 7]);
if namlen > reclen - 8 {
return None;
}
Some((reclen, &buf[off + 8..off + 8 + namlen]))
}
#[cfg(target_os = "macos")]
fn walk_dev_fd(mut f: impl FnMut(i32)) -> bool {
let dir = unsafe { libc::open(c"/dev/fd".as_ptr(), libc::O_RDONLY | libc::O_CLOEXEC) };
if dir < 0 {
return false;
}
let mut buf = [0u8; 4096];
let mut base: libc::c_long = 0;
loop {
let nread = unsafe {
getdirentries(
dir,
buf.as_mut_ptr().cast(),
buf.len() as libc::c_int,
&mut base,
)
};
if nread < 0 {
unsafe { libc::close(dir) };
return false;
}
if nread == 0 {
break;
}
let nread = usize::try_from(nread).unwrap_or(0);
if nread == 0 || nread > buf.len() {
unsafe { libc::close(dir) };
return false;
}
let mut off = 0usize;
while off + 8 <= nread {
let Some((reclen, name)) = macos_dirent_name(&buf, off) else {
unsafe { libc::close(dir) };
return false;
};
if let Some(fd) = parse_fd_name(name)
&& fd >= 3
&& fd != dir
{
f(fd);
}
off += reclen;
}
}
unsafe { libc::close(dir) };
true
}
#[cfg(target_os = "linux")]
fn walk_proc_fd(mut f: impl FnMut(i32)) -> bool {
let dir = unsafe {
libc::open(
c"/proc/self/fd".as_ptr(),
libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC,
)
};
if dir < 0 {
return false;
}
let mut buf = [0u8; 4096];
loop {
let nread = unsafe {
libc::syscall(
libc::SYS_getdents64,
dir,
buf.as_mut_ptr().cast::<libc::c_void>(),
buf.len() as libc::c_long,
)
};
if nread < 0 {
unsafe { libc::close(dir) };
return false;
}
if nread == 0 {
break;
}
let nread = usize::try_from(nread).unwrap_or(usize::MAX);
if nread > buf.len() {
unsafe { libc::close(dir) };
return false;
}
let mut off = 0usize;
while off + 19 <= nread {
let reclen = usize::from(u16::from_le_bytes([buf[off + 16], buf[off + 17]]));
if reclen < 19 || off + reclen > nread {
unsafe { libc::close(dir) };
return false;
}
let name = &buf[off + 19..off + reclen];
let end = name.iter().position(|b| *b == 0).unwrap_or(name.len());
if let Some(fd) = parse_fd_name(&name[..end])
&& fd >= 3
&& fd != dir
{
f(fd);
}
off += reclen;
}
}
unsafe { libc::close(dir) };
true
}
#[cfg(target_os = "macos")]
fn walk_open_fds(f: impl FnMut(i32)) -> bool {
walk_dev_fd(f)
}
#[cfg(target_os = "linux")]
fn walk_open_fds(f: impl FnMut(i32)) -> bool {
walk_proc_fd(f)
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
fn walk_open_fds(f: impl FnMut(i32)) -> bool {
let _ = f;
false
}
fn mark_listed_fds() -> bool {
walk_open_fds(set_cloexec)
}
fn close_listed_fds(mut pred: impl FnMut(i32) -> bool) -> bool {
loop {
let mut batch = [0i32; 128];
let mut n = 0usize;
let mut more = false;
let ok = walk_open_fds(|fd| {
if !pred(fd) {
return;
}
if n == batch.len() {
more = true;
return;
}
batch[n] = fd;
n += 1;
});
if !ok {
return false;
}
if n == 0 {
return true;
}
let mut closed = false;
for fd in &batch[..n] {
if unsafe { libc::close(*fd) } == 0 {
closed = true;
}
}
if !more {
return closed;
}
if !closed {
return false;
}
}
}
pub(super) fn cloexec_inherited_fds() -> io::Result<()> {
#[cfg(target_os = "linux")]
if linux_cloexec_from(3) {
return Ok(());
}
if mark_listed_fds() {
return Ok(());
}
let Some(end) = numeric_scan_end(soft_nofile()) else {
return Err(io::Error::other(
"could not mark inherited descriptors close-on-exec",
));
};
for fd in 3..end {
set_cloexec(fd);
}
Ok(())
}
fn close_extra_fds(keep_a: i32, keep_b: i32) {
#[cfg(target_os = "linux")]
if linux_close_from_except(3, keep_a, keep_b) {
return;
}
if close_listed_fds(|fd| fd != keep_a && fd != keep_b) {
return;
}
let Some(end) = numeric_scan_end(soft_nofile()) else {
for fd in 3..4096 {
if fd != keep_a && fd != keep_b {
unsafe {
libc::close(fd);
}
}
}
return;
};
for fd in 3..end {
if fd == keep_a || fd == keep_b {
continue;
}
unsafe {
libc::close(fd);
}
}
}
pub(super) fn close_cloexec_above_stdio() {
if close_listed_fds(|fd| {
let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
flags >= 0 && flags & libc::FD_CLOEXEC != 0
}) {
return;
}
let end = numeric_scan_end(soft_nofile()).unwrap_or(4096).min(4096);
for fd in 3..end {
close_if_cloexec(fd);
}
}
fn close_if_cloexec(fd: i32) {
let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
if flags >= 0 && flags & libc::FD_CLOEXEC != 0 {
unsafe {
libc::close(fd);
}
}
}
fn detach_stdio() {
let fd = unsafe { libc::open(c"/dev/null".as_ptr(), libc::O_RDWR) };
if fd < 0 {
return;
}
unsafe {
libc::dup2(fd, 0);
libc::dup2(fd, 1);
libc::dup2(fd, 2);
if fd > 2 {
libc::close(fd);
}
}
}
fn sleep_scan() {
let req = libc::timespec {
tv_sec: 0,
tv_nsec: SCAN_NS,
};
let mut rem = libc::timespec {
tv_sec: 0,
tv_nsec: 0,
};
unsafe {
libc::nanosleep(&req, &mut rem);
}
}
fn remember_tree(root: libc::pid_t, kq: i32) {
let mut stack = [0; LIST_MAX];
let mut sp = 0usize;
let mut kids = [0; LIST_MAX];
push_children(root, kq, &mut kids, &mut stack, &mut sp);
while sp > 0 {
sp -= 1;
let pid = stack[sp];
note_pid(pid, kq);
push_children(pid, kq, &mut kids, &mut stack, &mut sp);
}
}
fn push_children(
pid: libc::pid_t,
kq: i32,
kids: &mut [libc::pid_t; LIST_MAX],
stack: &mut [libc::pid_t; LIST_MAX],
sp: &mut usize,
) {
let (n, trunc) = direct_children(pid, kids);
if trunc {
mark_missed();
}
if n > 0 {
#[cfg(target_os = "macos")]
note_seen(pid);
}
for kid in kids.iter().take(n).copied() {
if *sp < stack.len() {
stack[*sp] = kid;
*sp += 1;
} else {
note_pid(kid, kq);
mark_missed();
}
}
}
fn note_pid(pid: libc::pid_t, kq: i32) -> Remember {
let stored = remember(pid);
if stored == Remember::Stored && !arm_knote(kq, pid) {
mark_missed();
}
stored
}
fn remember(pid: libc::pid_t) -> Remember {
if pid <= 0 {
return Remember::Already;
}
let table = unsafe { &mut *std::ptr::addr_of_mut!(TABLE) };
if table.rows.iter().take(table.n).any(|row| row.pid == pid) {
return Remember::Already;
}
if table.n >= MAX_PIDS {
mark_missed();
save_overflow(pid);
return Remember::Full;
}
#[cfg(target_os = "macos")]
let (sec, usec) = start_time(pid).unwrap_or((0, 0));
table.rows[table.n] = Row {
pid,
#[cfg(target_os = "macos")]
sec,
#[cfg(target_os = "macos")]
usec,
};
table.n += 1;
Remember::Stored
}
fn save_overflow(pid: libc::pid_t) {
#[cfg(target_os = "macos")]
{
let over = unsafe { &mut *std::ptr::addr_of_mut!(OVERFLOW) };
if over.rows.iter().take(over.n).any(|row| row.pid == pid) {
return;
}
if over.n >= LIST_MAX {
unsafe { libc::kill(pid, libc::SIGKILL) };
return;
}
let (sec, usec) = start_time(pid).unwrap_or((0, 0));
over.rows[over.n] = Row { pid, sec, usec };
over.n += 1;
}
#[cfg(not(target_os = "macos"))]
{
let _ = pid;
}
}
fn errno() -> libc::c_int {
#[cfg(target_os = "linux")]
unsafe {
*libc::__errno_location()
}
#[cfg(target_os = "macos")]
unsafe {
*libc::__error()
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
{
0
}
}
fn kill_recorded() {
#[cfg(not(target_os = "macos"))]
return;
#[cfg(target_os = "macos")]
{
kill_recorded_macos();
}
}
#[cfg(target_os = "macos")]
fn kill_recorded_macos() {
let table = unsafe { &*std::ptr::addr_of!(TABLE) };
let recorded: [Row; MAX_PIDS] = table.rows;
let recorded_n = table.n;
kill_rows(&recorded[..recorded_n]);
let over = unsafe { &*std::ptr::addr_of!(OVERFLOW) };
let n = over.n;
for i in 0..n {
let row = unsafe { (*std::ptr::addr_of!(OVERFLOW)).rows[i] };
kill_row(row);
}
}
#[cfg(target_os = "macos")]
fn kill_rows(rows: &[Row]) {
for row in rows {
kill_row(*row);
}
}
#[cfg(target_os = "macos")]
fn kill_row(row: Row) {
if row.pid <= 0 || !same_process(row) {
return;
}
unsafe {
libc::kill(row.pid, libc::SIGKILL);
}
}
#[cfg(target_os = "macos")]
fn same_process(row: Row) -> bool {
if row.sec == 0 && row.usec == 0 {
return parent_is_us_or_command(row.pid);
}
match start_time(row.pid) {
Some((sec, usec)) => sec == row.sec && usec == row.usec,
None => false,
}
}
#[cfg(target_os = "macos")]
fn parent_is_us_or_command(pid: libc::pid_t) -> bool {
let ppid = parent_pid(pid);
if ppid <= 0 {
return false;
}
ppid == unsafe { libc::getpid() } || child_of_command(ppid)
}
#[cfg(target_os = "macos")]
fn child_of_command(pid: libc::pid_t) -> bool {
let me = unsafe { libc::getpid() };
let mut kids = [0; LIST_MAX];
let (n, trunc) = direct_children(me, &mut kids);
if trunc {
mark_missed();
}
kids.into_iter().take(n).any(|kid| kid == pid)
}
fn kill_adopted() {
let mut kills = 0u32;
let mut empty = 0u32;
let empty_limit = empty_child_polls();
while kills < 32 {
let mut kids = [0; LIST_MAX];
let (n, trunc) = direct_children(unsafe { libc::getpid() }, &mut kids);
if trunc || n > MAX_PIDS {
mark_missed();
}
if n == 0 {
if empty >= empty_limit {
break;
}
empty += 1;
sleep_scan();
continue;
}
empty = 0;
kills += 1;
for kid in kids.into_iter().take(n) {
unsafe {
libc::kill(kid, libc::SIGKILL);
}
}
drain_zombies();
sleep_scan();
}
}
fn empty_child_polls() -> u32 {
#[cfg(target_os = "linux")]
{
EMPTY_CHILD_POLLS
}
#[cfg(not(target_os = "linux"))]
{
0
}
}
fn drain_zombies() {
loop {
let mut status = 0;
let waited = unsafe { libc::waitpid(-1, &mut status, libc::WNOHANG) };
if waited <= 0 {
break;
}
}
}
fn direct_children(pid: libc::pid_t, out: &mut [libc::pid_t]) -> (usize, bool) {
#[cfg(target_os = "macos")]
{
direct_children_macos(pid, out)
}
#[cfg(target_os = "linux")]
{
direct_children_linux(pid, out)
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
{
let _ = (pid, out);
(0, false)
}
}
#[cfg(target_os = "macos")]
fn direct_children_macos(pid: libc::pid_t, out: &mut [libc::pid_t]) -> (usize, bool) {
if out.is_empty() {
return (0, true);
}
let n = unsafe {
proc_listchildpids(
pid,
out.as_mut_ptr().cast(),
std::mem::size_of_val(out) as libc::c_int,
)
};
if n <= 0 {
return (0, false);
}
let n = n as usize;
if n > out.len() {
(out.len(), true)
} else {
(n, false)
}
}
#[cfg(target_os = "linux")]
fn direct_children_linux(pid: libc::pid_t, out: &mut [libc::pid_t]) -> (usize, bool) {
let mut path = [0u8; 80];
let Some(path) = children_path(pid, &mut path) else {
return (0, false);
};
let fd = unsafe { libc::open(path, libc::O_RDONLY | libc::O_CLOEXEC) };
if fd < 0 {
return (0, false);
}
let mut bytes = [0u8; 4096];
let n = unsafe { libc::read(fd, bytes.as_mut_ptr().cast(), bytes.len()) };
unsafe {
libc::close(fd);
}
if n <= 0 {
return (0, false);
}
let nread = n as usize;
let filled = nread == bytes.len();
let (count, overflow) = parse_pid_list(&bytes[..nread], out);
(count, overflow || filled)
}
#[cfg(target_os = "linux")]
fn children_path(pid: libc::pid_t, buf: &mut [u8; 80]) -> Option<*const libc::c_char> {
let mut n = 0usize;
for b in b"/proc/" {
buf[n] = *b;
n += 1;
}
push_u32(buf, &mut n, pid as u32);
for b in b"/task/" {
buf[n] = *b;
n += 1;
}
push_u32(buf, &mut n, pid as u32);
for b in b"/children\0" {
buf[n] = *b;
n += 1;
}
Some(buf.as_ptr().cast())
}
#[cfg(target_os = "linux")]
fn push_u32(buf: &mut [u8], n: &mut usize, mut value: u32) {
let mut tmp = [0u8; 10];
let mut i = 0usize;
if value == 0 {
tmp[0] = b'0';
i = 1;
} else {
while value > 0 {
tmp[i] = b'0' + (value % 10) as u8;
i += 1;
value /= 10;
}
}
while i > 0 {
i -= 1;
buf[*n] = tmp[i];
*n += 1;
}
}
#[cfg(any(test, target_os = "linux"))]
fn parse_pid_list(bytes: &[u8], out: &mut [libc::pid_t]) -> (usize, bool) {
let mut n = 0usize;
let mut cur: libc::pid_t = 0;
let mut in_num = false;
let mut overflow = false;
for byte in bytes {
if byte.is_ascii_digit() {
in_num = true;
cur = cur
.saturating_mul(10)
.saturating_add((byte - b'0') as libc::pid_t);
} else if in_num {
if n < out.len() {
out[n] = cur;
n += 1;
} else {
overflow = true;
}
cur = 0;
in_num = false;
}
}
if in_num {
if n < out.len() {
out[n] = cur;
n += 1;
} else {
overflow = true;
}
}
(n, overflow)
}
fn drain_proc_events(kq: i32) {
#[cfg(target_os = "macos")]
{
if kq < 0 {
return;
}
let zero = libc::timespec {
tv_sec: 0,
tv_nsec: 0,
};
for _ in 0..256 {
if !next_event(kq, &zero) {
break;
}
}
}
#[cfg(not(target_os = "macos"))]
{
let _ = kq;
}
}
fn block_until_scan(kq: i32) {
if waited_on_kqueue(kq) {
return;
}
sleep_scan();
}
fn waited_on_kqueue(kq: i32) -> bool {
#[cfg(target_os = "macos")]
{
if kq < 0 {
return false;
}
let ts = libc::timespec {
tv_sec: 0,
tv_nsec: SCAN_NS,
};
let _ = next_event(kq, &ts);
true
}
#[cfg(not(target_os = "macos"))]
{
let _ = kq;
false
}
}
fn arm_knote(kq: i32, pid: libc::pid_t) -> bool {
#[cfg(target_os = "macos")]
{
arm_knote_macos(kq, pid)
}
#[cfg(not(target_os = "macos"))]
{
let _ = (kq, pid);
true
}
}
#[cfg(target_os = "macos")]
fn arm_knote_macos(kq: i32, pid: libc::pid_t) -> bool {
if kq < 0 || pid <= 0 {
return false;
}
let mut ev: libc::kevent = unsafe { std::mem::zeroed() };
unsafe {
std::ptr::addr_of_mut!(ev.ident).write(pid as libc::uintptr_t);
std::ptr::addr_of_mut!(ev.filter).write(libc::EVFILT_PROC);
std::ptr::addr_of_mut!(ev.flags).write(libc::EV_ADD | libc::EV_ENABLE | libc::EV_CLEAR);
std::ptr::addr_of_mut!(ev.fflags).write(libc::NOTE_FORK | libc::NOTE_EXIT);
}
let rc = unsafe {
libc::kevent(
kq,
std::ptr::addr_of!(ev),
1,
std::ptr::null_mut(),
0,
std::ptr::null(),
)
};
if rc == 0 || (rc < 0 && errno() == libc::EEXIST) {
return true;
}
if rc < 0 && errno() == libc::ESRCH {
let cmd = unsafe { std::ptr::addr_of!(CMD_PID).read() };
if pid != cmd && proc_info_missing(pid) {
return true;
}
}
false
}
#[cfg(target_os = "macos")]
fn next_event(kq: i32, timeout: *const libc::timespec) -> bool {
let mut ev: libc::kevent = unsafe { std::mem::zeroed() };
let n = unsafe {
libc::kevent(
kq,
std::ptr::null(),
0,
std::ptr::addr_of_mut!(ev),
1,
timeout,
)
};
if n <= 0 {
return false;
}
handle_event(&ev, kq);
true
}
#[cfg(target_os = "macos")]
fn handle_event(ev: &libc::kevent, kq: i32) {
let flags = unsafe { std::ptr::addr_of!(ev.flags).read() };
if flags & libc::EV_ERROR != 0 {
return;
}
let fflags = unsafe { std::ptr::addr_of!(ev.fflags).read() };
let ident = unsafe { std::ptr::addr_of!(ev.ident).read() } as libc::pid_t;
let note_fork = fflags & libc::NOTE_FORK != 0;
let note_exit = fflags & libc::NOTE_EXIT != 0;
if note_fork {
on_fork(ident, kq, note_exit);
}
}
#[cfg(target_os = "macos")]
fn on_fork(parent: libc::pid_t, kq: i32, also_exit: bool) {
remember_identity(parent);
let cmd = unsafe { std::ptr::addr_of!(CMD_PID).read() };
remember_identity(cmd);
let mut kids = [0; LIST_MAX];
let (mut n, trunc) = direct_children(parent, &mut kids);
if trunc {
mark_missed();
}
if n == 0 && !also_exit && !parent_is_gone(parent) {
for _ in 0..16 {
let (n2, trunc2) = direct_children(parent, &mut kids);
if trunc2 {
mark_missed();
}
if n2 > 0 {
n = n2;
break;
}
if parent_is_gone(parent) {
break;
}
}
}
if n > 0 {
note_seen(parent);
for kid in kids.into_iter().take(n) {
note_pid(kid, kq);
}
return;
}
if !also_exit && !parent_is_gone(parent) {
return;
}
if untracked_same_name(parent) {
mark_missed();
}
}
#[cfg(target_os = "macos")]
fn note_seen(pid: libc::pid_t) {
let seen = unsafe { &mut *std::ptr::addr_of_mut!(SEEN) };
if !pidset_insert(seen, pid) {
mark_missed();
}
}
#[cfg(target_os = "macos")]
fn pidset_contains(set: &PidSet, pid: libc::pid_t) -> bool {
set.pids[..set.n].contains(&pid)
}
#[cfg(target_os = "macos")]
fn pidset_insert(set: &mut PidSet, pid: libc::pid_t) -> bool {
if pid <= 0 || pidset_contains(set, pid) {
return true;
}
if set.n >= set.pids.len() {
return false;
}
set.pids[set.n] = pid;
set.n += 1;
true
}
#[cfg(target_os = "macos")]
fn start_time(pid: libc::pid_t) -> Option<(u64, u64)> {
let mut buf = [0u8; 136];
let n = unsafe {
proc_pidinfo(
pid as libc::c_int,
3,
0,
buf.as_mut_ptr().cast(),
buf.len() as libc::c_int,
)
};
if n < 136 {
return None;
}
let sec = u64::from_ne_bytes(buf[120..128].try_into().ok()?);
let usec = u64::from_ne_bytes(buf[128..136].try_into().ok()?);
Some((sec, usec))
}
#[cfg(target_os = "macos")]
fn proc_info_missing(pid: libc::pid_t) -> bool {
if pid <= 0 || unsafe { libc::kill(pid, 0) } != 0 {
return false;
}
let mut buf = [0u8; 136];
let n = unsafe {
proc_pidinfo(
pid as libc::c_int,
3,
0,
buf.as_mut_ptr().cast(),
buf.len() as libc::c_int,
)
};
n < 8
}
#[cfg(target_os = "macos")]
fn parent_is_gone(pid: libc::pid_t) -> bool {
if pid <= 0 {
return true;
}
if unsafe { libc::kill(pid, 0) } != 0 {
return true;
}
let mut buf = [0u8; 8];
let n = unsafe {
proc_pidinfo(
pid as libc::c_int,
3,
0,
buf.as_mut_ptr().cast(),
buf.len() as libc::c_int,
)
};
if n < 8 {
return false;
}
u32::from_ne_bytes([buf[4], buf[5], buf[6], buf[7]]) == 5
}
#[cfg(target_os = "macos")]
fn parent_pid(pid: libc::pid_t) -> libc::pid_t {
let mut buf = [0u8; 136];
let n = unsafe {
proc_pidinfo(
pid as libc::c_int,
3,
0,
buf.as_mut_ptr().cast(),
buf.len() as libc::c_int,
)
};
if n < 20 {
return 0;
}
libc::pid_t::from_ne_bytes(buf[16..20].try_into().unwrap_or([0; 4]))
}
#[cfg(target_os = "macos")]
#[link(name = "proc")]
unsafe extern "C" {
fn proc_listchildpids(
ppid: libc::pid_t,
buffer: *mut libc::c_void,
buffersize: libc::c_int,
) -> libc::c_int;
fn proc_pidinfo(
pid: libc::c_int,
flavor: libc::c_int,
arg: u64,
buffer: *mut libc::c_void,
buffersize: libc::c_int,
) -> libc::c_int;
}
#[cfg(target_os = "macos")]
fn identity_ready() -> bool {
unsafe { std::ptr::addr_of!(IDENT).read().ready != 0 }
}
#[cfg(target_os = "macos")]
fn remember_identity(pid: libc::pid_t) {
if pid <= 0 || identity_ready() {
return;
}
let Some(info) = bsdinfo(pid) else {
return;
};
let comm = &info[48..64];
if comm.iter().all(|byte| *byte == 0) {
return;
}
let Some(mine) = reaper_comm() else {
return;
};
if comm == mine.as_slice() {
return;
}
let sec = u64::from_ne_bytes(info[120..128].try_into().unwrap_or([0; 8]));
let usec = u64::from_ne_bytes(info[128..136].try_into().unwrap_or([0; 8]));
if sec == 0 && usec == 0 {
return;
}
unsafe {
let ident = &mut *std::ptr::addr_of_mut!(IDENT);
ident.comm.copy_from_slice(comm);
ident.uid = u32::from_ne_bytes(info[20..24].try_into().unwrap_or([0; 4]));
ident.sec = sec;
ident.usec = usec;
ident.ready = 1;
}
}
#[cfg(target_os = "macos")]
fn reaper_comm() -> Option<[u8; 16]> {
unsafe {
if std::ptr::addr_of!(REAPER_COMM_READY).read() == 0 {
let info = bsdinfo(libc::getpid())?;
(*std::ptr::addr_of_mut!(REAPER_COMM)).copy_from_slice(&info[48..64]);
std::ptr::addr_of_mut!(REAPER_COMM_READY).write(1);
}
Some(std::ptr::addr_of!(REAPER_COMM).read())
}
}
#[cfg(target_os = "macos")]
fn bsd_status_is_stop(info: &[u8]) -> bool {
if info.len() < 8 {
return false;
}
let status = u32::from_ne_bytes(info[4..8].try_into().unwrap_or([0; 4]));
status == libc::SSTOP
}
#[cfg(target_os = "macos")]
const PROC_FLAG_EXEC: u32 = 0x4000;
#[cfg(target_os = "macos")]
fn preexec_stop_needs_continue(info: &[u8]) -> bool {
if info.len() < 8 || !bsd_status_is_stop(info) {
return false;
}
let flags = u32::from_ne_bytes(info[0..4].try_into().unwrap_or([0; 4]));
flags & PROC_FLAG_EXEC == 0
}
#[cfg(all(test, target_os = "macos"))]
fn command_is_stopped(pid: libc::pid_t) -> bool {
bsdinfo(pid).is_some_and(|info| bsd_status_is_stop(&info))
}
#[cfg(target_os = "macos")]
fn continue_stopped_preexec(cmd: libc::pid_t) {
if cmd <= 0 {
return;
}
let Some(info) = bsdinfo(cmd) else {
return;
};
if !preexec_stop_needs_continue(&info) {
return;
}
unsafe { libc::kill(cmd, libc::SIGCONT) };
}
#[cfg(target_os = "macos")]
fn cache_command_identity(cmd: libc::pid_t, kq: i32) {
for _ in 0..IDENTITY_POLLS {
continue_stopped_preexec(cmd);
drain_proc_events(kq);
if identity_ready() {
return;
}
remember_identity(cmd);
if identity_ready() {
return;
}
if unsafe { libc::kill(cmd, 0) } != 0 {
drain_proc_events(kq);
return;
}
}
}
#[cfg(target_os = "macos")]
fn untracked_same_name(parent: libc::pid_t) -> bool {
remember_identity(parent);
let cmd = unsafe { std::ptr::addr_of!(CMD_PID).read() };
remember_identity(cmd);
if !identity_ready() {
return false;
}
let ident = unsafe { std::ptr::addr_of!(IDENT).read() };
if ident.sec == 0 && ident.usec == 0 {
return false;
}
let me = unsafe { libc::getpid() };
let mut kids = [0; 4096];
let (n, trunc) = direct_children(1, &mut kids);
for pid in kids.into_iter().take(n) {
if pid <= 0 || pid == cmd || pid == me || pid == parent || is_recorded(pid) {
continue;
}
let Some(info) = bsdinfo(pid) else {
continue;
};
let status = u32::from_ne_bytes(info[4..8].try_into().unwrap_or([0; 4]));
if status == 5 || &info[48..64] != ident.comm.as_slice() {
continue;
}
let ouid = u32::from_ne_bytes(info[20..24].try_into().unwrap_or([0; 4]));
if ouid != ident.uid {
continue;
}
let stamp = (
u64::from_ne_bytes(info[120..128].try_into().unwrap_or([0; 8])),
u64::from_ne_bytes(info[128..136].try_into().unwrap_or([0; 8])),
);
if stamp.0 == 0 && stamp.1 == 0 {
continue;
}
if stamp >= (ident.sec, ident.usec) {
return true;
}
}
trunc
}
#[cfg(target_os = "macos")]
fn bsdinfo(pid: libc::pid_t) -> Option<[u8; 136]> {
if pid <= 0 {
return None;
}
let mut buf = [0u8; 136];
let n = unsafe {
proc_pidinfo(
pid as libc::c_int,
3,
0,
buf.as_mut_ptr().cast(),
buf.len() as libc::c_int,
)
};
if n < 136 { None } else { Some(buf) }
}
#[cfg(target_os = "macos")]
fn is_recorded(pid: libc::pid_t) -> bool {
let table = unsafe { &*std::ptr::addr_of!(TABLE) };
if table.rows[..table.n].iter().any(|row| row.pid == pid) {
return true;
}
let over = unsafe { &*std::ptr::addr_of!(OVERFLOW) };
over.rows[..over.n].iter().any(|row| row.pid == pid)
}
fn reset_tracking() {
unsafe {
std::ptr::addr_of_mut!(MISSED).write(0);
let table = &mut *std::ptr::addr_of_mut!(TABLE);
table.n = 0;
#[cfg(target_os = "macos")]
{
(*std::ptr::addr_of_mut!(OVERFLOW)).n = 0;
(*std::ptr::addr_of_mut!(SEEN)).n = 0;
std::ptr::addr_of_mut!(CMD_PID).write(0);
std::ptr::addr_of_mut!(IDENT).write(Identity {
ready: 0,
comm: [0; 16],
uid: 0,
sec: 0,
usec: 0,
});
}
}
}
fn mark_missed() {
unsafe { std::ptr::addr_of_mut!(MISSED).write(1) }
}
fn missed() -> bool {
unsafe { std::ptr::addr_of!(MISSED).read() != 0 }
}
fn write_report(fd: i32) {
#[cfg(target_os = "macos")]
if untracked_same_name(0) {
mark_missed();
}
if fd < 0 {
return;
}
let byte = [u8::from(missed())];
let mut off = 0usize;
while off < byte.len() {
let n = unsafe { libc::write(fd, byte[off..].as_ptr().cast(), byte.len() - off) };
if n < 0 {
if errno() == libc::EINTR {
continue;
}
break;
}
if n == 0 {
break;
}
off += n as usize;
}
unsafe { libc::close(fd) };
}
fn close_kq(kq: i32) {
if kq >= 0 {
unsafe { libc::close(kq) };
}
}
fn set_cloexec(fd: i32) {
unsafe {
let flags = libc::fcntl(fd, libc::F_GETFD);
if flags >= 0 {
libc::fcntl(fd, libc::F_SETFD, flags | libc::FD_CLOEXEC);
}
}
}
fn set_nonblock(fd: i32) {
unsafe {
let flags = libc::fcntl(fd, libc::F_GETFL);
if flags >= 0 {
libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK);
}
}
}
#[cfg(test)]
mod tests {
use super::parse_pid_list;
#[test]
fn parse_proc_children_list() {
let mut out = [0; 4];
let (n, overflow) = parse_pid_list(b"12 34 56\n", &mut out);
assert_eq!(n, 3);
assert!(!overflow);
assert_eq!(&out[..3], &[12, 34, 56]);
}
#[test]
fn parse_proc_children_ignores_empty() {
let mut out = [7; 2];
let (n, overflow) = parse_pid_list(b" \n", &mut out);
assert_eq!(n, 0);
assert!(!overflow);
}
#[test]
fn parse_proc_children_reports_overflow() {
let mut out = [0; 2];
let (n, overflow) = parse_pid_list(b"12 34 56\n", &mut out);
assert_eq!(n, 2);
assert!(overflow);
assert_eq!(&out[..2], &[12, 34]);
}
#[test]
fn report_byte_zero_is_tracked_and_one_is_a_miss() {
let report = super::open_report();
let write = report.write_raw();
let ok = [0u8];
assert_eq!(unsafe { libc::write(write, ok.as_ptr().cast(), 1) }, 1);
assert!(report.tracked(false));
let report = super::open_report();
let write = report.write_raw();
let miss = [1u8];
assert_eq!(unsafe { libc::write(write, miss.as_ptr().cast(), 1) }, 1);
assert!(!report.tracked(false));
}
#[test]
fn report_timeout_and_unarmed_pipe_are_not_misses() {
let report = super::open_report();
assert!(report.tracked(true));
assert!(super::unarmed_report().tracked(false));
}
#[test]
fn inherited_fd_scan_includes_the_fd_at_the_old_cap() {
assert_eq!(super::inherited_fd_scan_end(1024), 1024);
assert_eq!(super::inherited_fd_scan_end(65536), 65536);
assert!(!(3..super::inherited_fd_scan_end(65536)).contains(&65536));
let end = super::inherited_fd_scan_end(1_048_576);
assert_eq!(end, 1_048_576);
assert!((3..end).contains(&65536));
assert_eq!(
super::inherited_fd_scan_end(libc::RLIM_INFINITY),
libc::c_int::MAX
);
assert!(super::numeric_scan_end(libc::RLIM_INFINITY).is_none());
assert_eq!(super::numeric_scan_end(1_048_576), Some(1_048_576));
}
#[test]
fn close_ranges_skip_keepers_and_a_negative_watch() {
let (ranges, n) = super::close_ranges(3, 7, -1);
assert_eq!(&ranges[..n], &[(3, 6), (8, u32::MAX)]);
let (ranges, n) = super::close_ranges(3, 5, 5);
assert_eq!(&ranges[..n], &[(3, 4), (6, u32::MAX)]);
let (ranges, n) = super::close_ranges(3, 3, 4);
assert_eq!(&ranges[..n], &[(5, u32::MAX)]);
let (ranges, n) = super::close_ranges(3, 9, 4);
assert_eq!(&ranges[..n], &[(3, 3), (5, 8), (10, u32::MAX)]);
let (ranges, n) = super::close_ranges(3, libc::c_int::MAX, -1);
let last = u32::try_from(libc::c_int::MAX - 1).expect("last");
assert_eq!(&ranges[..n], &[(3, last)]);
}
#[test]
fn snapshot_lists_an_fd_at_65536() {
const HIGH: libc::c_int = 65536;
struct Restore(Option<libc::rlimit>);
impl Drop for Restore {
fn drop(&mut self) {
if let Some(prev) = self.0 {
unsafe {
libc::setrlimit(libc::RLIMIT_NOFILE, &prev);
}
}
}
}
struct Close(Option<libc::c_int>);
impl Drop for Close {
fn drop(&mut self) {
if let Some(fd) = self.0 {
unsafe {
libc::close(fd);
}
}
}
}
let mut limit = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
assert_eq!(
unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) },
0
);
let need = libc::rlim_t::try_from(HIGH).expect("fd") + 1;
let mut restore = Restore(None);
if limit.rlim_cur < need {
if limit.rlim_max < need {
return;
}
let prev = limit;
limit.rlim_cur = need;
assert_eq!(
unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &limit) },
0,
"setrlimit"
);
restore.0 = Some(prev);
}
let low = unsafe { libc::open(c"/dev/null".as_ptr(), libc::O_RDONLY) };
assert!(low >= 0, "open");
let duped = unsafe { libc::dup2(low, HIGH) };
if duped != HIGH {
let err = std::io::Error::last_os_error().raw_os_error();
unsafe { libc::close(low) };
if matches!(
err,
Some(libc::EBADF) | Some(libc::EMFILE) | Some(libc::EINVAL)
) {
return;
}
panic!("dup2 errno={err:?}");
}
unsafe { libc::close(low) };
let _held = Close(Some(HIGH));
let mut saw = false;
assert!(
super::walk_open_fds(|fd| {
if fd == HIGH {
saw = true;
}
}),
"open-fd list"
);
assert!(saw, "fd {HIGH} missing from the open-fd list");
let _ = restore;
}
#[test]
fn open_fd_walk_passes_1024_descriptors() {
const EXTRA: usize = 1100;
struct Restore(Option<libc::rlimit>);
impl Drop for Restore {
fn drop(&mut self) {
if let Some(prev) = self.0 {
unsafe {
libc::setrlimit(libc::RLIMIT_NOFILE, &prev);
}
}
}
}
let mut limit = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
assert_eq!(
unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) },
0
);
let need = limit.rlim_cur.saturating_add(EXTRA as libc::rlim_t);
let mut restore = Restore(None);
if limit.rlim_cur < need {
if limit.rlim_max < need {
return;
}
let prev = limit;
limit.rlim_cur = need;
assert_eq!(
unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &limit) },
0,
"setrlimit"
);
restore.0 = Some(prev);
}
let mut opened = Vec::with_capacity(EXTRA);
for _ in 0..EXTRA {
let fd = unsafe { libc::open(c"/dev/null".as_ptr(), libc::O_RDONLY) };
assert!(fd >= 0, "open");
opened.push(fd);
}
let mut n = 0usize;
let ok = super::walk_open_fds(|_| n += 1);
for fd in opened {
unsafe { libc::close(fd) };
}
let _ = restore;
assert!(ok, "open-fd list");
assert!(
n >= EXTRA,
"walk saw {n} fds above stdio, wanted at least {EXTRA}"
);
}
#[cfg(target_os = "macos")]
#[test]
fn command_is_stopped_sees_sigstop() {
let child = std::process::Command::new("/bin/sleep")
.arg("30")
.spawn()
.expect("sleep");
let pid = child.id() as libc::pid_t;
struct Reap(std::process::Child);
impl Drop for Reap {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
let reap = Reap(child);
assert_eq!(unsafe { libc::kill(pid, libc::SIGSTOP) }, 0, "SIGSTOP");
let start = std::time::Instant::now();
let mut status = 0;
let mut waited = 0;
while start.elapsed() < std::time::Duration::from_secs(2) {
waited = unsafe { libc::waitpid(pid, &mut status, libc::WNOHANG | libc::WUNTRACED) };
if waited == pid {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert_eq!(waited, pid, "sleep did not stop");
assert!(libc::WIFSTOPPED(status), "status {status}");
assert!(super::command_is_stopped(pid));
let info = super::bsdinfo(pid).expect("bsdinfo");
assert!(
!super::preexec_stop_needs_continue(&info),
"stopped /bin/sleep has already exec'd"
);
drop(reap);
}
#[cfg(target_os = "macos")]
#[test]
fn missed_preexec_stop_is_continued() {
if !crate::kernel_supported() {
return;
}
let _miss = super::arm_missed_stop();
let dir = tempfile::tempdir().expect("temp");
let policy = crate::process_jail(dir.path(), std::iter::empty::<&std::path::Path>())
.expect("policy");
let mut cmd = std::process::Command::new("/bin/echo");
cmd.arg("ok");
cmd.stdout(std::process::Stdio::null());
cmd.stderr(std::process::Stdio::null());
let err = policy.run_child(cmd).expect_err("skipped stop watch");
assert!(matches!(err, crate::KernelError::Descendants), "{err}");
}
#[cfg(target_os = "macos")]
#[test]
fn post_exec_same_name_stop_stays_stopped() {
if !crate::kernel_supported() {
return;
}
let self_info = super::bsdinfo(unsafe { libc::getpid() }).expect("self bsdinfo");
let comm = &self_info[48..64];
let name_len = comm
.iter()
.position(|byte| *byte == 0)
.unwrap_or(comm.len());
assert!(name_len > 0, "empty command name");
let name = std::str::from_utf8(&comm[..name_len]).expect("command name");
let dir = tempfile::tempdir().expect("temp");
let src = dir.path().join("stop.c");
let bin = dir.path().join(name);
let pidfile = dir.path().join("pid");
let marker = dir.path().join("continued");
std::fs::write(
&src,
r#"
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv) {
FILE *out;
if (argc != 3) return 2;
out = fopen(argv[1], "w");
if (!out) return 3;
fprintf(out, "%ld\n", (long)getpid());
if (fclose(out) != 0) return 4;
raise(SIGSTOP);
out = fopen(argv[2], "w");
if (!out) return 5;
fputs("continued\n", out);
fclose(out);
return 0;
}
"#,
)
.expect("write helper");
let compiled = std::process::Command::new("cc")
.arg("-o")
.arg(&bin)
.arg(&src)
.status()
.expect("cc");
assert!(compiled.success(), "cc {compiled}");
let dir_path = dir.path().to_path_buf();
let bin_path = bin.clone();
let pid_path = pidfile.clone();
let marker_path = marker.clone();
let ran = std::thread::spawn(move || {
let policy = crate::process_jail(&dir_path, std::iter::empty::<&std::path::Path>())
.expect("policy");
let mut cmd = std::process::Command::new(bin_path);
cmd.arg(&pid_path);
cmd.arg(&marker_path);
cmd.stdout(std::process::Stdio::null());
cmd.stderr(std::process::Stdio::null());
policy.run_child(cmd)
});
let start = std::time::Instant::now();
let mut cmd_pid = 0;
while start.elapsed() < std::time::Duration::from_secs(3) {
if let Ok(text) = std::fs::read_to_string(&pidfile)
&& let Ok(pid) = text.trim().parse::<i32>()
&& pid > 0
{
cmd_pid = pid;
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
if cmd_pid == 0 {
let outcome = ran.join().expect("run thread");
panic!("command never exec'd: {outcome:?}");
}
let watch = std::time::Instant::now();
let mut saw_stop = false;
while watch.elapsed() < std::time::Duration::from_millis(800) {
if marker.exists() {
break;
}
if super::command_is_stopped(cmd_pid) {
saw_stop = true;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
let continued = marker.exists();
if super::command_is_stopped(cmd_pid) {
saw_stop = true;
}
let reaper = super::parent_pid(cmd_pid);
unsafe {
libc::kill(cmd_pid, libc::SIGKILL);
if reaper > 1 {
libc::kill(reaper, libc::SIGKILL);
}
}
let outcome = ran.join().expect("run thread");
assert!(!continued, "post-exec stop was continued: {outcome:?}");
assert!(saw_stop, "post-exec stop was not visible: {outcome:?}");
}
}