use std::fmt;
use std::sync::{Condvar, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant};
use crate::elevation::front::TrackedKind;
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 },
Exited(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>,
kind: TrackedKind,
inner: Mutex<Inner>,
condvar: Condvar,
#[cfg(test)]
owner: Mutex<Option<std::thread::ThreadId>>,
}
impl OwnedChild {
pub(crate) fn new(os: Box<dyn OsChild>, kind: TrackedKind) -> OwnedChild {
OwnedChild {
os,
kind,
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(target_os = "linux")]
pub(crate) fn over_pidfd<K: crate::identity::Kernel + Send + 'static>(
kernel: K,
pid: Option<u32>,
pidfd: std::os::fd::OwnedFd,
kind: TrackedKind,
) -> OwnedChild {
OwnedChild::new(
Box::new(crate::os_process::linux::LinuxProcess::new(kernel, pid, pidfd)),
kind,
)
}
#[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,
kind: TrackedKind,
) -> Result<OwnedChild, (Error, std::process::Child)> {
crate::os_process::child::adopt_std(child, id).map(|os| OwnedChild::new(os, kind))
}
#[cfg(all(test, target_os = "macos"))]
#[allow(
clippy::result_large_err,
reason = "the child is handed back untouched for the caller to deal with"
)]
pub(crate) fn adopt_over<K: crate::identity::Kernel + Send + 'static>(
kernel: impl FnOnce(u32, u64) -> K,
child: std::process::Child,
id: crate::identity::ProcessId,
kind: TrackedKind,
) -> Result<OwnedChild, (Error, std::process::Child)> {
crate::os_process::child::adopt_std_over(kernel, child, id).map(|os| OwnedChild::new(os, kind))
}
pub(crate) fn pid(&self) -> Option<u32> {
self.os.pid()
}
pub(crate) fn tracked_kind(&self) -> TrackedKind {
self.kind
}
pub(crate) fn handle_id(&self) -> usize {
std::ptr::from_ref::<dyn OsChild>(&*self.os).cast::<()>() as usize
}
pub(crate) fn os_process(&self) -> &dyn crate::os_process::OsProcess {
&*self.os
}
pub(crate) fn kernel(&self) -> &dyn crate::identity::Kernel {
self.os.kernel()
}
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 exit_seen(&self) -> bool {
matches!(self.lock().state, State::Exited(_))
}
pub(crate) fn consumes_at_drop(&self) -> bool {
#[cfg(unix)]
return self.drop_consumes(self.exit_seen());
#[cfg(not(unix))]
true
}
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;
match self.os.exited() {
Ok(Exit::Exited) => return Ok(Liveness::Dead),
Ok(Exit::Running(_) | Exit::Recheck) => {}
Err(refused) => {
return match self.peek() {
Ok(PeekOutcome::Exit(_) | PeekOutcome::Foreign(_)) => Ok(Liveness::Dead),
Ok(PeekOutcome::Running) => Err(refused),
Err(peek) => {
log::debug!(
"liveness: child {:?}: the exit confirmation was refused ({}), and the peek behind it failed too ({})",
self.pid(),
crate::error::Report(&refused),
crate::error::Report(&peek)
);
Err(refused)
}
};
}
}
Ok(match self.peek()? {
PeekOutcome::Exit(_) | PeekOutcome::Foreign(_) => Liveness::Dead,
PeekOutcome::Running => Liveness::Alive,
})
}
#[cfg(unix)]
pub(crate) fn state(&self) -> crate::signal::RootState {
crate::signal::RootState::of_peek(self.os.peek().map_err(Error::into_io))
}
#[cfg(unix)]
fn drop_consumes(&self, seen: bool) -> bool {
seen || self.os.exact_consume()
}
#[cfg(unix)]
pub(crate) fn number_holder(&self, pid: u32) -> crate::identity::NumberRead {
self.os.number_holder(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 an OwnedChild 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
}
}
}
impl OwnedChild {
pub(crate) fn signal(&self, sig: Sig) -> Result<Sent, Error> {
let lock = self.lock();
if matches!(lock.state, State::Exited(_)) {
return Ok(Sent::Gone);
}
self.os.signal(sig)
}
fn peek_locked(&self, lock: &Guard<'_>) -> Result<PeekOutcome, Error> {
match lock.state {
State::Exited(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)
}
pub(crate) fn hold(&self, pid: u32) -> RootHandle<'_> {
RootHandle { child: self, pid }
}
#[cfg(unix)]
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!(
std::thread::panicking(),
"a consuming waitid on a zombie returned si_code {si_code}"
);
}
}
}
#[cfg(unix)]
impl Drop for OwnedChild {
fn drop(&mut self) {
use crate::wait::exit_only::Reap;
let seen = matches!(
self.inner.get_mut().unwrap_or_else(PoisonError::into_inner).state,
State::Exited(_)
);
if !self.drop_consumes(seen) {
return;
}
match self.os.try_reap() {
Ok(Reap::Reaped(record)) => self.log_unreadable(record),
Ok(Reap::Running) => {}
Ok(Reap::Foreign(foreign)) => {
log::debug!(
"{:?}: nothing left to reap at the end of the handle ({foreign:?})",
self.os
);
}
Err(error) => log::warn!(
"{:?}: reaping at the end of the handle failed ({}); a zombie may be left",
self.os,
crate::error::Report(&error)
),
}
}
}
pub(crate) struct RootHandle<'a> {
child: &'a OwnedChild,
pid: u32,
}
impl RootHandle<'_> {
pub(crate) fn signal(&self, sig: Sig) -> Result<Sent, Error> {
self.child.signal(sig)
}
#[cfg(unix)]
pub(crate) fn state(&self) -> crate::signal::RootState {
self.child.state()
}
}
impl crate::containment::Root for RootHandle<'_> {
fn pid(&self) -> u32 {
self.pid
}
fn signal(&self, sig: Sig) -> Result<Sent, Error> {
RootHandle::signal(self, sig)
}
#[cfg(unix)]
fn state(&self) -> crate::signal::RootState {
RootHandle::state(self)
}
#[cfg(target_os = "linux")]
fn pidfd(&self) -> Option<std::os::fd::BorrowedFd<'_>> {
self.child.pidfd()
}
}
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;