use std::process::{ChildStdin, ExitStatus};
use std::sync::mpsc::Receiver;
use std::sync::Arc;
use std::thread::JoinHandle;
use crate::child::owned::{ChildWaitOutcome, OwnedChild};
use crate::elevation::front::TrackedKind;
use crate::error::Error;
use crate::identity::ProcessId;
use crate::os_process::child::ExitRecord;
use crate::os_process::fake::FakeProcess;
pub(super) struct Blocker {
pub(super) owned: Arc<OwnedChild>,
pub(super) pid: u32,
stdin: Option<ChildStdin>,
}
pub(super) fn identity_of(child: &std::process::Child) -> ProcessId {
ProcessId::of(child.id())
.found()
.expect("the live child has an identity")
}
impl Blocker {
pub(super) fn spawn() -> Blocker {
Blocker::spawn_with(|_| {})
}
pub(super) fn spawn_with(configure: impl FnOnce(&mut std::process::Command)) -> Blocker {
let (child, stdin) = crate::test_child::blocker_with(configure).into_parts();
let id = identity_of(&child);
let owned = OwnedChild::adopt(child, id, TrackedKind::Own).unwrap_or_else(|(e, _)| panic!("adopt: {e}"));
Blocker {
owned: Arc::new(owned),
pid: id.pid(),
stdin: Some(stdin),
}
}
#[cfg(target_os = "macos")]
pub(super) fn spawn_over<K: crate::identity::Kernel + Send + 'static>(
kernel: impl FnOnce(u32, u64) -> K,
) -> (Blocker, Arc<K>) {
let (child, stdin) = crate::test_child::blocker().into_parts();
let id = identity_of(&child);
let mut shared = None;
let owned = OwnedChild::adopt_over(
|pid, unique| {
let kernel = Arc::new(kernel(pid, unique));
shared = Some(Arc::clone(&kernel));
kernel
},
child,
id,
TrackedKind::Own,
)
.unwrap_or_else(|(e, _)| panic!("adopt: {e}"));
let blocker = Blocker {
owned: Arc::new(owned),
pid: id.pid(),
stdin: Some(stdin),
};
(blocker, shared.expect("adopt_over builds the kernel"))
}
pub(super) fn end_child(&mut self) {
drop(self.stdin.take());
}
#[cfg(not(target_os = "linux"))]
pub(super) fn end_child_and_confirm_exit(&mut self) {
self.end_child();
confirm_exit(&self.owned, self.pid);
}
}
impl Drop for Blocker {
fn drop(&mut self) {
drop(self.stdin.take());
_ = self.owned.signal(crate::signal::Sig::Kill);
if !std::thread::panicking() {
_ = self.owned.wait(None);
}
}
}
#[cfg(not(target_os = "linux"))]
pub(super) fn confirm_exit(owned: &OwnedChild, pid: u32) {
let _ = (owned, pid);
#[cfg(target_os = "macos")]
{
let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
let r = unsafe { libc::waitid(libc::P_PID, pid as libc::id_t, &mut info, libc::WEXITED | libc::WNOWAIT) };
assert_eq!(r, 0, "waitid(WNOWAIT): {}", std::io::Error::last_os_error());
}
#[cfg(windows)]
{
use std::os::windows::io::AsRawHandle;
use windows::Win32::Foundation::{HANDLE, WAIT_OBJECT_0};
use windows::Win32::System::Threading::{WaitForSingleObject, INFINITE};
let r = unsafe { WaitForSingleObject(HANDLE(owned.os_handle().as_raw_handle()), INFINITE) };
assert_eq!(r, WAIT_OBJECT_0);
}
}
#[track_caller]
pub(super) fn status(outcome: Result<ChildWaitOutcome, Error>) -> ExitStatus {
match outcome {
Ok(ChildWaitOutcome::Exited(ExitRecord::Status(status))) => status,
other => panic!("expected an exit status, got {other:?}"),
}
}
#[track_caller]
pub(super) fn wait_status(owned: &OwnedChild) -> ExitStatus {
status(owned.wait(None))
}
pub(super) fn try_wait(owned: &OwnedChild) -> Result<ChildWaitOutcome, Error> {
owned.wait(Some(crate::wait::now()))
}
#[cfg(target_os = "macos")]
pub(super) fn signal_of(status: ExitStatus) -> Option<i32> {
std::os::unix::process::ExitStatusExt::signal(&status)
}
pub(super) fn assert_handed_off(owned: &OwnedChild, token: u64) {
use crate::child::owned::{Logged, State};
let mut lock = owned.lock();
let stranded = matches!(lock.state, State::W { token: t } if t == token);
let unnotified = lock
.log
.iter()
.enumerate()
.any(|(i, entry)| matches!(entry, Logged::Write(_)) && lock.log.get(i + 1) != Some(&Logged::Notify));
let unlogged = lock
.log
.iter()
.rev()
.find_map(|entry| match entry {
Logged::Write(state) => Some(*state),
Logged::Notify => None,
})
.is_some_and(|last| last != lock.state);
let mut prev = State::N;
let mut illegal = false;
for entry in &lock.log {
if let Logged::Write(next) = entry {
illegal |= !matches!(
(prev, *next),
(State::N, State::W { .. })
| (State::N | State::W { .. }, State::Exited(_))
| (State::W { .. }, State::N)
);
prev = *next;
}
}
if stranded || unnotified || unlogged || illegal {
let log = lock.log.clone();
lock.set(State::N);
owned.notify(&mut lock);
drop(lock);
panic!(
"the holder {token} left the handle stranded ({stranded}), unnotified ({unnotified}), \
with a state the log does not show ({unlogged}) or with an illegal write sequence \
({illegal}): {log:?}"
);
}
}
pub(super) fn owned_over(fake: &FakeProcess) -> Arc<OwnedChild> {
Arc::new(OwnedChild::new(Box::new(fake.clone()), TrackedKind::Own))
}
pub(super) struct ParkedHolder<T> {
thread: JoinHandle<T>,
fake: FakeProcess,
}
impl<T> ParkedHolder<T> {
pub(super) fn release_and_join(self) -> T {
self.fake.wake();
self.thread.join().expect("the holder thread must not panic")
}
pub(super) fn release_and_join_thread(self) -> std::thread::Result<T> {
self.fake.wake();
self.thread.join()
}
}
pub(super) fn park_holder<T: Send + 'static>(
owned: &Arc<OwnedChild>,
fake: &FakeProcess,
body: impl FnOnce(&OwnedChild) -> T + Send + 'static,
) -> ParkedHolder<T> {
let (reached_tx, reached_rx) = std::sync::mpsc::channel();
let owned = Arc::clone(owned);
let thread = std::thread::spawn(move || {
let _blocking = crate::wait::block_probe::on_blocking(move || {
_ = reached_tx.send(());
});
body(&owned)
});
reached_rx.recv().expect("the holder must reach its wait");
ParkedHolder {
thread,
fake: fake.clone(),
}
}
pub(super) fn spawn_waiter<T: Send + 'static>(
owned: &Arc<OwnedChild>,
body: impl FnOnce(&OwnedChild) -> T + Send + 'static,
) -> (JoinHandle<T>, Receiver<()>) {
let (blocked_tx, blocked_rx) = std::sync::mpsc::channel();
let owned = Arc::clone(owned);
let thread = std::thread::spawn(move || {
let _hook = crate::wait::block_probe::on_condvar_block(move || {
_ = blocked_tx.send(());
});
body(&owned)
});
(thread, blocked_rx)
}