use std::io;
use crate::identity::{held_by, uniq_info, Held, ReadPurpose, UniqRead, LAUNCHD};
use super::{exit_record_of, is_exit_record, Reap, Record, Target};
use crate::os_process::child::{Foreign, PeekOutcome};
fn pid_and_unique(target: &Target<'_>) -> (u32, Option<u64>) {
match target {
Target::Pid { pid, unique, .. } => (*pid, *unique),
}
}
pub(crate) fn waitid_record(pid: u32, options: libc::c_int) -> io::Result<Option<Record>> {
let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
loop {
let r = unsafe { libc::waitid(libc::P_PID, pid as libc::id_t, &mut info, options) };
if r == 0 {
break;
}
let e = io::Error::last_os_error();
if e.raw_os_error() != Some(libc::EINTR) {
return Err(e);
}
}
if info.si_pid == 0 {
return Ok(None);
}
Ok(Some(Record {
si_code: info.si_code,
si_status: info.si_status,
}))
}
fn is_echild(e: &io::Error) -> bool {
e.raw_os_error() == Some(libc::ECHILD)
}
fn peek_raw(pid: u32) -> io::Result<PeekOutcome> {
#[cfg(test)]
if let Some(forced) = super::seams::take_forced_peek() {
return forced;
}
match waitid_record(pid, libc::WEXITED | libc::WNOHANG | libc::WNOWAIT) {
Ok(Some(record)) if is_exit_record(record.si_code) => Ok(PeekOutcome::Exit(exit_record_of(record))),
Ok(_) => Ok(PeekOutcome::Running),
Err(e) if is_echild(&e) => Ok(PeekOutcome::Foreign(Foreign::Gone)),
Err(e) => Err(e),
}
}
enum IdCheck {
Matches,
Other,
Gone,
Unreadable(i32),
}
fn check_unique(pid: u32, unique: u64, purpose: ReadPurpose) -> IdCheck {
match uniq_info(pid, purpose) {
UniqRead::Found(now) if now.unique_id == unique => IdCheck::Matches,
UniqRead::Found(_) => IdCheck::Other,
UniqRead::Gone => IdCheck::Gone,
UniqRead::Refused(errno) => IdCheck::Unreadable(errno),
}
}
pub(super) fn peek(target: &Target<'_>) -> io::Result<PeekOutcome> {
peek_with(target, false)
}
pub(super) fn peek_with(target: &Target<'_>, verified: bool) -> io::Result<PeekOutcome> {
peek_holder(target, verified).map(|(peeked, _)| peeked)
}
pub(super) fn peek_holder(target: &Target<'_>, verified: bool) -> io::Result<(PeekOutcome, Option<u32>)> {
let (pid, unique) = pid_and_unique(target);
let peeked = peek_raw(pid)?;
let Some(unique) = unique else {
return Ok((peeked, None));
};
match peeked {
PeekOutcome::Exit(_) => match check_unique(pid, unique, ReadPurpose::Peek) {
IdCheck::Matches => Ok((peeked, None)),
IdCheck::Other => Ok((PeekOutcome::Foreign(Foreign::Other), None)),
IdCheck::Gone => Ok((PeekOutcome::Foreign(Foreign::Gone), None)),
IdCheck::Unreadable(errno) => Err(io::Error::new(
io::Error::from_raw_os_error(errno).kind(),
format!("pid {pid}: its identity could not be read (errno {errno}); its exit was not consumed"),
)),
},
PeekOutcome::Running => match check_unique(pid, unique, ReadPurpose::Running) {
IdCheck::Other => Ok((PeekOutcome::Foreign(Foreign::Other), None)),
IdCheck::Gone => Ok((PeekOutcome::Foreign(Foreign::Gone), None)),
IdCheck::Matches => Ok((peeked, None)),
IdCheck::Unreadable(_) if !verified => Ok((peeked, None)),
IdCheck::Unreadable(errno) => Err(io::Error::new(
io::Error::from_raw_os_error(errno).kind(),
format!("pid {pid}: its identity could not be read (errno {errno}); it cannot be shown to be ours"),
)),
},
PeekOutcome::Foreign(Foreign::Gone) => match held_by(pid, unique, ReadPurpose::Echild) {
Held::Other => Ok((PeekOutcome::Foreign(Foreign::Other), None)),
Held::Parent(ppid) if ppid == LAUNCHD => Ok((PeekOutcome::Foreign(Foreign::Orphaned), None)),
Held::Parent(ppid) if ppid == std::process::id() => Ok((PeekOutcome::Running, None)),
Held::Parent(tracer) => Ok((PeekOutcome::Running, Some(tracer))),
Held::Gone => Ok((peeked, None)),
Held::Refused(_) if !verified => Ok((peeked, None)),
Held::Refused(errno) => Err(io::Error::new(
io::Error::from_raw_os_error(errno).kind(),
format!("pid {pid}: its identity could not be read (errno {errno}); it cannot be shown to be reaped"),
)),
},
PeekOutcome::Foreign(Foreign::Other | Foreign::Orphaned) => Ok((peeked, None)),
}
}
fn consume(pid: u32) -> io::Result<Option<Record>> {
#[cfg(test)]
if super::seams::take_forced_empty_reap() {
return Ok(None);
}
waitid_record(pid, libc::WEXITED | libc::WNOHANG).map(|r| r.map(super::consumed))
}
pub(super) fn try_reap(target: &Target<'_>) -> io::Result<Reap> {
let (pid, unique) = pid_and_unique(target);
match peek(target)? {
PeekOutcome::Exit(_) => {}
PeekOutcome::Running => return Ok(Reap::Running),
PeekOutcome::Foreign(f) => return Ok(Reap::Foreign(f)),
}
let second_unique = unique.or_else(|| match uniq_info(pid, ReadPurpose::PreReap) {
UniqRead::Found(now) => Some(now.unique_id),
UniqRead::Gone | UniqRead::Refused(_) => None,
});
let first = match consume(pid) {
Ok(Some(record)) => exit_record_of(record),
Ok(None) => return Ok(Reap::Foreign(Foreign::Gone)),
Err(e) if is_echild(&e) => return Ok(Reap::Foreign(Foreign::Gone)),
Err(e) => return Err(e),
};
second_reap(pid, second_unique);
Ok(Reap::Reaped(first))
}
pub(crate) fn second_reap(pid: u32, unique: Option<u64>) {
#[cfg(test)]
super::seams::step(super::seams::HolderStep::SecondPeek);
match peek_raw(pid) {
Ok(PeekOutcome::Exit(_)) => {}
Ok(PeekOutcome::Running) => {
log::debug!("second reap of pid {pid}: nothing to consume");
return;
}
Ok(PeekOutcome::Foreign(_)) => {
log::debug!("second reap of pid {pid}: nothing left to consume");
return;
}
Err(e) if is_echild(&e) => {
log::debug!("second reap of pid {pid}: nothing left to consume");
return;
}
Err(e) => {
log::warn!("second reap of pid {pid}: peek failed ({e}); a zombie may be left");
return;
}
}
let Some(unique) = unique else {
log::warn!("second reap of pid {pid}: no identity to check it against; a zombie may be left");
return;
};
match check_unique(pid, unique, ReadPurpose::SecondPeek) {
IdCheck::Matches => {}
IdCheck::Other | IdCheck::Gone => {
log::debug!("second reap of pid {pid}: the pid names another process now");
return;
}
IdCheck::Unreadable(_) => {
log::warn!("second reap of pid {pid}: its identity could not be read; a zombie may be left");
return;
}
}
match consume(pid) {
Ok(_) => {}
Err(e) if is_echild(&e) => log::debug!("second reap of pid {pid}: already reaped elsewhere"),
Err(e) => log::warn!("second reap of pid {pid} failed ({e}); a zombie may be left"),
}
}