use std::process::ExitStatus;
use crate::error::{ChildFate, Error};
use crate::identity::ProcessId;
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)
}
}
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 self.classify(&child).0 == Ownership::Ours {
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)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Ownership {
Ours,
Foreign,
Unknown,
}
#[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(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.classify(child) {
(Ownership::Ours, _) => Ok(()),
(Ownership::Foreign, _) => {
self.forget_as("was reaped by someone else", true);
Err(gone())
}
(Ownership::Unknown, failed) => Err(Error::Unassessable {
detail: format!("pid {pid}: the child cannot be shown to be ours; it was not waited on"),
source: failed,
}),
}
}
#[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 not_ours(&self) -> Option<Ownership> {
let ProcSource::Tokio { child, .. } = self else {
return None;
};
match self.classify(child) {
(Ownership::Ours, _) => None,
(Ownership::Foreign, _) => Some(Ownership::Foreign),
(Ownership::Unknown, failed) => {
let pid = child.id().unwrap_or(0);
match failed {
Some(e) => log::warn!("child {pid} cannot be shown to be ours: its peek failed: {e}"),
None => log::warn!("child {pid} cannot be shown to be ours"),
}
Some(Ownership::Unknown)
}
}
}
#[cfg(unix)]
pub(crate) fn forget_unless_ours(&mut self, id: Option<ProcessId>) -> Option<ChildFate> {
let (fate, reaped_elsewhere) = match self.not_ours()? {
Ownership::Foreign => (ChildFate::Gone, true),
Ownership::Unknown => (ChildFate::Running { id }, false),
Ownership::Ours => unreachable!("not_ours answers only for a child that is not ours"),
};
self.forget_as(
"was reaped by someone else, or cannot be shown to be ours",
reaped_elsewhere,
);
Some(fate)
}
#[cfg(unix)]
fn classify(&self, child: &::tokio::process::Child) -> (Ownership, Option<std::io::Error>) {
use crate::wait::exit_only::Peek;
let ProcSource::Tokio { .. } = self else {
return (Ownership::Foreign, None);
};
if child.id().is_none() {
return (Ownership::Ours, None);
}
#[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 (Ownership::Unknown, None);
};
crate::wait::exit_only::peek_verified(&crate::wait::exit_only::Target::pid(pid, Some(identity)))
};
match peeked {
Ok(Peek::Running | Peek::Exit(_)) => (Ownership::Ours, None),
Ok(Peek::Foreign(_)) => (Ownership::Foreign, None),
Err(e) => (Ownership::Unknown, Some(e)),
}
}
#[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(),
}
}
pub(crate) fn wait_and_reap(&mut self, pid: u32) -> Waited {
crate::bounded::assert_may_block("wait_and_reap");
match self {
#[cfg(unix)]
ProcSource::Foreign { .. } => Waited::Unverified,
#[cfg(target_os = "linux")]
ProcSource::Tokio { child, pidfd, .. } => {
if !still_ours(child) {
return Waited::Exited;
}
#[cfg(test)]
crate::child::spawn::fault::run_between_kill_and_wait();
wait_on_pidfd(pid, pidfd)
}
#[cfg(target_os = "macos")]
ProcSource::Tokio { child, identity, .. } => {
if !still_ours(child) {
return Waited::Exited;
}
let Some(identity) = identity else {
return Waited::Unverified;
};
#[cfg(test)]
crate::child::spawn::fault::run_between_kill_and_wait();
wait_reapable(pid, *identity)
}
#[cfg(windows)]
ProcSource::Tokio { child, .. } => {
if !still_ours(child) {
return Waited::Exited;
}
#[cfg(test)]
crate::child::spawn::fault::run_between_kill_and_wait();
wait_on_handle(child, pid)
}
#[cfg(windows)]
ProcSource::Raw(_) => unreachable!("the raw backend tears its own spawn failures down"),
}
}
#[cfg(unix)]
pub(crate) fn forget_foreign(&mut self) {
self.forget_because("was reaped by someone else, or cannot be shown to be ours");
}
#[cfg(unix)]
pub(crate) fn forget_because(&mut self, why: &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) {
let ProcSource::Tokio {
child,
stdin,
stdout,
stderr,
..
} = self
else {
return;
};
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();
let leak = if cfg!(target_os = "linux") {
"tokio's pidfd and its reactor registration"
} else {
"tokio's SIGCHLD watch"
};
log::warn!("child {pid} {why}; forgetting tokio's handle for it leaks {leak}");
}
#[cfg(unix)]
pub(crate) fn forget_if_foreign(&mut self) {
_ = self.forget_unless_ours(None);
}
pub(crate) fn reap_now(mut self, pid: u32, id: Option<ProcessId>) -> ChildFate {
crate::bounded::assert_may_block("reap_now");
let killed = self.teardown_kill();
if let Err(e) = &killed {
#[cfg(unix)]
let forgotten = self.forget_unless_ours(id);
#[cfg(not(unix))]
let forgotten: Option<ChildFate> = None;
#[cfg(target_os = "linux")]
let handed = self.hand_to_pidfd_reaper(pid, id);
#[cfg(not(target_os = "linux"))]
let handed: Option<ChildFate> = {
self.release();
None
};
log::warn!(
"teardown kill of child {pid} failed ({e}); {}",
refused_kill_fate(handed.is_some())
);
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, forgotten, id);
}
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 => self.forget_as("was reaped by someone else", true),
Waited::Unverified => self.forget_foreign(),
}
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(
mut self,
pid: u32,
front: crate::elevation::front::Front,
id: Option<ProcessId>,
subtree: Option<&crate::containment::cgroup::Subtree>,
) -> (crate::child::spawn::FrontFate, ChildFate) {
self.forget_if_foreign();
let ProcSource::Tokio { pidfd, .. } = &mut self else {
log::warn!(
"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_because("is an elevation front, sent nothing, and handed to the pidfd teardown");
crate::child::spawn::leave_front_through_pidfd(Some(pid), pidfd, front, id, subtree)
}
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> {
let ProcSource::Tokio { pidfd, .. } = &mut self else {
return None;
};
let pidfd = pidfd.take();
self.forget_because("had its teardown kill refused and is handed to the pidfd teardown");
Some(crate::child::spawn::teardown_through_pidfd(Some(pid), pidfd, id))
}
#[cfg(target_os = "linux")]
pub(crate) fn teardown_through_pidfd(mut self, pid: u32, id: Option<ProcessId>) -> 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 forgotten = self.forget_unless_ours(id);
let handed = self.hand_to_pidfd_reaper(pid, id);
log::warn!(
"teardown kill of child {pid} failed ({e}); {}",
refused_kill_fate(handed.is_some())
);
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, forgotten, id);
}
let ProcSource::Tokio { pidfd, .. } = &self else {
unreachable!("a freshly spawned backend is a tokio child");
};
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) => {
log::warn!("teardown of child {pid}: reaping through its pidfd failed: {e}");
debug_assert!(false, "waitid on a child's own pidfd failed: {e}");
ChildFate::Killed
}
};
self.forget_foreign();
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) -> Waited {
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
}
Ok(Peek::Foreign(_)) => Waited::Foreign,
Ok(Peek::Running) => {
log::warn!("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
}
Err(e) => {
log::warn!("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
}
}
}
#[cfg(target_os = "macos")]
fn wait_reapable(pid: u32, identity: u64) -> Waited {
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
}
Ok(Awaited::Gone) => Waited::Foreign,
Ok(Awaited::Orphaned) => {
log::warn!(
"wait_and_reap: child {pid} is not ours to reap (launchd holds its zombie, because its tracer died)"
);
Waited::Foreign
}
Ok(Awaited::DeadlinePassed) => {
log::warn!("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
}
Err(e) => {
log::warn!("wait_and_reap: waiting on child {pid} failed: {e}");
Waited::Unverified
}
}
}
#[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;