use std::cell::{Cell, RefCell};
use std::collections::VecDeque;
use std::io;
use std::os::fd::{AsFd, AsRawFd, OwnedFd};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex, PoisonError};
use rustix::io::Errno;
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum ChildFault {
None,
Fail,
Sigkill,
SigkillAfterReport,
Gate(i32),
}
impl ChildFault {
pub(super) fn apply(self) -> io::Result<()> {
match self {
ChildFault::Fail => Err(io::Error::from_raw_os_error(libc::EIO)),
ChildFault::Sigkill => kill_self(),
ChildFault::Gate(fd) => {
let mut byte = 0u8;
while unsafe { libc::read(fd, (&raw mut byte).cast(), 1) } < 0
&& io::Error::last_os_error().kind() == io::ErrorKind::Interrupted
{}
Ok(())
}
ChildFault::None | ChildFault::SigkillAfterReport => Ok(()),
}
}
pub(super) fn apply_after_report(self) -> io::Result<()> {
match self {
ChildFault::SigkillAfterReport => kill_self(),
ChildFault::None | ChildFault::Fail | ChildFault::Sigkill | ChildFault::Gate(_) => Ok(()),
}
}
}
fn kill_self() -> io::Result<()> {
match rustix::process::kill_process(rustix::process::getpid(), rustix::process::Signal::KILL) {
Ok(()) => Err(io::Error::from_raw_os_error(libc::EIO)),
Err(e) => Err(io::Error::from_raw_os_error(e.raw_os_error())),
}
}
type VerdictHook = Box<dyn FnOnce(Option<u32>)>;
thread_local! {
static DONE_FD_FAILURE: Cell<Option<Errno>> = const { Cell::new(None) };
static CHILD_FAULT: Cell<ChildFault> = const { Cell::new(ChildFault::None) };
static SPAWNS: Cell<usize> = const { Cell::new(0) };
static LEAKED: Cell<Option<Option<u32>>> = const { Cell::new(None) };
static PROBE: RefCell<Option<HelperProbe>> = const { RefCell::new(None) };
static SEND_ERRNOS: RefCell<VecDeque<Errno>> = const { RefCell::new(VecDeque::new()) };
static VERDICT_HOOK: RefCell<Option<VerdictHook>> = const { RefCell::new(None) };
static HOLDER_ARMED: Cell<bool> = const { Cell::new(false) };
static HOLDER: RefCell<Option<Holder>> = const { RefCell::new(None) };
static ENDS_ARMED: Cell<bool> = const { Cell::new(false) };
static ENDS: Cell<Option<Ends>> = const { Cell::new(None) };
static AFTER_SPAWN: RefCell<Option<VerdictHook>> = const { RefCell::new(None) };
static WAIT_OVER: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
static PARENT_END_SHUT: Cell<Option<bool>> = const { Cell::new(None) };
static BEFORE_AWAITING: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
static VERDICT_GUARDED: Cell<bool> = const { Cell::new(false) };
static WATCH_FAULT: Cell<Option<WatchFault>> = const { Cell::new(None) };
static UNWOUND: Cell<Option<Unwound>> = const { Cell::new(None) };
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Unwound {
pub(crate) eof_reached: bool,
pub(crate) probe_open: Option<bool>,
}
pub(crate) fn take_unwound() -> Option<Unwound> {
UNWOUND.with(Cell::take)
}
pub(super) struct UnwindChecks<'a> {
parent_end: &'a OwnedFd,
probe: Option<HelperProbe>,
}
impl<'a> UnwindChecks<'a> {
pub(super) fn new(parent_end: &'a OwnedFd, seams: &HelperSeams) -> Self {
UNWOUND.with(|u| u.set(None));
UnwindChecks {
parent_end,
probe: seams.probe.clone(),
}
}
}
impl Drop for UnwindChecks<'_> {
fn drop(&mut self) {
if !std::thread::panicking() {
return;
}
let eof_reached = !probe_shut_read(self.parent_end);
let probe_open = self.probe.as_ref().map(|p| {
let open = p.gate.is_open();
p.release();
open
});
UNWOUND.with(|u| {
u.set(Some(Unwound {
eof_reached,
probe_open,
}))
});
}
}
fn probe_shut_read(parent_end: &OwnedFd) -> bool {
use rustix::event::{poll, PollFd, PollFlags, Timespec};
let mut fds = [PollFd::new(parent_end, PollFlags::RDHUP)];
poll(&mut fds, Some(&Timespec { tv_sec: 0, tv_nsec: 0 })).expect("poll the parent's end");
let reached = fds[0].revents().contains(PollFlags::RDHUP);
if !reached {
_ = rustix::net::shutdown(parent_end, rustix::net::Shutdown::Both);
}
!reached
}
#[derive(Clone, Copy, Debug)]
pub(crate) enum WatchFault {
Open(Errno),
Move(Errno),
Peek(Errno),
Poll(Errno),
}
#[must_use = "dropping this disarms the failure at once"]
pub(crate) struct ArmedDoneFdFailure(());
pub(crate) fn fail_done_fd(errno: Errno) -> ArmedDoneFdFailure {
DONE_FD_FAILURE.with(|f| f.set(Some(errno)));
ArmedDoneFdFailure(())
}
impl Drop for ArmedDoneFdFailure {
fn drop(&mut self) {
DONE_FD_FAILURE.with(|f| f.set(None));
}
}
pub(super) fn take_done_fd_failure() -> Option<Errno> {
DONE_FD_FAILURE.with(Cell::take)
}
#[must_use = "dropping this disarms the fault at once"]
pub(crate) struct ArmedWatchFault(());
pub(crate) fn fail_watch(fault: WatchFault) -> ArmedWatchFault {
WATCH_FAULT.with(|f| f.set(Some(fault)));
ArmedWatchFault(())
}
impl Drop for ArmedWatchFault {
fn drop(&mut self) {
WATCH_FAULT.with(|f| f.set(None));
}
}
pub(super) fn watch_open_errno() -> Option<Errno> {
match WATCH_FAULT.with(Cell::get) {
Some(WatchFault::Open(errno)) => {
WATCH_FAULT.with(|f| f.set(None));
Some(errno)
}
_ => None,
}
}
pub(super) fn watch_peek_errno() -> Option<Errno> {
match WATCH_FAULT.with(Cell::get) {
Some(WatchFault::Peek(errno)) => {
WATCH_FAULT.with(|f| f.set(None));
Some(errno)
}
_ => None,
}
}
pub(super) fn watch_poll_armed() -> bool {
matches!(WATCH_FAULT.with(Cell::get), Some(WatchFault::Poll(_)))
}
pub(super) fn watch_poll_errno() -> Option<Errno> {
match WATCH_FAULT.with(Cell::get) {
Some(WatchFault::Poll(errno)) => {
WATCH_FAULT.with(|f| f.set(None));
Some(errno)
}
_ => None,
}
}
pub(super) fn watch_move_errno() -> Option<Errno> {
match WATCH_FAULT.with(Cell::get) {
Some(WatchFault::Move(errno)) => {
WATCH_FAULT.with(|f| f.set(None));
Some(errno)
}
_ => None,
}
}
#[must_use = "dropping this disarms the hook at once"]
pub(crate) struct AfterSpawn(());
pub(crate) fn after_spawn_returns_do(hook: impl FnOnce(Option<u32>) + 'static) -> AfterSpawn {
AFTER_SPAWN.with(|h| *h.borrow_mut() = Some(Box::new(hook)));
AfterSpawn(())
}
impl Drop for AfterSpawn {
fn drop(&mut self) {
AFTER_SPAWN.with(|h| h.borrow_mut().take());
}
}
pub(super) fn spawn_returned(pid: Option<u32>) {
if let Some(hook) = AFTER_SPAWN.with(|h| h.borrow_mut().take()) {
hook(pid);
}
}
pub(crate) fn before_awaiting_the_child_do(hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
crate::oneshot_hook::arm(&BEFORE_AWAITING, hook)
}
pub(super) fn before_awaiting_the_child() {
crate::oneshot_hook::fire(&BEFORE_AWAITING);
}
pub(crate) fn wait_over_do(hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
crate::oneshot_hook::arm(&WAIT_OVER, hook)
}
pub(super) fn wait_over() {
crate::oneshot_hook::fire(&WAIT_OVER);
}
#[must_use = "dropping this fires the hook at once"]
pub(super) struct WaitOverOnDrop;
impl Drop for WaitOverOnDrop {
fn drop(&mut self) {
_ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(wait_over));
}
}
#[must_use = "dropping this disarms the fault at once"]
pub(crate) struct ArmedChildFault(());
pub(crate) fn arm_child_fault(fault: ChildFault) -> ArmedChildFault {
CHILD_FAULT.with(|f| f.set(fault));
ArmedChildFault(())
}
impl Drop for ArmedChildFault {
fn drop(&mut self) {
CHILD_FAULT.with(|f| f.set(ChildFault::None));
}
}
pub(super) fn child_fault() -> ChildFault {
CHILD_FAULT.with(|f| f.replace(ChildFault::None))
}
pub(crate) fn spawns() -> usize {
SPAWNS.with(Cell::get)
}
pub(crate) fn reset_spawns() {
SPAWNS.with(|c| c.set(0));
}
pub(super) fn count_spawn() {
SPAWNS.with(|c| c.set(c.get() + 1));
}
pub(crate) fn reset_leaked_pid() {
LEAKED.with(|c| c.set(None));
}
pub(crate) fn take_leaked_pid() -> Option<Option<u32>> {
LEAKED.with(Cell::take)
}
pub(super) fn leaked_pid(pid: Option<u32>) {
LEAKED.with(|c| c.set(Some(pid)));
}
struct Holder {
release: OwnedFd,
pidfd: OwnedFd,
}
#[must_use = "dropping this disarms the holder, or releases the one forked"]
pub(crate) struct ArmedHolder(());
pub(crate) fn arm_fork_holder() -> ArmedHolder {
HOLDER_ARMED.with(|a| a.set(true));
ArmedHolder(())
}
impl Drop for ArmedHolder {
fn drop(&mut self) {
HOLDER_ARMED.with(|a| a.set(false));
if let Some(holder) = HOLDER.with(|h| h.borrow_mut().take()) {
drop(holder.release);
let reaped = rustix::process::waitid(
rustix::process::WaitId::PidFd(holder.pidfd.as_fd()),
rustix::process::WaitIdOptions::EXITED,
);
assert!(reaped.is_ok(), "reap the holder: {reaped:?}");
}
}
}
pub(super) fn fork_holder_if_armed() {
if !HOLDER_ARMED.with(|a| a.replace(false)) {
return;
}
let (release_r, release_w) = std::io::pipe().expect("pipe");
let (release_r, release_w) = (OwnedFd::from(release_r), OwnedFd::from(release_w));
let (r, w) = (release_r.as_raw_fd(), release_w.as_raw_fd());
let pid = unsafe { libc::fork() };
if pid == 0 {
unsafe {
libc::close(w);
let mut byte = 0u8;
while libc::read(r, (&raw mut byte).cast(), 1) < 0 && *libc::__errno_location() == libc::EINTR {}
libc::_exit(0);
}
}
assert!(pid > 0, "fork the holder: {}", io::Error::last_os_error());
drop(release_r);
let pidfd = rustix::process::pidfd_open(
rustix::process::Pid::from_raw(pid).expect("a forked pid is positive"),
rustix::process::PidfdFlags::empty(),
)
.expect("the holder's pidfd");
HOLDER.with(|h| {
*h.borrow_mut() = Some(Holder {
release: release_w,
pidfd,
})
});
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Ends {
pub(crate) child_end_copy_held: bool,
pub(crate) eof_reached: bool,
pub(crate) eof_forced: bool,
}
#[must_use = "dropping this disarms the probes at once"]
pub(crate) struct ArmedEndProbes(());
pub(crate) fn arm_end_probes() -> ArmedEndProbes {
ENDS_ARMED.with(|a| a.set(true));
ENDS.with(|e| e.set(None));
ArmedEndProbes(())
}
impl Drop for ArmedEndProbes {
fn drop(&mut self) {
ENDS_ARMED.with(|a| a.set(false));
}
}
pub(crate) fn take_ends() -> Option<Ends> {
ENDS.with(Cell::take)
}
pub(super) struct EndProbes {
child_end: Option<(u64, u64)>,
held: bool,
forced: bool,
}
impl EndProbes {
pub(super) fn start(child_end: &OwnedFd) -> Self {
use std::os::unix::fs::MetadataExt;
let armed = ENDS_ARMED.with(|a| a.replace(false));
let child_end = armed.then(|| {
let meta = std::fs::File::from(child_end.try_clone().expect("clone the child's end")).metadata();
let meta = meta.expect("stat the child's end");
(meta.dev(), meta.ino())
});
EndProbes {
child_end,
held: false,
forced: false,
}
}
pub(super) fn check_copies_closed(&mut self) {
use std::os::fd::{BorrowedFd, RawFd};
use std::os::unix::fs::{FileTypeExt, MetadataExt};
let Some((dev, ino)) = self.child_end else { return };
let entries = std::fs::read_dir("/proc/self/fd").expect("list this process's descriptors");
for entry in entries.flatten() {
let Ok(meta) = std::fs::metadata(entry.path()) else {
continue;
};
if !(meta.file_type().is_socket() && meta.dev() == dev && meta.ino() == ino) {
continue;
}
let Ok(fd) = entry.file_name().to_string_lossy().parse::<RawFd>() else {
continue;
};
self.held = true;
_ = rustix::net::shutdown(unsafe { BorrowedFd::borrow_raw(fd) }, rustix::net::Shutdown::Both);
}
}
pub(super) fn forced_eof(&mut self) {
self.forced = true;
}
pub(super) fn finish(self, parent_end: &OwnedFd) {
use rustix::event::{poll, PollFd, PollFlags, Timespec};
if self.child_end.is_none() {
return;
}
let mut fds = [PollFd::new(parent_end, PollFlags::RDHUP)];
poll(&mut fds, Some(&Timespec { tv_sec: 0, tv_nsec: 0 })).expect("poll the parent's end");
let eof_reached = fds[0].revents().contains(PollFlags::RDHUP);
if !eof_reached {
_ = rustix::net::shutdown(parent_end, rustix::net::Shutdown::Both);
}
ENDS.with(|e| {
e.set(Some(Ends {
child_end_copy_held: self.held,
eof_reached,
eof_forced: self.forced,
}))
});
}
}
fn probe_shut(fd: &OwnedFd) -> bool {
use rustix::event::{poll, PollFd, PollFlags, Timespec};
let mut fds = [PollFd::new(fd, PollFlags::empty())];
poll(&mut fds, Some(&Timespec { tv_sec: 0, tv_nsec: 0 })).expect("poll the channel");
let shut = fds[0].revents().contains(PollFlags::HUP);
if !shut {
_ = rustix::net::shutdown(fd, rustix::net::Shutdown::Both);
}
shut
}
pub(crate) fn parent_end_shut() -> Option<bool> {
PARENT_END_SHUT.with(Cell::take)
}
#[must_use = "dropping this disarms the forced errnos at once"]
pub(crate) struct ForcedGoSend(());
pub(crate) fn force_go_send_errnos(errnos: impl IntoIterator<Item = Errno>) -> ForcedGoSend {
SEND_ERRNOS.with(|s| *s.borrow_mut() = errnos.into_iter().collect());
ForcedGoSend(())
}
impl Drop for ForcedGoSend {
fn drop(&mut self) {
SEND_ERRNOS.with(|s| s.borrow_mut().clear());
}
}
#[must_use = "dropping this disarms the held verdict at once"]
pub(crate) struct HeldVerdict(());
pub(crate) fn hold_verdict_until_spawn_returns(hook: impl FnOnce(Option<u32>) + 'static) -> HeldVerdict {
VERDICT_HOOK.with(|h| *h.borrow_mut() = Some(Box::new(hook)));
HeldVerdict(())
}
impl Drop for HeldVerdict {
fn drop(&mut self) {
VERDICT_HOOK.with(|h| h.borrow_mut().take());
}
}
#[derive(Clone, Default)]
struct Gate(Arc<(Mutex<bool>, Condvar)>);
impl Gate {
fn wait(&self) {
let (lock, condvar) = &*self.0;
let mut open = lock.lock().unwrap_or_else(PoisonError::into_inner);
while !*open {
open = condvar.wait(open).unwrap_or_else(PoisonError::into_inner);
}
}
fn is_open(&self) -> bool {
*self.0 .0.lock().unwrap_or_else(PoisonError::into_inner)
}
fn open(&self) {
let (lock, condvar) = &*self.0;
*lock.lock().unwrap_or_else(PoisonError::into_inner) = true;
condvar.notify_all();
}
}
#[derive(Clone, Default)]
pub(crate) struct HelperSeams {
probe: Option<HelperProbe>,
send_errnos: Arc<Mutex<VecDeque<Errno>>>,
move_errno: Arc<Mutex<Option<Errno>>>,
verdict: Option<Gate>,
parent_end_shut: Arc<Mutex<Option<bool>>>,
}
pub(super) fn take_helper_seams() -> HelperSeams {
HelperSeams {
probe: PROBE.with(|p| p.borrow_mut().take()),
send_errnos: Arc::new(Mutex::new(SEND_ERRNOS.with(|s| std::mem::take(&mut *s.borrow_mut())))),
verdict: VERDICT_HOOK.with(|h| h.borrow().is_some()).then(Gate::default),
parent_end_shut: Arc::default(),
..HelperSeams::default()
}
}
impl HelperSeams {
pub(super) fn finish(&self) {
if let Some(probe) = &self.probe {
probe.wait_gate_then_finish();
}
}
pub(super) fn release_probe(&self) {
if let Some(probe) = &self.probe {
probe.release();
}
}
pub(super) fn take_send_errno(&self) -> Option<Errno> {
self.send_errnos
.lock()
.unwrap_or_else(PoisonError::into_inner)
.pop_front()
}
pub(crate) fn failing_move(errno: Errno) -> Self {
HelperSeams {
move_errno: Arc::new(Mutex::new(Some(errno))),
..HelperSeams::default()
}
}
pub(super) fn take_move_errno(&self) -> Option<Errno> {
self.move_errno.lock().unwrap_or_else(PoisonError::into_inner).take()
}
pub(super) fn wait_verdict(&self) {
if let Some(gate) = &self.verdict {
gate.wait();
}
}
pub(super) fn release_verdict(&self, pid: Option<u32>) {
if let Some(gate) = &self.verdict {
if let Some(hook) = VERDICT_HOOK.with(|h| h.borrow_mut().take()) {
hook(pid);
}
gate.open();
}
}
pub(super) fn open_on_drop(&self) -> OpenOnDrop {
VERDICT_GUARDED.with(|g| g.set(true));
OpenOnDrop {
verdict: self.verdict.clone(),
probe: self.probe.clone(),
}
}
pub(super) fn record_parent_end_shut(&self, fd: &OwnedFd) {
*self.parent_end_shut.lock().unwrap_or_else(PoisonError::into_inner) = Some(probe_shut(fd));
}
pub(super) fn publish(&self) {
let shut = self
.parent_end_shut
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take();
PARENT_END_SHUT.with(|c| c.set(shut));
}
}
#[must_use = "dropping this opens the gate at once"]
pub(super) struct OpenOnDrop {
verdict: Option<Gate>,
probe: Option<HelperProbe>,
}
pub(crate) fn verdict_guarded() -> bool {
VERDICT_GUARDED.with(Cell::get)
}
impl Drop for OpenOnDrop {
fn drop(&mut self) {
VERDICT_GUARDED.with(|g| g.set(false));
if let Some(gate) = &self.verdict {
gate.open();
}
if let Some(probe) = self.probe.as_ref().filter(|_| std::thread::panicking()) {
probe.release();
}
}
}
#[derive(Clone)]
pub(crate) struct HelperProbe {
gate: Gate,
finished: Arc<AtomicBool>,
}
impl HelperProbe {
fn wait_gate_then_finish(&self) {
self.gate.wait();
self.finished.store(true, Ordering::Release);
}
fn release(&self) {
self.gate.open();
}
pub(crate) fn finished(&self) -> bool {
self.finished.load(Ordering::Acquire)
}
}
pub(crate) fn arm_helper_probe() -> HelperProbe {
let probe = HelperProbe {
gate: Gate::default(),
finished: Arc::new(AtomicBool::new(false)),
};
PROBE.with(|p| *p.borrow_mut() = Some(probe.clone()));
probe
}