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