1 use std::time::{Duration, SystemTime, Instant};
2 use std::convert::TryFrom;
4 use crate::stacked_borrows::Tag;
6 use helpers::{immty_from_int_checked, immty_from_uint_checked};
9 /// Returns the time elapsed between the provided time and the unix epoch as a `Duration`.
10 pub fn system_time_to_duration<'tcx>(time: &SystemTime) -> InterpResult<'tcx, Duration> {
11 time.duration_since(SystemTime::UNIX_EPOCH)
12 .map_err(|_| err_unsup_format!("times before the Unix epoch are not supported").into())
15 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
16 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
19 clk_id_op: OpTy<'tcx, Tag>,
20 tp_op: OpTy<'tcx, Tag>,
21 ) -> InterpResult<'tcx, i32> {
22 let this = self.eval_context_mut();
24 this.assert_target_os("linux", "clock_gettime");
25 this.check_no_isolation("clock_gettime")?;
27 let clk_id = this.read_scalar(clk_id_op)?.to_i32()?;
28 let tp = this.deref_operand(tp_op)?;
30 let duration = if clk_id == this.eval_libc_i32("CLOCK_REALTIME")? {
31 system_time_to_duration(&SystemTime::now())?
32 } else if clk_id == this.eval_libc_i32("CLOCK_MONOTONIC")? {
33 // Absolute time does not matter, only relative time does, so we can just
34 // use our own time anchor here.
35 Instant::now().duration_since(this.machine.time_anchor)
37 let einval = this.eval_libc("EINVAL")?;
38 this.set_last_error(einval)?;
42 let tv_sec = duration.as_secs();
43 let tv_nsec = duration.subsec_nanos();
46 immty_from_int_checked(tv_sec, this.libc_ty_layout("time_t")?)?,
47 immty_from_int_checked(tv_nsec, this.libc_ty_layout("c_long")?)?,
50 this.write_packed_immediates(tp, &imms)?;
57 tv_op: OpTy<'tcx, Tag>,
58 tz_op: OpTy<'tcx, Tag>,
59 ) -> InterpResult<'tcx, i32> {
60 let this = self.eval_context_mut();
62 this.assert_target_os("macos", "gettimeofday");
63 this.check_no_isolation("gettimeofday")?;
65 // Using tz is obsolete and should always be null
66 let tz = this.read_scalar(tz_op)?.check_init()?;
67 if !this.is_null(tz)? {
68 let einval = this.eval_libc("EINVAL")?;
69 this.set_last_error(einval)?;
73 let tv = this.deref_operand(tv_op)?;
75 let duration = system_time_to_duration(&SystemTime::now())?;
76 let tv_sec = duration.as_secs();
77 let tv_usec = duration.subsec_micros();
80 immty_from_int_checked(tv_sec, this.libc_ty_layout("time_t")?)?,
81 immty_from_int_checked(tv_usec, this.libc_ty_layout("suseconds_t")?)?,
84 this.write_packed_immediates(tv, &imms)?;
89 #[allow(non_snake_case)]
90 fn GetSystemTimeAsFileTime(&mut self, LPFILETIME_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx> {
91 let this = self.eval_context_mut();
93 this.assert_target_os("windows", "GetSystemTimeAsFileTime");
94 this.check_no_isolation("GetSystemTimeAsFileTime")?;
96 let NANOS_PER_SEC = this.eval_windows_u64("time", "NANOS_PER_SEC")?;
97 let INTERVALS_PER_SEC = this.eval_windows_u64("time", "INTERVALS_PER_SEC")?;
98 let INTERVALS_TO_UNIX_EPOCH = this.eval_windows_u64("time", "INTERVALS_TO_UNIX_EPOCH")?;
99 let NANOS_PER_INTERVAL = NANOS_PER_SEC / INTERVALS_PER_SEC;
100 let SECONDS_TO_UNIX_EPOCH = INTERVALS_TO_UNIX_EPOCH / INTERVALS_PER_SEC;
102 let duration = system_time_to_duration(&SystemTime::now())? + Duration::from_secs(SECONDS_TO_UNIX_EPOCH);
103 let duration_ticks = u64::try_from(duration.as_nanos() / u128::from(NANOS_PER_INTERVAL))
104 .map_err(|_| err_unsup_format!("programs running more than 2^64 Windows ticks after the Windows epoch are not supported"))?;
106 let dwLowDateTime = u32::try_from(duration_ticks & 0x00000000FFFFFFFF).unwrap();
107 let dwHighDateTime = u32::try_from((duration_ticks & 0xFFFFFFFF00000000) >> 32).unwrap();
108 let DWORD_tylayout = this.machine.layouts.u32;
110 immty_from_uint_checked(dwLowDateTime, DWORD_tylayout)?,
111 immty_from_uint_checked(dwHighDateTime, DWORD_tylayout)?,
113 this.write_packed_immediates(this.deref_operand(LPFILETIME_op)?, &imms)?;
117 #[allow(non_snake_case)]
118 fn QueryPerformanceCounter(&mut self, lpPerformanceCount_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
119 let this = self.eval_context_mut();
121 this.assert_target_os("windows", "QueryPerformanceCounter");
122 this.check_no_isolation("QueryPerformanceCounter")?;
124 // QueryPerformanceCounter uses a hardware counter as its basis.
125 // Miri will emulate a counter with a resolution of 1 nanosecond.
126 let duration = Instant::now().duration_since(this.machine.time_anchor);
127 let qpc = i64::try_from(duration.as_nanos())
128 .map_err(|_| err_unsup_format!("programs running longer than 2^63 nanoseconds are not supported"))?;
129 this.write_scalar(Scalar::from_i64(qpc), this.deref_operand(lpPerformanceCount_op)?.into())?;
130 Ok(-1) // return non-zero on success
133 #[allow(non_snake_case)]
134 fn QueryPerformanceFrequency(&mut self, lpFrequency_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
135 let this = self.eval_context_mut();
137 this.assert_target_os("windows", "QueryPerformanceFrequency");
138 this.check_no_isolation("QueryPerformanceFrequency")?;
140 // Retrieves the frequency of the hardware performance counter.
141 // The frequency of the performance counter is fixed at system boot and
142 // is consistent across all processors.
143 // Miri emulates a "hardware" performance counter with a resolution of 1ns,
144 // and thus 10^9 counts per second.
145 this.write_scalar(Scalar::from_i64(1_000_000_000), this.deref_operand(lpFrequency_op)?.into())?;
146 Ok(-1) // Return non-zero on success
149 fn mach_absolute_time(&self) -> InterpResult<'tcx, u64> {
150 let this = self.eval_context_ref();
152 this.assert_target_os("macos", "mach_absolute_time");
153 this.check_no_isolation("mach_absolute_time")?;
155 // This returns a u64, with time units determined dynamically by `mach_timebase_info`.
156 // We return plain nanoseconds.
157 let duration = Instant::now().duration_since(this.machine.time_anchor);
158 u64::try_from(duration.as_nanos())
159 .map_err(|_| err_unsup_format!("programs running longer than 2^64 nanoseconds are not supported").into())
162 fn mach_timebase_info(&mut self, info_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
163 let this = self.eval_context_mut();
165 this.assert_target_os("macos", "mach_timebase_info");
166 this.check_no_isolation("mach_timebase_info")?;
168 let info = this.deref_operand(info_op)?;
170 // Since our emulated ticks in `mach_absolute_time` *are* nanoseconds,
171 // no scaling needs to happen.
172 let (numer, denom) = (1,1);
174 immty_from_int_checked(numer, this.machine.layouts.u32)?,
175 immty_from_int_checked(denom, this.machine.layouts.u32)?
178 this.write_packed_immediates(info, &imms)?;
179 Ok(0) // KERN_SUCCESS
184 req_op: OpTy<'tcx, Tag>,
185 _rem: OpTy<'tcx, Tag>,
186 ) -> InterpResult<'tcx, i32> {
187 // Signal handlers are not supported, so rem will never be written to.
189 let this = self.eval_context_mut();
191 this.check_no_isolation("nanosleep")?;
193 let duration = match this.read_timespec(req_op)? {
194 Some(duration) => duration,
196 let einval = this.eval_libc("EINVAL")?;
197 this.set_last_error(einval)?;
201 let timeout_time = Time::Monotonic(Instant::now().checked_add(duration).unwrap());
203 let active_thread = this.get_active_thread();
204 this.block_thread(active_thread);
206 this.register_timeout_callback(
209 Box::new(move |ecx| {
210 ecx.unblock_thread(active_thread);