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
12pub 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 let this = self.eval_context_ref();
26
27 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 match &this.tcx.sess.target.os {
36 Os::Linux | Os::FreeBsd | Os::Android => {
37 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)] Os::MacOs => {
48 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 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 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 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 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 let dt: DateTime<Tz> = dt_utc.with_timezone(&tz);
158
159 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 if !matches!(&this.tcx.sess.target.os, Os::Solaris | Os::Illumos) {
182 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 tm_zone.push('\0');
202
203 let tm_zone_ptr = this.allocate_bytes_dedup(tm_zone.as_bytes())?;
205
206 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 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)) }
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 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)) }
279
280 #[allow(clippy::arithmetic_side_effects)]
281 fn system_time_since_windows_epoch(&self, time: &SystemTime) -> InterpResult<'tcx, Duration> {
282 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 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 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 let (numerator, denom) = (1, 1);
326 this.write_int_fields(&[numerator.into(), denom.into()], &info)?;
327
328 interp_ok(Scalar::from_i32(0)) }
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 let deadline = Duration::from_nanos(deadline);
339 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)) }
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)?; 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)?; 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(×pec)? else {
405 return this.set_errno_and_return_neg1_i32(LibcError("EINVAL"));
406 };
407
408 let timeout_style = if flags == 0 {
409 TimeoutStyle::Relative
412 } else if flags == this.eval_libc_i32("TIMER_ABSTIME") {
413 TimeoutStyle::Absolute
416 } else {
417 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 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 let seconds: u64 = sec.try_into().ok()?;
477 let nanoseconds: u32 = nsec.try_into().ok()?;
479 if nanoseconds >= 1_000_000_000 {
480 None?
482 }
483 Duration::new(seconds, nanoseconds)
484 })
485 }
486
487 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 let seconds: u64 = sec.try_into().ok()?;
501 let microseconds: u32 = usec.try_into().ok()?;
503 if microseconds >= 1_000_000 {
504 None?
506 }
507 Duration::new(seconds, microseconds.strict_mul(1000))
508 })
509 }
510}