use std::fmt;
use std::sync::{Condvar, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant};
use crate::error::Error;
use crate::os_process::child::{ExitRecord, Foreign, OsChild, PeekOutcome};
use crate::signal::{Sent, Sig};
#[path = "owned/holder.rs"]
mod holder;
#[path = "owned/slot.rs"]
pub(crate) mod slot;
#[path = "owned/teardown.rs"]
pub(crate) mod teardown;
#[path = "owned/unreaped.rs"]
pub(crate) mod unreaped;
#[path = "owned/waiting.rs"]
mod waiting;
#[cfg(test)]
#[path = "owned/over.rs"]
mod over;
#[cfg(test)]
#[path = "owned/seams.rs"]
pub(crate) mod seams;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum State {
N,
W { token: u64 },
E(ExitRecord),
}
struct Inner {
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;
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ChildWaitOutcome {
Exited(ExitRecord),
Foreign(Foreign),
DeadlinePassed,
}
pub(crate) struct OwnedChild {
os: Box<dyn OsChild>,
inner: Mutex<Inner>,
condvar: Condvar,
#[cfg(test)]
owner: Mutex<Option<std::thread::ThreadId>>,
}
impl OwnedChild {
pub(crate) fn new(os: Box<dyn OsChild>) -> OwnedChild {
OwnedChild {
os,
inner: Mutex::new(Inner {
state: State::N,
next_token: 0,
#[cfg(test)]
log: Vec::new(),
}),
condvar: Condvar::new(),
#[cfg(test)]
owner: Mutex::new(None),
}
}
#[cfg(test)]
#[allow(
clippy::result_large_err,
reason = "the child is handed back untouched for the caller to deal with"
)]
pub(crate) fn adopt(
child: std::process::Child,
id: crate::identity::ProcessId,
) -> Result<OwnedChild, (Error, std::process::Child)> {
crate::os_process::child::adopt_std(child, id).map(OwnedChild::new)
}
pub(crate) fn pid(&self) -> Option<u32> {
self.os.pid()
}
#[cfg(any(target_os = "linux", windows))]
pub(crate) fn kill_refusal(&self) -> crate::os_process::child::KillRefusal {
self.os.kill_refusal()
}
#[cfg(any(target_os = "linux", windows))]
pub(crate) fn os_handle(&self) -> crate::os_process::child::OsHandle<'_> {
self.os.os_handle()
}
#[cfg(unix)]
pub(crate) fn pidfd(&self) -> Option<std::os::fd::BorrowedFd<'_>> {
#[cfg(target_os = "linux")]
return Some(self.os_handle());
#[cfg(not(target_os = "linux"))]
None
}
pub(crate) fn is_reaped(&self) -> bool {
matches!(self.lock().state, State::E(_))
}
pub(crate) fn peek(&self) -> Result<PeekOutcome, Error> {
self.peek_locked(&self.lock())
}
pub(crate) fn liveness(&self) -> Result<crate::identity::Liveness, Error> {
use crate::identity::Liveness;
use crate::os_process::Exit;
if matches!(self.os.exited()?, Exit::Exited) {
return Ok(Liveness::Dead);
}
Ok(match self.peek()? {
PeekOutcome::Exit(_) | PeekOutcome::Foreign(_) => Liveness::Dead,
PeekOutcome::Running if self.os.exited_unannounced()? => Liveness::Dead,
PeekOutcome::Running => Liveness::Alive,
})
}
#[cfg(unix)]
pub(crate) fn state(&self) -> crate::signal::RootState {
self.state_locked(&self.lock())
}
#[cfg(unix)]
fn state_locked(&self, lock: &Guard<'_>) -> crate::signal::RootState {
use crate::signal::RootState;
if matches!(lock.state, State::E(_)) {
return RootState::Reaped { own: true };
}
RootState::of_peek(self.os.peek().map_err(Error::into_io))
}
#[cfg(all(unix, test))]
pub(crate) fn is_held_by_current_thread(&self) -> bool {
*self.owner.lock().unwrap_or_else(PoisonError::into_inner) == Some(std::thread::current().id())
}
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 an OwnedChild it already holds"
);
drop(owner);
let guard = match self.inner.try_lock() {
Ok(guard) => guard,
Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(),
Err(std::sync::TryLockError::WouldBlock) => {
seams::lock_contended();
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
}
}
}
impl OwnedChild {
pub(crate) fn signal(&self, sig: Sig) -> Result<Sent, Error> {
self.signal_locked(&self.lock(), sig)
}
fn signal_locked(&self, lock: &Guard<'_>, sig: Sig) -> Result<Sent, Error> {
if matches!(lock.state, State::E(_)) {
return Ok(Sent::Gone);
}
self.os.signal(sig)
}
fn peek_locked(&self, lock: &Guard<'_>) -> Result<PeekOutcome, Error> {
match lock.state {
State::E(record) => Ok(PeekOutcome::Exit(record)),
State::N | State::W { .. } => self.os.peek(),
}
}
pub(crate) fn exited_by(&self, deadline: Option<Instant>) -> Result<bool, Error> {
crate::os_process::drive::exited_until(&*self.os, deadline)
}
#[cfg(unix)]
pub(crate) fn hold(&self, pid: u32) -> ReapHold<'_> {
ReapHold {
child: self,
pid,
lock: self.lock(),
}
}
fn log_unreadable(&self, record: ExitRecord) {
if let ExitRecord::Unreadable { si_code } = record {
log::warn!(
"{:?}: a consuming waitid returned si_code {si_code}, not an exit record",
self.os
);
debug_assert!(false, "a consuming waitid on a zombie returned si_code {si_code}");
}
}
}
#[cfg(unix)]
pub(crate) struct ReapHold<'a> {
child: &'a OwnedChild,
pid: u32,
lock: Guard<'a>,
}
#[cfg(unix)]
impl ReapHold<'_> {
pub(crate) fn peek(&self) -> Result<PeekOutcome, Error> {
self.child.peek_locked(&self.lock)
}
pub(crate) fn state(&self) -> crate::signal::RootState {
self.child.state_locked(&self.lock)
}
pub(crate) fn signal(&self, sig: Sig) -> Result<Sent, Error> {
self.child.signal_locked(&self.lock, sig)
}
pub(crate) fn group(&self) -> crate::containment::GroupRoot<'_> {
crate::containment::GroupRoot::new(self.child.pidfd(), self)
}
}
#[cfg(unix)]
impl crate::containment::RootCheck for ReapHold<'_> {
fn check(&self) -> Result<(), String> {
super::tree_call::group_number_holds(self.pid, self.state())
}
}
impl fmt::Debug for OwnedChild {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut d = f.debug_struct("OwnedChild");
d.field("os", &self.os);
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()
}
}
#[cfg(test)]
#[path = "owned_tests.rs"]
pub(crate) mod owned_tests;