use std::fmt;
use std::io;
use std::process::ExitStatus;
use std::sync::{Condvar, Mutex, MutexGuard, PoisonError};
use std::time::Duration;
use std::time::Instant;
#[cfg(any(windows, test))]
use crate::error::Error;
use crate::identity::ProcessId;
use crate::wait::exit_only::{self, Peek, Reap, Reaped, Target};
#[path = "shared/holder.rs"]
mod holder;
#[path = "shared/unlocked.rs"]
mod unlocked;
#[cfg(test)]
#[path = "shared/seams.rs"]
pub(crate) mod seams;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum State {
N,
W { token: u64 },
E(Reaped),
}
struct Inner {
#[cfg_attr(
unix,
allow(dead_code, reason = "Unix signals through the pidfd or the verified pid")
)]
child: std::process::Child,
state: State,
next_token: u64,
#[cfg(test)]
log: Vec<Logged>,
}
#[cfg(test)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Logged {
Write(State),
Notify,
}
impl Inner {
fn set(&mut self, state: State) {
self.state = state;
#[cfg(test)]
self.log.push(Logged::Write(state));
}
}
#[cfg(not(test))]
type Guard<'a> = MutexGuard<'a, Inner>;
#[cfg(test)]
struct Guard<'a> {
guard: Option<MutexGuard<'a, Inner>>,
owner: &'a Mutex<Option<std::thread::ThreadId>>,
}
#[cfg(test)]
impl std::ops::Deref for Guard<'_> {
type Target = Inner;
fn deref(&self) -> &Inner {
self.guard.as_ref().expect("a live guard")
}
}
#[cfg(test)]
impl std::ops::DerefMut for Guard<'_> {
fn deref_mut(&mut self) -> &mut Inner {
self.guard.as_mut().expect("a live guard")
}
}
#[cfg(test)]
impl Drop for Guard<'_> {
fn drop(&mut self) {
if self.guard.is_some() {
*self.owner.lock().unwrap_or_else(PoisonError::into_inner) = None;
}
}
}
pub(crate) struct SharedChild {
id: ProcessId,
#[cfg(target_os = "linux")]
pidfd: Option<std::os::fd::OwnedFd>,
#[cfg(target_os = "macos")]
identity: Option<u64>,
#[cfg(windows)]
handle: std::os::windows::io::OwnedHandle,
inner: Mutex<Inner>,
condvar: Condvar,
#[cfg(test)]
owner: Mutex<Option<std::thread::ThreadId>>,
}
impl SharedChild {
#[allow(
clippy::result_large_err,
reason = "the child is handed back untouched for the caller to deal with"
)]
#[cfg(any(windows, test))]
pub(crate) fn adopt(
child: std::process::Child,
id: ProcessId,
) -> Result<SharedChild, (Error, std::process::Child)> {
debug_assert_eq!(child.id(), id.pid(), "the identity must be the child's");
#[cfg(target_os = "linux")]
let pidfd = match crate::wait::backend::open_own_child(id.pid(), Some(id)) {
Ok(pidfd) => pidfd,
Err(e) => return Err((e, child)),
};
#[cfg(target_os = "macos")]
{
match crate::signal::read_identity(id.pid()) {
Ok(identity) => Ok(Self::new_macos(child, id, identity)),
Err(errno) => Err((crate::signal::identity_unreadable(id.pid(), errno), child)),
}
}
#[cfg(windows)]
let handle = match Self::duplicate_handle(&child) {
Ok(handle) => handle,
Err(e) => return Err((Error::Io(e), child)),
};
#[cfg(not(target_os = "macos"))]
Ok(SharedChild {
id,
#[cfg(target_os = "linux")]
pidfd,
#[cfg(windows)]
handle,
inner: Mutex::new(Inner {
child,
state: State::N,
next_token: 0,
#[cfg(test)]
log: Vec::new(),
}),
condvar: Condvar::new(),
#[cfg(test)]
owner: Mutex::new(None),
})
}
#[cfg(target_os = "macos")]
pub(crate) fn adopt_verified(child: std::process::Child, id: ProcessId, identity: u64) -> SharedChild {
debug_assert_eq!(child.id(), id.pid(), "the identity must be the child's");
Self::new_macos(child, id, Some(identity))
}
#[cfg(target_os = "macos")]
fn new_macos(child: std::process::Child, id: ProcessId, identity: Option<u64>) -> SharedChild {
SharedChild {
id,
identity,
inner: Mutex::new(Inner {
child,
state: State::N,
next_token: 0,
#[cfg(test)]
log: Vec::new(),
}),
condvar: Condvar::new(),
#[cfg(test)]
owner: Mutex::new(None),
}
}
#[cfg(target_os = "linux")]
pub(crate) fn adopt_opened(child: std::process::Child, id: ProcessId, pidfd: std::os::fd::OwnedFd) -> SharedChild {
debug_assert_eq!(child.id(), id.pid(), "the identity must be the child's");
SharedChild {
id,
pidfd: Some(pidfd),
inner: Mutex::new(Inner {
child,
state: State::N,
next_token: 0,
#[cfg(test)]
log: Vec::new(),
}),
condvar: Condvar::new(),
#[cfg(test)]
owner: Mutex::new(None),
}
}
#[cfg(windows)]
fn duplicate_handle(child: &std::process::Child) -> io::Result<std::os::windows::io::OwnedHandle> {
use std::os::windows::io::AsHandle;
#[cfg(test)]
if seams::take_forced_duplicate_handle_error() {
return Err(io::Error::from_raw_os_error(
windows::Win32::Foundation::ERROR_ACCESS_DENIED.0 as i32,
));
}
child.as_handle().try_clone_to_owned()
}
#[cfg_attr(not(unix), allow(dead_code, reason = "read only on unix and in tests"))]
pub(crate) fn is_reaped(&self) -> bool {
matches!(self.lock().state, State::E(_))
}
#[cfg(all(target_os = "macos", test))]
pub(crate) fn adopted_unique(&self) -> Option<u64> {
self.identity
}
pub(crate) fn id(&self) -> u32 {
self.id.pid()
}
fn lock(&self) -> Guard<'_> {
#[cfg(test)]
{
let me = std::thread::current().id();
let owner = self.owner.lock().unwrap_or_else(PoisonError::into_inner);
assert_ne!(
*owner,
Some(me),
"self-deadlock: this thread locked a SharedChild it already holds"
);
drop(owner);
let guard = self.inner.lock().unwrap_or_else(PoisonError::into_inner);
*self.owner.lock().unwrap_or_else(PoisonError::into_inner) = Some(me);
Guard {
guard: Some(guard),
owner: &self.owner,
}
}
#[cfg(not(test))]
self.inner.lock().unwrap_or_else(PoisonError::into_inner)
}
#[cfg_attr(not(test), allow(unused_variables, reason = "only a test build logs the wake"))]
fn notify(&self, lock: &mut Guard<'_>) {
#[cfg(test)]
lock.log.push(Logged::Notify);
self.condvar.notify_all();
}
fn cv_wait<'a>(&'a self, lock: Guard<'a>) -> Guard<'a> {
#[cfg(test)]
{
let mut lock = lock;
let inner = lock.guard.take().expect("a live guard");
*self.owner.lock().unwrap_or_else(PoisonError::into_inner) = None;
let inner = self.condvar.wait(inner).unwrap_or_else(PoisonError::into_inner);
*self.owner.lock().unwrap_or_else(PoisonError::into_inner) = Some(std::thread::current().id());
lock.guard = Some(inner);
lock
}
#[cfg(not(test))]
self.condvar.wait(lock).unwrap_or_else(PoisonError::into_inner)
}
fn cv_wait_timeout<'a>(&'a self, lock: Guard<'a>, dur: Duration) -> Guard<'a> {
#[cfg(test)]
{
let mut lock = lock;
let inner = lock.guard.take().expect("a live guard");
*self.owner.lock().unwrap_or_else(PoisonError::into_inner) = None;
let (inner, _) = self
.condvar
.wait_timeout(inner, dur)
.unwrap_or_else(PoisonError::into_inner);
*self.owner.lock().unwrap_or_else(PoisonError::into_inner) = Some(std::thread::current().id());
lock.guard = Some(inner);
lock
}
#[cfg(not(test))]
{
let (lock, _) = self
.condvar
.wait_timeout(lock, dur)
.unwrap_or_else(PoisonError::into_inner);
lock
}
}
fn target(&self) -> Option<Target<'_>> {
#[cfg(target_os = "linux")]
{
use std::os::fd::AsFd;
self.pidfd.as_ref().map(|fd| Target::PidFd(fd.as_fd()))
}
#[cfg(target_os = "macos")]
{
self.identity.map(|unique| Target::pid(self.id.pid(), Some(unique)))
}
#[cfg(windows)]
{
use std::os::windows::io::AsHandle;
Some(Target::Handle(self.handle.as_handle()))
}
}
}
fn echild() -> io::Error {
#[cfg(unix)]
{
io::Error::from_raw_os_error(libc::ECHILD)
}
#[cfg(windows)]
{
io::Error::other("the child was already reaped elsewhere")
}
}
fn status_of(reaped: Reaped) -> io::Result<ExitStatus> {
match reaped {
Reaped::Status(status) => Ok(status),
Reaped::Unreadable { si_code } => Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("the child's exit record was unreadable (si_code {si_code})"),
)),
}
}
impl SharedChild {
pub(crate) fn wait(&self) -> io::Result<ExitStatus> {
match self.wait_inner(None)? {
Some(status) => Ok(status),
None => {
debug_assert!(false, "an unbounded wait ended with no exit");
Err(io::Error::other("an unbounded wait ended with no exit"))
}
}
}
pub(crate) fn try_wait(&self) -> io::Result<Option<ExitStatus>> {
let mut lock = self.lock();
if let State::E(reaped) = lock.state {
return status_of(reaped).map(Some);
}
let Some(target) = self.target() else {
return Err(echild());
};
match lock.state {
State::E(_) => unreachable!("handled above"),
State::W { .. } => self.peeked_status(&target),
State::N => match exit_only::try_reap(&target)? {
Reap::Reaped(reaped) => {
lock.set(State::E(reaped));
self.notify(&mut lock);
drop(lock);
#[cfg(test)]
seams::park_after_reap_recorded();
self.log_unreadable(reaped);
status_of(reaped).map(Some)
}
Reap::Running => Ok(None),
Reap::Foreign(_) => Err(echild()),
},
}
}
pub(crate) fn wait_deadline(&self, deadline: Instant) -> io::Result<Option<ExitStatus>> {
self.wait_inner(Some(deadline))
}
#[cfg(target_os = "linux")]
pub(crate) fn pidfd(&self) -> Option<std::os::fd::BorrowedFd<'_>> {
use std::os::fd::AsFd;
self.pidfd.as_ref().map(AsFd::as_fd)
}
#[cfg(unix)]
pub(crate) fn is_running(&self) -> io::Result<bool> {
let lock = self.lock();
if matches!(lock.state, State::E(_)) {
return Ok(false);
}
let Some(target) = self.target() else {
return Ok(false);
};
Ok(matches!(exit_only::peek(&target)?, Peek::Running))
}
pub(crate) fn kill(&self) -> io::Result<()> {
#[cfg(unix)]
{
self.kill_sent().map(drop)
}
#[cfg(windows)]
{
self.kill_windows()
}
}
#[cfg(unix)]
pub(crate) fn kill_sent(&self) -> io::Result<crate::signal::Sent> {
let lock = self.lock();
if matches!(lock.state, State::E(_)) {
return Ok(crate::signal::Sent::Gone);
}
#[cfg(test)]
exit_only::seams::signal_sent();
#[cfg(target_os = "linux")]
{
use std::os::fd::AsFd;
crate::signal::via_pidfd(
self.pidfd.as_ref().map(AsFd::as_fd),
self.id(),
crate::signal::Sig::Kill,
)
}
#[cfg(target_os = "macos")]
{
crate::signal::via_verified_pid(self.id(), self.identity, crate::signal::Sig::Kill)
}
}
#[cfg(windows)]
fn kill_windows(&self) -> io::Result<()> {
let mut lock = self.lock();
if matches!(lock.state, State::E(_)) {
return Ok(());
}
#[cfg(test)]
exit_only::seams::signal_sent();
lock.child.kill()
}
fn log_unreadable(&self, reaped: Reaped) {
if let Reaped::Unreadable { si_code } = reaped {
log::warn!(
"pid {}: a consuming waitid returned si_code {si_code}, not an exit record",
self.id()
);
debug_assert!(false, "a consuming waitid on a zombie returned si_code {si_code}");
}
}
fn peeked_status(&self, target: &Target<'_>) -> io::Result<Option<ExitStatus>> {
match exit_only::peek(target)? {
Peek::Running => Ok(None),
Peek::Exit(reaped) => status_of(reaped).map(Some),
Peek::Foreign(_) => Err(echild()),
}
}
}
impl fmt::Debug for SharedChild {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut d = f.debug_struct("SharedChild");
d.field("pid", &self.id.pid());
match self.inner.try_lock() {
Ok(inner) => d.field("state", &inner.state),
Err(std::sync::TryLockError::Poisoned(e)) => d.field("state", &e.into_inner().state),
Err(std::sync::TryLockError::WouldBlock) => d.field("state", &format_args!("locked")),
};
d.finish_non_exhaustive()
}
}
#[path = "shared/waiting.rs"]
mod waiting;
#[cfg(test)]
#[path = "shared_tests.rs"]
mod shared_tests;