oscall 0.1.0

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! Waiting on an address and waking.

use std::sync::atomic::{AtomicU32, Ordering};
use std::time::{Duration, Instant};

use oscall::sync::{self, WaitOutcome};

/// Long enough for a thread to reach its wait on a loaded machine, in the
/// tests that need one to be asleep; nothing fails if it is not.
#[cfg(not(target_os = "wasi"))]
const SETTLE: Duration = Duration::from_millis(100);

#[test]
fn mismatch_returns_at_once() {
    let atomic = AtomicU32::new(7);
    // With no timeout: a hang here is the failure.
    assert_eq!(sync::wait(&atomic, 8, None).unwrap(), WaitOutcome::Woken);
    let start = Instant::now();
    let outcome = sync::wait(&atomic, 0, Some(Duration::from_secs(60))).unwrap();
    assert_eq!(outcome, WaitOutcome::Woken);
    assert!(start.elapsed() < Duration::from_secs(30));
    assert_eq!(
        sync::wait(&atomic, u32::MAX, Some(Duration::ZERO)).unwrap(),
        WaitOutcome::Woken
    );
    assert_eq!(atomic.load(Ordering::Relaxed), 7);
}

/// Waits on `atomic`, which holds `value` and that nobody wakes, until the
/// timeout is reported, and returns how long that took.
///
/// A spurious wake-up is allowed, if rare (Windows hashes addresses, and
/// the test harness has locks of its own): wait again for what is left, like
/// a real caller.
fn wait_out(atomic: &AtomicU32, value: u32, timeout: Duration) -> Duration {
    let start = Instant::now();
    loop {
        let left = timeout.saturating_sub(start.elapsed());
        match sync::wait(atomic, value, Some(left)).unwrap() {
            WaitOutcome::TimedOut => return start.elapsed(),
            WaitOutcome::Woken => assert!(!left.is_zero(), "woken with nothing to wait for"),
        }
    }
}

#[test]
fn timeout() {
    let atomic = AtomicU32::new(7);
    for timeout in [
        Duration::from_nanos(1),
        Duration::from_micros(2500),
        Duration::from_millis(50),
    ] {
        let elapsed = wait_out(&atomic, 7, timeout);
        // The timeout must not come early. The system's clock for this is
        // not exactly std's: 100 µs between them.
        assert!(
            elapsed + Duration::from_micros(100) >= timeout,
            "{elapsed:?} < {timeout:?}"
        );
    }
}

#[test]
fn zero_timeout_only_compares() {
    let atomic = AtomicU32::new(7);
    let start = Instant::now();
    for _ in 0..100 {
        assert_eq!(
            sync::wait(&atomic, 7, Some(Duration::ZERO)).unwrap(),
            WaitOutcome::TimedOut
        );
    }
    assert!(start.elapsed() < Duration::from_secs(10));
}

#[test]
fn wake_without_waiters() {
    let atomic = AtomicU32::new(0);
    sync::wake_one(&atomic);
    sync::wake_all(&atomic);
    // Wake-ups are not stored: a later wait still sleeps.
    let timeout = Duration::from_millis(20);
    assert!(wait_out(&atomic, 0, timeout) + Duration::from_micros(100) >= timeout);
}

// WebAssembly: a wait nobody can end is refused, not started.
#[cfg(target_family = "wasm")]
#[test]
fn wait_forever_is_refused() {
    let atomic = AtomicU32::new(7);
    assert_eq!(
        sync::wait(&atomic, 7, None).unwrap_err(),
        oscall::ErrorKind::Deadlock
    );
}

// The tests below need other threads, which WASI does not have.

/// Waits until `atomic` is no longer `value`, the way a lock would.
#[cfg(not(target_os = "wasi"))]
fn wait_while(atomic: &AtomicU32, value: u32) -> u32 {
    loop {
        let now = atomic.load(Ordering::Acquire);
        if now != value {
            return now;
        }
        // Whatever the outcome, the loop looks again.
        let _ = sync::wait(atomic, value, None).unwrap();
    }
}

#[cfg(not(target_os = "wasi"))]
#[test]
fn woken_by_another_thread() {
    for wake_all in [false, true] {
        let atomic = AtomicU32::new(0);
        let start = Instant::now();
        std::thread::scope(|s| {
            let waiter = s.spawn(|| wait_while(&atomic, 0));
            std::thread::sleep(SETTLE);
            assert!(!waiter.is_finished());
            atomic.store(5, Ordering::Release);
            if wake_all {
                sync::wake_all(&atomic);
            } else {
                sync::wake_one(&atomic);
            }
            assert_eq!(waiter.join().unwrap(), 5);
        });
        assert!(start.elapsed() >= SETTLE);
    }
}

#[cfg(not(target_os = "wasi"))]
#[test]
fn woken_before_timeout() {
    let atomic = AtomicU32::new(0);
    std::thread::scope(|s| {
        let waiter = s.spawn(|| {
            let start = Instant::now();
            let timeout = Duration::from_secs(120);
            while atomic.load(Ordering::Acquire) == 0 {
                let outcome = sync::wait(&atomic, 0, Some(timeout)).unwrap();
                assert_eq!(outcome, WaitOutcome::Woken);
            }
            start.elapsed()
        });
        std::thread::sleep(SETTLE);
        atomic.store(1, Ordering::Release);
        sync::wake_one(&atomic);
        assert!(waiter.join().unwrap() < Duration::from_secs(60));
    });
}

#[cfg(not(target_os = "wasi"))]
#[test]
fn wake_without_change_is_a_wakeup() {
    // A wake-up with the value unchanged still ends the wait: the waiter
    // sees `Woken` with the value it was waiting on, and must cope.
    let atomic = AtomicU32::new(0);
    let returned = AtomicU32::new(0);
    std::thread::scope(|s| {
        s.spawn(|| {
            let outcome = sync::wait(&atomic, 0, Some(Duration::from_secs(120))).unwrap();
            assert_eq!(outcome, WaitOutcome::Woken);
            returned.store(1, Ordering::Release);
        });
        // The waiter may not be asleep yet when the first wake-up goes out:
        // keep waking until it has returned.
        let start = Instant::now();
        while returned.load(Ordering::Acquire) == 0 {
            sync::wake_one(&atomic);
            std::thread::sleep(Duration::from_millis(1));
            assert!(start.elapsed() < Duration::from_secs(60));
        }
    });
    assert_eq!(atomic.load(Ordering::Relaxed), 0);
}

#[cfg(not(target_os = "wasi"))]
#[test]
fn wake_all_wakes_everyone() {
    const WAITERS: u32 = 8;
    let atomic = AtomicU32::new(0);
    let done = AtomicU32::new(0);
    std::thread::scope(|s| {
        for _ in 0..WAITERS {
            s.spawn(|| {
                assert_eq!(wait_while(&atomic, 0), 1);
                done.fetch_add(1, Ordering::Release);
            });
        }
        std::thread::sleep(SETTLE);
        assert_eq!(done.load(Ordering::Acquire), 0);
        atomic.store(1, Ordering::Release);
        sync::wake_all(&atomic);
        // The scope joins them all: a waiter left asleep hangs the test.
    });
    assert_eq!(done.load(Ordering::Acquire), WAITERS);
}

#[cfg(not(target_os = "wasi"))]
#[test]
fn wake_one_wakes_one_at_a_time() {
    const WAITERS: u32 = 4;
    // Each waiter takes one token; each token comes with one wake-up.
    let tokens = AtomicU32::new(0);
    let taken = AtomicU32::new(0);
    std::thread::scope(|s| {
        for _ in 0..WAITERS {
            s.spawn(|| {
                loop {
                    let available = tokens.load(Ordering::Acquire);
                    if available == 0 {
                        let _ = sync::wait(&tokens, 0, None).unwrap();
                    } else if tokens
                        .compare_exchange(
                            available,
                            available - 1,
                            Ordering::AcqRel,
                            Ordering::Acquire,
                        )
                        .is_ok()
                    {
                        break;
                    }
                }
                taken.fetch_add(1, Ordering::Release);
            });
        }
        std::thread::sleep(SETTLE);
        for given in 1..=WAITERS {
            tokens.fetch_add(1, Ordering::Release);
            sync::wake_one(&tokens);
            // One token: exactly one waiter gets through, however many wake.
            let start = Instant::now();
            while taken.load(Ordering::Acquire) < given {
                std::thread::yield_now();
                assert!(start.elapsed() < Duration::from_secs(60), "lost wake-up");
            }
            std::thread::sleep(Duration::from_millis(10));
            assert_eq!(taken.load(Ordering::Acquire), given);
        }
    });
    assert_eq!(tokens.load(Ordering::Relaxed), 0);
}

#[cfg(not(target_os = "wasi"))]
#[test]
fn mutex_built_on_it() {
    // The use it is meant for: a three-state mutex (0 free, 1 locked,
    // 2 locked with waiters) protecting a counter that is not atomic in
    // effect (load, then store).
    const THREADS: u32 = 4;
    const ROUNDS: u32 = 5000;
    let lock = AtomicU32::new(0);
    let counter = AtomicU32::new(0);
    std::thread::scope(|s| {
        for _ in 0..THREADS {
            s.spawn(|| {
                for _ in 0..ROUNDS {
                    if lock
                        .compare_exchange(0, 1, Ordering::Acquire, Ordering::Relaxed)
                        .is_err()
                    {
                        while lock.swap(2, Ordering::Acquire) != 0 {
                            let _ = sync::wait(&lock, 2, None).unwrap();
                        }
                    }
                    let value = counter.load(Ordering::Relaxed);
                    std::hint::spin_loop();
                    counter.store(value + 1, Ordering::Relaxed);
                    if lock.swap(0, Ordering::Release) == 2 {
                        sync::wake_one(&lock);
                    }
                }
            });
        }
    });
    assert_eq!(counter.load(Ordering::Relaxed), THREADS * ROUNDS);
}

/// Timeouts longer than any system counts (`Duration::MAX` is 584 billion
/// years): each is a wait that lasts until it is woken, not one that is
/// over at once, with or without a timeout to report.
#[cfg(not(target_os = "wasi"))]
#[test]
fn huge_timeouts() {
    for timeout in [
        Duration::MAX,
        Duration::from_secs(u64::MAX),
        Duration::from_secs(i64::MAX as u64),
        Duration::from_nanos(u64::MAX) + Duration::from_nanos(1),
        Duration::from_nanos(u64::MAX),
        Duration::from_nanos(i64::MAX as u64 + 1),
        Duration::from_nanos(i64::MAX as u64),
        // Windows counts 49 days of milliseconds.
        Duration::from_millis(u32::MAX as u64 + 1),
        Duration::from_millis(u32::MAX as u64),
        Duration::from_millis(u32::MAX as u64 - 1),
    ] {
        // How many times a wait that nobody wakes for a while returns
        // with nothing changed.
        let early_returns = || {
            let atomic = AtomicU32::new(0);
            std::thread::scope(|s| {
                let waiter = s.spawn(|| {
                    let mut early = 0u64;
                    loop {
                        let outcome = sync::wait(&atomic, 0, Some(timeout));
                        let outcome = outcome.map_err(|e| e.raw_os_error());
                        assert_eq!(outcome, Ok(WaitOutcome::Woken), "{timeout:?}");
                        if atomic.load(Ordering::Acquire) != 0 {
                            return early;
                        }
                        early += 1;
                    }
                });
                std::thread::sleep(SETTLE);
                assert!(!waiter.is_finished(), "{timeout:?}");
                atomic.store(1, Ordering::Release);
                sync::wake_all(&atomic);
                waiter.join().unwrap()
            })
        };
        // A spurious wake-up is allowed, and so are many of them while the
        // other tests wake waiters of their own thousands of times a
        // second: Windows finds waiters by a hash of the address, and wakes
        // those of another address that has the same one. That ends with
        // those tests; a wait that does not wait never stops returning.
        let mut early = early_returns();
        for _ in 0..50 {
            if early < 100 {
                break;
            }
            early = early_returns();
        }
        assert!(early < 100, "{timeout:?}: {early} waits returned early");
    }
}

/// macOS: the documented calls report through `errno` what is no failure
/// here (no waiter to wake, a timeout). A program that reads `errno` after
/// an unlock must find what it was looking for.
#[cfg(target_os = "macos")]
#[test]
fn errno_is_left_alone() {
    let file = std::env::current_exe().unwrap();
    // ENOTDIR, which nothing below reports.
    let error = std::fs::read_dir(file.join("x")).unwrap_err();
    let code = error.raw_os_error();
    assert_eq!(code, Some(20));
    let atomic = AtomicU32::new(0);
    sync::wake_one(&atomic);
    assert_eq!(std::io::Error::last_os_error().raw_os_error(), code);
    sync::wake_all(&atomic);
    assert_eq!(std::io::Error::last_os_error().raw_os_error(), code);
    let outcome = sync::wait(&atomic, 0, Some(Duration::from_millis(1))).unwrap();
    assert_eq!(std::io::Error::last_os_error().raw_os_error(), code);
    // A spurious wake-up is allowed.
    let _ = outcome;
    let outcome = sync::wait(&atomic, 1, None).unwrap();
    assert_eq!(outcome, WaitOutcome::Woken);
    assert_eq!(std::io::Error::last_os_error().raw_os_error(), code);
}