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
//! Clocks and sleeping.
//!
//! - [`now`] reads the wall clock, as a [`Timestamp`].
//! - [`Clock`] names the clocks that only measure intervals: two monotonic
//!   ones, which differ in what they do while the system is suspended, and
//!   the processor time of the process and of the thread.
//! - [`sleep`] and [`sleep_until`] suspend the calling thread.
//!
//! # Reading a clock on Linux
//!
//! Elsewhere a reading is one call into the system's library. On Linux and
//! fullrust it is `clock_gettime`, and the kernel offers a version of it
//! that runs in the process, in the vDSO, the small shared object it maps
//! into every program: for the wall clock and the two monotonic clocks it
//! reads the time without entering the kernel, in a few tens of
//! nanoseconds, as `std::time::Instant::now` does through libc. oscall
//! finds that function itself and calls it, on x86_64, x86, aarch64, arm and
//! riscv64, and makes the system call otherwise:
//!
//! - when there is no vDSO, when it has no such function (riscv32 has none;
//!   a 32-bit ARM kernel has none without a suitable timer; an emulator may
//!   provide none) or when it cannot be found: it is looked for through
//!   `/proc/self/auxv`, since nothing else tells a program without libc
//!   where it is;
//! - when that function does not answer, which the processor time clocks
//!   never let it do and other clocks do not on some systems (a clock source
//!   the vDSO cannot read, some virtual machines).
//!
//! The result is the same either way. The lookup happens once per process,
//! at the first reading, and it opens `/proc/self/auxv` and makes a pipe
//! for a moment: a program that confines itself with a seccomp filter
//! should read a clock once before it installs the filter.

use core::time::Duration;

use crate::Result;
use crate::sys;
// Without `std`, only the documentation names it.
#[cfg_attr(not(feature = "std"), allow(unused_imports))]
use crate::ErrorKind;

const NANOS_PER_SEC: u32 = 1_000_000_000;

/// A point in calendar time: seconds and nanoseconds since the Unix epoch
/// (1970-01-01 00:00:00 UTC), which `secs` may precede.
///
/// The fields are public, so a value can be made whose `nanos` is not below
/// one second. Such a value is no point in time: the methods here return
/// `None` for it, and the functions that take a timestamp fail with
/// [`InvalidInput`](ErrorKind::InvalidInput). The comparisons compare the
/// fields as they are.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Timestamp {
    /// Whole seconds since the epoch; negative before it.
    pub secs: i64,
    /// Nanoseconds after `secs`, always below 1,000,000,000.
    pub nanos: u32,
}

impl Timestamp {
    /// The Unix epoch, 1970-01-01 00:00:00 UTC.
    pub const UNIX_EPOCH: Self = Self { secs: 0, nanos: 0 };

    /// Whether `nanos` is below one second, as it must be.
    const fn is_valid(self) -> bool {
        self.nanos < NANOS_PER_SEC
    }

    /// The time `duration` after `self`, or `None` if it cannot be
    /// represented.
    pub const fn checked_add(self, duration: Duration) -> Option<Self> {
        if !self.is_valid() || duration.as_secs() > i64::MAX as u64 {
            return None;
        }
        let Some(mut secs) = self.secs.checked_add(duration.as_secs() as i64) else {
            return None;
        };
        let mut nanos = self.nanos + duration.subsec_nanos();
        if nanos >= NANOS_PER_SEC {
            nanos -= NANOS_PER_SEC;
            secs = match secs.checked_add(1) {
                Some(secs) => secs,
                None => return None,
            };
        }
        Some(Self { secs, nanos })
    }

    /// The time `duration` before `self`, or `None` if it cannot be
    /// represented.
    pub const fn checked_sub(self, duration: Duration) -> Option<Self> {
        if !self.is_valid() || duration.as_secs() > i64::MAX as u64 {
            return None;
        }
        let Some(mut secs) = self.secs.checked_sub(duration.as_secs() as i64) else {
            return None;
        };
        let mut nanos = self.nanos;
        if nanos < duration.subsec_nanos() {
            nanos += NANOS_PER_SEC;
            secs = match secs.checked_sub(1) {
                Some(secs) => secs,
                None => return None,
            };
        }
        nanos -= duration.subsec_nanos();
        Some(Self { secs, nanos })
    }

    /// The time elapsed from `earlier` to `self`, or `None` if `earlier` is
    /// in fact later than `self`.
    ///
    /// The wall clock can be set, and can go backwards: use a monotonic
    /// [`Clock`] to measure intervals.
    pub const fn duration_since(self, earlier: Self) -> Option<Duration> {
        if !self.is_valid() || !earlier.is_valid() {
            return None;
        }
        // Seconds as i128: the difference of two i64 does not fit in one.
        let mut secs = self.secs as i128 - earlier.secs as i128;
        let mut nanos = self.nanos as i64 - earlier.nanos as i64;
        if nanos < 0 {
            nanos += NANOS_PER_SEC as i64;
            secs -= 1;
        }
        if secs < 0 || secs > u64::MAX as i128 {
            return None;
        }
        Some(Duration::new(secs as u64, nanos as u32))
    }

    /// The time `duration` after the Unix epoch, or `None` if it cannot be
    /// represented.
    pub const fn from_unix(duration: Duration) -> Option<Self> {
        Self::UNIX_EPOCH.checked_add(duration)
    }

    /// The time elapsed since the Unix epoch, or `None` if `self` precedes
    /// it.
    pub const fn to_unix(self) -> Option<Duration> {
        self.duration_since(Self::UNIX_EPOCH)
    }
}

/// The same point in time. Every `SystemTime` has a `Timestamp`.
#[cfg(feature = "std")]
impl From<std::time::SystemTime> for Timestamp {
    fn from(time: std::time::SystemTime) -> Self {
        let epoch = std::time::SystemTime::UNIX_EPOCH;
        let converted = match time.duration_since(epoch) {
            Ok(after) => Self::UNIX_EPOCH.checked_add(after),
            Err(before) => Self::UNIX_EPOCH.checked_sub(before.duration()),
        };
        // No system's `SystemTime` reaches beyond 64-bit seconds.
        converted.unwrap_or(if time < epoch {
            Self {
                secs: i64::MIN,
                nanos: 0,
            }
        } else {
            Self {
                secs: i64::MAX,
                nanos: NANOS_PER_SEC - 1,
            }
        })
    }
}

/// The same point in time, which fails with
/// [`InvalidInput`](ErrorKind::InvalidInput) if the platform's `SystemTime`
/// cannot represent it (Windows' starts in 1601 and counts 100 ns units),
/// or if the nanoseconds of the timestamp are not below one second.
#[cfg(feature = "std")]
impl TryFrom<Timestamp> for std::time::SystemTime {
    type Error = crate::Error;

    fn try_from(time: Timestamp) -> Result<Self> {
        let epoch = Self::UNIX_EPOCH;
        let converted = if !time.is_valid() {
            None
        } else if time.secs >= 0 {
            epoch.checked_add(Duration::new(time.secs as u64, time.nanos))
        } else {
            epoch
                .checked_sub(Duration::from_secs(time.secs.unsigned_abs()))
                .and_then(|t| t.checked_add(Duration::new(0, time.nanos)))
        };
        converted.ok_or(ErrorKind::InvalidInput.into())
    }
}

/// The current time of the wall clock.
///
/// This clock follows the calendar: it can be set, by the user or by time
/// synchronisation, and can therefore jump in either direction. Measure
/// intervals with a [`Clock`] instead.
///
/// Linux: `clock_gettime(CLOCK_REALTIME)`, through the vDSO when it has it
/// (see the [module documentation](self#reading-a-clock-on-linux)); macOS:
/// the same function of `libSystem`; Windows: `GetSystemTimePreciseAsFileTime`; WASI:
/// `clock_time_get(realtime)`.
///
/// Fails with [`Unsupported`](ErrorKind::Unsupported) on WebAssembly without
/// WASI.
pub fn now() -> Result<Timestamp> {
    sys::time::now()
}

/// A clock that measures intervals.
///
/// A reading is a [`Duration`] since an origin that is fixed, at least for
/// the life of the process, but otherwise arbitrary: only the difference of
/// two readings of the same clock means something. No clock here ever goes
/// backwards.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Clock {
    /// Time that passes while the system runs, and **stops while it is
    /// suspended** (sleep, hibernation). This is the clock timeouts are
    /// measured against, and the one `std::time::Instant` reads on Linux and
    /// macOS.
    ///
    /// Linux: `CLOCK_MONOTONIC`, whose rate is adjusted by time
    /// synchronisation (never its value). macOS: `CLOCK_UPTIME_RAW`
    /// (`mach_absolute_time`). Windows:
    /// `QueryUnbiasedInterruptTimePrecise`. WASI: the `monotonic` clock,
    /// whose behaviour across a suspension is the host's.
    Monotonic,
    /// Time that passes whether the system runs or is **suspended**.
    ///
    /// Linux: `CLOCK_BOOTTIME`. macOS: `CLOCK_MONOTONIC_RAW`
    /// (`mach_continuous_time`). Windows: `QueryInterruptTimePrecise`.
    /// WebAssembly has no such clock: reading it fails with
    /// [`Unsupported`](ErrorKind::Unsupported).
    Boottime,
    /// The processor time used by all the threads of the process, in user
    /// and in kernel mode.
    ///
    /// Linux and macOS: `CLOCK_PROCESS_CPUTIME_ID`. Windows:
    /// `GetProcessTimes`, which advances in steps of a scheduler tick
    /// (about 16 ms). WASI: the `process_cputime_id` clock, which few hosts
    /// have (wasmtime does not): reading it then fails with
    /// [`Unsupported`](ErrorKind::Unsupported) or the host's own error.
    ProcessCpu,
    /// The processor time used by the calling thread, in user and in kernel
    /// mode.
    ///
    /// Linux and macOS: `CLOCK_THREAD_CPUTIME_ID`. Windows:
    /// `GetThreadTimes`, in steps of a scheduler tick. WASI: the
    /// `thread_cputime_id` clock, with the same caveat as
    /// [`ProcessCpu`](Clock::ProcessCpu).
    ThreadCpu,
}

impl Clock {
    /// Reads the clock.
    ///
    /// Linux: `clock_gettime`, through the vDSO when it has it (see the
    /// [module documentation](self#reading-a-clock-on-linux)).
    ///
    /// Fails with [`Unsupported`](ErrorKind::Unsupported) on WebAssembly
    /// without WASI, and on WASI for the clocks the host does not have.
    pub fn now(self) -> Result<Duration> {
        sys::time::clock(self)
    }

    /// The resolution of the clock: the smallest step its readings can
    /// advance by. The precision of an actual measurement can be worse.
    ///
    /// Linux and macOS: `clock_getres`. Windows: the period of the
    /// performance counter, but no less than the 100 ns unit readings are
    /// made in, for the monotonic clocks; the scheduler tick
    /// (`GetSystemTimeAdjustment`) for the processor times. WASI:
    /// `clock_res_get`.
    ///
    /// Fails like [`now`](Clock::now).
    pub fn resolution(self) -> Result<Duration> {
        sys::time::resolution(self)
    }
}

/// Suspends the calling thread for at least `duration`.
///
/// A zero duration returns at once. A duration longer than the system can
/// count (centuries) is shortened to what it can.
///
/// On Linux and macOS a signal handler that runs in the thread ends the
/// sleep early, and the call fails with
/// [`Interrupted`](ErrorKind::Interrupted). The time left is not reported:
/// to sleep through interruptions, compute a deadline once
/// (`Clock::Monotonic.now()? + duration`) and call [`sleep_until`] until it
/// succeeds. On Windows and WASI nothing interrupts a sleep.
///
/// Time the system spends suspended does not count towards `duration`
/// on Linux and macOS; whether it does elsewhere is the system's choice.
///
/// Linux: `clock_nanosleep(CLOCK_MONOTONIC)`. macOS: `nanosleep`. Windows: a
/// high-resolution waitable timer, or `Sleep` (rounded up to a millisecond,
/// and to the timer tick) where the system has none (before Windows 10
/// 1803). WASI: `poll_oneoff` on the monotonic clock.
///
/// Fails with [`Unsupported`](ErrorKind::Unsupported) on WebAssembly without
/// WASI.
pub fn sleep(duration: Duration) -> Result<()> {
    if duration.is_zero() {
        return Ok(());
    }
    sys::time::sleep(duration)
}

/// Suspends the calling thread until [`Clock::Monotonic`] reaches
/// `deadline`, and returns at once if it already has.
///
/// Like [`sleep`], it fails with [`Interrupted`](ErrorKind::Interrupted)
/// when a signal handler runs on Linux or macOS; calling it again with the
/// same deadline resumes the sleep without drifting.
///
/// Linux: `clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME)`. Elsewhere the
/// clock is read and the thread sleeps for the difference, as [`sleep`]
/// does.
///
/// Fails with [`Unsupported`](ErrorKind::Unsupported) on WebAssembly without
/// WASI.
pub fn sleep_until(deadline: Duration) -> Result<()> {
    sys::time::sleep_until(deadline)
}