use std::io;
use std::os::fd::{AsRawFd, OwnedFd};
use std::sync::Arc;
use super::fd_channel::{self, publish_ends, Shared};
use super::SpawnLockGuard;
use crate::error::Error;
const REPORT_ID: u32 = 1;
const REPORT_ERRNO: u32 = 2;
const REPORT_LEN: usize = 12;
#[derive(Debug)]
pub(crate) enum Report {
Id(u64),
ChildRefused(i32),
Missing,
Late(u64),
Unwritten,
ReadFailed(io::Error),
WaitFailed(io::Error),
BadTag(u32),
}
pub(crate) struct Pending {
shared: Arc<Shared>,
}
pub(crate) struct Channel {
read_end: OwnedFd,
write_end: OwnedFd,
shared: Arc<Shared>,
}
pub(crate) fn register(cmd: &mut std::process::Command) -> Pending {
#[cfg(test)]
let seam = seams::armed();
let shared = unsafe {
fd_channel::register(cmd, move |shared| {
report(
shared,
#[cfg(test)]
seam,
)
})
};
Pending { shared }
}
impl Pending {
pub(crate) fn open(self, _lock: &SpawnLockGuard) -> Result<Channel, Error> {
let (read_end, write_end) = crate::pipe::pair().map_err(|e| Error::Io(crate::error::io_context("pipe", e)))?;
let (write_end, read_end) = publish_ends(&self.shared, OwnedFd::from(write_end), OwnedFd::from(read_end))?;
set_nonblocking(&read_end)?;
Ok(Channel {
read_end,
write_end,
shared: self.shared,
})
}
}
fn set_nonblocking(fd: &OwnedFd) -> Result<(), Error> {
let flags = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_GETFL) };
if flags < 0 || unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_SETFL, flags | libc::O_NONBLOCK) } < 0 {
return Err(Error::Io(crate::error::io_context("fcntl", io::Error::last_os_error())));
}
Ok(())
}
impl Channel {
pub(crate) fn run<T, E>(
self,
spawn: impl FnOnce() -> Result<T, E>,
pid_of: impl FnOnce(&T) -> Option<u32>,
) -> (Result<T, E>, FirstRead) {
let Channel {
read_end,
write_end,
shared,
} = self;
let exposed = std_pipe_exposed();
let spawned = spawn();
shared.withdraw();
drop(write_end);
#[cfg(test)]
seams::before_first_read(&read_end);
let report = read_report(&read_end);
let pid = spawned.as_ref().ok().and_then(|child| {
let pid = pid_of(child);
debug_assert!(pid.is_some(), "a freshly spawned child has a pid");
pid
});
#[cfg(test)]
seams::first_read_done(pid);
let first = FirstRead {
read_end,
report,
pid,
exposed,
};
(spawned, first)
}
}
pub(crate) struct FirstRead {
read_end: OwnedFd,
report: Report,
pid: Option<u32>,
exposed: bool,
}
impl FirstRead {
pub(crate) fn finish(self) -> Report {
#[cfg(any(test, debug_assertions))]
debug_assert!(
!super::spawn_lock_held_by_this_thread(),
"the wait for a unique-id report must not hold spawn_lock"
);
let FirstRead {
read_end,
report,
pid,
exposed,
} = self;
match (report, pid) {
(Report::Unwritten, Some(pid)) => await_report(&read_end, pid),
(Report::Id(id), Some(_)) if exposed => Report::Late(id),
(report, _) => report,
}
}
}
fn std_pipe_exposed() -> bool {
let free = (0..=2)
.filter(|&fd| unsafe { libc::fcntl(fd, libc::F_GETFD) } == -1)
.count();
free >= 2
}
const SAY_WAITING_AFTER: std::time::Duration = std::time::Duration::from_secs(1);
fn await_report(read_end: &OwnedFd, pid: u32) -> Report {
#[cfg(test)]
if seams::wait_is_refused() {
return Report::WaitFailed(io::Error::other("test seam: the wait for a report was entered"));
}
match watch(read_end, pid) {
Ok(Watch::Pipe(report)) => {
#[cfg(test)]
seams::woke(seams::Wake::Pipe);
report
}
Ok(Watch::ChildGone) => {
#[cfg(test)]
seams::woke(seams::Wake::ChildGone);
match read_report(read_end) {
Report::Id(id) => Report::Late(id),
Report::Unwritten => Report::Missing,
report => report,
}
}
Err(e) => Report::WaitFailed(e),
}
}
enum Watch {
Pipe(Report),
ChildGone,
}
fn watch(read_end: &OwnedFd, pid: u32) -> io::Result<Watch> {
use crate::os_process::macos::kqueue::{Event, Kqueue, Subscription};
use crate::wait::macos::{OnTracer, TracerWatch};
use nix::sys::event::{EvFlags, EventFilter, FilterFlag, KEvent};
let kq = Kqueue::new().map_err(Error::into_io)?;
#[cfg(test)]
seams::wait_begins();
let pipe = Subscription::Readable {
fd: read_end.as_raw_fd(),
low_water: 1,
};
kq.subscribe(pipe).map_err(Error::into_io)?;
let child = Subscription::Process {
pid,
signals: true,
reap: false,
};
match kq.subscribe(child) {
Ok(()) => {}
Err(e) if e.raw_os_error() == Some(libc::ESRCH) => return Ok(Watch::ChildGone),
Err(e) => return Err(e.into_io()),
}
let mut tracer = TracerWatch::default();
let blank = KEvent::new(0, EventFilter::EVFILT_READ, EvFlags::empty(), FilterFlag::empty(), 0, 0);
let mut events = [blank; 8];
let started = std::time::Instant::now();
#[cfg(not(test))]
let say_after = Some(SAY_WAITING_AFTER);
#[cfg(test)]
let say_after = seams::say_waiting_after();
let mut warned = false;
loop {
match read_report(read_end) {
Report::Unwritten => {}
Report::Id(id) => return Ok(Watch::Pipe(Report::Late(id))),
report => return Ok(Watch::Pipe(report)),
}
let recheck = match check(pid)? {
Check::Gone => return Ok(Watch::ChildGone),
Check::Running => None,
Check::Traced(by) => match tracer.held_by(&kq, by)? {
OnTracer::Block => None,
OnTracer::Recheck(after) if after.is_zero() => continue,
OnTracer::Recheck(after) => Some(after),
},
};
#[cfg(test)]
seams::blocking(kq.native());
let warn_in = say_after
.filter(|_| !warned)
.map(|after| after.saturating_sub(started.elapsed()));
let timeout = match (recheck, warn_in) {
(Some(recheck), Some(warn_in)) => Some(recheck.min(warn_in)),
(recheck, warn_in) => recheck.or(warn_in),
};
#[cfg(test)]
seams::record_timeout(timeout);
let n = match kq.native().kevent(
&[],
&mut events,
timeout.map(crate::os_process::macos::kqueue::kevent_timeout),
) {
Ok(n) => n,
Err(nix::errno::Errno::EINTR) => continue,
Err(e) => return Err(e.into()),
};
if !warned && say_after.is_some_and(|after| started.elapsed() >= after) {
warned = true;
log::warn!(
"the spawned child {pid} has not reported its unique id after 1 s; waiting for its report, or \
for it to exit"
);
}
let woke: Vec<Event> = events[..n].iter().filter_map(Event::from_kevent).collect();
if woke
.iter()
.any(|e| matches!(e, Event::Process { pid: p, exited: true, .. } if *p == pid))
{
return Ok(Watch::ChildGone);
}
for event in &woke {
tracer.fired(event, pid);
}
}
}
enum Check {
Running,
Traced(u32),
Gone,
}
fn check(pid: u32) -> io::Result<Check> {
use crate::identity::{origin, Origin, LAUNCHD};
use crate::os_process::child::PeekOutcome;
use crate::wait::exit_only::{peek, Target};
Ok(match peek(&Target::pid(pid, None))? {
PeekOutcome::Running => Check::Running,
PeekOutcome::Exit(_) => Check::Gone,
PeekOutcome::Foreign(_) => match origin(pid) {
Origin::Ours { parent } if parent == LAUNCHD => Check::Gone,
Origin::Ours { parent } if parent == std::process::id() => Check::Running,
Origin::Ours { parent } => Check::Traced(parent),
Origin::NotOurs | Origin::Gone => Check::Gone,
Origin::Refused(errno) => {
return Err(io::Error::new(
io::Error::from_raw_os_error(errno).kind(),
format!("pid {pid}: whether it is this process's child could not be read (errno {errno})"),
))
}
Origin::Unreadable => {
return Err(io::Error::other(format!(
"pid {pid}: whether it is this process's child could not be read (kinfo_proc refused)"
)))
}
},
})
}
fn read_report(read_end: &OwnedFd) -> Report {
#[cfg(test)]
if let Some(errno) = seams::parent_read_fails() {
return Report::ReadFailed(io::Error::from_raw_os_error(errno));
}
#[cfg(test)]
if seams::parent_read_finds_nothing() {
return Report::Unwritten;
}
let mut buf = [0u8; REPORT_LEN];
let mut got = 0;
while got < REPORT_LEN {
let n = unsafe { libc::read(read_end.as_raw_fd(), buf[got..].as_mut_ptr().cast(), REPORT_LEN - got) };
if n > 0 {
got += n as usize;
} else if n == 0 {
return Report::Missing;
} else {
let e = io::Error::last_os_error();
match e.raw_os_error() {
Some(libc::EINTR) => {}
Some(libc::EAGAIN) => return Report::Unwritten,
_ => return Report::ReadFailed(e),
}
}
}
let tag = u32::from_ne_bytes(buf[..4].try_into().expect("four bytes"));
let value = u64::from_ne_bytes(buf[4..].try_into().expect("eight bytes"));
match tag {
REPORT_ID => Report::Id(value),
REPORT_ERRNO => Report::ChildRefused(value as i32),
other => Report::BadTag(other),
}
}
#[derive(Debug)]
pub(crate) struct NotAdopted {
pub(crate) error: Error,
pub(crate) why: Unadoptable,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Unadoptable {
DiedBeforeExec,
Late(u64),
Unverified,
}
pub(crate) fn adopted_id(report: Report, pid: u32) -> Result<u64, NotAdopted> {
let not = |why, error| Err(NotAdopted { error, why });
match report {
Report::Id(id) => Ok(id),
Report::ChildRefused(errno) => not(Unadoptable::DiedBeforeExec, refused_error(errno)),
Report::Missing => not(
Unadoptable::DiedBeforeExec,
Error::Io(io::Error::other(format!(
"the spawned child {pid} died before exec; the program did not start"
))),
),
Report::Late(id) => not(
Unadoptable::Late(id),
Error::Io(io::Error::other(format!(
"the spawned child {pid}'s exec cannot be confirmed: at least two of this process's descriptors 0 to 2 \
were closed at its spawn, so std's own error pipe could not show it; the child was not adopted"
))),
),
Report::Unwritten => {
debug_assert!(false, "`FirstRead::finish` waits out an unwritten report");
not(
Unadoptable::Unverified,
Error::Unassessable {
detail: format!("pid {pid}: its unique-id report is still unwritten; the child was not adopted"),
source: None,
},
)
}
Report::ReadFailed(e) => not(
Unadoptable::Unverified,
Error::Unassessable {
detail: format!("pid {pid}: its unique-id report could not be read ({e}); the child was not adopted"),
source: Some(e),
},
),
Report::WaitFailed(e) => not(
Unadoptable::Unverified,
Error::Unassessable {
detail: format!("pid {pid}: the wait for its unique-id report failed ({e}); the child was not adopted"),
source: Some(e),
},
),
Report::BadTag(tag) => {
debug_assert!(false, "a unique-id report with tag {tag}");
not(
Unadoptable::Unverified,
Error::Unassessable {
detail: format!(
"pid {pid}: its unique-id report is malformed (tag {tag}); the child was not adopted"
),
source: None,
},
)
}
}
}
#[cfg(any(test, feature = "tokio"))]
pub(crate) fn proves_no_exec(report: &Report) -> bool {
match report {
Report::ChildRefused(_) | Report::Missing => true,
Report::Id(_)
| Report::Late(_)
| Report::Unwritten
| Report::ReadFailed(_)
| Report::WaitFailed(_)
| Report::BadTag(_) => false,
}
}
pub(crate) fn failed_spawn_error(error: Error, report: &Report) -> Error {
match report {
Report::ChildRefused(errno) => refused_error(*errno),
other => {
debug_assert!(
!matches!(other, Report::BadTag(_)),
"a unique-id report is malformed: {other:?}"
);
log::debug!("the spawn failed ({error}); the child's unique-id report was {other:?}");
error
}
}
}
pub(crate) fn refused_error(errno: i32) -> Error {
Error::Unassessable {
detail: format!(
"the spawned child could not read its own unique id (errno {errno}); it was stopped before exec, so the program did not start"
),
source: Some(io::Error::from_raw_os_error(errno)),
}
}
fn report(shared: &Shared, #[cfg(test)] seam: seams::Armed) -> io::Result<()> {
#[cfg(test)]
seam.await_gate();
#[cfg(test)]
if let Some(errno) = seam.fail_before_report() {
return Err(io::Error::from_raw_os_error(errno));
}
#[cfg(test)]
let read = seam.read(shared.child_end());
#[cfg(not(test))]
let read = crate::identity::own_unique_id();
let (tag, value) = match read {
Ok(id) => (REPORT_ID, id),
Err(errno) => (REPORT_ERRNO, errno as u64),
};
let mut buf = [0u8; REPORT_LEN];
buf[..4].copy_from_slice(&tag.to_ne_bytes());
buf[4..].copy_from_slice(&value.to_ne_bytes());
loop {
let n = unsafe { libc::write(shared.child_end(), buf.as_ptr().cast(), REPORT_LEN) };
if n == REPORT_LEN as isize {
#[cfg(test)]
seam.await_after_gate();
return match tag {
REPORT_ERRNO => Err(io::Error::from_raw_os_error(value as i32)),
_ => Ok(()),
};
}
if n < 0 {
let e = io::Error::last_os_error();
if e.raw_os_error() == Some(libc::EINTR) {
continue;
}
return Err(e);
}
return Err(io::Error::from_raw_os_error(libc::EIO));
}
}
#[cfg(test)]
pub(crate) mod seams {
use std::cell::Cell;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Force {
None,
Errno(i32),
KillSelf,
FailBeforeReport(i32),
Gate(std::os::fd::RawFd),
}
struct Gate {
read: std::io::PipeReader,
write: std::io::PipeWriter,
at_first_read: bool,
}
impl Gate {
fn new(at_first_read: bool) -> Gate {
let (read, write) = std::io::pipe().expect("the gate pipe");
Gate {
read,
write,
at_first_read,
}
}
fn release(mut self) {
use std::io::Write;
self.write.write_all(b"r").expect("release the held child");
}
}
type BlockHook = Box<dyn FnMut(u32, &nix::sys::event::Kqueue)>;
type FirstReadHook = Box<dyn FnOnce(u32)>;
thread_local! {
static FORCE: Cell<Force> = const { Cell::new(Force::None) };
static PARENT_READ_ERRNO: Cell<Option<i32>> = const { Cell::new(None) };
static PARENT_READ_UNWRITTEN: Cell<bool> = const { Cell::new(false) };
static WAIT_REFUSED: Cell<bool> = const { Cell::new(false) };
static GATE: std::cell::RefCell<Option<Gate>> = const { std::cell::RefCell::new(None) };
static AFTER_GATE: std::cell::RefCell<Option<Gate>> = const { std::cell::RefCell::new(None) };
static ON_FIRST_READ: std::cell::RefCell<Option<FirstReadHook>> = const { std::cell::RefCell::new(None) };
static ON_FIRST_BLOCK: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
static ON_EACH_BLOCK: std::cell::RefCell<Option<BlockHook>> = const { std::cell::RefCell::new(None) };
static BLOCKS_IN_WAIT: Cell<u32> = const { Cell::new(0) };
static BLOCKS: Cell<u32> = const { Cell::new(0) };
static WAKE: Cell<Option<Wake>> = const { Cell::new(None) };
}
#[derive(Debug, Clone, Copy)]
pub(super) struct Armed(Force, Option<std::os::fd::RawFd>);
fn await_byte(fd: std::os::fd::RawFd) {
let mut byte = 0u8;
loop {
let n = unsafe { libc::read(fd, (&raw mut byte).cast(), 1) };
if n < 0 && unsafe { *libc::__error() } == libc::EINTR {
continue;
}
return;
}
}
impl Armed {
pub(super) fn fail_before_report(self) -> Option<i32> {
match self.0 {
Force::FailBeforeReport(errno) => Some(errno),
_ => None,
}
}
pub(super) fn await_gate(self) {
if let Force::Gate(fd) = self.0 {
await_byte(fd);
}
}
pub(super) fn await_after_gate(self) {
if let Some(fd) = self.1 {
await_byte(fd);
}
}
pub(super) fn read(self, child_end: std::os::fd::RawFd) -> Result<u64, i32> {
match self.0 {
Force::None | Force::FailBeforeReport(_) | Force::Gate(_) => crate::identity::own_unique_id(),
Force::Errno(errno) => Err(errno),
Force::KillSelf => {
unsafe {
libc::close(child_end);
libc::kill(libc::getpid(), libc::SIGKILL);
}
Err(libc::EINTR)
}
}
}
}
pub(super) fn armed() -> Armed {
use std::os::fd::AsRawFd;
let after = AFTER_GATE.with(|g| g.borrow().as_ref().map(|gate| gate.read.as_raw_fd()));
Armed(FORCE.with(Cell::get), after)
}
#[must_use = "dropping this immediately disarms the force; bind it for the probe's duration"]
pub(crate) struct Forced(());
impl Drop for Forced {
fn drop(&mut self) {
FORCE.with(|f| f.set(Force::None));
}
}
pub(crate) fn force_child_read_errno(errno: i32) -> Forced {
FORCE.with(|f| f.set(Force::Errno(errno)));
Forced(())
}
pub(crate) fn force_hook_failure_before_report(errno: i32) -> Forced {
FORCE.with(|f| f.set(Force::FailBeforeReport(errno)));
Forced(())
}
pub(crate) fn fail_parent_read(errno: i32) -> FailedParentRead {
PARENT_READ_ERRNO.with(|f| f.set(Some(errno)));
FailedParentRead(())
}
#[must_use = "the read succeeds again as soon as the guard is dropped"]
pub(crate) struct FailedParentRead(());
impl Drop for FailedParentRead {
fn drop(&mut self) {
PARENT_READ_ERRNO.with(|f| f.set(None));
}
}
pub(super) fn parent_read_fails() -> Option<i32> {
PARENT_READ_ERRNO.with(Cell::get)
}
pub(crate) fn find_the_report_unwritten() -> UnwrittenRead {
PARENT_READ_UNWRITTEN.with(|f| f.set(true));
UnwrittenRead(())
}
#[must_use = "the read finds the report again as soon as the guard is dropped"]
pub(crate) struct UnwrittenRead(());
impl Drop for UnwrittenRead {
fn drop(&mut self) {
PARENT_READ_UNWRITTEN.with(|f| f.set(false));
}
}
pub(super) fn parent_read_finds_nothing() -> bool {
PARENT_READ_UNWRITTEN.with(|f| f.replace(false))
}
pub(crate) fn refuse_the_wait() -> RefusedWait {
WAIT_REFUSED.with(|f| f.set(true));
RefusedWait(())
}
#[must_use = "the wait runs again as soon as the guard is dropped"]
pub(crate) struct RefusedWait(());
impl Drop for RefusedWait {
fn drop(&mut self) {
WAIT_REFUSED.with(|f| f.set(false));
}
}
pub(super) fn wait_is_refused() -> bool {
WAIT_REFUSED.with(Cell::get)
}
pub(crate) fn hold_the_report_until_the_first_read() -> HeldReport {
hold(Gate::new(true))
}
pub(crate) fn hold_the_report() -> HeldReport {
hold(Gate::new(false))
}
fn hold(gate: Gate) -> HeldReport {
use std::os::fd::AsRawFd;
FORCE.with(|f| f.set(Force::Gate(gate.read.as_raw_fd())));
GATE.with(|g| *g.borrow_mut() = Some(gate));
HeldReport(())
}
pub(crate) fn release_the_report() {
GATE.with(|g| g.borrow_mut().take())
.expect("a held report to release")
.release();
}
pub(crate) fn hold_the_child_after_its_report() -> HeldAfterReport {
AFTER_GATE.with(|g| *g.borrow_mut() = Some(Gate::new(false)));
HeldAfterReport(())
}
#[must_use = "the child is held only while the guard lives"]
pub(crate) struct HeldAfterReport(());
impl Drop for HeldAfterReport {
fn drop(&mut self) {
AFTER_GATE.with(|g| g.borrow_mut().take());
}
}
pub(crate) fn release_the_child_after_its_report() {
AFTER_GATE
.with(|g| g.borrow_mut().take())
.expect("a child held after its report")
.release();
}
#[must_use = "the report is held only while the guard lives"]
pub(crate) struct HeldReport(());
impl Drop for HeldReport {
fn drop(&mut self) {
FORCE.with(|f| f.set(Force::None));
GATE.with(|g| g.borrow_mut().take());
}
}
pub(super) fn first_read_done(pid: Option<u32>) {
let gate = GATE.with(|g| {
let mut g = g.borrow_mut();
if g.as_ref().is_some_and(|gate| gate.at_first_read) {
g.take()
} else {
None
}
});
if let Some(gate) = gate {
gate.release();
}
let hook = ON_FIRST_READ.with(|h| h.borrow_mut().take());
if let (Some(hook), Some(pid)) = (hook, pid) {
hook(pid);
}
}
pub(crate) fn on_first_read(hook: impl FnOnce(u32) + 'static) -> FirstRead {
ON_FIRST_READ.with(|h| {
let previous = h.borrow_mut().replace(Box::new(hook));
debug_assert!(previous.is_none(), "a first-read hook is already armed");
});
FirstRead(())
}
#[must_use = "the hook is cleared as soon as the guard is dropped"]
pub(crate) struct FirstRead(());
impl Drop for FirstRead {
fn drop(&mut self) {
ON_FIRST_READ.with(|h| h.borrow_mut().take());
}
}
pub(crate) fn on_first_block(hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
crate::oneshot_hook::arm(&ON_FIRST_BLOCK, hook)
}
pub(crate) fn block_count() -> u32 {
BLOCKS.with(Cell::get)
}
pub(crate) fn on_each_block(hook: impl FnMut(u32, &nix::sys::event::Kqueue) + 'static) -> EachBlock {
ON_EACH_BLOCK.with(|h| {
let previous = h.borrow_mut().replace(Box::new(hook));
debug_assert!(previous.is_none(), "a block hook is already armed");
});
EachBlock(())
}
#[must_use = "the hook is cleared as soon as the guard is dropped"]
pub(crate) struct EachBlock(());
impl Drop for EachBlock {
fn drop(&mut self) {
ON_EACH_BLOCK.with(|h| h.borrow_mut().take());
}
}
pub(super) fn wait_begins() {
BLOCKS_IN_WAIT.with(|b| b.set(0));
}
pub(super) fn blocking(kq: &nix::sys::event::Kqueue) {
BLOCKS.with(|b| b.set(b.get() + 1));
let n = BLOCKS_IN_WAIT.with(|b| {
b.set(b.get() + 1);
b.get()
});
crate::oneshot_hook::fire(&ON_FIRST_BLOCK);
let hook = ON_EACH_BLOCK.with(|h| h.borrow_mut().take());
if let Some(mut hook) = hook {
hook(n, kq);
ON_EACH_BLOCK.with(|h| {
h.borrow_mut().get_or_insert(hook);
});
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Wake {
Pipe,
ChildGone,
}
pub(super) fn woke(wake: Wake) {
WAKE.with(|w| w.set(Some(wake)));
}
pub(crate) fn take_wake() -> Option<Wake> {
WAKE.with(Cell::take)
}
pub(crate) fn force_child_killed_before_report() -> Forced {
FORCE.with(|f| f.set(Force::KillSelf));
Forced(())
}
thread_local! {
static REPORT_FIRST: Cell<bool> = const { Cell::new(false) };
static SAY_AFTER: Cell<Option<std::time::Duration>> = const { Cell::new(None) };
static TIMEOUTS: std::cell::RefCell<Vec<Option<std::time::Duration>>> = const { std::cell::RefCell::new(Vec::new()) };
}
pub(crate) fn let_the_report_come_first() -> ReportFirst {
REPORT_FIRST.with(|f| f.set(true));
ReportFirst(())
}
#[must_use = "the first read no longer waits once the guard is dropped"]
pub(crate) struct ReportFirst(());
impl Drop for ReportFirst {
fn drop(&mut self) {
REPORT_FIRST.with(|f| f.set(false));
}
}
pub(super) fn before_first_read(read_end: &std::os::fd::OwnedFd) {
if !REPORT_FIRST.with(Cell::get) {
return;
}
let mut fds = [rustix::event::PollFd::new(read_end, rustix::event::PollFlags::IN)];
crate::wait::poll_ready(&mut fds).expect("poll the report pipe");
}
pub(crate) fn say_waiting_after_then_record(after: std::time::Duration) -> SayAfter {
SAY_AFTER.with(|s| s.set(Some(after)));
TIMEOUTS.with(|t| t.borrow_mut().clear());
SayAfter(())
}
#[must_use = "the wait stops warning as soon as the guard is dropped"]
pub(crate) struct SayAfter(());
impl SayAfter {
pub(crate) fn timeouts(&self) -> Vec<Option<std::time::Duration>> {
TIMEOUTS.with(|t| t.borrow().clone())
}
}
impl Drop for SayAfter {
fn drop(&mut self) {
SAY_AFTER.with(|s| s.set(None));
TIMEOUTS.with(|t| t.borrow_mut().clear());
}
}
pub(super) fn say_waiting_after() -> Option<std::time::Duration> {
SAY_AFTER.with(Cell::get)
}
pub(super) fn record_timeout(timeout: Option<std::time::Duration>) {
if SAY_AFTER.with(Cell::get).is_some() {
TIMEOUTS.with(|t| t.borrow_mut().push(timeout));
}
}
}
#[cfg(test)]
#[path = "unique_report_tests.rs"]
mod unique_report_tests;