Skip to main content

libc_rs/
time.rs

1//! Clocks, timestamps, and high-resolution sleep syscalls.
2
3use core::mem::size_of;
4
5use crate::errno::SysResult;
6use crate::raw::{nr, syscall2, syscall4};
7
8/// System-wide real-time clock identifier.
9pub const CLOCK_REALTIME: i32 = 0;
10/// Monotonic clock identifier (cannot jump backwards).
11pub const CLOCK_MONOTONIC: i32 = 1;
12/// Flag indicating an absolute target time for `clock_nanosleep`.
13pub const TIMER_ABSTIME: i32 = 1;
14
15/// Seconds and nanoseconds timestamp matching the 64-bit kernel `struct timespec`.
16#[repr(C)]
17#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
18pub struct Timespec {
19    pub tv_sec: i64,
20    pub tv_nsec: i64,
21}
22
23/// Seconds and microseconds timestamp matching the 64-bit kernel `struct timeval`.
24#[repr(C)]
25#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
26pub struct Timeval {
27    pub tv_sec: i64,
28    pub tv_usec: i64,
29}
30
31const _: () = {
32    assert!(size_of::<Timespec>() == 16);
33    assert!(size_of::<Timeval>() == 16);
34};
35
36/// Queries the current value of `clock_id`.
37pub fn clock_gettime(clock_id: i32) -> SysResult<Timespec> {
38    let mut ts = Timespec::default();
39    // SAFETY: `ts` is a valid, aligned stack `Timespec` for the kernel to write into.
40    unsafe {
41        syscall2(
42            nr::CLOCK_GETTIME,
43            clock_id as usize,
44            core::ptr::from_mut(&mut ts) as usize,
45        )?;
46    }
47    Ok(ts)
48}
49
50/// Sets the time of `clock_id` to `ts`.
51pub fn clock_settime(clock_id: i32, ts: &Timespec) -> SysResult<()> {
52    // SAFETY: `ts` is a valid shared reference to a `Timespec`.
53    unsafe {
54        syscall2(
55            nr::CLOCK_SETTIME,
56            clock_id as usize,
57            core::ptr::from_ref(ts) as usize,
58        )?;
59    }
60    Ok(())
61}
62
63/// Sleeps for the relative interval `req` on `CLOCK_MONOTONIC`, optionally writing
64/// any remaining duration into `rem` if interrupted.
65pub fn nanosleep(req: &Timespec, rem: Option<&mut Timespec>) -> SysResult<()> {
66    let rem_ptr = rem.map_or(0, |r| core::ptr::from_mut(r) as usize);
67    // SAFETY: `req` is a valid `Timespec` reference and `rem_ptr` is either 0 (null)
68    // or a valid mutable `Timespec` pointer.
69    unsafe {
70        syscall4(
71            nr::CLOCK_NANOSLEEP,
72            CLOCK_MONOTONIC as usize,
73            0,
74            core::ptr::from_ref(req) as usize,
75            rem_ptr,
76        )?;
77    }
78    Ok(())
79}
80
81#[cfg(test)]
82mod tests {
83    use super::*;
84    use crate::raw::with_mock_syscall;
85
86    #[test]
87    fn clock_gettime_and_nanosleep_pass_expected_arguments() {
88        let ts = with_mock_syscall(
89            |sysno, args| {
90                assert_eq!(sysno, nr::CLOCK_GETTIME);
91                assert_eq!(args[0], CLOCK_MONOTONIC as usize);
92                let out = args[1] as *mut Timespec;
93                // SAFETY: `out` points to the stack `Timespec` in `clock_gettime`.
94                unsafe {
95                    *out = Timespec {
96                        tv_sec: 42,
97                        tv_nsec: 123_456_789,
98                    };
99                }
100                Ok(0)
101            },
102            || clock_gettime(CLOCK_MONOTONIC).unwrap(),
103        );
104        assert_eq!(
105            ts,
106            Timespec {
107                tv_sec: 42,
108                tv_nsec: 123_456_789,
109            }
110        );
111
112        const REQ: Timespec = Timespec {
113            tv_sec: 1,
114            tv_nsec: 500,
115        };
116        let mut rem = Timespec::default();
117        with_mock_syscall(
118            |sysno, args| {
119                assert_eq!(sysno, nr::CLOCK_NANOSLEEP);
120                assert_eq!(args[0], CLOCK_MONOTONIC as usize);
121                assert_eq!(args[1], 0);
122                let req_ptr = args[2] as *const Timespec;
123                // SAFETY: `req_ptr` points to `REQ`.
124                assert_eq!(unsafe { *req_ptr }, REQ);
125                assert!(args[3] != 0);
126                Ok(0)
127            },
128            || nanosleep(&REQ, Some(&mut rem)).unwrap(),
129        );
130    }
131}