#[cfg(unix)]
use std::io;
#[cfg(unix)]
use crate::error::io_context;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Sig {
Kill,
}
#[cfg(target_os = "linux")]
impl Sig {
fn as_rustix(self) -> rustix::process::Signal {
match self {
Sig::Kill => rustix::process::Signal::KILL,
}
}
}
#[cfg(target_os = "macos")]
impl Sig {
fn as_libc(self) -> libc::c_int {
match self {
Sig::Kill => libc::SIGKILL,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Sent {
Delivered,
Gone,
#[cfg_attr(
not(any(target_os = "macos", all(unix, feature = "tokio"))),
allow(
dead_code,
reason = "only macOS's by-pid send and tokio's forgotten backend cannot verify a process"
)
)]
Unverified,
}
#[cfg(unix)]
#[derive(Debug)]
pub(crate) enum RootState {
Unreaped,
Reaped,
Unknown(io::Error),
#[cfg_attr(
not(target_os = "macos"),
allow(dead_code, reason = "only macOS reports an unpinned root")
)]
Unpinned,
}
#[cfg(unix)]
#[cfg_attr(
not(target_os = "macos"),
allow(dead_code, reason = "only macOS reports an unpinned root")
)]
pub(crate) const UNPINNED_WHY: &str = "launchd holds its zombie (its tracer died), so it is not ours to reap";
#[cfg(target_os = "macos")]
pub(crate) fn unpinned_refusal(pid: u32, op: &str, earlier: Option<&str>) -> crate::error::Error {
let earlier = earlier.map_or_else(String::new, |sent| format!(", though {sent} was sent before it"));
crate::error::Error::Unassessable {
detail: format!("pid {pid}: the child cannot be shown to be ours: {UNPINNED_WHY}; {op} sent nothing{earlier}"),
source: None,
}
}
#[cfg(unix)]
pub(crate) fn is_unpinned(state: impl FnOnce() -> RootState) -> bool {
#[cfg(target_os = "macos")]
return matches!(state(), RootState::Unpinned);
#[cfg(not(target_os = "macos"))]
{
let _ = state;
false
}
}
#[cfg(target_os = "macos")]
pub(crate) fn unpinned_status(pid: u32, op: &str) -> crate::error::Error {
crate::error::Error::Unassessable {
detail: format!("pid {pid}: {op} signalled the tree, but its exit status cannot be collected: {UNPINNED_WHY}"),
source: None,
}
}
#[cfg(unix)]
pub(crate) fn refuse_unpinned(
pid: u32,
op: &str,
earlier: Option<&str>,
state: impl FnOnce() -> RootState,
) -> Result<(), crate::error::Error> {
#[cfg(target_os = "macos")]
if is_unpinned(state) {
return Err(unpinned_refusal(pid, op, earlier));
}
#[cfg(not(target_os = "macos"))]
let _ = (pid, op, earlier, state);
Ok(())
}
#[cfg(target_os = "macos")]
pub(crate) fn untrusted_root(state: impl FnOnce() -> RootState) -> Option<RootState> {
let state = state();
matches!(state, RootState::Unpinned | RootState::Unknown(_)).then_some(state)
}
#[cfg(target_os = "macos")]
pub(crate) fn why_untrusted(state: &RootState) -> String {
match state {
RootState::Unpinned => format!("the root is not pinned by this process (RootState::Unpinned: {UNPINNED_WHY})"),
RootState::Unknown(e) => format!("the root could not be shown to be unreaped (RootState::Unknown: {e})"),
RootState::Unreaped | RootState::Reaped => {
debug_assert!(false, "{state:?} leaves the root's number trusted");
"the root's number is trusted".to_owned()
}
}
}
#[cfg(unix)]
impl RootState {
pub(crate) fn of_peek(peeked: io::Result<crate::wait::exit_only::Peek>) -> RootState {
use crate::wait::exit_only::Peek;
match peeked {
Ok(Peek::Running | Peek::Exit(_)) => RootState::Unreaped,
#[cfg(target_os = "macos")]
Ok(Peek::Foreign(crate::wait::exit_only::Foreign::Orphaned)) => RootState::Unpinned,
Ok(Peek::Foreign(_)) => RootState::Reaped,
Err(e) => RootState::Unknown(e),
}
}
}
#[cfg(target_os = "linux")]
pub(crate) fn via_pidfd(pidfd: Option<std::os::fd::BorrowedFd<'_>>, pid: u32, sig: Sig) -> io::Result<Sent> {
let Some(pidfd) = pidfd else {
log::debug!("child {pid} has no pidfd (it was gone when adopted); {sig:?} not sent");
return Ok(Sent::Gone);
};
#[cfg(test)]
crate::send_log::record(pid, sig, crate::send_log::Via::Pidfd);
#[cfg(test)]
if let Some(errno) = seams::kills_refused() {
return Err(io_context("pidfd_send_signal", io::Error::from_raw_os_error(errno)));
}
match rustix::process::pidfd_send_signal(pidfd, sig.as_rustix()) {
Ok(()) => Ok(Sent::Delivered),
Err(rustix::io::Errno::SRCH) => {
log::debug!("pidfd_send_signal({sig:?}) to child {pid}: it is already gone");
Ok(Sent::Gone)
}
Err(e) => Err(io_context("pidfd_send_signal", e.into())),
}
}
#[cfg(all(target_os = "macos", test))]
pub(crate) fn read_identity(pid: u32) -> Result<Option<u64>, i32> {
use crate::identity::{uniq_info, ReadPurpose, UniqRead};
match uniq_info(pid, ReadPurpose::Adopt) {
UniqRead::Found(info) => Ok(Some(info.unique_id)),
UniqRead::Gone => Ok(None),
UniqRead::Refused(errno) => Err(errno),
}
}
#[cfg(all(target_os = "macos", test))]
pub(crate) fn identity_unreadable(pid: u32, errno: i32) -> crate::error::Error {
crate::error::Error::Unassessable {
detail: format!("pid {pid}: its identity could not be read (errno {errno}); the child was not adopted"),
source: Some(io::Error::from_raw_os_error(errno)),
}
}
#[cfg(target_os = "macos")]
pub(crate) fn via_verified_pid(pid: u32, identity: Option<u64>, sig: Sig) -> io::Result<Sent> {
use crate::identity::{uniq_info, ReadPurpose, UniqRead};
let unreadable = |errno: i32| {
io_context(
format!("pid {pid}: its identity could not be read; {sig:?} not sent"),
io::Error::from_raw_os_error(errno),
)
};
let Some(expected) = identity else {
log::debug!("child {pid} holds no unique id; {sig:?} not sent");
return Ok(Sent::Unverified);
};
match uniq_info(pid, ReadPurpose::Kill) {
UniqRead::Found(now) if now.unique_id == expected => {}
UniqRead::Found(_) | UniqRead::Gone => {
log::debug!("child {pid} is gone or its pid names another process; {sig:?} not sent");
return Ok(Sent::Gone);
}
UniqRead::Refused(errno) => return Err(unreadable(errno)),
}
let Some(target) = crate::identity::probe::signal_target(pid) else {
debug_assert!(false, "a child's pid {pid} is not a single-process signal target");
return Err(io::Error::other(format!(
"pid {pid} is not a single-process signal target; {sig:?} not sent"
)));
};
#[cfg(test)]
crate::send_log::record(pid, sig, crate::send_log::Via::Pid);
#[cfg(test)]
if let Some(errno) = seams::kills_refused() {
return Err(io_context("kill", io::Error::from_raw_os_error(errno)));
}
if unsafe { libc::kill(target, sig.as_libc()) } == 0 {
return Ok(Sent::Delivered);
}
let e = io::Error::last_os_error();
if e.raw_os_error() == Some(libc::ESRCH) {
log::debug!("kill({pid}, {sig:?}): the child is already gone");
return Ok(Sent::Gone);
}
Err(io_context("kill", e))
}
#[cfg(all(test, unix))]
pub(crate) mod seams {
use std::cell::Cell;
thread_local! {
static REFUSED: Cell<Option<i32>> = const { Cell::new(None) };
}
pub(crate) fn refuse_kills() -> RefusedKills {
fail_kills_with(libc::EPERM)
}
pub(crate) fn fail_kills_with(errno: i32) -> RefusedKills {
REFUSED.with(|r| r.set(Some(errno)));
RefusedKills(())
}
#[must_use = "kills are sent again as soon as the guard is dropped"]
pub(crate) struct RefusedKills(());
impl Drop for RefusedKills {
fn drop(&mut self) {
REFUSED.with(|r| r.set(None));
}
}
pub(super) fn kills_refused() -> Option<i32> {
REFUSED.with(Cell::get)
}
}
#[cfg(all(test, unix))]
#[path = "signal_tests.rs"]
mod signal_tests;