1 use std::time::{Duration, SystemTime};
3 use crate::concurrency::thread::MachineCallback;
6 /// Returns the time elapsed between the provided time and the unix epoch as a `Duration`.
7 pub fn system_time_to_duration<'tcx>(time: &SystemTime) -> InterpResult<'tcx, Duration> {
8 time.duration_since(SystemTime::UNIX_EPOCH)
9 .map_err(|_| err_unsup_format!("times before the Unix epoch are not supported").into())
12 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {}
13 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
16 clk_id_op: &OpTy<'tcx, Provenance>,
17 tp_op: &OpTy<'tcx, Provenance>,
18 ) -> InterpResult<'tcx, Scalar<Provenance>> {
19 // This clock support is deliberately minimal because a lot of clock types have fiddly
20 // properties (is it possible for Miri to be suspended independently of the host?). If you
21 // have a use for another clock type, please open an issue.
23 let this = self.eval_context_mut();
25 this.assert_target_os("linux", "clock_gettime");
27 let clk_id = this.read_scalar(clk_id_op)?.to_i32()?;
29 // Linux has two main kinds of clocks. REALTIME clocks return the actual time since the
30 // Unix epoch, including effects which may cause time to move backwards such as NTP.
31 // Linux further distinguishes regular and "coarse" clocks, but the "coarse" version
32 // is just specified to be "faster and less precise", so we implement both the same way.
34 [this.eval_libc_i32("CLOCK_REALTIME")?, this.eval_libc_i32("CLOCK_REALTIME_COARSE")?];
35 // The second kind is MONOTONIC clocks for which 0 is an arbitrary time point, but they are
36 // never allowed to go backwards. We don't need to do any additonal monotonicity
37 // enforcement because std::time::Instant already guarantees that it is monotonic.
39 [this.eval_libc_i32("CLOCK_MONOTONIC")?, this.eval_libc_i32("CLOCK_MONOTONIC_COARSE")?];
41 let duration = if absolute_clocks.contains(&clk_id) {
42 this.check_no_isolation("`clock_gettime` with `REALTIME` clocks")?;
43 system_time_to_duration(&SystemTime::now())?
44 } else if relative_clocks.contains(&clk_id) {
45 this.machine.clock.now().duration_since(this.machine.clock.anchor())
47 let einval = this.eval_libc("EINVAL")?;
48 this.set_last_error(einval)?;
49 return Ok(Scalar::from_i32(-1));
52 let tv_sec = duration.as_secs();
53 let tv_nsec = duration.subsec_nanos();
55 this.write_int_fields(&[tv_sec.into(), tv_nsec.into()], &this.deref_operand(tp_op)?)?;
57 Ok(Scalar::from_i32(0))
62 tv_op: &OpTy<'tcx, Provenance>,
63 tz_op: &OpTy<'tcx, Provenance>,
64 ) -> InterpResult<'tcx, i32> {
65 let this = self.eval_context_mut();
67 this.assert_target_os_is_unix("gettimeofday");
68 this.check_no_isolation("`gettimeofday`")?;
70 // Using tz is obsolete and should always be null
71 let tz = this.read_pointer(tz_op)?;
72 if !this.ptr_is_null(tz)? {
73 let einval = this.eval_libc("EINVAL")?;
74 this.set_last_error(einval)?;
78 let duration = system_time_to_duration(&SystemTime::now())?;
79 let tv_sec = duration.as_secs();
80 let tv_usec = duration.subsec_micros();
82 this.write_int_fields(&[tv_sec.into(), tv_usec.into()], &this.deref_operand(tv_op)?)?;
87 #[allow(non_snake_case, clippy::integer_arithmetic)]
88 fn GetSystemTimeAsFileTime(
90 LPFILETIME_op: &OpTy<'tcx, Provenance>,
91 ) -> InterpResult<'tcx> {
92 let this = self.eval_context_mut();
94 this.assert_target_os("windows", "GetSystemTimeAsFileTime");
95 this.check_no_isolation("`GetSystemTimeAsFileTime`")?;
97 let NANOS_PER_SEC = this.eval_windows_u64("time", "NANOS_PER_SEC")?;
98 let INTERVALS_PER_SEC = this.eval_windows_u64("time", "INTERVALS_PER_SEC")?;
99 let INTERVALS_TO_UNIX_EPOCH = this.eval_windows_u64("time", "INTERVALS_TO_UNIX_EPOCH")?;
100 let NANOS_PER_INTERVAL = NANOS_PER_SEC / INTERVALS_PER_SEC;
101 let SECONDS_TO_UNIX_EPOCH = INTERVALS_TO_UNIX_EPOCH / INTERVALS_PER_SEC;
103 let duration = system_time_to_duration(&SystemTime::now())?
104 + Duration::from_secs(SECONDS_TO_UNIX_EPOCH);
105 let duration_ticks = u64::try_from(duration.as_nanos() / u128::from(NANOS_PER_INTERVAL))
106 .map_err(|_| err_unsup_format!("programs running more than 2^64 Windows ticks after the Windows epoch are not supported"))?;
108 let dwLowDateTime = u32::try_from(duration_ticks & 0x00000000FFFFFFFF).unwrap();
109 let dwHighDateTime = u32::try_from((duration_ticks & 0xFFFFFFFF00000000) >> 32).unwrap();
110 this.write_int_fields(
111 &[dwLowDateTime.into(), dwHighDateTime.into()],
112 &this.deref_operand(LPFILETIME_op)?,
118 #[allow(non_snake_case)]
119 fn QueryPerformanceCounter(
121 lpPerformanceCount_op: &OpTy<'tcx, Provenance>,
122 ) -> InterpResult<'tcx, Scalar<Provenance>> {
123 let this = self.eval_context_mut();
125 this.assert_target_os("windows", "QueryPerformanceCounter");
127 // QueryPerformanceCounter uses a hardware counter as its basis.
128 // Miri will emulate a counter with a resolution of 1 nanosecond.
129 let duration = this.machine.clock.now().duration_since(this.machine.clock.anchor());
130 let qpc = i64::try_from(duration.as_nanos()).map_err(|_| {
131 err_unsup_format!("programs running longer than 2^63 nanoseconds are not supported")
134 Scalar::from_i64(qpc),
135 &this.deref_operand(lpPerformanceCount_op)?.into(),
137 Ok(Scalar::from_i32(-1)) // return non-zero on success
140 #[allow(non_snake_case)]
141 fn QueryPerformanceFrequency(
143 lpFrequency_op: &OpTy<'tcx, Provenance>,
144 ) -> InterpResult<'tcx, Scalar<Provenance>> {
145 let this = self.eval_context_mut();
147 this.assert_target_os("windows", "QueryPerformanceFrequency");
149 // Retrieves the frequency of the hardware performance counter.
150 // The frequency of the performance counter is fixed at system boot and
151 // is consistent across all processors.
152 // Miri emulates a "hardware" performance counter with a resolution of 1ns,
153 // and thus 10^9 counts per second.
155 Scalar::from_i64(1_000_000_000),
156 &this.deref_operand(lpFrequency_op)?.into(),
158 Ok(Scalar::from_i32(-1)) // Return non-zero on success
161 fn mach_absolute_time(&self) -> InterpResult<'tcx, Scalar<Provenance>> {
162 let this = self.eval_context_ref();
164 this.assert_target_os("macos", "mach_absolute_time");
166 // This returns a u64, with time units determined dynamically by `mach_timebase_info`.
167 // We return plain nanoseconds.
168 let duration = this.machine.clock.now().duration_since(this.machine.clock.anchor());
169 let res = u64::try_from(duration.as_nanos()).map_err(|_| {
170 err_unsup_format!("programs running longer than 2^64 nanoseconds are not supported")
172 Ok(Scalar::from_u64(res))
175 fn mach_timebase_info(
177 info_op: &OpTy<'tcx, Provenance>,
178 ) -> InterpResult<'tcx, Scalar<Provenance>> {
179 let this = self.eval_context_mut();
181 this.assert_target_os("macos", "mach_timebase_info");
183 let info = this.deref_operand(info_op)?;
185 // Since our emulated ticks in `mach_absolute_time` *are* nanoseconds,
186 // no scaling needs to happen.
187 let (numer, denom) = (1, 1);
188 this.write_int_fields(&[numer.into(), denom.into()], &info)?;
190 Ok(Scalar::from_i32(0)) // KERN_SUCCESS
195 req_op: &OpTy<'tcx, Provenance>,
196 _rem: &OpTy<'tcx, Provenance>, // Signal handlers are not supported, so rem will never be written to.
197 ) -> InterpResult<'tcx, i32> {
198 let this = self.eval_context_mut();
200 this.assert_target_os_is_unix("nanosleep");
202 let duration = match this.read_timespec(&this.deref_operand(req_op)?)? {
203 Some(duration) => duration,
205 let einval = this.eval_libc("EINVAL")?;
206 this.set_last_error(einval)?;
210 // If adding the duration overflows, let's just sleep for an hour. Waking up early is always acceptable.
211 let now = this.machine.clock.now();
212 let timeout_time = now
213 .checked_add(duration)
214 .unwrap_or_else(|| now.checked_add(Duration::from_secs(3600)).unwrap());
216 let active_thread = this.get_active_thread();
217 this.block_thread(active_thread);
219 this.register_timeout_callback(
221 Time::Monotonic(timeout_time),
222 Box::new(UnblockCallback { thread_to_unblock: active_thread }),
228 #[allow(non_snake_case)]
229 fn Sleep(&mut self, timeout: &OpTy<'tcx, Provenance>) -> InterpResult<'tcx> {
230 let this = self.eval_context_mut();
232 this.assert_target_os("windows", "Sleep");
234 let timeout_ms = this.read_scalar(timeout)?.to_u32()?;
236 let duration = Duration::from_millis(timeout_ms.into());
237 let timeout_time = this.machine.clock.now().checked_add(duration).unwrap();
239 let active_thread = this.get_active_thread();
240 this.block_thread(active_thread);
242 this.register_timeout_callback(
244 Time::Monotonic(timeout_time),
245 Box::new(UnblockCallback { thread_to_unblock: active_thread }),
252 struct UnblockCallback {
253 thread_to_unblock: ThreadId,
256 impl VisitTags for UnblockCallback {
257 fn visit_tags(&self, _visit: &mut dyn FnMut(SbTag)) {}
260 impl<'mir, 'tcx: 'mir> MachineCallback<'mir, 'tcx> for UnblockCallback {
261 fn call(&self, ecx: &mut MiriInterpCx<'mir, 'tcx>) -> InterpResult<'tcx> {
262 ecx.unblock_thread(self.thread_to_unblock);