use std::time::{Duration, Instant};
pub(crate) mod exit_only;
pub(crate) mod teardown_warn;
#[cfg(target_os = "macos")]
pub(crate) mod macos;
#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
compile_error!("cosca::wait is implemented only for Linux, macOS, and Windows");
#[cfg(test)]
pub(crate) mod fault {
use std::cell::Cell;
thread_local! {
static FORCE_WATCH_ERROR: Cell<bool> = const { Cell::new(false) };
}
pub(crate) fn set_force_watch_error(on: bool) {
FORCE_WATCH_ERROR.with(|f| f.set(on));
}
pub(crate) fn take_force_watch_error() -> bool {
FORCE_WATCH_ERROR.with(|f| f.replace(false))
}
pub(crate) fn armed() -> bool {
FORCE_WATCH_ERROR.with(|f| f.get())
}
pub(crate) fn forced_watch_error() -> crate::error::Error {
crate::error::Error::Io(std::io::Error::other("forced grace-watch failure (test seam)"))
}
}
#[cfg(test)]
pub(crate) mod test_clock {
use std::cell::Cell;
use std::time::{Duration, Instant};
thread_local! {
static FROZEN: Cell<Option<Instant>> = const { Cell::new(None) };
static ADVANCES: Cell<u64> = const { Cell::new(0) };
static SKIP_ADVANCE: Cell<bool> = const { Cell::new(false) };
static ZERO_ELAPSED: Cell<bool> = const { Cell::new(false) };
}
fn freeze_now() -> Instant {
debug_assert!(
FROZEN.with(Cell::get).is_none(),
"test_clock::freeze_now called while already frozen — nesting FrozenClockGuard is \
not supported"
);
let at = Instant::now();
FROZEN.with(|f| f.set(Some(at)));
at
}
pub(crate) fn advance(by: Duration) {
FROZEN.with(|f| {
let cur = f.get().expect("test_clock::advance called before the clock was frozen");
f.set(Some(cur + by));
});
}
pub(crate) fn advance_by_elapsed_if_frozen(real_elapsed: Duration) {
if SKIP_ADVANCE.with(Cell::get) {
return;
}
ADVANCES.with(|a| a.set(a.get() + 1));
let real_elapsed = if ZERO_ELAPSED.with(Cell::get) {
Duration::ZERO
} else {
real_elapsed
};
FROZEN.with(|f| {
if let Some(cur) = f.get() {
f.set(Some(cur + real_elapsed));
}
});
}
pub(crate) fn is_frozen() -> bool {
FROZEN.with(|f| f.get()).is_some()
}
#[must_use]
pub(crate) struct SkipAdvanceGuard(());
impl SkipAdvanceGuard {
pub(crate) fn install() -> Self {
SKIP_ADVANCE.with(|s| s.set(true));
Self(())
}
}
impl Drop for SkipAdvanceGuard {
fn drop(&mut self) {
SKIP_ADVANCE.with(|s| s.set(false));
}
}
#[must_use]
pub(crate) struct ZeroElapsedGuard(());
impl ZeroElapsedGuard {
pub(crate) fn install() -> Self {
ZERO_ELAPSED.with(|z| z.set(true));
Self(())
}
}
impl Drop for ZeroElapsedGuard {
fn drop(&mut self) {
ZERO_ELAPSED.with(|z| z.set(false));
}
}
pub(crate) const VIOLATION_EXIT_CODE: i32 = 113;
const _: () = assert!(VIOLATION_EXIT_CODE != 0 && VIOLATION_EXIT_CODE != 101);
fn exit_now(code: i32) -> ! {
#[cfg(unix)]
unsafe {
libc::_exit(code)
}
#[cfg(windows)]
{
use windows::Win32::System::Threading::{GetCurrentProcess, TerminateProcess};
unsafe { TerminateProcess(GetCurrentProcess(), code as u32) }.ok();
std::process::abort()
}
}
pub(crate) struct RoundCheck {
site: &'static str,
last: Option<u64>,
}
impl RoundCheck {
pub(crate) fn new(site: &'static str) -> Self {
Self { site, last: None }
}
pub(crate) fn round(&mut self) {
let generation = ADVANCES.with(Cell::get);
let stalled = self.last == Some(generation) && is_frozen();
self.last = Some(generation);
if !stalled {
return;
}
let message = format!(
"{}: a round followed a round with no `advance_by_elapsed_if_frozen` call under a \
frozen clock: no progress (the loop dropped its advance)",
self.site
);
if std::thread::panicking() {
use std::io::Write as _;
writeln!(std::io::stderr(), "{message}").ok();
exit_now(VIOLATION_EXIT_CODE);
}
panic!("{message}");
}
}
pub(crate) fn now() -> Instant {
FROZEN.with(|f| f.get()).unwrap_or_else(Instant::now)
}
fn reset() {
FROZEN.with(|f| f.set(None));
}
#[must_use]
pub(crate) struct FrozenClockGuard {
_private: (),
}
impl FrozenClockGuard {
pub(crate) fn install() -> (Self, Instant) {
let at = freeze_now();
(Self { _private: () }, at)
}
pub(crate) fn install_lagging(lag: Duration) -> (Self, Instant) {
let at = Instant::now()
.checked_sub(lag)
.expect("the platform's monotonic clock has run for less than the requested lag");
FROZEN.with(|f| {
debug_assert!(f.get().is_none(), "nesting FrozenClockGuard is not supported");
f.set(Some(at));
});
(Self { _private: () }, at)
}
}
impl Drop for FrozenClockGuard {
fn drop(&mut self) {
reset();
}
}
}
#[cfg(not(test))]
pub(crate) fn now() -> Instant {
Instant::now()
}
#[cfg(test)]
pub(crate) fn now() -> Instant {
test_clock::now()
}
pub(crate) fn remaining(deadline: Option<Instant>) -> Option<Duration> {
remaining_at(deadline, now())
}
pub(crate) fn remaining_at(deadline: Option<Instant>, now: Instant) -> Option<Duration> {
let remaining = deadline.map(|at| at.saturating_duration_since(now));
#[cfg(test)]
read_probe::record(read_probe::Event::Read { deadline, remaining });
remaining
}
#[cfg(test)]
pub(crate) mod read_probe {
use crate::relayed_probe::{self, Probe};
use std::sync::mpsc::Sender;
use std::time::{Duration, Instant};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Event {
Read {
deadline: Option<Instant>,
remaining: Option<Duration>,
},
Mark(&'static str),
}
pub(crate) struct Log;
impl Probe for Log {
type Event = Event;
}
pub(crate) type Guard = relayed_probe::Guard<Log>;
#[cfg_attr(
not(all(windows, feature = "tokio")),
allow(dead_code, reason = "Windows tokio tests are the only non-portable-test consumers")
)]
pub(crate) fn install(tx: Sender<Event>) -> Guard {
relayed_probe::install(tx)
}
pub(crate) fn current() -> Option<Sender<Event>> {
relayed_probe::current::<Log>()
}
pub(super) fn record(event: Event) {
relayed_probe::notify::<Log>(event);
}
#[cfg_attr(not(windows), allow(dead_code, reason = "only Windows call sites drop markers"))]
pub(crate) fn mark(name: &'static str) {
record(Event::Mark(name));
}
}
pub(crate) const TOKIO_TIMER_ROUNDING_MARGIN: Duration = Duration::from_millis(1);
pub(crate) fn clears_tokio_timer_margin(at: Instant) -> bool {
at.checked_add(TOKIO_TIMER_ROUNDING_MARGIN).is_some()
}
pub(crate) fn deadline_at(now: Instant, duration: Duration) -> Option<Instant> {
now.checked_add(duration).filter(|at| clears_tokio_timer_margin(*at))
}
pub(crate) fn deadline_from(duration: Duration) -> Option<Instant> {
deadline_at(now(), duration)
}
#[cfg(test)]
pub(crate) fn instant_near_ceiling(start: Instant) -> Instant {
let mut at = start;
let mut step = Duration::from_secs(1 << 62);
loop {
while let Some(next) = at.checked_add(step) {
at = next;
}
if step <= Duration::from_nanos(1) {
return at;
}
step /= 2;
}
}
#[cfg_attr(
not(any(test, windows)),
allow(
dead_code,
reason = "called only by win32_timeout_ms and tests; win32_timeout_ms is itself dead off-windows"
)
)]
fn ceil_millis(d: Duration) -> u128 {
d.as_nanos().div_ceil(1_000_000)
}
#[cfg_attr(
not(any(test, windows)),
allow(
dead_code,
reason = "used only by win32_timeout_ms and tests; win32_timeout_ms is itself dead off-windows"
)
)]
const WIN32_INFINITE: u32 = u32::MAX;
#[cfg_attr(
not(any(test, windows)),
allow(dead_code, reason = "only the Windows backend and portable tests call it")
)]
pub(crate) fn win32_timeout_ms(remaining: Option<Duration>) -> u32 {
match remaining {
None => WIN32_INFINITE,
Some(requested) => {
#[cfg(test)]
let d = remaining_override_seam::take().unwrap_or(requested);
#[cfg(not(test))]
let d = requested;
let ms = ceil_millis(d).min(win32_wait_clamp() as u128) as u32;
debug_assert!(
ms != WIN32_INFINITE,
"a finite remaining duration must never clamp up to the Win32 INFINITE sentinel"
);
#[cfg(test)]
wait_ms_probe::record(ms, d, requested);
ms
}
}
}
#[cfg_attr(
not(any(test, target_os = "linux", windows)),
allow(
dead_code,
reason = "called only by the Windows `wait_until` and the Linux holder's poll; macOS blocks on kqueue"
)
)]
pub(crate) fn rearm_until<T, E>(
deadline: Option<Instant>,
mut round: impl FnMut(Option<Duration>) -> Result<Option<T>, E>,
) -> Result<Option<T>, E> {
#[cfg(test)]
let mut check = test_clock::RoundCheck::new("rearm_until");
loop {
#[cfg(test)]
check.round();
let remaining_now = remaining(deadline);
#[cfg(test)]
let round_start = Instant::now();
let out = round(remaining_now)?;
#[cfg(test)]
test_clock::advance_by_elapsed_if_frozen(round_start.elapsed());
if out.is_some() || remaining(deadline) == Some(Duration::ZERO) {
return Ok(out);
}
}
}
#[cfg(unix)]
pub(crate) fn any_ready_now(fds: &mut [rustix::event::PollFd<'_>]) -> Result<bool, rustix::io::Errno> {
let zero = rustix::event::Timespec { tv_sec: 0, tv_nsec: 0 };
loop {
match rustix::event::poll(fds, Some(&zero)) {
Ok(ready) => return Ok(ready > 0),
Err(rustix::io::Errno::INTR) => continue,
Err(e) => return Err(e),
}
}
}
#[cfg(unix)]
pub(crate) fn poll_ready(fds: &mut [rustix::event::PollFd<'_>]) -> Result<(), rustix::io::Errno> {
loop {
match rustix::event::poll(fds, None) {
Ok(_) => return Ok(()),
Err(rustix::io::Errno::INTR) => continue,
Err(e) => return Err(e),
}
}
}
#[cfg(windows)]
pub(crate) fn wait_until(
deadline: Option<Instant>,
mut wait: impl FnMut(u32) -> windows::Win32::Foundation::WAIT_EVENT,
) -> windows::Win32::Foundation::WAIT_EVENT {
use windows::Win32::Foundation::WAIT_TIMEOUT;
let waited = rearm_until(deadline, |remaining| {
let waited = wait(win32_timeout_ms(remaining));
Ok::<_, std::convert::Infallible>((waited != WAIT_TIMEOUT).then_some(waited))
});
match waited {
Ok(Some(event)) => event,
Ok(None) => WAIT_TIMEOUT,
Err(never) => match never {},
}
}
#[cfg(target_os = "linux")]
#[cfg_attr(
not(any(test, feature = "tokio")),
allow(dead_code, reason = "only an async spawn's teardown looks at a killed child's exit")
)]
pub(crate) fn pidfd_exit_visible_by(pidfd: std::os::fd::BorrowedFd<'_>, until: Instant) -> bool {
use crate::os_process::drive::{run, RunOutcome};
match run(&mut PidfdExit::new(pidfd), Some(until)) {
Ok(RunOutcome::Done(())) => true,
Ok(RunOutcome::DeadlinePassed) => false,
Err(e) => {
log::debug!("a look at a killed child's exit failed ({e}); the wait that follows decides");
debug_assert!(false, "a pidfd look does not fail: {e}");
true
}
}
}
#[cfg(target_os = "linux")]
#[cfg_attr(
not(any(test, feature = "tokio")),
allow(dead_code, reason = "only an async spawn's teardown looks at a killed child's exit")
)]
struct PidfdExit<'a> {
pidfd: std::os::fd::BorrowedFd<'a>,
poll_failed: bool,
}
#[cfg(target_os = "linux")]
#[cfg_attr(
not(any(test, feature = "tokio")),
allow(dead_code, reason = "only an async spawn's teardown looks at a killed child's exit")
)]
impl<'a> PidfdExit<'a> {
fn new(pidfd: std::os::fd::BorrowedFd<'a>) -> Self {
Self {
pidfd,
poll_failed: false,
}
}
fn note_poll_failed(&mut self, e: &dyn std::fmt::Display) {
self.poll_failed = true;
log::debug!("a look at a killed child's exit could not poll its pidfd ({e}); it peeks instead");
}
}
#[cfg(target_os = "linux")]
impl crate::os_process::drive::Waitable for PidfdExit<'_> {
type Output = ();
fn look(&mut self) -> Result<crate::os_process::drive::Step<'_, ()>, crate::error::Error> {
use crate::os_process::child::PeekOutcome;
use crate::os_process::drive::Step;
use crate::os_process::WaitFor;
use crate::wait::exit_only::{self, Target};
match exit_only::peek(&Target::PidFd(self.pidfd)) {
Ok(PeekOutcome::Running) => {}
Ok(PeekOutcome::Exit(_) | PeekOutcome::Foreign(_)) => return Ok(Step::Done(())),
Err(e) => {
log::debug!(
"a look at a killed child's exit could not peek at it ({e}); the wait that follows decides"
);
return Ok(Step::Done(()));
}
}
if self.poll_failed {
return Ok(Step::Recheck);
}
match crate::os_process::poll::is_readable(self.pidfd) {
Ok(false) => Ok(Step::Wait(WaitFor::Readable(self.pidfd))),
Ok(true) => Ok(Step::Recheck),
Err(e) => {
self.note_poll_failed(&e);
Ok(Step::Recheck)
}
}
}
fn block_failed(&mut self, e: crate::error::Error) -> Result<(), crate::error::Error> {
self.note_poll_failed(&e);
Ok(())
}
}
pub(crate) const MAX_BLOCK: Duration = Duration::from_millis(0xFFFF_FFFE);
pub(crate) fn clamp_block(remaining: Duration) -> Duration {
remaining.min(MAX_BLOCK)
}
#[cfg_attr(
not(any(test, windows)),
allow(
dead_code,
reason = "called only by win32_timeout_ms and tests; win32_timeout_ms is itself dead off-windows"
)
)]
fn win32_wait_clamp() -> u32 {
#[cfg(test)]
if let Some(v) = wait_clamp_seam::get() {
return v;
}
WIN32_INFINITE - 1
}
#[cfg(test)]
pub(crate) mod block_probe {
#[cfg(target_os = "macos")]
use std::cell::Cell;
use std::cell::RefCell;
use std::time::Duration;
#[cfg(target_os = "macos")]
type RoundHook = Box<dyn FnMut(u32)>;
type Slot = RefCell<Option<Box<dyn FnOnce(Option<Duration>)>>>;
thread_local! {
static ARMED: RefCell<Vec<Option<Duration>>> = const { RefCell::new(Vec::new()) };
static ON_BLOCKING: Slot = const { RefCell::new(None) };
static ON_PAUSE: Slot = const { RefCell::new(None) };
static ON_CONDVAR_BLOCK: Slot = const { RefCell::new(None) };
#[cfg(target_os = "macos")]
static ROUND: Cell<u32> = const { Cell::new(0) };
#[cfg(target_os = "macos")]
static ON_ROUND: RefCell<Option<RoundHook>> = const { RefCell::new(None) };
#[cfg(target_os = "macos")]
static ROUND_OWNER: Cell<u64> = const { Cell::new(0) };
}
fn record(armed: Option<Duration>) {
ARMED.with(|a| a.borrow_mut().push(armed));
}
pub(crate) fn record_blocking(armed: Option<Duration>) {
record(armed);
fire(&ON_BLOCKING, armed);
#[cfg(target_os = "macos")]
fire_round();
}
pub(crate) fn record_pause(d: Duration) {
record(Some(d));
fire(&ON_PAUSE, Some(d));
}
pub(crate) fn record_condvar_block(armed: Option<Duration>) {
record(armed);
fire(&ON_CONDVAR_BLOCK, armed);
}
fn fire(slot: &'static std::thread::LocalKey<Slot>, armed: Option<Duration>) {
if let Some(hook) = slot.with(|h| h.borrow_mut().take()) {
hook(armed);
}
}
#[cfg(target_os = "macos")]
fn fire_round() {
let round = ROUND.with(|r| r.replace(r.get() + 1));
if let Some(mut hook) = ON_ROUND.with(|h| h.borrow_mut().take()) {
let owner = ROUND_OWNER.with(Cell::get);
hook(round);
if ROUND_OWNER.with(Cell::get) == owner {
ON_ROUND.with(|h| *h.borrow_mut() = Some(hook));
}
}
}
#[cfg(target_os = "macos")]
#[must_use = "dropping this immediately disarms the hook; bind it for the probe's duration"]
pub(crate) struct Rounds(u64);
#[cfg(target_os = "macos")]
impl Drop for Rounds {
fn drop(&mut self) {
if ROUND_OWNER.with(Cell::get) == self.0 {
ON_ROUND.with(|h| *h.borrow_mut() = None);
ROUND_OWNER.with(|o| o.set(self.0 + 1));
}
}
}
#[cfg(target_os = "macos")]
pub(crate) fn on_every_round(hook: impl FnMut(u32) + 'static) -> Rounds {
ROUND.with(|r| r.set(0));
let owner = ROUND_OWNER.with(|o| o.replace(o.get() + 1)) + 1;
ON_ROUND.with(|h| *h.borrow_mut() = Some(Box::new(hook)));
Rounds(owner)
}
#[cfg(target_os = "macos")]
pub(crate) fn on_round(round: u32, hook: impl FnOnce() + 'static) -> Rounds {
let mut hook = Some(hook);
on_every_round(move |at| {
if at == round {
hook.take().expect("a round comes once")();
}
})
}
#[must_use = "dropping this immediately disarms the hook; bind it for the probe's duration"]
pub(crate) struct Armed(&'static std::thread::LocalKey<Slot>);
impl Drop for Armed {
fn drop(&mut self) {
self.0.with(|h| *h.borrow_mut() = None);
}
}
pub(crate) fn on_blocking(hook: impl FnOnce() + 'static) -> Armed {
ON_BLOCKING.with(|h| *h.borrow_mut() = Some(Box::new(move |_| hook())));
Armed(&ON_BLOCKING)
}
pub(crate) fn on_pause(hook: impl FnOnce() + 'static) -> Armed {
ON_PAUSE.with(|h| *h.borrow_mut() = Some(Box::new(move |_| hook())));
Armed(&ON_PAUSE)
}
pub(crate) fn on_condvar_block(hook: impl FnOnce() + 'static) -> Armed {
on_condvar_block_with(move |_| hook())
}
pub(crate) fn on_condvar_block_with(hook: impl FnOnce(Option<Duration>) + 'static) -> Armed {
ON_CONDVAR_BLOCK.with(|h| *h.borrow_mut() = Some(Box::new(hook)));
Armed(&ON_CONDVAR_BLOCK)
}
pub(crate) fn take() -> Vec<Option<Duration>> {
ARMED.with(|a| std::mem::take(&mut *a.borrow_mut()))
}
}
#[cfg(test)]
pub(crate) mod wait_clamp_seam {
use std::cell::Cell;
thread_local! {
static OVERRIDE_MS: Cell<Option<u32>> = const { Cell::new(None) };
}
#[must_use]
pub(crate) fn set(ms: u32) -> Guard {
OVERRIDE_MS.with(|c| c.set(Some(ms)));
Guard(())
}
pub(crate) fn get() -> Option<u32> {
OVERRIDE_MS.with(|c| c.get())
}
pub(crate) struct Guard(());
impl Drop for Guard {
fn drop(&mut self) {
OVERRIDE_MS.with(|c| c.set(None));
}
}
}
#[cfg(test)]
pub(crate) mod remaining_override_seam {
use std::cell::Cell;
use std::time::Duration;
thread_local! {
static OVERRIDE: Cell<Option<Duration>> = const { Cell::new(None) };
}
#[must_use]
pub(crate) fn set(d: Duration) -> Guard {
OVERRIDE.with(|c| c.set(Some(d)));
Guard(())
}
pub(crate) fn take() -> Option<Duration> {
OVERRIDE.with(|c| c.take())
}
pub(crate) struct Guard(());
impl Drop for Guard {
fn drop(&mut self) {
OVERRIDE.with(|c| c.set(None));
}
}
}
#[cfg(test)]
pub(crate) mod wait_ms_probe {
use std::cell::RefCell;
use std::time::Duration;
#[derive(Clone, Copy, Debug)]
pub(crate) struct Arm {
pub(crate) ms: u32,
pub(crate) remaining: Duration,
pub(crate) requested: Duration,
}
thread_local! {
static RECORDED: RefCell<Vec<Arm>> = const { RefCell::new(Vec::new()) };
static HOOK: RefCell<Option<Box<dyn FnOnce()>>> = const { RefCell::new(None) };
}
pub(crate) fn record(ms: u32, remaining: Duration, requested: Duration) {
let count = RECORDED.with(|r| {
let mut r = r.borrow_mut();
r.push(Arm {
ms,
remaining,
requested,
});
r.len()
});
if count == 2 {
if let Some(hook) = HOOK.with(|h| h.borrow_mut().take()) {
hook();
}
}
}
#[cfg_attr(not(windows), allow(dead_code, reason = "only Windows tests register a hook"))]
pub(crate) fn on_second_arm(hook: impl FnOnce() + 'static) {
HOOK.with(|h| *h.borrow_mut() = Some(Box::new(hook)));
}
#[cfg_attr(not(windows), allow(dead_code, reason = "only Windows tests read the probe back"))]
pub(crate) fn take() -> Vec<Arm> {
HOOK.with(|h| *h.borrow_mut() = None);
RECORDED.with(|r| r.take())
}
#[cfg_attr(not(windows), allow(dead_code, reason = "only Windows tests call it"))]
#[track_caller]
pub(crate) fn assert_rearmed_with_fresh_remaining(arms: &[Arm], clamp: u32) {
assert!(arms.len() >= 2, "expected a re-arm, got {} arm(s)", arms.len());
for arm in arms {
assert_eq!(arm.ms, expected_ms(arm.remaining, clamp), "{arm:?}");
}
for pair in arms.windows(2) {
assert!(
pair[1].remaining < pair[0].remaining,
"remaining must be recomputed each round: {:?} then {:?}",
pair[0],
pair[1]
);
}
}
#[cfg_attr(not(windows), allow(dead_code, reason = "only Windows tests call it"))]
pub(crate) fn expected_ms(remaining: Duration, clamp: u32) -> u32 {
let ceil = remaining.as_nanos().div_ceil(1_000_000);
u32::try_from(ceil.min(u128::from(clamp))).expect("capped at a u32 clamp")
}
}
#[cfg(test)]
#[path = "wait_tests.rs"]
mod wait_tests;