use super::{
ceil_millis, clears_tokio_timer_margin, deadline_at, deadline_from, instant_near_ceiling, read_probe, rearm_until,
remaining, remaining_override_seam, test_clock, wait_clamp_seam, wait_ms_probe, win32_timeout_ms,
TOKIO_TIMER_ROUNDING_MARGIN,
};
use std::time::{Duration, Instant};
#[skuld::test]
fn remaining_unbounded_is_none() {
assert_eq!(remaining(None), None);
}
#[skuld::test]
fn remaining_past_deadline_saturates_to_zero() {
let past = Instant::now().checked_sub(Duration::from_secs(1)).unwrap();
assert_eq!(remaining(Some(past)), Some(Duration::ZERO));
}
#[skuld::test]
fn deadline_from_saturates_when_the_result_is_too_close_to_instants_ceiling() {
let now = Instant::now();
let duration = instant_near_ceiling(now).saturating_duration_since(now) - Duration::from_micros(500);
assert_eq!(deadline_from(duration), None);
}
#[skuld::test]
fn remaining_pins_the_exact_zero_boundary() {
let (_guard, t0) = test_clock::FrozenClockGuard::install();
let at = t0 + Duration::from_millis(250);
let deadline = Some(at);
assert_eq!(remaining(deadline), Some(Duration::from_millis(250)));
test_clock::advance(Duration::from_millis(250) - Duration::from_nanos(1));
assert_eq!(remaining(deadline), Some(Duration::from_nanos(1)));
test_clock::advance(Duration::from_nanos(1));
assert_eq!(remaining(deadline), Some(Duration::ZERO));
}
#[skuld::test]
fn ceil_millis_rounds_up_sub_millisecond_remainders() {
assert_eq!(ceil_millis(Duration::from_nanos(1)), 1);
assert_eq!(ceil_millis(Duration::from_micros(500)), 1);
assert_eq!(ceil_millis(Duration::from_micros(999)), 1);
assert_eq!(ceil_millis(Duration::from_micros(1500)), 2);
assert_eq!(ceil_millis(Duration::from_micros(2001)), 3);
}
#[skuld::test]
fn ceil_millis_zero_stays_zero() {
assert_eq!(ceil_millis(Duration::ZERO), 0);
}
#[skuld::test]
fn ceil_millis_whole_milliseconds_are_unchanged() {
assert_eq!(ceil_millis(Duration::from_millis(1)), 1);
assert_eq!(ceil_millis(Duration::from_millis(7)), 7);
assert_eq!(ceil_millis(Duration::from_secs(3)), 3_000);
}
#[skuld::test]
fn win32_timeout_ms_unbounded_is_the_win32_infinite_sentinel() {
assert_eq!(win32_timeout_ms(None), u32::MAX);
}
#[skuld::test]
fn win32_timeout_ms_ceils_rather_than_truncates() {
assert_eq!(win32_timeout_ms(Some(Duration::from_micros(500))), 1);
assert_eq!(win32_timeout_ms(Some(Duration::ZERO)), 0);
assert_eq!(win32_timeout_ms(Some(Duration::from_millis(7))), 7);
}
#[skuld::test]
fn win32_timeout_ms_never_returns_the_infinite_sentinel_for_a_finite_remaining() {
let ms = win32_timeout_ms(Some(Duration::from_millis(u64::from(u32::MAX))));
assert_ne!(ms, u32::MAX);
assert_eq!(ms, u32::MAX - 1);
}
#[skuld::test]
fn win32_timeout_ms_honors_the_clamp_seam() {
let guard = wait_clamp_seam::set(5);
assert_eq!(win32_timeout_ms(Some(Duration::from_secs(1))), 5);
drop(guard);
assert_eq!(win32_timeout_ms(Some(Duration::from_millis(3))), 3);
}
#[skuld::test]
fn remaining_override_seam_is_consumed_exactly_once() {
let guard = remaining_override_seam::set(Duration::from_millis(3));
assert_eq!(win32_timeout_ms(Some(Duration::from_millis(999))), 3);
assert_eq!(win32_timeout_ms(Some(Duration::from_millis(999))), 999);
drop(guard);
}
#[skuld::test]
fn remaining_override_seam_guard_clears_an_unconsumed_override_on_drop() {
let guard = remaining_override_seam::set(Duration::from_millis(3));
drop(guard);
assert_eq!(win32_timeout_ms(Some(Duration::from_millis(999))), 999);
}
#[skuld::test]
fn wait_ms_probe_records_the_requested_remaining_beside_the_armed_one() {
wait_ms_probe::take();
let _override = remaining_override_seam::set(Duration::from_millis(3));
win32_timeout_ms(Some(Duration::from_millis(999)));
let arms = wait_ms_probe::take();
assert_eq!(arms.len(), 1);
assert_eq!(arms[0].ms, 3);
assert_eq!(arms[0].remaining, Duration::from_millis(3));
assert_eq!(arms[0].requested, Duration::from_millis(999));
}
#[skuld::test]
fn deadline_at_passes_through_up_to_the_margin_and_is_unbounded_past_it() {
let now = Instant::now();
let ceiling = instant_near_ceiling(now);
let span = ceiling.saturating_duration_since(now);
let edge = span - TOKIO_TIMER_ROUNDING_MARGIN;
assert_eq!(deadline_at(now, edge), Some(now + edge));
assert_eq!(deadline_at(now, edge + Duration::from_nanos(1)), None);
assert_eq!(deadline_at(now, span), None);
assert_eq!(
deadline_at(now, span + Duration::from_nanos(1)),
None,
"overflow itself"
);
assert_eq!(deadline_at(now, Duration::MAX), None);
assert_eq!(deadline_at(now, Duration::ZERO), Some(now));
assert_eq!(
deadline_at(now, Duration::from_secs(1)),
Some(now + Duration::from_secs(1))
);
}
#[skuld::test]
fn clears_tokio_timer_margin_is_true_exactly_up_to_the_margin() {
let ceiling = instant_near_ceiling(Instant::now());
assert!(clears_tokio_timer_margin(ceiling - TOKIO_TIMER_ROUNDING_MARGIN));
assert!(!clears_tokio_timer_margin(
ceiling - TOKIO_TIMER_ROUNDING_MARGIN + Duration::from_nanos(1)
));
}
#[skuld::test]
fn deadline_from_applies_deadline_at_on_the_test_clock() {
let (_guard, t0) = test_clock::FrozenClockGuard::install();
let span = instant_near_ceiling(t0).saturating_duration_since(t0);
let edge = span - TOKIO_TIMER_ROUNDING_MARGIN;
assert_eq!(deadline_from(edge), Some(t0 + edge));
assert_eq!(deadline_from(edge + Duration::from_nanos(1)), None);
assert_eq!(deadline_from(Duration::MAX), None);
}
#[skuld::test]
fn rearm_until_advances_the_frozen_clock_by_each_round() {
let (_clock, at) = test_clock::FrozenClockGuard::install();
let deadline = Some(at + Duration::from_millis(30));
let mut previous: Option<Instant> = None;
let out = rearm_until(deadline, |remaining| {
let seen = super::now();
if let Some(previous) = previous {
assert!(seen > previous, "the frozen clock did not advance across a real wait");
}
previous = Some(seen);
std::thread::park_timeout(remaining.expect("finite deadline"));
Ok::<Option<()>, ()>(None)
});
assert_eq!(out, Ok(None));
}
#[skuld::test]
fn rearm_until_hands_a_round_the_frozen_remaining() {
let (_clock, at) = test_clock::FrozenClockGuard::install_lagging(Duration::from_secs(1));
let deadline = Some(at + Duration::from_millis(50));
let mut seen = None;
let out = rearm_until(deadline, |remaining| {
seen = Some(remaining);
Ok::<_, ()>(Some(()))
});
assert_eq!(out, Ok(Some(())));
assert_eq!(seen, Some(Some(Duration::from_millis(50))));
}
#[skuld::test]
fn rearm_until_polls_once_for_a_past_deadline() {
let past = Instant::now().checked_sub(Duration::from_secs(1)).unwrap();
let mut rounds = Vec::new();
let out = rearm_until(Some(past), |remaining| {
rounds.push(remaining);
Ok::<Option<()>, ()>(None)
});
assert_eq!(out, Ok(None));
assert_eq!(rounds, [Some(Duration::ZERO)]);
}
#[skuld::test]
fn rearm_until_stops_at_a_round_error() {
let (_clock, at) = test_clock::FrozenClockGuard::install();
let deadline = Some(at + Duration::from_secs(3600));
let mut rounds = 0;
let out = rearm_until(deadline, |_| {
rounds += 1;
match rounds {
1 => Ok(None),
2 => Err("boom"),
_ => Ok(Some(())),
}
});
assert_eq!(out, Err("boom"));
assert_eq!(rounds, 2);
}
#[skuld::test]
fn read_probe_records_reads_and_marks_in_order() {
let (tx, rx) = std::sync::mpsc::channel();
let (_clock, at) = test_clock::FrozenClockGuard::install();
let deadline = Some(at + Duration::from_secs(5));
let guard = read_probe::install(tx);
read_probe::mark("before");
remaining(deadline);
remaining(None);
drop(guard);
let want = [
read_probe::Event::Mark("before"),
read_probe::Event::Read {
deadline,
remaining: Some(Duration::from_secs(5)),
},
read_probe::Event::Read {
deadline: None,
remaining: None,
},
];
assert_eq!(rx.try_iter().collect::<Vec<_>>(), want);
}
#[skuld::test]
fn read_probe_guard_uninstalls_on_drop_even_when_unwinding() {
let (tx, rx) = std::sync::mpsc::channel();
let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let _guard = read_probe::install(tx);
panic!("unwind with the probe installed");
}));
assert!(unwound.is_err());
remaining(None);
read_probe::mark("after");
assert_eq!(rx.try_iter().count(), 0);
assert!(read_probe::current().is_none());
}
#[skuld::test]
fn read_probe_reaches_another_thread_only_through_current() {
let (tx, rx) = std::sync::mpsc::channel();
let _guard = read_probe::install(tx);
std::thread::scope(|s| {
s.spawn(|| remaining(None));
});
assert_eq!(rx.try_iter().count(), 0, "an uninstalled thread must not record");
let carried = read_probe::current().expect("installed on this thread");
std::thread::scope(|s| {
s.spawn(move || {
let _guard = read_probe::install(carried);
remaining(None);
});
});
assert_eq!(
rx.try_iter().count(),
1,
"the installed thread records into the same log"
);
}
#[skuld::test]
#[should_panic(expected = "no progress")]
fn round_check_panics_on_two_rounds_without_an_advance() {
let (_clock, _at) = test_clock::FrozenClockGuard::install();
let mut check = test_clock::RoundCheck::new("test");
check.round();
check.round();
}
#[skuld::test]
fn round_check_accepts_an_advance_of_zero_between_rounds() {
let (_clock, _at) = test_clock::FrozenClockGuard::install();
let mut check = test_clock::RoundCheck::new("test");
check.round();
test_clock::advance_by_elapsed_if_frozen(Duration::ZERO);
check.round();
test_clock::advance_by_elapsed_if_frozen(Duration::ZERO);
check.round();
}
#[skuld::test]
fn round_check_state_is_per_invocation() {
let (_clock, _at) = test_clock::FrozenClockGuard::install();
let mut first = test_clock::RoundCheck::new("first");
first.round();
let mut second = test_clock::RoundCheck::new("second");
second.round();
}
#[skuld::test]
fn skip_advance_guard_resets_on_drop() {
let (_clock, at) = test_clock::FrozenClockGuard::install();
let skip = test_clock::SkipAdvanceGuard::install();
test_clock::advance_by_elapsed_if_frozen(Duration::from_millis(10));
assert_eq!(test_clock::now(), at, "the advance is skipped while the guard lives");
drop(skip);
test_clock::advance_by_elapsed_if_frozen(Duration::from_millis(10));
assert_eq!(test_clock::now(), at + Duration::from_millis(10));
}
#[skuld::test]
fn zero_elapsed_guard_resets_on_drop() {
let (_clock, at) = test_clock::FrozenClockGuard::install();
let zero = test_clock::ZeroElapsedGuard::install();
test_clock::advance_by_elapsed_if_frozen(Duration::from_millis(10));
assert_eq!(
test_clock::now(),
at,
"the elapsed is pinned to zero while the guard lives"
);
drop(zero);
test_clock::advance_by_elapsed_if_frozen(Duration::from_millis(10));
assert_eq!(test_clock::now(), at + Duration::from_millis(10));
}
#[skuld::test]
#[should_panic(expected = "no progress")]
fn round_check_compares_against_the_previous_round_only() {
let (_clock, _at) = test_clock::FrozenClockGuard::install();
let mut check = test_clock::RoundCheck::new("test");
check.round();
test_clock::advance_by_elapsed_if_frozen(Duration::ZERO);
check.round();
check.round();
}
#[skuld::test]
fn round_check_ignores_an_unfrozen_clock() {
{
let (_clock, _at) = test_clock::FrozenClockGuard::install();
assert!(test_clock::is_frozen());
}
assert!(!test_clock::is_frozen());
let mut check = test_clock::RoundCheck::new("test");
check.round();
check.round();
}
#[skuld::test]
fn two_sequential_waits_with_the_same_remaining_do_not_trip_the_check() {
let (_clock, _at) = test_clock::FrozenClockGuard::install();
for _ in 0..2 {
let mut rounds = 0;
let out = rearm_until(None, |_| {
rounds += 1;
Ok::<_, ()>((rounds == 2).then_some(()))
});
assert_eq!(out, Ok(Some(())));
assert_eq!(rounds, 2);
}
}
#[skuld::test]
fn wait_ms_probe_does_not_judge_progress() {
let (_clock, _at) = test_clock::FrozenClockGuard::install();
wait_ms_probe::take();
let r = Duration::from_millis(7);
wait_ms_probe::record(7, r, r);
wait_ms_probe::record(7, r, r);
wait_ms_probe::take();
wait_ms_probe::record(7, r, r);
wait_ms_probe::take();
}
#[skuld::test]
fn the_override_seam_and_a_zero_elapsed_round_do_not_trip_the_check() {
let (_clock, at) = test_clock::FrozenClockGuard::install();
let _zero = test_clock::ZeroElapsedGuard::install();
let deadline = Some(at + Duration::from_millis(5));
let _override = remaining_override_seam::set(Duration::from_micros(500));
wait_ms_probe::take();
let mut seen = Vec::new();
let mut rounds = 0;
let out = rearm_until(deadline, |remaining| {
seen.push(remaining);
win32_timeout_ms(remaining);
rounds += 1;
Ok::<_, ()>((rounds == 3).then_some(()))
});
assert_eq!(out, Ok(Some(())));
assert_eq!(
test_clock::now(),
at,
"a zero-elapsed round leaves the frozen clock where it was"
);
assert_eq!(
seen,
vec![Some(Duration::from_millis(5)); 3],
"the rounds saw the same remaining, and still made progress"
);
wait_ms_probe::take();
}
#[skuld::test]
#[should_panic(expected = "no progress")]
fn rearm_until_panics_when_its_advance_is_dropped() {
let (_clock, at) = test_clock::FrozenClockGuard::install();
let _skip = test_clock::SkipAdvanceGuard::install();
let deadline = Some(at + Duration::from_secs(3600));
let mut rounds = 0;
rearm_until(deadline, |_| {
rounds += 1;
assert!(rounds < 2, "the check let a second round run");
Ok::<Option<()>, ()>(None)
})
.ok();
}
#[cfg(windows)]
#[skuld::test]
#[should_panic(expected = "no progress")]
fn wait_until_panics_when_its_advance_is_dropped() {
use windows::Win32::Foundation::WAIT_TIMEOUT;
let (_clock, at) = test_clock::FrozenClockGuard::install();
let _skip = test_clock::SkipAdvanceGuard::install();
let deadline = Some(at + Duration::from_secs(3600));
let mut waits = 0;
super::wait_until(deadline, |_ms| {
waits += 1;
assert!(waits < 2, "the check let a second round run");
WAIT_TIMEOUT
});
}
const ROUND_CHECK_ABORT_MARKER: &str = "COSCA_FIXTURE_ROUND_CHECK_ABORT";
#[skuld::test]
fn fixture_round_check_violation_while_panicking() {
struct StalledInDrop;
impl Drop for StalledInDrop {
fn drop(&mut self) {
let mut check = test_clock::RoundCheck::new("drop path");
check.round();
check.round();
}
}
if !crate::test_child::is_marked_fixture_reexec(ROUND_CHECK_ABORT_MARKER) {
return; }
let (_clock, _at) = test_clock::FrozenClockGuard::install();
let _stalled = StalledInDrop;
panic!("the fixture's own failure");
}
#[skuld::test]
fn round_check_exits_when_it_fires_while_panicking() {
let output = crate::test_child::run_fixture_output(
crate::test_child::fixture_path!(fixture_round_check_violation_while_panicking),
ROUND_CHECK_ABORT_MARKER,
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains(crate::test_child::FIXTURE_GATE_PASSED_LINE),
"the fixture never passed its gate, so nothing ran:\n{stderr}"
);
assert!(
!matches!(output.status.code(), Some(0 | 101)),
"the exit code must differ from a pass and from libtest's failure: {:?}\n{stderr}",
output.status
);
assert_eq!(
output.status.code(),
Some(test_clock::VIOLATION_EXIT_CODE),
"the process must exit with the violation code, not abort or fail as a test: {:?}\n{stderr}",
output.status
);
assert!(
stderr.contains("drop path") && stderr.contains("no progress"),
"the exit names its site and cause on stderr:\n{stderr}"
);
}
#[cfg(target_os = "linux")]
mod pidfd_exit_visible {
use std::os::fd::AsFd as _;
use std::time::{Duration, Instant};
use super::super::{pidfd_exit_visible_by, PidfdExit};
use crate::test_groups::{tracer_group, Group};
use crate::test_support::foreign_tracer::{self, EXIT};
fn blocker() -> std::process::Child {
let mut cmd = crate::test_child::held_std_blocker(std::process::Stdio::null());
foreign_tracer::allow_any_tracer(&mut cmd);
crate::test_spawn::spawn(&mut cmd).expect("spawn the blocker")
}
#[skuld::test]
fn pidfd_exit_visible_by_is_true_for_a_zombie_and_false_at_the_deadline_for_a_running_child() {
let mut child = blocker();
let pidfd = crate::containment::cgroup::test_support::pidfd_of(child.id());
let until = Instant::now() + Duration::from_millis(30);
assert!(!pidfd_exit_visible_by(pidfd.as_fd(), until));
assert!(
Instant::now() >= until,
"a running child is reported before the deadline"
);
child.kill().expect("kill");
crate::test_child::wait_until_zombie(child.id());
let far = Instant::now() + Duration::from_secs(3600);
assert!(pidfd_exit_visible_by(pidfd.as_fd(), far));
child.wait().expect("reap");
}
#[skuld::test]
fn a_failed_poll_leaves_the_peek_to_decide_until_the_deadline() {
crate::test_child::run_fixture(crate::test_child::fixture_path!(
fixture_a_failed_poll_leaves_the_peek_to_decide
));
}
#[skuld::test]
fn fixture_a_failed_poll_leaves_the_peek_to_decide() {
if !crate::test_child::is_fixture_reexec() {
return;
}
let mut child = blocker();
let pidfd = crate::containment::cgroup::test_support::pidfd_of(child.id());
let mut before = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
assert_eq!(unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut before) }, 0);
let none = libc::rlimit {
rlim_cur: 0,
rlim_max: before.rlim_max,
};
assert_eq!(unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &none) }, 0);
assert!(
crate::os_process::poll::is_readable(pidfd.as_fd()).is_err(),
"the precondition: poll fails"
);
let blocking = crate::wait::block_probe::on_blocking(|| panic!("a block after a failed poll"));
let until = Instant::now() + Duration::from_millis(30);
assert!(!pidfd_exit_visible_by(pidfd.as_fd(), until));
assert!(Instant::now() >= until, "reported before the deadline");
drop(blocking);
assert_eq!(unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &before) }, 0);
child.kill().expect("kill");
crate::test_child::wait_until_zombie(child.id());
let far = Instant::now() + Duration::from_secs(3600);
assert!(pidfd_exit_visible_by(pidfd.as_fd(), far));
child.wait().expect("reap");
}
#[skuld::test]
fn a_child_reaped_by_someone_else_is_visible_at_once() {
let mut child = blocker();
let pidfd = crate::containment::cgroup::test_support::pidfd_of(child.id());
child.kill().expect("kill");
child.wait().expect("reap");
assert!(pidfd_exit_visible_by(pidfd.as_fd(), Instant::now()));
}
#[skuld::test]
fn a_peek_that_fails_is_visible_at_once() {
use crate::wait::exit_only::seams::{assert_peeks_exhausted, force_peek_once};
let mut child = blocker();
let pidfd = crate::containment::cgroup::test_support::pidfd_of(child.id());
let forced = force_peek_once(Err(std::io::Error::other("forced peek failure")));
assert!(pidfd_exit_visible_by(pidfd.as_fd(), Instant::now()));
assert_peeks_exhausted();
drop(forced);
child.kill().expect("kill");
child.wait().expect("reap");
}
#[skuld::test]
fn a_zombie_a_tracer_holds_is_visible_only_once_the_tracer_lets_go(#[fixture(tracer_group)] _group: &Group) {
use crate::os_process::drive::{Step, Waitable as _};
let mut child = blocker();
let pidfd = crate::containment::cgroup::test_support::pidfd_of(child.id());
let mut tracer = foreign_tracer::spawn_helper(child.id());
child.kill().expect("kill");
assert!(
crate::os_process::poll::poll_readable(pidfd.as_fd(), None).expect("poll"),
"the pidfd turns readable at the zombie"
);
assert!(
matches!(PidfdExit::new(pidfd.as_fd()).look().expect("look"), Step::Recheck),
"a readable pidfd with no visible exit is looked at again, not blocked on"
);
let until = Instant::now() + Duration::from_millis(30);
assert!(
!pidfd_exit_visible_by(pidfd.as_fd(), until),
"the tracer still holds it"
);
assert!(Instant::now() >= until, "reported before the deadline");
tracer.send(EXIT);
tracer.finish();
let far = Instant::now() + Duration::from_secs(3600);
assert!(pidfd_exit_visible_by(pidfd.as_fd(), far), "the tracer let go");
child.wait().expect("reap");
}
}
#[cfg(unix)]
mod poll {
use std::io::Write as _;
use rustix::event::{PollFd, PollFlags};
use rustix::io::Errno;
use crate::test_own_process::{own_process, test_path};
use crate::wait::{any_ready_now, poll_ready};
const OVERSIZE: usize = 10_241;
fn lower_the_descriptor_limit() {
let limit = libc::rlimit {
rlim_cur: 16,
rlim_max: 16,
};
let set = unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &limit) };
assert_eq!(set, 0, "lower RLIMIT_NOFILE");
}
#[skuld::test]
fn any_ready_now_is_true_for_a_readable_descriptor() {
let (rx, mut tx) = std::io::pipe().unwrap();
tx.write_all(&[1]).unwrap();
let mut fds = [PollFd::new(&rx, PollFlags::IN)];
assert_eq!(any_ready_now(&mut fds), Ok(true));
assert!(
fds[0].revents().contains(PollFlags::IN),
"the events found are in the slice"
);
}
#[skuld::test]
fn any_ready_now_is_false_when_nothing_is_ready() {
let (rx, _tx) = std::io::pipe().unwrap();
let mut fds = [PollFd::new(&rx, PollFlags::IN)];
assert_eq!(any_ready_now(&mut fds), Ok(false));
assert!(fds[0].revents().is_empty());
}
#[skuld::test]
fn any_ready_now_reports_a_failed_poll_as_an_error() {
let Some(_done) = own_process(
test_path!(any_ready_now_reports_a_failed_poll_as_an_error),
crate::test_spawn::spawn,
) else {
return;
};
let (rx, _tx) = std::io::pipe().unwrap();
let mut fds: Vec<_> = (0..OVERSIZE).map(|_| PollFd::new(&rx, PollFlags::IN)).collect();
lower_the_descriptor_limit();
assert_eq!(any_ready_now(&mut fds), Err(Errno::INVAL));
}
#[skuld::test]
fn poll_ready_returns_once_a_descriptor_is_ready() {
let (rx, mut tx) = std::io::pipe().unwrap();
tx.write_all(&[1]).unwrap();
let mut fds = [PollFd::new(&rx, PollFlags::IN)];
assert_eq!(poll_ready(&mut fds), Ok(()));
assert!(
fds[0].revents().contains(PollFlags::IN),
"the events found are in the slice"
);
}
#[skuld::test]
fn poll_ready_reports_a_failed_poll_as_an_error() {
let Some(_done) = own_process(
test_path!(poll_ready_reports_a_failed_poll_as_an_error),
crate::test_spawn::spawn,
) else {
return;
};
let (rx, _tx) = std::io::pipe().unwrap();
let mut fds: Vec<_> = (0..OVERSIZE).map(|_| PollFd::new(&rx, PollFlags::IN)).collect();
lower_the_descriptor_limit();
assert_eq!(poll_ready(&mut fds), Err(Errno::INVAL));
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn poll_ready_retries_an_interrupted_poll() {
use std::os::unix::thread::JoinHandleExt as _;
use std::sync::atomic::{AtomicUsize, Ordering};
use nix::sys::signal::{sigaction, SaFlags, SigAction, SigHandler, SigSet, Signal};
static HANDLED: AtomicUsize = AtomicUsize::new(0);
extern "C" fn count(_: libc::c_int) {
HANDLED.fetch_add(1, Ordering::SeqCst);
}
fn blocked_in_poll(tid: u32) -> bool {
let path = format!("/proc/self/task/{tid}/syscall");
let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {path}: {e}"));
let Some(Ok(number)) = text.split_whitespace().next().map(str::parse::<libc::c_long>) else {
return false; };
#[cfg(target_arch = "x86_64")]
let polls = [libc::SYS_poll, libc::SYS_ppoll];
#[cfg(not(target_arch = "x86_64"))]
let polls = [libc::SYS_ppoll];
polls.contains(&number)
}
let Some(_done) = own_process(
test_path!(poll_ready_retries_an_interrupted_poll),
crate::test_spawn::spawn,
) else {
return;
};
let action = SigAction::new(SigHandler::Handler(count), SaFlags::empty(), SigSet::empty());
unsafe { sigaction(Signal::SIGUSR2, &action) }.expect("install the handler");
let (rx, mut tx) = std::io::pipe().unwrap();
let (tid_tx, tid_rx) = std::sync::mpsc::channel();
let poller = std::thread::spawn(move || {
tid_tx
.send(rustix::thread::gettid().as_raw_nonzero().get() as u32)
.unwrap();
poll_ready(&mut [PollFd::new(&rx, PollFlags::IN)])
});
let tid = tid_rx.recv().unwrap();
while !blocked_in_poll(tid) {
std::thread::yield_now();
}
let sent = unsafe { libc::pthread_kill(poller.as_pthread_t(), libc::SIGUSR2) };
assert_eq!(sent, 0, "signal the polling thread");
while HANDLED.load(Ordering::SeqCst) == 0 {
std::thread::yield_now();
}
tx.write_all(&[1]).unwrap();
assert_eq!(
poller.join().unwrap(),
Ok(()),
"the interrupted poll was retried, not returned"
);
}
}