use std::process::ExitStatus;
#[cfg(unix)]
use crate::child::drop_report::Forgot;
use crate::child::owned::teardown::HandleTeardown;
#[cfg(target_os = "linux")]
use crate::child::owned::teardown::{Disposition, Past};
#[cfg(target_os = "linux")]
use crate::child::owned::OwnedChild;
#[cfg(target_os = "linux")]
use crate::child::spawn::held_teardown::{tear_down_held, tear_down_pidfd, HeldTeardown};
use crate::child::spawn::Diagnosis;
use crate::containment::dispatch::TeardownCaller;
use crate::error::{ChildFate, Error};
use crate::identity::ProcessId;
use crate::os_process::child::Foreign;
use crate::os_process::OsProcess;
#[cfg(unix)]
use crate::signal::RootState;
use crate::signal::{Sent, Sig};
#[cfg(target_os = "linux")]
use crate::wait::teardown_warn::Due;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Waited {
Exited,
#[cfg_attr(
windows,
allow(dead_code, reason = "a process handle pins its process: no foreign reap")
)]
Foreign,
#[cfg(target_os = "macos")]
Orphaned,
Unverified,
}
#[cfg(unix)]
impl Waited {
fn forgotten(self) -> Option<Forgotten> {
match self {
Waited::Exited => None,
Waited::Foreign => Some(Forgotten::ReapedElsewhere),
#[cfg(target_os = "macos")]
Waited::Orphaned => Some(Forgotten::Unpinned),
Waited::Unverified => Some(Forgotten::Unproven),
}
}
}
#[cfg(unix)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Forgotten {
ReapedElsewhere,
Unpinned,
Unproven,
}
#[cfg(unix)]
impl Forgotten {
fn of(state: &RootState) -> Forgotten {
match state {
RootState::Unknown(_) => Forgotten::Unproven,
RootState::Unpinned => Forgotten::Unpinned,
RootState::Unreaped | RootState::Reaped { .. } => {
debug_assert!(
!matches!(state, RootState::Unreaped),
"a child its handle shows ours is forgotten"
);
Forgotten::ReapedElsewhere
}
}
}
fn gone(self) -> bool {
self != Forgotten::Unproven
}
fn why(self) -> &'static str {
match self {
Forgotten::ReapedElsewhere => "was reaped by someone else",
Forgotten::Unpinned => "is a zombie launchd holds",
Forgotten::Unproven => "cannot be shown to be ours",
}
}
}
#[allow(
clippy::large_enum_variant,
reason = "boxing Raw to shrink it would add an allocation to every async spawn on the common Tokio path"
)]
#[derive(Debug)]
pub(crate) enum ProcSource {
Tokio {
child: Held,
pid: u32,
#[cfg(target_os = "linux")]
pidfd: PinnedPidfd,
#[cfg(target_os = "macos")]
identity: Option<u64>,
},
#[cfg(unix)]
Foreign {
fate: Forgotten,
pid: u32,
#[cfg(target_os = "linux")]
pidfd: PinnedPidfd,
},
#[cfg(windows)]
Raw(crate::tokio::spawn::windows_raw::RawAsyncChild),
}
#[cfg(target_os = "linux")]
#[derive(Debug)]
pub(crate) struct PinnedPidfd(Option<std::os::fd::OwnedFd>);
#[cfg(target_os = "linux")]
const PIDFD_TAKEN: &str = "the pidfd was taken by a teardown that consumes the backend";
#[cfg(target_os = "linux")]
impl PinnedPidfd {
fn take(&mut self) -> std::os::fd::OwnedFd {
self.0.take().expect(PIDFD_TAKEN)
}
fn hand_off(&mut self) -> PinnedPidfd {
PinnedPidfd(Some(self.take()))
}
}
#[cfg(target_os = "linux")]
impl std::ops::Deref for PinnedPidfd {
type Target = std::os::fd::OwnedFd;
fn deref(&self) -> &std::os::fd::OwnedFd {
self.0.as_ref().expect(PIDFD_TAKEN)
}
}
#[cfg(target_os = "linux")]
impl std::os::fd::AsRawFd for PinnedPidfd {
fn as_raw_fd(&self) -> std::os::fd::RawFd {
std::os::fd::AsRawFd::as_raw_fd(&**self)
}
}
#[cfg(target_os = "linux")]
impl std::os::fd::AsFd for PinnedPidfd {
fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
std::os::fd::AsFd::as_fd(&**self)
}
}
#[cfg(all(unix, test))]
const FORGET_FOREIGN: &str = "was reaped by someone else, or cannot be shown to be ours";
#[cfg(unix)]
fn foreign_why(state: &RootState) -> String {
match state {
RootState::Unknown(e) => format!("cannot be shown to be ours (RootState::Unknown: {e})"),
RootState::Unpinned => format!(
"is not pinned by this process (RootState::Unpinned: {})",
crate::signal::UNPINNED_WHY
),
RootState::Unreaped | RootState::Reaped { .. } => {
debug_assert!(
!matches!(state, RootState::Unreaped),
"a child its handle shows ours is forgotten"
);
"was reaped by someone else, or cannot be shown to be ours".to_owned()
}
}
}
#[cfg_attr(
not(target_os = "linux"),
allow(dead_code, reason = "only Linux tears a child down again through its pidfd")
)]
struct TornDown {
torn: HandleTeardown,
leak: Option<&'static str>,
why: Option<String>,
}
#[cfg_attr(
not(unix),
allow(dead_code, reason = "only Unix forgets a child the handle cannot answer for")
)]
struct Forgetting {
leak: &'static str,
why: String,
fate: ChildFate,
}
enum Refused {
Forgotten(Forgetting),
#[cfg_attr(
not(target_os = "linux"),
allow(dead_code, reason = "only Linux tears a child down again through its pidfd")
)]
TornDown(TornDown),
#[cfg_attr(
target_os = "linux",
allow(dead_code, reason = "only macOS and Windows release a child after a refused kill")
)]
Released,
}
fn refused_kill_warning(pid: u32, e: &Error, after: &Refused) -> String {
let mut text = format!("teardown kill of child {pid} failed ({e})");
match after {
Refused::Forgotten(forgotten) => text.push_str(&format!(
"; the child {}; forgetting tokio's handle for it leaks {}",
forgotten.why, forgotten.leak
)),
Refused::TornDown(torn_down) => {
if let Some(why) = &torn_down.why {
text.push_str(&format!("; the child {why}"));
}
match torn_down.leak {
Some(leak) => text.push_str(&format!("; forgetting tokio's handle for it leaks {leak}")),
None => text.push_str("; tokio's handle for it was already forgotten"),
}
if let Some(said) = torn_down.torn.outcome.said() {
text.push_str(&format!("; {}", said.text()));
}
}
Refused::Released => {
#[cfg(target_os = "linux")]
debug_assert!(false, "Linux tears every child not shown gone down again");
#[cfg(target_os = "macos")]
text.push_str(&format!("; it is {HANDED_TO_ORPHAN_REAPER}"));
#[cfg(windows)]
text.push_str(crate::child::owned::teardown::Disposition::Leave.suffix(true));
}
}
text
}
#[cfg(target_os = "macos")]
pub(crate) const HANDED_TO_ORPHAN_REAPER: &str = "handed to tokio's orphan reaper, which reaps it once it exits";
#[derive(Debug)]
pub(crate) struct Held(Option<::tokio::process::Child>);
impl Held {
fn take(&mut self) -> Option<::tokio::process::Child> {
self.0.take()
}
}
impl std::ops::Deref for Held {
type Target = ::tokio::process::Child;
fn deref(&self) -> &::tokio::process::Child {
self.0
.as_ref()
.expect("the backend's tokio child was released or forgotten")
}
}
impl std::ops::DerefMut for Held {
fn deref_mut(&mut self) -> &mut ::tokio::process::Child {
self.0
.as_mut()
.expect("the backend's tokio child was released or forgotten")
}
}
#[cfg(test)]
fn counted(child: ::tokio::process::Child) -> super::fault::CountedDrop {
super::fault::CountedDrop { _child: child }
}
#[cfg(not(test))]
fn counted(child: ::tokio::process::Child) -> ::tokio::process::Child {
child
}
#[cfg(unix)]
impl Drop for ProcSource {
fn drop(&mut self) {
let ProcSource::Tokio { child, .. } = self else {
return;
};
let Some(child) = child.take() else {
return;
};
if child.id().is_none() || matches!(self.state_of(), RootState::Unreaped) {
drop(counted(child));
} else {
std::mem::forget(child);
#[cfg(test)]
super::drop_fault::note_forget();
if !std::thread::panicking() {
log::debug!("a backend dropped without a release was forgotten: its child is not shown to be ours");
}
}
}
}
#[cfg(unix)]
fn gone() -> Error {
Error::Io(std::io::Error::from_raw_os_error(libc::ECHILD))
}
fn debug_assert_no_tokio_pipes(child: &::tokio::process::Child) {
debug_assert!(
child.stdin.is_none() && child.stdout.is_none() && child.stderr.is_none(),
"the spawn keeps every pipe; tokio's Child must arrive with stdin, stdout and stderr taken"
);
}
impl ProcSource {
#[cfg(target_os = "linux")]
pub(crate) fn new(child: ::tokio::process::Child, pid: u32, pidfd: std::os::fd::OwnedFd) -> ProcSource {
debug_assert_no_tokio_pipes(&child);
ProcSource::Tokio {
child: Held(Some(child)),
pid,
pidfd: PinnedPidfd(Some(pidfd)),
}
}
#[cfg(target_os = "macos")]
pub(crate) fn new(child: ::tokio::process::Child, pid: u32, identity: Option<u64>) -> ProcSource {
debug_assert_no_tokio_pipes(&child);
ProcSource::Tokio {
child: Held(Some(child)),
pid,
identity,
}
}
#[cfg(windows)]
pub(crate) fn new(child: ::tokio::process::Child, pid: u32) -> ProcSource {
debug_assert_no_tokio_pipes(&child);
ProcSource::Tokio {
child: Held(Some(child)),
pid,
}
}
pub(crate) fn pid(&self) -> u32 {
match self {
ProcSource::Tokio { pid, .. } => *pid,
#[cfg(unix)]
ProcSource::Foreign { pid, .. } => *pid,
#[cfg(windows)]
ProcSource::Raw(raw) => raw.pid(),
}
}
pub(crate) fn target(&self) -> Option<crate::wait::exit_only::Target<'_>> {
use crate::wait::exit_only::Target;
match self {
#[cfg(target_os = "linux")]
ProcSource::Tokio { pidfd, .. } => Some(Target::PidFd(std::os::fd::AsFd::as_fd(pidfd))),
#[cfg(target_os = "macos")]
ProcSource::Tokio {
child, pid, identity, ..
} => {
child.id()?;
Some(Target::pid(*pid, Some((*identity)?)))
}
#[cfg(windows)]
ProcSource::Tokio { child, .. } => {
let handle = child.raw_handle()?;
Some(Target::Handle(unsafe {
std::os::windows::io::BorrowedHandle::borrow_raw(handle)
}))
}
#[cfg(unix)]
ProcSource::Foreign { .. } => None,
#[cfg(windows)]
ProcSource::Raw(_) => None,
}
}
#[cfg(windows)]
pub(crate) fn raw_handle(&self) -> Option<std::os::windows::io::RawHandle> {
match self {
ProcSource::Tokio { child, .. } => child.raw_handle(),
ProcSource::Raw(raw) => Some(raw.raw_handle()),
}
}
#[cfg(target_os = "linux")]
pub(crate) fn child_handle(&self, pid: u32) -> Option<crate::containment::ChildHandle<'_>> {
let crate::wait::exit_only::Target::PidFd(pidfd) = self.target()?;
Some(crate::containment::ChildHandle { pid, pidfd })
}
pub(crate) async fn wait(&mut self) -> Result<ExitStatus, Error> {
match self {
ProcSource::Tokio { .. } => {
#[cfg(unix)]
{
self.gate()?;
match self.reap_on_events().await {
Ok(status) => Ok(status),
Err(Halt::State(state)) => Err(self.refuse(state)),
Err(Halt::ReapedBetween(why)) => {
self.forget_as(
&format!("was reaped by someone else ({why})"),
Forgotten::ReapedElsewhere,
);
Err(gone())
}
Err(Halt::ReapFailed(e)) => Err(Error::Io(e)),
Err(Halt::Watch(e)) => Err(e),
}
}
#[cfg(windows)]
{
let ProcSource::Tokio { child: c, .. } = self else {
unreachable!("matched above")
};
c.wait().await.map_err(Error::Io)
}
}
#[cfg(unix)]
ProcSource::Foreign { .. } => Err(gone()),
#[cfg(windows)]
ProcSource::Raw(r) => r.wait().await,
}
}
pub(crate) fn try_wait(&mut self) -> Result<Option<ExitStatus>, Error> {
#[cfg(unix)]
self.gate()?;
match self {
ProcSource::Tokio { child: c, .. } => c.try_wait().map_err(Error::Io),
#[cfg(unix)]
ProcSource::Foreign { .. } => Err(gone()),
#[cfg(windows)]
ProcSource::Raw(r) => r.try_wait(),
}
}
#[cfg(unix)]
fn gate(&mut self) -> Result<(), Error> {
let ProcSource::Tokio { child, .. } = &*self else {
return Ok(());
};
if child.id().is_none() {
return Ok(());
}
match self.state_of() {
RootState::Unreaped => Ok(()),
state => Err(self.refuse(state)),
}
}
#[cfg(unix)]
fn refuse(&mut self, state: RootState) -> Error {
let pid = self.pid();
match state {
RootState::Unreaped => unreachable!("a wait refused a child its handle shows ours"),
RootState::Reaped { .. } => {
self.forget_as("was reaped by someone else", Forgotten::ReapedElsewhere);
gone()
}
RootState::Unknown(failed) => Error::Unassessable {
detail: format!("pid {pid}: the child cannot be shown to be ours; it was not waited on"),
source: Some(failed),
},
RootState::Unpinned => Error::Unassessable {
detail: format!(
"pid {pid}: the child cannot be shown to be ours ({}); it was not waited on",
crate::signal::UNPINNED_WHY
),
source: None,
},
}
}
#[cfg(target_os = "linux")]
pub(crate) async fn exited_within(&self, grace: std::time::Duration) -> Result<bool, Error> {
match self {
ProcSource::Foreign { fate, .. } if fate.gone() => Ok(true),
ProcSource::Tokio { pidfd, .. } | ProcSource::Foreign { pidfd, .. } => {
crate::tokio::wait::pidfd_exited_within(std::os::fd::AsFd::as_fd(pidfd), grace).await
}
}
}
pub(crate) fn held_os_process(&self) -> Result<Option<Box<dyn OsProcess>>, Error> {
let pid = self.pid();
#[cfg(target_os = "linux")]
{
let pidfd = match self {
ProcSource::Foreign { fate, .. } if fate.gone() => return Ok(None),
ProcSource::Tokio { child, .. } if child.id().is_none() => return Ok(None),
ProcSource::Tokio { pidfd, .. } | ProcSource::Foreign { pidfd, .. } => pidfd,
};
let held = std::os::fd::AsFd::as_fd(pidfd)
.try_clone_to_owned()
.map_err(Error::Io)?;
Ok(Some(Box::new(crate::os_process::linux::LinuxProcess::new(
Some(pid),
held,
))))
}
#[cfg(target_os = "macos")]
{
match self {
ProcSource::Foreign { fate, .. } if fate.gone() => Ok(None),
ProcSource::Foreign { .. } => Err(Error::Unassessable {
detail: "the child cannot be shown to be ours, and its exit cannot be watched".to_owned(),
source: None,
}),
ProcSource::Tokio { child, .. } if child.id().is_none() => Ok(None),
ProcSource::Tokio {
identity: Some(unique), ..
} => {
let watched = crate::os_process::macos::child::MacChild::new(pid, *unique)?;
let after = crate::os_process::macos::read_for_open(
pid,
"graceful shutdown",
"the graceful signal was sent, but the child's exit cannot be watched",
)?;
Ok(after
.filter(|now| now.unique_id == *unique)
.map(|_| Box::new(watched) as Box<dyn OsProcess>))
}
ProcSource::Tokio { identity: None, .. } => {
debug_assert!(false, "a spawn that left a child with no unique id fails");
Err(Error::Unassessable {
detail: "the child has no unique id, and its exit cannot be watched".to_owned(),
source: None,
})
}
}
}
#[cfg(windows)]
{
use std::os::windows::io::BorrowedHandle;
let Some(raw) = self.raw_handle() else {
return Ok(None);
};
let held = unsafe { BorrowedHandle::borrow_raw(raw) }
.try_clone_to_owned()
.map_err(Error::Io)?;
Ok(Some(Box::new(crate::os_process::windows::WindowsProcess::for_child(
held, pid,
))))
}
}
#[cfg(windows)]
pub(crate) fn pins_pid(&self) -> bool {
match self {
ProcSource::Tokio { child: c, .. } => c.id().is_some(),
ProcSource::Raw(_) => true,
}
}
pub(crate) fn signal(&self, sig: Sig) -> Result<Sent, Error> {
match self {
#[cfg(target_os = "linux")]
ProcSource::Foreign {
fate: Forgotten::Unproven,
pidfd,
pid,
..
} => crate::signal::via_pidfd(Some(std::os::fd::AsFd::as_fd(pidfd)), *pid, sig).map_err(Error::Io),
#[cfg(unix)]
ProcSource::Foreign { fate, .. } => {
log::debug!("the child {}; {sig:?} not sent", fate.why());
Ok(if fate.gone() { Sent::Gone } else { Sent::Unverified })
}
#[cfg(unix)]
ProcSource::Tokio { child, .. } if child.id().is_none() => {
log::debug!("the child is already reaped; {sig:?} not sent");
Ok(Sent::Gone)
}
#[cfg(target_os = "linux")]
ProcSource::Tokio { pid, pidfd, .. } => {
crate::signal::via_pidfd(Some(std::os::fd::AsFd::as_fd(pidfd)), *pid, sig).map_err(Error::Io)
}
#[cfg(target_os = "macos")]
ProcSource::Tokio { pid, identity, .. } => {
crate::signal::via_audit_token(*pid, *identity, sig).map_err(Error::Io)
}
#[cfg(windows)]
ProcSource::Tokio { child, .. } => {
let Sig::Kill = sig;
let Some(h) = child.raw_handle() else {
return Ok(Sent::Gone);
};
terminate_unreaped(
windows::Win32::Foundation::HANDLE(h),
crate::os_process::windows::CREATE_PROCESS_ACCESS,
)
}
#[cfg(windows)]
ProcSource::Raw(r) => {
let Sig::Kill = sig;
r.start_kill().map(|()| Sent::Delivered)
}
}
}
#[cfg(unix)]
pub(crate) fn state(&self) -> RootState {
match self {
ProcSource::Foreign { fate, .. } => match fate {
Forgotten::ReapedElsewhere => RootState::Reaped { own: false },
Forgotten::Unpinned => RootState::Unpinned,
Forgotten::Unproven => RootState::Unknown(std::io::Error::other(
"its handle was forgotten because it could not be shown to be ours, so it may still be running",
)),
},
ProcSource::Tokio { child, .. } if child.id().is_none() => RootState::Reaped { own: true },
ProcSource::Tokio { .. } => self.state_of(),
}
}
#[cfg(unix)]
fn state_of(&self) -> RootState {
let ProcSource::Tokio { .. } = self else {
return RootState::Reaped { own: false };
};
#[cfg(target_os = "linux")]
let peeked = {
let ProcSource::Tokio { pidfd, .. } = self else {
unreachable!("checked above")
};
crate::wait::exit_only::peek(&crate::wait::exit_only::Target::PidFd(std::os::fd::AsFd::as_fd(pidfd)))
};
#[cfg(target_os = "macos")]
let peeked = {
let ProcSource::Tokio { pid, identity, .. } = self else {
unreachable!("checked above")
};
let Some(identity) = *identity else {
return RootState::Unknown(std::io::Error::other(
"the child's unique id is unknown, so nothing shows its pid still names it",
));
};
crate::wait::exit_only::peek_verified(&crate::wait::exit_only::Target::pid(*pid, Some(identity)))
};
RootState::of_peek(peeked)
}
#[cfg(unix)]
fn elsewhere(&self) -> Option<(u32, RootState)> {
let ProcSource::Tokio { child, .. } = self else {
return None;
};
child.id()?;
match self.state_of() {
RootState::Unreaped => None,
state => Some((self.pid(), state)),
}
}
#[cfg(unix)]
pub(crate) fn forget(mut self) {
if let ProcSource::Tokio { child, .. } = &mut self {
if let Some(child) = child.take() {
std::mem::forget(child);
}
}
}
pub(crate) fn release(mut self) {
if let ProcSource::Tokio { child, .. } = &mut self {
drop(child.take().map(counted));
}
}
#[cfg(unix)]
pub(crate) fn pidfd(&self) -> Option<std::os::fd::BorrowedFd<'_>> {
#[cfg(target_os = "linux")]
if let ProcSource::Foreign { pidfd, .. } = self {
return Some(std::os::fd::AsFd::as_fd(pidfd));
}
match self.target()? {
#[cfg(target_os = "linux")]
crate::wait::exit_only::Target::PidFd(fd) => Some(fd),
#[allow(unreachable_patterns, reason = "a Linux backend's target is always its pidfd")]
_ => None,
}
}
#[cfg(unix)]
pub(crate) fn is_running(&self) -> std::io::Result<bool> {
#[cfg(target_os = "linux")]
if let ProcSource::Foreign {
fate: Forgotten::Unproven,
pidfd,
..
} = self
{
let target = crate::wait::exit_only::Target::PidFd(std::os::fd::AsFd::as_fd(pidfd));
return Ok(matches!(
crate::wait::exit_only::peek(&target)?,
crate::os_process::child::PeekOutcome::Running
));
}
if self.is_reaped() {
return Ok(false);
}
let Some(target) = self.target() else {
return Err(std::io::Error::other(
"the child's unique id is unknown, so nothing shows its pid still names it",
));
};
Ok(matches!(
crate::wait::exit_only::peek(&target)?,
crate::os_process::child::PeekOutcome::Running
))
}
#[cfg(unix)]
fn has_exited(&self) -> std::io::Result<bool> {
#[cfg(target_os = "linux")]
{
let pidfd = self.pidfd().expect("a Linux backend always has its pidfd");
crate::os_process::poll::is_readable(pidfd)
}
#[cfg(target_os = "macos")]
{
if !self.is_running()? {
return Ok(true);
}
let ProcSource::Tokio {
pid,
identity: Some(unique),
..
} = self
else {
unreachable!("`is_running` read a running child by its unique id");
};
crate::identity::has_exited(*pid, *unique, crate::identity::ReadPurpose::Running)
.map_err(|errno| crate::identity::has_exited_error(*pid, errno))
}
}
pub(crate) fn liveness(&self) -> crate::identity::Liveness {
use crate::identity::Liveness;
#[cfg(unix)]
{
#[cfg(target_os = "macos")]
if self.forgot_unproven() {
return Liveness::Unknown;
}
match self.has_exited() {
Ok(true) => Liveness::Dead,
Ok(false) => Liveness::Alive,
Err(e) => {
log::debug!("child {}: its liveness could not be read ({e})", self.pid());
Liveness::Unknown
}
}
}
#[cfg(windows)]
{
use std::os::windows::io::BorrowedHandle;
use crate::os_process::child::PeekOutcome;
let Some(raw) = self.raw_handle() else {
return Liveness::Dead;
};
if self.is_reaped() {
return Liveness::Dead;
}
let handle = unsafe { BorrowedHandle::borrow_raw(raw) };
match crate::wait::exit_only::peek(&crate::wait::exit_only::Target::Handle(handle)) {
Ok(PeekOutcome::Running) => Liveness::Alive,
Ok(PeekOutcome::Exit(_) | PeekOutcome::Foreign(_)) => Liveness::Dead,
Err(e) => {
log::debug!("child {}: its liveness could not be read ({e})", self.pid());
Liveness::Unknown
}
}
}
}
pub(crate) fn is_reaped(&self) -> bool {
match self {
ProcSource::Tokio { child: c, .. } => c.id().is_none(),
#[cfg(unix)]
ProcSource::Foreign { .. } => true,
#[cfg(windows)]
ProcSource::Raw(r) => r.is_reaped(),
}
}
#[cfg(any(windows, test))]
pub(crate) fn wait_and_reap(&mut self, pid: u32) -> Waited {
self.wait_and_reap_at(pid, log::Level::Warn)
}
#[cfg(any(windows, test))]
pub(crate) fn wait_and_reap_at(&mut self, pid: u32, level: log::Level) -> Waited {
self.wait_and_reap_caused(pid, level).0
}
pub(crate) fn wait_and_reap_caused(
&mut self,
pid: u32,
#[cfg_attr(
windows,
allow(unused_variables, reason = "a process handle pins its process: nothing to log")
)]
level: log::Level,
) -> (Waited, Option<String>) {
crate::bounded::assert_may_block("wait_and_reap");
match self {
#[cfg(unix)]
ProcSource::Foreign { .. } => (Waited::Unverified, None),
#[cfg(target_os = "linux")]
ProcSource::Tokio { child, pidfd, .. } => {
if !still_ours(child) {
return (Waited::Exited, None);
}
#[cfg(test)]
crate::child::spawn::fault::run_between_kill_and_wait();
wait_on_pidfd(pid, pidfd, level)
}
#[cfg(target_os = "macos")]
ProcSource::Tokio { child, identity, .. } => {
if !still_ours(child) {
return (Waited::Exited, None);
}
let Some(identity) = identity else {
return (
Waited::Unverified,
Some("no unique id is held, so nothing shows its pid names it".to_owned()),
);
};
#[cfg(test)]
crate::child::spawn::fault::run_between_kill_and_wait();
wait_reapable(pid, *identity, level)
}
#[cfg(windows)]
ProcSource::Tokio { child, .. } => {
if !still_ours(child) {
return (Waited::Exited, None);
}
#[cfg(test)]
crate::child::spawn::fault::run_between_kill_and_wait();
(wait_on_handle(child, pid), None)
}
#[cfg(windows)]
ProcSource::Raw(_) => unreachable!("the raw backend tears its own spawn failures down"),
}
}
#[cfg(unix)]
pub(crate) async fn wait_and_reap_awaiting(&mut self) -> Result<(Waited, Option<String>), Error> {
#[cfg(test)]
crate::child::spawn::fault::run_between_kill_and_wait();
#[cfg(test)]
if super::fault::take_pend_awaited_reap() {
std::future::pending::<()>().await;
}
Ok(match self.reap_on_events().await {
Ok(_) => (Waited::Exited, None),
Err(Halt::State(state)) => verdict_of(state),
Err(Halt::ReapedBetween(why)) => (Waited::Foreign, Some(why)),
Err(Halt::ReapFailed(e)) => (Waited::Unverified, Some(format!("tokio's try_wait failed: {e}"))),
Err(Halt::Watch(e)) => return Err(e),
})
}
#[cfg(unix)]
async fn reap_on_events(&mut self) -> Result<ExitStatus, Halt> {
#[cfg(target_os = "linux")]
use crate::wait::exit_only::{self, Target};
if !matches!(self, ProcSource::Tokio { .. }) {
return Err(Halt::State(self.state()));
}
#[cfg(target_os = "linux")]
{
use std::os::fd::AsFd as _;
let ProcSource::Tokio { child, pidfd, .. } = self else {
unreachable!("checked above")
};
if child.id().is_none() {
return collected(child);
}
let target = Target::PidFd(pidfd.as_fd());
let watch = event_reap::PidfdWatch::arm(pidfd.as_fd()).map_err(Halt::Watch)?;
loop {
let ready = watch.ready().await.map_err(Halt::Watch)?;
if let Some(status) = reap_after_look(child, exit_only::peek(&target))? {
return Ok(status);
}
#[cfg(test)]
super::fault::run_reap_parked();
ready.seen();
}
}
#[cfg(target_os = "macos")]
{
let ProcSource::Tokio {
child, pid, identity, ..
} = self
else {
unreachable!("checked above")
};
if child.id().is_none() {
return collected(child);
}
let Some(identity) = *identity else {
return Err(Halt::State(RootState::Unknown(std::io::Error::other(
"the child's unique id is unknown, so nothing shows its pid still names it",
))));
};
look_on_events(*pid, identity, |looked| reap_after_look(child, looked)).await
}
}
pub(crate) fn exit_visible_by(&self, pid: u32, until: std::time::Instant) -> bool {
crate::bounded::assert_may_block("exit_visible_by");
#[cfg(windows)]
{
let _ = pid;
let ProcSource::Tokio { child, .. } = self else {
return true;
};
child.raw_handle().is_none_or(|handle| {
crate::wait::teardown_warn::handle_signaled_by(windows::Win32::Foundation::HANDLE(handle), until)
})
}
#[cfg(target_os = "linux")]
{
use std::os::fd::AsFd as _;
let _ = pid;
let ProcSource::Tokio { pidfd, .. } = self else {
return true;
};
crate::wait::pidfd_exit_visible_by(pidfd.as_fd(), until)
}
#[cfg(target_os = "macos")]
{
use crate::wait::macos::{await_reapable, Waited as Awaited};
let ProcSource::Tokio {
identity: Some(identity),
..
} = self
else {
return true;
};
match await_reapable(pid, Some(*identity), Some(until)) {
Ok(waited) => waited != Awaited::DeadlinePassed,
Err(e) => {
log::debug!("child {pid}: a look at its exit failed ({e}); the wait that follows decides");
true
}
}
}
}
#[cfg(all(unix, test))]
pub(crate) fn forget_foreign(&mut self) -> Option<&'static str> {
self.forget_noting(FORGET_FOREIGN, Forgotten::Unproven, &mut Diagnosis::default())
}
#[cfg(target_os = "macos")]
pub(crate) fn forget_because(&mut self, why: &str) -> Option<&'static str> {
self.forget_as(why, Forgotten::Unproven)
}
#[cfg(unix)]
pub(crate) fn forgot_unproven(&self) -> bool {
matches!(
self,
ProcSource::Foreign {
fate: Forgotten::Unproven,
..
}
)
}
#[cfg(unix)]
pub(crate) fn forgotten_fate(&self, id: Option<ProcessId>) -> Option<ChildFate> {
match self {
ProcSource::Foreign { fate, .. } => Some(if fate.gone() {
ChildFate::Gone
} else {
ChildFate::Running { id }
}),
_ => None,
}
}
#[cfg(unix)]
pub(crate) fn forget_as(&mut self, why: &str, fate: Forgotten) -> Option<&'static str> {
self.forget_noting(why, fate, &mut Diagnosis::default())
}
#[cfg(target_os = "linux")]
fn forget_deferring(&mut self, why: &str, fate: Forgotten, owed: &mut Diagnosis) -> Option<&'static str> {
let (pid, leak) = self.forget_quietly(fate)?;
owed.add(format!(
"child {pid} {why}; forgetting tokio's handle for it leaks {leak}"
));
Some(leak)
}
#[cfg(unix)]
pub(crate) fn forget_noting(
&mut self,
why: &str,
fate: Forgotten,
diagnosis: &mut Diagnosis,
) -> Option<&'static str> {
let (pid, leak) = self.forget_quietly(fate)?;
log::warn!(
"{}",
diagnosis.fold(format!(
"child {pid} {why}; forgetting tokio's handle for it leaks {leak}"
))
);
Some(leak)
}
#[cfg(unix)]
fn forget_quietly(&mut self, fate: Forgotten) -> Option<(String, &'static str)> {
let leak = if cfg!(target_os = "linux") {
"tokio's pidfd and its reactor registration"
} else {
"tokio's SIGCHLD watch"
};
let ProcSource::Tokio {
pid,
#[cfg(target_os = "linux")]
pidfd,
..
} = self
else {
return None;
};
let pid = *pid;
let foreign = ProcSource::Foreign {
fate,
pid,
#[cfg(target_os = "linux")]
pidfd: pidfd.hand_off(),
};
std::mem::replace(self, foreign).forget();
#[cfg(test)]
super::drop_fault::note_forget();
Some((pid.to_string(), leak))
}
#[cfg(unix)]
pub(crate) fn forget_for(&mut self, view: &crate::containment::DropView) -> Option<Forgot> {
use crate::containment::dispatch::RootView;
let now = match view.root {
RootView::Reaped => {
if !self.holds_unreaped_child() {
return None;
}
None
}
RootView::Unknown(_) | RootView::Unpinned | RootView::Trusted => Some(self.elsewhere()?.1),
};
let fate = now.as_ref().map_or(Forgotten::ReapedElsewhere, Forgotten::of);
let (_, leak) = self.forget_quietly(fate)?;
Some(Forgot { leak, now, cause: None })
}
#[cfg(unix)]
pub(crate) fn forget_for_wait(&mut self, waited: Waited, cause: Option<String>) -> Option<Forgot> {
let (_, leak) = self.forget_quietly(waited.forgotten()?)?;
Some(Forgot { leak, now: None, cause })
}
#[cfg(unix)]
fn holds_unreaped_child(&self) -> bool {
matches!(self, ProcSource::Tokio { child, .. } if child.id().is_some())
}
#[cfg(unix)]
pub(crate) fn forget_if_foreign(&mut self) -> Option<&'static str> {
self.forget_if_foreign_noting(&mut Diagnosis::default())
}
#[cfg(unix)]
fn forget_if_foreign_noting(&mut self, diagnosis: &mut Diagnosis) -> Option<&'static str> {
let (_, state) = self.elsewhere()?;
self.forget_noting(&foreign_why(&state), Forgotten::of(&state), diagnosis)
}
#[cfg(unix)]
fn forget_if_foreign_quietly(&mut self, id: Option<ProcessId>) -> Option<Forgetting> {
let (_, state) = self.elsewhere()?;
let (_, leak) = self.forget_quietly(Forgotten::of(&state))?;
let fate = if Forgotten::of(&state).gone() {
ChildFate::Gone
} else {
ChildFate::Running { id }
};
Some(Forgetting {
leak,
why: foreign_why(&state),
fate,
})
}
#[cfg(any(unix, test))]
pub(crate) fn reap_now(self, pid: u32, id: Option<ProcessId>) -> ChildFate {
self.reap_now_noting(pid, id, &mut Diagnosis::default())
}
pub(crate) fn reap_now_noting(mut self, pid: u32, id: Option<ProcessId>, why: &mut Diagnosis) -> ChildFate {
crate::bounded::assert_may_block("reap_now");
let killed = self.teardown_kill();
if let Err(e) = &killed {
return self.after_refused_kill(pid, id, e, why);
}
#[cfg(unix)]
let (waited, cause) = self.wait_warning(pid, |proc| proc.wait_and_reap_caused(pid, log::Level::Debug));
#[cfg(not(unix))]
let waited = self.wait_warning(pid, |proc| proc.wait_and_reap(pid));
let fate = match waited {
Waited::Exited => self.collect_exit(id),
Waited::Unverified => match killed {
Ok(Sent::Delivered) => ChildFate::Killed,
_ => ChildFate::Running { id },
},
_ => Foreign::Gone.fate(matches!(killed, Ok(Sent::Delivered))),
};
#[cfg(unix)]
if let Some(fate) = waited.forgotten() {
let cause = cause.map_or_else(String::new, |c| format!(" ({c})"));
self.forget_noting(
&format!("was reaped by someone else, or cannot be shown to be ours{cause}"),
fate,
why,
);
}
self.release();
fate
}
#[cfg(target_os = "macos")]
pub(crate) fn reap_unreported(
mut self,
pid: u32,
unique: u64,
prepared: crate::containment::Prepared,
) -> ChildFate {
crate::bounded::assert_may_block("reap_unreported");
let done = crate::child::spawn::kill_and_reap_unreported(pid, unique, prepared, super::slow_teardown_after());
if matches!(done.fate, ChildFate::Running { .. }) {
self.release();
return done.warn(pid, Some(&format!("it is {HANDED_TO_ORPHAN_REAPER}")));
}
let tail = self
.forget_quietly(Forgotten::Unproven)
.map(|(_, leak)| format!("forgetting tokio's handle for it leaks {leak}"));
done.warn(pid, tail.as_deref())
}
#[cfg(target_os = "macos")]
pub(crate) fn leave_late_front(mut self, pid: u32) {
let tail = self
.forget_quietly(Forgotten::Unproven)
.map(|(_, leak)| format!("forgetting tokio's handle for it leaks {leak}"));
crate::child::spawn::warn_late_front(pid, tail.as_deref());
}
pub(crate) fn collect_exit(&mut self, id: Option<ProcessId>) -> ChildFate {
#[cfg(test)]
let pid = self.pid();
let ProcSource::Tokio { child, .. } = self else {
unreachable!("only a tokio backend's wait answers `Exited`")
};
let looked = child.try_wait();
#[cfg(test)]
if let Ok(Some(status)) = &looked {
crate::child::spawn::fault::record_teardown_reap(pid, *status);
}
crate::child::spawn::fate_of_a_look(looked.map_err(|e| e.raw_os_error()), id)
}
#[cfg(target_os = "linux")]
pub(crate) fn leave_front_noting(
mut self,
pid: u32,
id: Option<ProcessId>,
subtree: Option<&crate::containment::cgroup::Subtree>,
why: &mut Diagnosis,
error: Error,
front: crate::elevation::front::Front,
) -> (Error, ChildFate) {
use crate::child::spawn::FrontFate;
if let Some((_, state)) = self.elsewhere() {
self.forget_deferring(&foreign_why(&state), Forgotten::of(&state), why);
let fate = match state {
RootState::Unknown(_) => ChildFate::Unknown,
_ => ChildFate::Gone,
};
return (FrontFate::Unaccounted.note(error, Some(front), Some(pid)), fate);
}
if !matches!(self, ProcSource::Tokio { .. }) {
debug_assert!(
false,
"{}: a spawn's backend is forgotten before its teardown",
crate::elevation::front::front_named(Some(pid))
);
return (
FrontFate::Unaccounted.note(error, Some(front), Some(pid)),
ChildFate::Unknown,
);
}
self.forget_deferring("is an elevation front, sent nothing", Forgotten::Unproven, why);
let child = OwnedChild::new(Box::new(crate::os_process::linux::LinuxProcess::new(
Some(pid),
self.take_forgotten_pidfd(),
)));
let how = HeldTeardown {
front: Some(front),
id,
subtree,
disposition: Disposition::Leave,
due: Due::in_(super::slow_teardown_after()),
};
let (error, fate, _) = tear_down_held(child, how, why, error);
(error, fate)
}
pub(crate) fn wait_warning<R>(&mut self, pid: u32, wait: impl FnOnce(&mut Self) -> R) -> R {
crate::wait::teardown_warn::wait_warning(
self,
crate::wait::teardown_warn::Due::in_(super::slow_teardown_after()),
|proc, until| proc.exit_visible_by(pid, until),
|after| crate::child::spawn::warn_still_waiting(Some(pid), after),
wait,
)
}
fn teardown_kill(&self) -> Result<Sent, Error> {
#[cfg(test)]
if let Some((marker, kind)) = crate::child::spawn::fault::take_force_kill_failure() {
return Err(Error::Io(std::io::Error::new(kind, marker)));
}
self.signal(Sig::Kill)
}
#[cfg(target_os = "linux")]
fn tear_down_forgotten(mut self, pid: u32, id: Option<ProcessId>, forgot: Option<Forgetting>) -> TornDown {
let (past, leak, why) = match forgot {
Some(forgot) => (Past::WaitMayFail, Some(forgot.leak), Some(forgot.why)),
None => match self.forget_quietly(Forgotten::Unproven) {
Some((_, leak)) => (Past::Clean, Some(leak), None),
None => (Past::WaitMayFail, None, None),
},
};
let torn = tear_down_pidfd(
Some(pid),
self.take_forgotten_pidfd(),
id,
past,
Due::in_(super::slow_teardown_after()),
);
TornDown { torn, leak, why }
}
#[cfg_attr(not(unix), allow(unused_mut, reason = "only Unix forgets through `&mut self`"))]
fn after_refused_kill(mut self, pid: u32, id: Option<ProcessId>, e: &Error, why: &mut Diagnosis) -> ChildFate {
#[cfg(unix)]
let forgotten = self.forget_if_foreign_quietly(id);
#[cfg(not(unix))]
let forgotten: Option<Forgetting> = None;
let after = match forgotten {
#[cfg(target_os = "linux")]
Some(forgot) if !matches!(forgot.fate, ChildFate::Gone) => {
Refused::TornDown(self.tear_down_forgotten(pid, id, Some(forgot)))
}
Some(forgotten) => Refused::Forgotten(forgotten),
#[cfg(target_os = "linux")]
None => Refused::TornDown(self.tear_down_forgotten(pid, id, None)),
#[cfg(not(target_os = "linux"))]
None => {
self.release();
Refused::Released
}
};
let line = format!(
"{}: {}",
TeardownCaller::FailedSpawn.label(),
why.fold(refused_kill_warning(pid, e, &after))
);
match &after {
Refused::TornDown(torn_down) => torn_down.torn.warn(Some(&line)),
_ => log::warn!("{line}"),
}
debug_assert!(
matches!(e, Error::Io(io) if io.kind() == std::io::ErrorKind::PermissionDenied),
"the teardown kill of an owned child failed: {e}"
);
refused_kill_answer(&after, id)
}
#[cfg(target_os = "linux")]
fn take_forgotten_pidfd(&mut self) -> std::os::fd::OwnedFd {
let ProcSource::Foreign { pidfd, .. } = self else {
unreachable!("called on a backend that is not forgotten")
};
pidfd.take()
}
#[cfg(all(test, windows))]
pub(crate) fn install_wait_observer(
&mut self,
started: ::tokio::sync::oneshot::Sender<()>,
outcome: ::tokio::sync::oneshot::Sender<crate::child::spawn::windows_raw::WaitOutcome>,
) {
match self {
ProcSource::Raw(r) => r.set_observer(started, outcome),
ProcSource::Tokio { .. } => panic!("wait observer requires the raw CreateProcessW backend"),
}
}
}
fn refused_kill_answer(after: &Refused, id: Option<ProcessId>) -> ChildFate {
match after {
Refused::Forgotten(forgotten) => forgotten.fate,
Refused::TornDown(torn_down) => torn_down.torn.outcome.fate(),
Refused::Released => {
#[cfg(target_os = "linux")]
debug_assert!(false, "Linux tears every child not shown gone down again");
ChildFate::Running { id }
}
}
}
#[cfg(unix)]
#[derive(Debug)]
enum Halt {
State(RootState),
ReapedBetween(String),
ReapFailed(std::io::Error),
Watch(Error),
}
#[cfg(unix)]
fn verdict_of(state: RootState) -> (Waited, Option<String>) {
match state {
RootState::Unreaped => unreachable!("a wait's look halted on a child its handle shows ours"),
RootState::Reaped { .. } => (
Waited::Foreign,
Some("its handle shows it reaped by someone else".to_owned()),
),
#[cfg(target_os = "macos")]
RootState::Unpinned => (Waited::Orphaned, Some(crate::signal::UNPINNED_WHY.to_owned())),
#[cfg(not(target_os = "macos"))]
RootState::Unpinned => (Waited::Unverified, Some(crate::signal::UNPINNED_WHY.to_owned())),
RootState::Unknown(e) => (
Waited::Unverified,
Some(format!("its handle cannot show it is ours ({e})")),
),
}
}
#[cfg(unix)]
fn collected(child: &mut ::tokio::process::Child) -> Result<ExitStatus, Halt> {
match child.try_wait() {
Ok(Some(status)) => Ok(status),
Ok(None) => unreachable!("tokio answers its collected status once it has reaped"),
Err(e) => Err(Halt::ReapFailed(e)),
}
}
#[cfg(target_os = "macos")]
async fn look_on_events<T>(
pid: u32,
identity: u64,
mut on_look: impl FnMut(std::io::Result<crate::os_process::child::PeekOutcome>) -> Result<Option<T>, Halt>,
) -> Result<T, Halt> {
use crate::wait::exit_only::{self, Target};
let target = Target::pid(pid, Some(identity));
let mut watch = event_reap::KqueueWatch::arm(pid).map_err(Halt::Watch)?;
loop {
if watch.reaped().map_err(Halt::Watch)? {
return Err(Halt::State(RootState::Reaped { own: false }));
}
let (looked, holder) = match exit_only::peek_verified_traced(&target) {
Ok((peeked, holder)) => (Ok(peeked), holder),
Err(e) => (Err(e), None),
};
if let Some(found) = on_look(looked)? {
return Ok(found);
}
if let Some(holder) = holder {
use crate::wait::macos::WalkError;
match watch.held_by(holder) {
Ok(true) => continue,
Ok(false) => {}
Err(WalkError::Identity(e)) => return Err(Halt::State(RootState::Unknown(e))),
Err(WalkError::Watch(e)) => return Err(Halt::Watch(Error::Io(e))),
}
}
#[cfg(test)]
super::fault::run_reap_parked();
watch.next().await.map_err(Halt::Watch)?;
}
}
#[cfg(unix)]
fn reap_after_look(
child: &mut ::tokio::process::Child,
looked: std::io::Result<crate::os_process::child::PeekOutcome>,
) -> Result<Option<ExitStatus>, Halt> {
use crate::os_process::child::PeekOutcome;
match looked {
Ok(PeekOutcome::Exit(_)) => match child.try_wait() {
Ok(Some(status)) => Ok(Some(status)),
Ok(None) => Err(Halt::ReapedBetween(
"waitpid found no exit record after its handle showed one".to_owned(),
)),
Err(e) if e.raw_os_error() == Some(libc::ECHILD) => Err(Halt::ReapedBetween(
"waitpid answered ECHILD after its handle showed its exit".to_owned(),
)),
Err(e) => Err(Halt::ReapFailed(e)),
},
Ok(PeekOutcome::Running) => Ok(None),
other => Err(Halt::State(RootState::of_peek(other))),
}
}
fn still_ours(child: &::tokio::process::Child) -> bool {
let ours = child.id().is_some();
debug_assert!(
ours,
"wait_and_reap found an already-reaped child where one was impossible"
);
ours
}
#[cfg(target_os = "linux")]
fn wait_on_pidfd(pid: u32, pidfd: &std::os::fd::OwnedFd, level: log::Level) -> (Waited, Option<String>) {
use std::os::fd::AsFd;
use crate::os_process::child::PeekOutcome;
use crate::wait::exit_only::{self, Target};
match exit_only::wait_visible_exit(&Target::PidFd(pidfd.as_fd())) {
Ok(PeekOutcome::Exit(_record)) => {
#[cfg(test)]
if let crate::os_process::child::ExitRecord::Status(status) = _record {
crate::child::spawn::fault::record_teardown_reap(pid, status);
}
(Waited::Exited, None)
}
Ok(PeekOutcome::Foreign(_)) => (
Waited::Foreign,
Some("waitid on its pidfd found it reaped by someone else (ECHILD)".to_owned()),
),
Ok(PeekOutcome::Running) => {
log::log!(
level,
"wait_and_reap: waitid on child {pid}'s pidfd returned without an exit"
);
debug_assert!(false, "a blocking waitid on a pidfd returned without an exit");
(
Waited::Unverified,
Some("waitid on its pidfd returned without an exit".to_owned()),
)
}
Err(e) => {
log::log!(level, "wait_and_reap: waitid on child {pid}'s pidfd failed: {e}");
debug_assert!(false, "waitid on a child's own pidfd failed: {e}");
(Waited::Unverified, Some(format!("waitid on its pidfd failed: {e}")))
}
}
}
#[cfg(target_os = "macos")]
fn wait_reapable(pid: u32, identity: u64, level: log::Level) -> (Waited, Option<String>) {
use crate::wait::macos::{await_reapable, Waited as Awaited};
match await_reapable(pid, Some(identity), None) {
Ok(Awaited::Reapable) => {
#[cfg(test)]
if let Ok(crate::os_process::child::PeekOutcome::Exit(crate::os_process::child::ExitRecord::Status(
status,
))) = crate::wait::exit_only::peek(&crate::wait::exit_only::Target::pid(pid, Some(identity)))
{
crate::child::spawn::fault::record_teardown_reap(pid, status);
}
(Waited::Exited, None)
}
Ok(Awaited::Gone) => (
Waited::Foreign,
Some("its pid is gone, or names another process".to_owned()),
),
Ok(Awaited::Orphaned) => {
log::log!(
level,
"wait_and_reap: child {pid} is not ours to reap (launchd holds its zombie, because its tracer died)"
);
(Waited::Orphaned, Some(crate::signal::UNPINNED_WHY.to_owned()))
}
Ok(Awaited::DeadlinePassed) => {
log::log!(
level,
"wait_and_reap: the unbounded wait on child {pid} reported a passed deadline"
);
debug_assert!(false, "an unbounded wait reported a passed deadline");
(
Waited::Unverified,
Some("the unbounded wait reported a passed deadline".to_owned()),
)
}
Err(e) => {
log::log!(level, "wait_and_reap: waiting on child {pid} failed: {e}");
(Waited::Unverified, Some(format!("waiting on it failed: {e}")))
}
}
}
#[cfg(windows)]
pub(super) fn terminate_unreaped(
h: windows::Win32::Foundation::HANDLE,
granted: windows::Win32::System::Threading::PROCESS_ACCESS_RIGHTS,
) -> Result<Sent, Error> {
use crate::identity::{windows_terminate_held, Termination};
match windows_terminate_held(h, granted) {
Termination::Terminated | Termination::Exited => Ok(Sent::Delivered),
Termination::Failed(e) => Err(Error::Io(crate::error::win32_io_error(e))),
}
}
#[cfg(windows)]
fn wait_on_handle(child: &::tokio::process::Child, pid: u32) -> Waited {
let h = child.raw_handle().expect("tokio owns the handle while id() is Some");
#[cfg(test)]
let forced = super::fault::take_fail_handle_wait();
#[cfg(not(test))]
let forced = false;
let waited = if forced {
wait_failed(pid, windows::Win32::Foundation::WAIT_FAILED)
} else {
wait_for_exit(windows::Win32::Foundation::HANDLE(h), pid)
};
debug_assert!(
forced || matches!(waited, Waited::Exited),
"wait_and_reap did not observe the child's exit"
);
waited
}
#[cfg(windows)]
pub(super) fn wait_for_exit(h: windows::Win32::Foundation::HANDLE, pid: u32) -> Waited {
use windows::Win32::Foundation::WAIT_OBJECT_0;
use windows::Win32::System::Threading::{WaitForSingleObject, INFINITE};
let waited = unsafe { WaitForSingleObject(h, INFINITE) };
if waited != WAIT_OBJECT_0 {
return wait_failed(pid, waited);
}
#[cfg(test)]
{
use std::os::windows::process::ExitStatusExt as _;
let mut code = 0u32;
unsafe { windows::Win32::System::Threading::GetExitCodeProcess(h, &mut code) }
.expect("GetExitCodeProcess on an exited child");
crate::child::spawn::fault::record_teardown_reap(pid, std::process::ExitStatus::from_raw(code));
}
Waited::Exited
}
#[cfg(windows)]
fn wait_failed(pid: u32, waited: windows::Win32::Foundation::WAIT_EVENT) -> Waited {
log::warn!("wait_and_reap: the wait on child {pid}'s handle failed: {waited:?}");
Waited::Unverified
}
#[cfg(unix)]
#[path = "proc_source/event_reap.rs"]
mod event_reap;
#[cfg(test)]
#[path = "proc_source_tests.rs"]
mod proc_source_tests;