use std::os::fd::AsFd;
use rustix::io::Errno;
use rustix::process::{waitid, WaitId, WaitIdOptions, WaitIdStatus};
use super::child::signal;
use super::log::Log;
use crate::elevation::shim::step::ToChild;
use crate::os_process::linux::fork::NewChild;
fn wait_status(status: &WaitIdStatus) -> Option<i32> {
if let Some(code) = status.exit_status() {
Some((code & 0xff) << 8)
} else {
status
.terminating_signal()
.map(|signal| signal | if status.dumped() { 0x80 } else { 0 })
}
}
pub(super) fn kill(child: &NewChild, log: &Log) {
let sent = signal(child, ToChild::Kill);
log.line(format_args!("kill rc={sent:?}"));
match sent {
Ok(()) => {}
Err(Errno::SRCH) => log::debug!("the program's process is already gone"),
Err(e) => {
log.warn(format_args!(
"cannot kill the program's process: {}",
crate::error::Report(&e)
));
debug_assert!(false, "pidfd_send_signal(SIGKILL): {}", crate::error::Report(&e));
}
}
}
pub(super) fn reap(child: &NewChild, ready: bool, log: &Log) -> Option<i32> {
let mut options = WaitIdOptions::EXITED;
if ready {
options |= WaitIdOptions::NOHANG;
}
match wait_on(child, options, log) {
Wait::Status(status) => return Some(status),
Wait::Gone => return None,
Wait::NotYet => {}
}
log.line(format_args!(
"exited, but only its tracer can see it yet: waiting for its status"
));
match wait_on(child, WaitIdOptions::EXITED, log) {
Wait::Status(status) => Some(status),
Wait::Gone => None,
Wait::NotYet => {
debug_assert!(false, "a blocking waitid returned with nothing to collect");
None
}
}
}
enum Wait {
Status(i32),
Gone,
NotYet,
}
fn wait_on(child: &NewChild, options: WaitIdOptions, log: &Log) -> Wait {
loop {
return match waitid(WaitId::PidFd(child.pidfd.as_fd()), options) {
Ok(Some(status)) => wait_status(&status).map_or(Wait::Gone, Wait::Status),
Ok(None) => Wait::NotYet,
Err(Errno::INTR) => continue,
Err(Errno::CHILD) => Wait::Gone,
Err(e) => {
log.warn(format_args!(
"waitid on the program's pidfd: {}",
crate::error::Report(&e)
));
debug_assert!(false, "waitid on the program's pidfd: {}", crate::error::Report(&e));
Wait::Gone
}
};
}
}
#[cfg(test)]
#[path = "reap_tests.rs"]
mod reap_tests;