oscall 0.0.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! `time` on Windows: the precise system and interrupt times, process and
//! thread times, and a high-resolution waitable timer to sleep.

use core::ffi::c_void;
use core::time::Duration;

use crate::sys::{cvt, dll, last_error};
use crate::time::{Clock, Timestamp};
use crate::{ErrorKind, Result};

/// Seconds from 1601-01-01, the origin of `FILETIME`, to the Unix epoch.
const EPOCH_DIFFERENCE: i64 = 11_644_473_600;
/// The 100 ns units of `FILETIME` and of the interrupt time, per second.
const UNITS_PER_SEC: u64 = 10_000_000;

/// The longest wait asked of a timer at once: 14,000 years.
const MAX_TIMER_UNITS: u64 = i64::MAX as u64 / 2;

const CREATE_WAITABLE_TIMER_HIGH_RESOLUTION: u32 = 2;
const TIMER_ALL_ACCESS: u32 = 0x1F0003;
const INFINITE: u32 = u32::MAX;
const WAIT_OBJECT_0: u32 = 0;

/// `FILETIME`.
#[repr(C)]
#[derive(Clone, Copy, Default)]
struct FileTime {
    low: u32,
    high: u32,
}

impl FileTime {
    fn units(self) -> u64 {
        (self.high as u64) << 32 | self.low as u64
    }
}

dll!("kernel32.dll" {
    fn GetSystemTimePreciseAsFileTime(time: *mut FileTime);
    fn GetCurrentProcess() -> *mut c_void;
    fn GetCurrentThread() -> *mut c_void;
    fn GetProcessTimes(
        process: *mut c_void,
        creation: *mut FileTime,
        exit: *mut FileTime,
        kernel: *mut FileTime,
        user: *mut FileTime,
    ) -> i32;
    fn GetThreadTimes(
        thread: *mut c_void,
        creation: *mut FileTime,
        exit: *mut FileTime,
        kernel: *mut FileTime,
        user: *mut FileTime,
    ) -> i32;
    fn GetSystemTimeAdjustment(
        adjustment: *mut u32,
        increment: *mut u32,
        disabled: *mut i32,
    ) -> i32;
    fn QueryPerformanceFrequency(frequency: *mut i64) -> i32;
    fn CreateWaitableTimerExW(
        attributes: *const c_void,
        name: *const u16,
        flags: u32,
        access: u32,
    ) -> *mut c_void;
    fn SetWaitableTimer(
        timer: *mut c_void,
        due: *const i64,
        period: i32,
        routine: *const c_void,
        argument: *const c_void,
        resume: i32,
    ) -> i32;
    fn WaitForSingleObject(handle: *mut c_void, milliseconds: u32) -> u32;
    fn CloseHandle(handle: *mut c_void) -> i32;
    fn Sleep(milliseconds: u32);
});

dll!("api-ms-win-core-realtime-l1-1-1.dll" {
    fn QueryInterruptTimePrecise(time: *mut u64);
    fn QueryUnbiasedInterruptTimePrecise(time: *mut u64);
});

fn from_units(units: u64) -> Duration {
    Duration::new(units / UNITS_PER_SEC, (units % UNITS_PER_SEC) as u32 * 100)
}

pub(crate) fn now() -> Result<Timestamp> {
    let mut time = FileTime::default();
    // SAFETY: the function writes one `FILETIME`.
    unsafe { GetSystemTimePreciseAsFileTime(&raw mut time) };
    let units = time.units();
    Ok(Timestamp {
        secs: (units / UNITS_PER_SEC) as i64 - EPOCH_DIFFERENCE,
        nanos: (units % UNITS_PER_SEC) as u32 * 100,
    })
}

/// The unbiased interrupt time: the 100 ns units the system has run for, not
/// counting suspension.
pub(crate) fn unbiased() -> u64 {
    let mut units = 0;
    // SAFETY: the function writes one `u64`.
    unsafe { QueryUnbiasedInterruptTimePrecise(&raw mut units) };
    units
}

pub(crate) fn clock(clock: Clock) -> Result<Duration> {
    let units = match clock {
        Clock::Monotonic => unbiased(),
        Clock::Boottime => {
            let mut units = 0;
            // SAFETY: the function writes one `u64`.
            unsafe { QueryInterruptTimePrecise(&raw mut units) };
            units
        }
        Clock::ProcessCpu | Clock::ThreadCpu => {
            let mut times = [FileTime::default(); 4];
            let [creation, exit, kernel, user] = &mut times;
            // SAFETY: the pseudo-handle of the current process or thread is
            // always valid, and the function writes four `FILETIME`s.
            cvt(unsafe {
                if clock == Clock::ProcessCpu {
                    GetProcessTimes(GetCurrentProcess(), creation, exit, kernel, user)
                } else {
                    GetThreadTimes(GetCurrentThread(), creation, exit, kernel, user)
                }
            })?;
            times[2].units().saturating_add(times[3].units())
        }
    };
    Ok(from_units(units))
}

pub(crate) fn resolution(clock: Clock) -> Result<Duration> {
    match clock {
        Clock::Monotonic | Clock::Boottime => {
            let mut frequency = 0;
            // SAFETY: the function writes one `i64`.
            cvt(unsafe { QueryPerformanceFrequency(&raw mut frequency) })?;
            if frequency <= 0 {
                return Err(ErrorKind::Other.into());
            }
            let nanos = 1_000_000_000u64.div_ceil(frequency as u64);
            Ok(Duration::from_nanos(nanos.max(100)))
        }
        Clock::ProcessCpu | Clock::ThreadCpu => {
            let (mut adjustment, mut increment, mut disabled) = (0, 0, 0);
            // SAFETY: the function writes the three values.
            cvt(unsafe {
                GetSystemTimeAdjustment(&raw mut adjustment, &raw mut increment, &raw mut disabled)
            })?;
            Ok(from_units(increment.into()))
        }
    }
}

/// Waits `units` (100 ns each, at least one) on a high-resolution timer.
/// Fails if the system has no such timer (before Windows 10 1803).
fn timer_sleep(units: u64) -> Result<()> {
    // SAFETY: an unnamed timer with default security.
    let timer = unsafe {
        CreateWaitableTimerExW(
            core::ptr::null(),
            core::ptr::null(),
            CREATE_WAITABLE_TIMER_HIGH_RESOLUTION,
            TIMER_ALL_ACCESS,
        )
    };
    if timer.is_null() {
        return Err(last_error());
    }
    // A negative due time is relative.
    let due = -i64::try_from(units).unwrap_or(i64::MAX);
    // SAFETY: `timer` is the timer created above; no completion routine.
    let set = cvt(unsafe {
        SetWaitableTimer(
            timer,
            &raw const due,
            0,
            core::ptr::null(),
            core::ptr::null(),
            0,
        )
    });
    let waited = set.and_then(|()| {
        // SAFETY: `timer` is open.
        match unsafe { WaitForSingleObject(timer, INFINITE) } {
            WAIT_OBJECT_0 => Ok(()),
            _ => Err(last_error()),
        }
    });
    // SAFETY: `timer` is open and not used afterwards.
    unsafe { CloseHandle(timer) };
    waited
}

/// Sleeps until the unbiased interrupt time reaches `deadline`.
///
/// This loops, which the timer alone would not need: `Sleep` counts in timer
/// ticks and returns up to one tick early, and neither primitive is
/// specified against the clock `Clock::Monotonic` reads.
fn sleep_until_units(deadline: u64) -> Result<()> {
    let mut high_resolution = true;
    loop {
        let now = unbiased();
        if now >= deadline {
            return Ok(());
        }
        // No more at a time than the timer surely counts: it adds the
        // wait to a clock of its own, in 63 bits.
        let left = (deadline - now).min(MAX_TIMER_UNITS);
        if high_resolution && timer_sleep(left).is_err() {
            high_resolution = false;
        }
        if !high_resolution {
            let milliseconds = left.div_ceil(10_000).min((INFINITE - 1).into()) as u32;
            // SAFETY: Sleep has no requirement; the wait is not alertable.
            unsafe { Sleep(milliseconds) };
        }
    }
}

pub(crate) fn to_units(duration: Duration) -> u64 {
    // No more than the timer can count: 29,000 years.
    duration.as_nanos().div_ceil(100).min(i64::MAX as u128) as u64
}

pub(crate) fn sleep(duration: Duration) -> Result<()> {
    sleep_until_units(unbiased().saturating_add(to_units(duration)))
}

pub(crate) fn sleep_until(deadline: Duration) -> Result<()> {
    sleep_until_units(to_units(deadline))
}