use std::process::ExitStatus;
#[cfg(unix)]
use crate::child::drop_report::Forgot;
use crate::child::spawn::Diagnosis;
use crate::error::{ChildFate, Error};
use crate::identity::ProcessId;
#[cfg(unix)]
use crate::signal::RootState;
use crate::signal::{Sent, Sig};
use crate::wait::exit_only::Foreign;
#[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,
Unverified,
}
#[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,
stdin: Option<::tokio::process::ChildStdin>,
stdout: Option<::tokio::process::ChildStdout>,
stderr: Option<::tokio::process::ChildStderr>,
#[cfg(target_os = "linux")]
pidfd: PinnedPidfd,
#[cfg(target_os = "macos")]
identity: Option<u64>,
},
#[cfg(unix)]
Foreign {
stdin: Option<::tokio::process::ChildStdin>,
stdout: Option<::tokio::process::ChildStdout>,
stderr: Option<::tokio::process::ChildStderr>,
reaped_elsewhere: bool,
},
#[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")]
impl PinnedPidfd {
fn take(&mut self) -> std::os::fd::OwnedFd {
self.0
.take()
.expect("the pidfd was taken by a hand-off that forgot the backend")
}
}
#[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("the pidfd was taken by a hand-off that forgot the backend")
}
}
#[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(unix)]
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 => {
"was reaped by someone else, or cannot be shown to be ours".to_owned()
}
}
}
#[cfg(unix)]
fn shown_reaped_elsewhere(state: &RootState) -> bool {
!matches!(state, RootState::Unknown(_))
}
fn refused_kill_warning(
pid: u32,
e: &Error,
handed: bool,
foreign: Option<&str>,
leak: Option<&'static str>,
) -> String {
let mut text = format!(
"teardown kill of child {pid} failed ({e}); {}",
refused_kill_fate(handed)
);
if let Some(why) = foreign {
text.push_str(&format!("; the child {why}"));
}
if let Some(leak) = leak {
text.push_str(&format!("; forgetting tokio's handle for it leaks {leak}"));
}
text
}
fn refused_kill_fate(handed: bool) -> &'static str {
if handed {
"it is handed to the pidfd teardown"
} else {
"it is not waited on"
}
}
#[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")
}
}
fn hold(
mut child: ::tokio::process::Child,
) -> (
Held,
Option<::tokio::process::ChildStdin>,
Option<::tokio::process::ChildStdout>,
Option<::tokio::process::ChildStderr>,
) {
let streams = (child.stdin.take(), child.stdout.take(), child.stderr.take());
(Held(Some(child)), streams.0, streams.1, streams.2)
}
#[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(&child), 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))
}
impl ProcSource {
#[cfg(target_os = "linux")]
pub(crate) fn new(child: ::tokio::process::Child, pidfd: std::os::fd::OwnedFd) -> ProcSource {
let (child, stdin, stdout, stderr) = hold(child);
ProcSource::Tokio {
child,
stdin,
stdout,
stderr,
pidfd: PinnedPidfd(Some(pidfd)),
}
}
#[cfg(target_os = "macos")]
pub(crate) fn new(child: ::tokio::process::Child, identity: Option<u64>) -> ProcSource {
let (child, stdin, stdout, stderr) = hold(child);
ProcSource::Tokio {
child,
stdin,
stdout,
stderr,
identity,
}
}
#[cfg(windows)]
pub(crate) fn new(child: ::tokio::process::Child) -> ProcSource {
let (child, stdin, stdout, stderr) = hold(child);
ProcSource::Tokio {
child,
stdin,
stdout,
stderr,
}
}
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, identity, .. } => Some(Target::pid(child.id()?, 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) fn take_stdin(&mut self) -> Option<::tokio::process::ChildStdin> {
match self {
ProcSource::Tokio { stdin, .. } => stdin.take(),
#[cfg(unix)]
ProcSource::Foreign { stdin, .. } => stdin.take(),
#[cfg(windows)]
ProcSource::Raw(_) => None,
}
}
pub(crate) fn take_stdout(&mut self) -> Option<::tokio::process::ChildStdout> {
match self {
ProcSource::Tokio { stdout, .. } => stdout.take(),
#[cfg(unix)]
ProcSource::Foreign { stdout, .. } => stdout.take(),
#[cfg(windows)]
ProcSource::Raw(_) => None,
}
}
pub(crate) fn take_stderr(&mut self) -> Option<::tokio::process::ChildStderr> {
match self {
ProcSource::Tokio { stderr, .. } => stderr.take(),
#[cfg(unix)]
ProcSource::Foreign { stderr, .. } => stderr.take(),
#[cfg(windows)]
ProcSource::Raw(_) => None,
}
}
pub(crate) async fn wait(&mut self) -> Result<ExitStatus, Error> {
match self {
ProcSource::Tokio { stdin, .. } => {
drop(stdin.take());
#[cfg(unix)]
{
self.gate()?;
self.await_exit().await?;
self.gate()?;
}
let ProcSource::Tokio { child: c, .. } = self else {
unreachable!("a gate that forgot the child returned an error")
};
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(());
};
let Some(pid) = child.id() else {
return Ok(());
};
match self.state_of(child) {
RootState::Unreaped => Ok(()),
RootState::Reaped => {
self.forget_as("was reaped by someone else", true);
Err(gone())
}
RootState::Unknown(failed) => Err(Error::Unassessable {
detail: format!("pid {pid}: the child cannot be shown to be ours; it was not waited on"),
source: Some(failed),
}),
RootState::Unpinned => Err(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(unix)]
async fn await_exit(&self) -> Result<(), Error> {
#[cfg(target_os = "linux")]
{
let ProcSource::Tokio { pidfd, .. } = self else {
return Ok(());
};
let pidfd = pidfd.try_clone().map_err(Error::Io)?;
crate::tokio::wait::watch_pidfd(pidfd).await
}
#[cfg(target_os = "macos")]
{
let ProcSource::Tokio { child, identity, .. } = self else {
return Ok(());
};
let (Some(pid), Some(identity)) = (child.id(), *identity) else {
return Ok(());
};
crate::tokio::wait::wait_exit_for(pid, identity).await
}
}
#[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(unix)]
ProcSource::Foreign { reaped_elsewhere, .. } => {
log::debug!("the child was reaped by someone else, or cannot be shown to be ours; {sig:?} not sent");
Ok(if *reaped_elsewhere {
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 { child, pidfd, .. } => {
let pid = child.id().expect("checked above");
crate::signal::via_pidfd(Some(std::os::fd::AsFd::as_fd(pidfd)), pid, sig).map_err(Error::Io)
}
#[cfg(target_os = "macos")]
ProcSource::Tokio { child, identity, .. } => {
let pid = child.id().expect("checked above");
crate::signal::via_verified_pid(pid, *identity, sig).map_err(Error::Io)
}
#[cfg(windows)]
ProcSource::Tokio { child, .. } => {
let Sig::Kill = sig;
use windows::Win32::Foundation::{ERROR_ACCESS_DENIED, HANDLE, WAIT_FAILED};
use windows::Win32::System::Threading::{TerminateProcess, WaitForSingleObject};
let Some(h) = child.raw_handle() else {
return Ok(Sent::Gone);
};
match unsafe { TerminateProcess(HANDLE(h), 1) } {
Ok(()) => Ok(Sent::Delivered),
Err(e) if e.code() == windows::core::HRESULT::from_win32(ERROR_ACCESS_DENIED.0) => {
if unsafe { WaitForSingleObject(HANDLE(h), 0) } == WAIT_FAILED {
Err(Error::Io(e.into()))
} else {
Ok(Sent::Delivered)
}
}
Err(e) => Err(Error::Io(e.into())),
}
}
#[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 { .. } => RootState::Reaped,
ProcSource::Tokio { child, .. } if child.id().is_none() => RootState::Reaped,
ProcSource::Tokio { child, .. } => self.state_of(child),
}
}
#[cfg(unix)]
fn state_of(
&self,
#[cfg_attr(
target_os = "linux",
allow(unused_variables, reason = "Linux peeks the pidfd, not the pid")
)]
child: &::tokio::process::Child,
) -> RootState {
let ProcSource::Tokio { .. } = self else {
return RootState::Reaped;
};
#[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 { identity, .. } = self else {
unreachable!("checked above")
};
let (Some(pid), Some(identity)) = (child.id(), *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;
};
let pid = child.id()?;
match self.state_of(child) {
RootState::Unreaped => None,
state => Some((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<'_>> {
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> {
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::wait::exit_only::Peek::Running
))
}
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(all(unix, test))]
pub(crate) fn forget_foreign(&mut self) -> Option<&'static str> {
self.forget_foreign_noting(&mut Diagnosis::default())
}
#[cfg(unix)]
pub(crate) fn forget_foreign_noting(&mut self, why: &mut Diagnosis) -> Option<&'static str> {
self.forget_noting(FORGET_FOREIGN, false, why)
}
#[cfg(target_os = "macos")]
pub(crate) fn forget_because(&mut self, why: &str) -> Option<&'static str> {
self.forget_as(why, false)
}
#[cfg(unix)]
pub(crate) fn forgotten_fate(&self, id: Option<ProcessId>) -> Option<ChildFate> {
match self {
ProcSource::Foreign { reaped_elsewhere, .. } => Some(if *reaped_elsewhere {
ChildFate::Gone
} else {
ChildFate::Running { id }
}),
_ => None,
}
}
#[cfg(unix)]
pub(crate) fn forget_as(&mut self, why: &str, reaped_elsewhere: bool) -> Option<&'static str> {
self.forget_noting(why, reaped_elsewhere, &mut Diagnosis::default())
}
#[cfg(target_os = "linux")]
fn forget_deferring(&mut self, why: &str, reaped_elsewhere: bool, owed: &mut Diagnosis) -> Option<&'static str> {
let (pid, leak) = self.forget_quietly(reaped_elsewhere)?;
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,
reaped_elsewhere: bool,
diagnosis: &mut Diagnosis,
) -> Option<&'static str> {
let (pid, leak) = self.forget_quietly(reaped_elsewhere)?;
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, reaped_elsewhere: bool) -> 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 {
child,
stdin,
stdout,
stderr,
..
} = self
else {
return None;
};
let pid = child.id().map_or_else(|| "?".to_owned(), |pid| pid.to_string());
let foreign = ProcSource::Foreign {
stdin: stdin.take(),
stdout: stdout.take(),
stderr: stderr.take(),
reaped_elsewhere,
};
std::mem::replace(self, foreign).forget();
#[cfg(test)]
super::drop_fault::note_forget();
Some((pid, 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 reaped_elsewhere = now.as_ref().is_none_or(shown_reaped_elsewhere);
let (_, leak) = self.forget_quietly(reaped_elsewhere)?;
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 == Waited::Foreign)?;
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), shown_reaped_elsewhere(&state), diagnosis)
}
#[cfg(unix)]
fn forget_if_foreign_quietly(&mut self, id: Option<ProcessId>) -> Option<(&'static str, String, ChildFate)> {
let (_, state) = self.elsewhere()?;
let (_, leak) = self.forget_quietly(shown_reaped_elsewhere(&state))?;
let fate = if shown_reaped_elsewhere(&state) {
ChildFate::Gone
} else {
ChildFate::Running { id }
};
Some((leak, foreign_why(&state), fate))
}
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 {
#[cfg(unix)]
let foreign = self.forget_if_foreign_quietly(id);
#[cfg(not(unix))]
let foreign: Option<(&'static str, String, ChildFate)> = None;
#[cfg(target_os = "linux")]
let (handed, hand_leak) = self.hand_to_pidfd_reaper(pid, id);
#[cfg(not(target_os = "linux"))]
let (handed, hand_leak): (Option<ChildFate>, Option<&'static str>) = {
self.release();
(None, None)
};
log::warn!(
"{}",
why.fold(refused_kill_warning(
pid,
e,
handed.is_some(),
foreign.as_ref().map(|f| f.1.as_str()),
foreign.as_ref().map(|f| f.0).or(hand_leak)
))
);
debug_assert!(
matches!(e, Error::Io(io) if io.kind() == std::io::ErrorKind::PermissionDenied),
"the teardown kill of an owned child failed: {e}"
);
return after_refused_kill(handed, foreign.map(|f| f.2), id);
}
#[cfg(unix)]
let (waited, cause) = self.wait_and_reap_caused(pid, log::Level::Debug);
#[cfg(not(unix))]
let waited = self.wait_and_reap(pid);
let fate = match waited {
Waited::Exited => self.collect_exit(id),
Waited::Foreign => Foreign::Gone.fate(matches!(killed, Ok(Sent::Delivered))),
Waited::Unverified => match killed {
Ok(Sent::Delivered) => ChildFate::Killed,
_ => ChildFate::Running { id },
},
};
#[cfg(unix)]
match waited {
Waited::Exited => {}
Waited::Foreign | Waited::Unverified => {
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}"),
waited == Waited::Foreign,
why,
);
}
}
self.release();
fate
}
pub(crate) fn collect_exit(&mut self, id: Option<ProcessId>) -> ChildFate {
let ProcSource::Tokio { child, .. } = self else {
unreachable!("only a tokio backend's wait answers `Exited`")
};
crate::child::spawn::fate_of_a_look(child.try_wait().map_err(|e| e.raw_os_error()), id)
}
#[cfg(target_os = "linux")]
pub(crate) fn leave_front(
self,
pid: u32,
front: crate::elevation::front::Front,
id: Option<ProcessId>,
subtree: Option<&crate::containment::cgroup::Subtree>,
) -> (crate::child::spawn::FrontFate, ChildFate) {
self.leave_front_noting(pid, front, id, subtree, &mut Diagnosis::default())
}
#[cfg(target_os = "linux")]
pub(crate) fn leave_front_noting(
mut self,
pid: u32,
front: crate::elevation::front::Front,
id: Option<ProcessId>,
subtree: Option<&crate::containment::cgroup::Subtree>,
why: &mut Diagnosis,
) -> (crate::child::spawn::FrontFate, ChildFate) {
if let Some((_, state)) = self.elsewhere() {
self.forget_deferring(&foreign_why(&state), shown_reaped_elsewhere(&state), why);
}
let ProcSource::Tokio { pidfd, .. } = &mut self else {
log::warn!(
"{}",
why.fold(format!(
"elevation front pid {pid}: its backend is foreign (reaped elsewhere), so it cannot be waited on"
))
);
debug_assert!(
false,
"elevation front pid {pid}: a spawn's backend is foreign before its teardown"
);
return (crate::child::spawn::FrontFate::Unaccounted, ChildFate::Unknown);
};
let pidfd = pidfd.take();
self.forget_deferring(
"is an elevation front, sent nothing, and handed to the pidfd teardown",
false,
why,
);
crate::child::spawn::leave_front_through_pidfd_noting(Some(pid), pidfd, front, id, subtree, why)
}
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 hand_to_pidfd_reaper(mut self, pid: u32, id: Option<ProcessId>) -> (Option<ChildFate>, Option<&'static str>) {
let ProcSource::Tokio { pidfd, .. } = &mut self else {
return (None, None);
};
let pidfd = pidfd.take();
let leak = self.forget_quietly(false).map(|(_, leak)| leak);
let fate = crate::child::spawn::teardown_through_pidfd(Some(pid), pidfd, id);
(Some(fate), leak)
}
#[cfg(target_os = "linux")]
pub(crate) fn teardown_through_pidfd(mut self, pid: u32, id: Option<ProcessId>, why: &mut Diagnosis) -> ChildFate {
use crate::wait::exit_only::{self, Target};
crate::bounded::assert_may_block("teardown_through_pidfd");
let killed = self.teardown_kill();
if let Err(e) = &killed {
let foreign = self.forget_if_foreign_quietly(id);
let (handed, hand_leak) = self.hand_to_pidfd_reaper(pid, id);
log::warn!(
"{}",
why.fold(refused_kill_warning(
pid,
e,
handed.is_some(),
foreign.as_ref().map(|f| f.1.as_str()),
foreign.as_ref().map(|f| f.0).or(hand_leak)
))
);
debug_assert!(
matches!(&e, Error::Io(io) if io.kind() == std::io::ErrorKind::PermissionDenied),
"the teardown kill of an owned child failed: {e}"
);
return after_refused_kill(handed, foreign.map(|f| f.2), id);
}
let ProcSource::Tokio { pidfd, .. } = &self else {
unreachable!("a freshly spawned backend is a tokio child");
};
let mut failed = None;
let fate = match exit_only::reap_blocking(&Target::PidFd(std::os::fd::AsFd::as_fd(pidfd))) {
Ok(Ok(_reaped)) => {
#[cfg(test)]
if let exit_only::Reaped::Status(status) = _reaped {
crate::child::spawn::fault::record_teardown_reap(pid, status);
}
ChildFate::Reaped
}
Ok(Err(foreign)) => {
log::debug!("child {pid} was reaped by someone else during its teardown");
foreign.fate(matches!(killed, Ok(Sent::Delivered)))
}
Err(e) => {
failed = Some(e);
ChildFate::Killed
}
};
match &failed {
Some(e) => self.forget_noting(&format!("could not be reaped through its pidfd ({e})"), false, why),
None => self.forget_foreign_noting(why),
};
debug_assert!(failed.is_none(), "waitid on a child's own pidfd failed: {failed:?}");
fate
}
#[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 after_refused_kill(handed: Option<ChildFate>, forgotten: Option<ChildFate>, id: Option<ProcessId>) -> ChildFate {
if let Some(fate) = handed.or(forgotten) {
return fate;
}
#[cfg(target_os = "linux")]
debug_assert!(
false,
"a refused teardown kill left a child neither handed to the pidfd reaper nor forgotten"
);
ChildFate::Running { id }
}
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::wait::exit_only::{self, Peek, Target};
match exit_only::wait_visible_exit(&Target::PidFd(pidfd.as_fd())) {
Ok(Peek::Exit(_reaped)) => {
#[cfg(test)]
if let exit_only::Reaped::Status(status) = _reaped {
crate::child::spawn::fault::record_teardown_reap(pid, status);
}
(Waited::Exited, None)
}
Ok(Peek::Foreign(_)) => (
Waited::Foreign,
Some("waitid on its pidfd found it reaped by someone else (ECHILD)".to_owned()),
),
Ok(Peek::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::backend::{await_reapable, Waited as Awaited};
match await_reapable(pid, Some(identity), None) {
Ok(Awaited::Reapable) => {
#[cfg(test)]
if let Ok(crate::wait::exit_only::Peek::Exit(crate::wait::exit_only::Reaped::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::Foreign, 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)]
fn wait_on_handle(child: &::tokio::process::Child, pid: u32) -> Waited {
use windows::Win32::Foundation::{HANDLE, WAIT_OBJECT_0};
use windows::Win32::System::Threading::{WaitForSingleObject, INFINITE};
let _ = pid;
let h = child.raw_handle().expect("tokio owns the handle while id() is Some");
let waited = unsafe { WaitForSingleObject(HANDLE(h), INFINITE) };
debug_assert!(
waited == WAIT_OBJECT_0,
"wait_and_reap did not observe the child's exit: {waited:?}"
);
if waited != WAIT_OBJECT_0 {
log::warn!("wait_and_reap: the wait on child {pid}'s handle failed: {waited:?}");
return Waited::Unverified;
}
#[cfg(test)]
{
use std::os::windows::process::ExitStatusExt as _;
let mut code = 0u32;
unsafe { windows::Win32::System::Threading::GetExitCodeProcess(HANDLE(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(test)]
#[path = "proc_source_tests.rs"]
mod proc_source_tests;