Skip to main content

miri/shims/
time.rs

1use std::ffi::{OsStr, OsString};
2use std::fmt::Write;
3use std::str::FromStr;
4use std::time::{Duration, SystemTime};
5
6use chrono::{DateTime, Datelike, Offset, Timelike, Utc};
7use chrono_tz::Tz;
8use rustc_target::spec::Os;
9
10use crate::*;
11
12/// Returns the time elapsed between the provided time and the unix epoch as a `Duration`.
13pub fn system_time_to_duration<'tcx>(time: &SystemTime) -> InterpResult<'tcx, Duration> {
14    time.duration_since(SystemTime::UNIX_EPOCH)
15        .map_err(|_| err_unsup_format!("times before the Unix epoch are not supported"))
16        .into()
17}
18
19impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
20pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
21    fn parse_clockid(&self, clk_id: Scalar) -> Option<TimeoutClock> {
22        // This clock support is deliberately minimal because a lot of clock types have fiddly
23        // properties (is it possible for Miri to be suspended independently of the host?). If you
24        // have a use for another clock type, please open an issue.
25        let this = self.eval_context_ref();
26
27        // Portable names that exist everywhere.
28        if clk_id == this.eval_libc("CLOCK_REALTIME") {
29            return Some(TimeoutClock::RealTime);
30        } else if clk_id == this.eval_libc("CLOCK_MONOTONIC") {
31            return Some(TimeoutClock::Monotonic);
32        }
33
34        // Some further platform-specific names we support.
35        match &this.tcx.sess.target.os {
36            Os::Linux | Os::FreeBsd | Os::Android => {
37                // Linux further distinguishes regular and "coarse" clocks, but the "coarse" version
38                // is just specified to be "faster and less precise", so we treat it like normal
39                // clocks.
40                if clk_id == this.eval_libc("CLOCK_REALTIME_COARSE") {
41                    return Some(TimeoutClock::RealTime);
42                } else if clk_id == this.eval_libc("CLOCK_MONOTONIC_COARSE") {
43                    return Some(TimeoutClock::Monotonic);
44                }
45            }
46            #[allow(clippy::collapsible_match)] // collapsing would remove symmetry
47            Os::MacOs => {
48                // `CLOCK_UPTIME_RAW` supposed to not increment while the system is asleep... but
49                // that's not really something a program running inside Miri can tell, anyway.
50                // We need to support it because std uses it.
51                if clk_id == this.eval_libc("CLOCK_UPTIME_RAW") {
52                    return Some(TimeoutClock::Monotonic);
53                }
54            }
55            _ => {}
56        }
57
58        None
59    }
60
61    fn clock_gettime(
62        &mut self,
63        clk_id_op: &OpTy<'tcx>,
64        tp_op: &OpTy<'tcx>,
65        dest: &MPlaceTy<'tcx>,
66    ) -> InterpResult<'tcx> {
67        let this = self.eval_context_mut();
68
69        this.assert_target_os_is_unix("clock_gettime");
70
71        let clk_id = this.read_scalar(clk_id_op)?;
72        let tp = this.deref_pointer_as(tp_op, this.libc_ty_layout("timespec"))?;
73
74        let duration = match this.parse_clockid(clk_id) {
75            Some(TimeoutClock::RealTime) => {
76                this.check_no_isolation("`clock_gettime` with `REALTIME` clocks")?;
77                system_time_to_duration(&SystemTime::now())?
78            }
79            Some(TimeoutClock::Monotonic) =>
80                this.machine
81                    .monotonic_clock
82                    .now()
83                    .duration_since(this.machine.monotonic_clock.epoch()),
84            None => {
85                return this.set_errno_and_return_neg1(LibcError("EINVAL"), dest);
86            }
87        };
88
89        let tv_sec = duration.as_secs();
90        let tv_nsec = duration.subsec_nanos();
91
92        this.write_int_fields(&[tv_sec.into(), tv_nsec.into()], &tp)?;
93        this.write_int(0, dest)?;
94
95        interp_ok(())
96    }
97
98    fn gettimeofday(
99        &mut self,
100        tv_op: &OpTy<'tcx>,
101        tz_op: &OpTy<'tcx>,
102    ) -> InterpResult<'tcx, Scalar> {
103        let this = self.eval_context_mut();
104
105        this.assert_target_os_is_unix("gettimeofday");
106        this.check_no_isolation("`gettimeofday`")?;
107
108        let tv = this.deref_pointer_as(tv_op, this.libc_ty_layout("timeval"))?;
109
110        // Using tz is obsolete and should always be null
111        let tz = this.read_pointer(tz_op)?;
112        if !this.ptr_is_null(tz)? {
113            return this.set_errno_and_return_neg1_i32(LibcError("EINVAL"));
114        }
115
116        let duration = system_time_to_duration(&SystemTime::now())?;
117        let tv_sec = duration.as_secs();
118        let tv_usec = duration.subsec_micros();
119
120        this.write_int_fields(&[tv_sec.into(), tv_usec.into()], &tv)?;
121
122        interp_ok(Scalar::from_i32(0))
123    }
124
125    // The localtime() function shall convert the time in seconds since the Epoch pointed to by
126    // timer into a broken-down time, expressed as a local time.
127    // https://linux.die.net/man/3/localtime_r
128    fn localtime_r(
129        &mut self,
130        timep: &OpTy<'tcx>,
131        result_op: &OpTy<'tcx>,
132    ) -> InterpResult<'tcx, Pointer> {
133        let this = self.eval_context_mut();
134
135        this.assert_target_os_is_unix("localtime_r");
136        this.check_no_isolation("`localtime_r`")?;
137
138        let time_layout = this.libc_ty_layout("time_t");
139        let timep = this.deref_pointer_as(timep, time_layout)?;
140        let result = this.deref_pointer_as(result_op, this.libc_ty_layout("tm"))?;
141
142        // The input "represents the number of seconds elapsed since the Epoch,
143        // 1970-01-01 00:00:00 +0000 (UTC)".
144        let sec_since_epoch: i64 =
145            this.read_scalar(&timep)?.to_int(time_layout.size)?.try_into().unwrap();
146        let dt_utc: DateTime<Utc> =
147            DateTime::from_timestamp(sec_since_epoch, 0).expect("Invalid timestamp");
148
149        // Figure out what time zone is in use
150        let tz = this.get_env_var(OsStr::new("TZ"))?.unwrap_or_else(|| OsString::from("UTC"));
151        let tz = match tz.into_string() {
152            Ok(tz) => Tz::from_str(&tz).unwrap_or(Tz::UTC),
153            _ => Tz::UTC,
154        };
155
156        // Convert that to local time, then return the broken-down time value.
157        let dt: DateTime<Tz> = dt_utc.with_timezone(&tz);
158
159        // This value is always set to -1, because there is no way to know if dst is in effect with
160        // chrono crate yet.
161        // This may not be consistent with libc::localtime_r's result.
162        let tm_isdst = -1;
163        this.write_int_fields_named(
164            &[
165                ("tm_sec", dt.second().into()),
166                ("tm_min", dt.minute().into()),
167                ("tm_hour", dt.hour().into()),
168                ("tm_mday", dt.day().into()),
169                ("tm_mon", dt.month0().into()),
170                ("tm_year", dt.year().strict_sub(1900).into()),
171                ("tm_wday", dt.weekday().num_days_from_sunday().into()),
172                ("tm_yday", dt.ordinal0().into()),
173                ("tm_isdst", tm_isdst),
174            ],
175            &result,
176        )?;
177
178        // solaris/illumos system tm struct does not have
179        // the additional tm_zone/tm_gmtoff fields.
180        // https://docs.oracle.com/cd/E36784_01/html/E36874/localtime-r-3c.html
181        if !matches!(&this.tcx.sess.target.os, Os::Solaris | Os::Illumos) {
182            // tm_zone represents the timezone value in the form of: +0730, +08, -0730 or -08.
183            // This may not be consistent with libc::localtime_r's result.
184
185            let offset_in_seconds = dt.offset().fix().local_minus_utc();
186            let tm_gmtoff = offset_in_seconds;
187            let mut tm_zone = String::new();
188            if offset_in_seconds < 0 {
189                tm_zone.push('-');
190            } else {
191                tm_zone.push('+');
192            }
193            let offset_hour = offset_in_seconds.abs() / 3600;
194            write!(tm_zone, "{offset_hour:02}").unwrap();
195            let offset_min = (offset_in_seconds.abs() % 3600) / 60;
196            if offset_min != 0 {
197                write!(tm_zone, "{offset_min:02}").unwrap();
198            }
199
200            // Add null terminator for C string compatibility.
201            tm_zone.push('\0');
202
203            // Deduplicate and allocate the string.
204            let tm_zone_ptr = this.allocate_bytes_dedup(tm_zone.as_bytes())?;
205
206            // Write the timezone pointer and offset into the result structure.
207            this.write_pointer(tm_zone_ptr, &this.project_field_named(&result, "tm_zone")?)?;
208            this.write_int_fields_named(&[("tm_gmtoff", tm_gmtoff.into())], &result)?;
209        }
210        interp_ok(result.ptr())
211    }
212    #[allow(non_snake_case, clippy::arithmetic_side_effects)]
213    fn GetSystemTimeAsFileTime(
214        &mut self,
215        shim_name: &str,
216        LPFILETIME_op: &OpTy<'tcx>,
217    ) -> InterpResult<'tcx> {
218        let this = self.eval_context_mut();
219
220        this.assert_target_os(Os::Windows, shim_name);
221        this.check_no_isolation(shim_name)?;
222
223        let filetime = this.deref_pointer_as(LPFILETIME_op, this.windows_ty_layout("FILETIME"))?;
224
225        let duration = this.system_time_since_windows_epoch(&SystemTime::now())?;
226        let duration_ticks = this.windows_ticks_for(duration)?;
227
228        let dwLowDateTime = u32::try_from(duration_ticks & 0x00000000FFFFFFFF).unwrap();
229        let dwHighDateTime = u32::try_from((duration_ticks & 0xFFFFFFFF00000000) >> 32).unwrap();
230        this.write_int_fields(&[dwLowDateTime.into(), dwHighDateTime.into()], &filetime)?;
231
232        interp_ok(())
233    }
234
235    #[allow(non_snake_case)]
236    fn QueryPerformanceCounter(
237        &mut self,
238        lpPerformanceCount_op: &OpTy<'tcx>,
239    ) -> InterpResult<'tcx, Scalar> {
240        let this = self.eval_context_mut();
241
242        this.assert_target_os(Os::Windows, "QueryPerformanceCounter");
243
244        // QueryPerformanceCounter uses a hardware counter as its basis.
245        // Miri will emulate a counter with a resolution of 1 nanosecond.
246        let duration =
247            this.machine.monotonic_clock.now().duration_since(this.machine.monotonic_clock.epoch());
248        let qpc = i64::try_from(duration.as_nanos()).map_err(|_| {
249            err_unsup_format!("programs running longer than 2^63 nanoseconds are not supported")
250        })?;
251
252        this.write_scalar(
253            Scalar::from_i64(qpc),
254            &this.deref_pointer_as(lpPerformanceCount_op, this.machine.layouts.i64)?,
255        )?;
256        interp_ok(Scalar::from_i32(-1)) // return non-zero on success
257    }
258
259    #[allow(non_snake_case)]
260    fn QueryPerformanceFrequency(
261        &mut self,
262        lpFrequency_op: &OpTy<'tcx>,
263    ) -> InterpResult<'tcx, Scalar> {
264        let this = self.eval_context_mut();
265
266        this.assert_target_os(Os::Windows, "QueryPerformanceFrequency");
267
268        // Retrieves the frequency of the hardware performance counter.
269        // The frequency of the performance counter is fixed at system boot and
270        // is consistent across all processors.
271        // Miri emulates a "hardware" performance counter with a resolution of 1ns,
272        // and thus 10^9 counts per second.
273        this.write_scalar(
274            Scalar::from_i64(1_000_000_000),
275            &this.deref_pointer_as(lpFrequency_op, this.machine.layouts.u64)?,
276        )?;
277        interp_ok(Scalar::from_i32(-1)) // Return non-zero on success
278    }
279
280    #[allow(clippy::arithmetic_side_effects)]
281    fn system_time_since_windows_epoch(&self, time: &SystemTime) -> InterpResult<'tcx, Duration> {
282        // The amount of seconds between 1601/1/1 and 1970/1/1.
283        // See https://learn.microsoft.com/en-us/windows/win32/sysinfo/converting-a-time-t-value-to-a-file-time
284        // (just divide by the number of 100 ns intervals per second).
285        const SECONDS_TO_UNIX_EPOCH: u64 = 11_644_473_600;
286
287        interp_ok(system_time_to_duration(time)? + Duration::from_secs(SECONDS_TO_UNIX_EPOCH))
288    }
289
290    #[allow(non_snake_case, clippy::arithmetic_side_effects)]
291    fn windows_ticks_for(&self, duration: Duration) -> InterpResult<'tcx, u64> {
292        // 1 interval = 100 ns.
293        // See https://learn.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-filetime
294        const NANOS_PER_INTERVAL: u128 = 100;
295
296        let ticks = u64::try_from(duration.as_nanos() / NANOS_PER_INTERVAL)
297            .map_err(|_| err_unsup_format!("programs running more than 2^64 Windows ticks after the Windows epoch are not supported"))?;
298        interp_ok(ticks)
299    }
300
301    fn mach_absolute_time(&self) -> InterpResult<'tcx, Scalar> {
302        let this = self.eval_context_ref();
303
304        this.assert_target_os(Os::MacOs, "mach_absolute_time");
305
306        // This returns a u64, with time units determined dynamically by `mach_timebase_info`.
307        // We return plain nanoseconds.
308        let duration =
309            this.machine.monotonic_clock.now().duration_since(this.machine.monotonic_clock.epoch());
310        let res = u64::try_from(duration.as_nanos()).map_err(|_| {
311            err_unsup_format!("programs running longer than 2^64 nanoseconds are not supported")
312        })?;
313        interp_ok(Scalar::from_u64(res))
314    }
315
316    fn mach_timebase_info(&mut self, info_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
317        let this = self.eval_context_mut();
318
319        this.assert_target_os(Os::MacOs, "mach_timebase_info");
320
321        let info = this.deref_pointer_as(info_op, this.libc_ty_layout("mach_timebase_info"))?;
322
323        // Since our emulated ticks in `mach_absolute_time` *are* nanoseconds,
324        // no scaling needs to happen.
325        let (numerator, denom) = (1, 1);
326        this.write_int_fields(&[numerator.into(), denom.into()], &info)?;
327
328        interp_ok(Scalar::from_i32(0)) // KERN_SUCCESS
329    }
330
331    fn mach_wait_until(&mut self, deadline_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
332        let this = self.eval_context_mut();
333
334        this.assert_target_os(Os::MacOs, "mach_wait_until");
335
336        let deadline = this.read_scalar(deadline_op)?.to_u64()?;
337        // Our mach_absolute_time "ticks" are plain nanoseconds.
338        let deadline = Duration::from_nanos(deadline);
339        // This is *absolute* time.
340        let deadline = this.machine.monotonic_clock.epoch().add_lossy(deadline);
341
342        this.block_thread(
343            BlockReason::Sleep,
344            Some(deadline.into()),
345            callback!(
346                @capture<'tcx> {}
347                |_this, unblock: UnblockKind| {
348                    assert_eq!(unblock, UnblockKind::TimedOut);
349                    interp_ok(())
350                }
351            ),
352        );
353
354        interp_ok(Scalar::from_i32(0)) // KERN_SUCCESS
355    }
356
357    fn nanosleep(&mut self, duration: &OpTy<'tcx>, rem: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
358        let this = self.eval_context_mut();
359
360        this.assert_target_os_is_unix("nanosleep");
361
362        let duration = this.deref_pointer_as(duration, this.libc_ty_layout("timespec"))?;
363        let _rem = this.read_pointer(rem)?; // Signal handlers are not supported, so rem will never be written to.
364
365        let Some(duration) = this.read_timespec(&duration)? else {
366            return this.set_errno_and_return_neg1_i32(LibcError("EINVAL"));
367        };
368        let deadline = this.machine.monotonic_clock.now().add_lossy(duration);
369
370        this.block_thread(
371            BlockReason::Sleep,
372            Some(deadline.into()),
373            callback!(
374                @capture<'tcx> {}
375                |_this, unblock: UnblockKind| {
376                    assert_eq!(unblock, UnblockKind::TimedOut);
377                    interp_ok(())
378                }
379            ),
380        );
381        interp_ok(Scalar::from_i32(0))
382    }
383
384    fn clock_nanosleep(
385        &mut self,
386        clock_id: &OpTy<'tcx>,
387        flags: &OpTy<'tcx>,
388        timespec: &OpTy<'tcx>,
389        rem: &OpTy<'tcx>,
390    ) -> InterpResult<'tcx, Scalar> {
391        let this = self.eval_context_mut();
392        let clockid_t_size = this.libc_ty_layout("clockid_t").size;
393
394        let clock_id = this.read_scalar(clock_id)?.to_int(clockid_t_size)?;
395        let timespec = this.deref_pointer_as(timespec, this.libc_ty_layout("timespec"))?;
396        let flags = this.read_scalar(flags)?.to_i32()?;
397        let _rem = this.read_pointer(rem)?; // Signal handlers are not supported, so rem will never be written to.
398
399        // The standard lib through sleep_until only needs CLOCK_MONOTONIC
400        if clock_id != this.eval_libc("CLOCK_MONOTONIC").to_int(clockid_t_size)? {
401            throw_unsup_format!("clock_nanosleep: only CLOCK_MONOTONIC is supported");
402        }
403
404        let Some(duration) = this.read_timespec(&timespec)? else {
405            return this.set_errno_and_return_neg1_i32(LibcError("EINVAL"));
406        };
407
408        let timeout_style = if flags == 0 {
409            // No flags set, the timespec should be interpreted as a duration
410            // to sleep for, i.e., a relative time.
411            TimeoutStyle::Relative
412        } else if flags == this.eval_libc_i32("TIMER_ABSTIME") {
413            // Only flag TIMER_ABSTIME set, the timespec should be interpreted as
414            // an absolute time.
415            TimeoutStyle::Absolute
416        } else {
417            // The standard lib (through `sleep_until`) only needs TIMER_ABSTIME
418            throw_unsup_format!(
419                "`clock_nanosleep` unsupported flags {flags}, only no flags or \
420                TIMER_ABSTIME is supported"
421            );
422        };
423        let deadline = this.machine.timeout(TimeoutClock::Monotonic, timeout_style, duration);
424
425        this.block_thread(
426            BlockReason::Sleep,
427            Some(deadline),
428            callback!(
429                @capture<'tcx> {}
430                |_this, unblock: UnblockKind| {
431                    assert_eq!(unblock, UnblockKind::TimedOut);
432                    interp_ok(())
433                }
434            ),
435        );
436        interp_ok(Scalar::from_i32(0))
437    }
438
439    #[allow(non_snake_case)]
440    fn Sleep(&mut self, timeout: &OpTy<'tcx>) -> InterpResult<'tcx> {
441        let this = self.eval_context_mut();
442
443        this.assert_target_os(Os::Windows, "Sleep");
444
445        let timeout_ms = this.read_scalar(timeout)?.to_u32()?;
446
447        let duration = Duration::from_millis(timeout_ms.into());
448        let deadline = this.machine.monotonic_clock.now().add_lossy(duration);
449
450        this.block_thread(
451            BlockReason::Sleep,
452            Some(deadline.into()),
453            callback!(
454                @capture<'tcx> {}
455                |_this, unblock: UnblockKind| {
456                    assert_eq!(unblock, UnblockKind::TimedOut);
457                    interp_ok(())
458                }
459            ),
460        );
461        interp_ok(())
462    }
463
464    /// Parse a `timespec` struct and return it as a [`Duration`]. It returns [`None`]
465    /// if the value in the `timespec` struct is invalid. Some libc functions will return
466    /// EINVAL in this case.
467    fn read_timespec(&self, tp: &MPlaceTy<'tcx>) -> InterpResult<'tcx, Option<Duration>> {
468        let this = self.eval_context_ref();
469        let sec_field = this.project_field_named(tp, "tv_sec")?;
470        let sec = this.read_scalar(&sec_field)?.to_int(sec_field.layout.size)?;
471        let nsec_field = this.project_field_named(tp, "tv_nsec")?;
472        let nsec = this.read_scalar(&nsec_field)?.to_int(nsec_field.layout.size)?;
473
474        interp_ok(try {
475            // tv_sec must be non-negative.
476            let seconds: u64 = sec.try_into().ok()?;
477            // tv_nsec must be non-negative.
478            let nanoseconds: u32 = nsec.try_into().ok()?;
479            if nanoseconds >= 1_000_000_000 {
480                // tv_nsec must not be greater than 999,999,999.
481                None?
482            }
483            Duration::new(seconds, nanoseconds)
484        })
485    }
486
487    /// Parse a `timeval` struct and return it as a [`Duration`]. It returns [`None`]
488    /// if the value in the `timeval` struct is invalid. Some libc functions will return
489    /// EINVAL in this case.
490    fn read_timeval(&mut self, tp: &MPlaceTy<'tcx>) -> InterpResult<'tcx, Option<Duration>> {
491        let this = self.eval_context_mut();
492        let sec_field = this.project_field_named(tp, "tv_sec")?;
493        let sec = this.read_scalar(&sec_field)?.to_int(sec_field.layout.size)?;
494
495        let usec_field = this.project_field_named(tp, "tv_usec")?;
496        let usec = this.read_scalar(&usec_field)?.to_int(usec_field.layout.size)?;
497
498        interp_ok(try {
499            // tv_sec must be non-negative.
500            let seconds: u64 = sec.try_into().ok()?;
501            // tv_usec must be non-negative.
502            let microseconds: u32 = usec.try_into().ok()?;
503            if microseconds >= 1_000_000 {
504                // tv_usec must not be greater than 999,999.
505                None?
506            }
507            Duration::new(seconds, microseconds.strict_mul(1000))
508        })
509    }
510}