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: i32) -> Option<TimeoutClock> {
22 let this = self.eval_context_ref();
26
27 if clk_id == this.eval_libc_i32("CLOCK_REALTIME") {
29 return Some(TimeoutClock::RealTime);
30 } else if clk_id == this.eval_libc_i32("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_i32("CLOCK_REALTIME_COARSE") {
41 return Some(TimeoutClock::RealTime);
42 } else if clk_id == this.eval_libc_i32("CLOCK_MONOTONIC_COARSE") {
43 return Some(TimeoutClock::Monotonic);
44 }
45 }
46 #[allow(clippy::collapsible_match)] Os::MacOs => {
48 if clk_id == this.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 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)?.to_i32()?;
72 let tp = this.deref_pointer(tp_op)?;
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(tv_op)?;
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 timep = this.deref_pointer(timep)?;
139 let result = this.deref_pointer(result_op)?;
140
141 let sec_since_epoch: i64 =
144 this.read_scalar(&timep)?.to_int(timep.layout.size)?.try_into().unwrap();
145 let dt_utc: DateTime<Utc> =
146 DateTime::from_timestamp(sec_since_epoch, 0).expect("Invalid timestamp");
147
148 let tz = this.get_env_var(OsStr::new("TZ"))?.unwrap_or_else(|| OsString::from("UTC"));
150 let tz = match tz.into_string() {
151 Ok(tz) => Tz::from_str(&tz).unwrap_or(Tz::UTC),
152 _ => Tz::UTC,
153 };
154
155 let dt: DateTime<Tz> = dt_utc.with_timezone(&tz);
157
158 let tm_isdst = -1;
162 this.write_int_fields_named(
163 &[
164 ("tm_sec", dt.second().into()),
165 ("tm_min", dt.minute().into()),
166 ("tm_hour", dt.hour().into()),
167 ("tm_mday", dt.day().into()),
168 ("tm_mon", dt.month0().into()),
169 ("tm_year", dt.year().strict_sub(1900).into()),
170 ("tm_wday", dt.weekday().num_days_from_sunday().into()),
171 ("tm_yday", dt.ordinal0().into()),
172 ("tm_isdst", tm_isdst),
173 ],
174 &result,
175 )?;
176
177 if !matches!(&this.tcx.sess.target.os, Os::Solaris | Os::Illumos) {
181 let offset_in_seconds = dt.offset().fix().local_minus_utc();
185 let tm_gmtoff = offset_in_seconds;
186 let mut tm_zone = String::new();
187 if offset_in_seconds < 0 {
188 tm_zone.push('-');
189 } else {
190 tm_zone.push('+');
191 }
192 let offset_hour = offset_in_seconds.abs() / 3600;
193 write!(tm_zone, "{offset_hour:02}").unwrap();
194 let offset_min = (offset_in_seconds.abs() % 3600) / 60;
195 if offset_min != 0 {
196 write!(tm_zone, "{offset_min:02}").unwrap();
197 }
198
199 tm_zone.push('\0');
201
202 let tm_zone_ptr = this.allocate_bytes_dedup(tm_zone.as_bytes())?;
204
205 this.write_pointer(tm_zone_ptr, &this.project_field_named(&result, "tm_zone")?)?;
207 this.write_int_fields_named(&[("tm_gmtoff", tm_gmtoff.into())], &result)?;
208 }
209 interp_ok(result.ptr())
210 }
211 #[allow(non_snake_case, clippy::arithmetic_side_effects)]
212 fn GetSystemTimeAsFileTime(
213 &mut self,
214 shim_name: &str,
215 LPFILETIME_op: &OpTy<'tcx>,
216 ) -> InterpResult<'tcx> {
217 let this = self.eval_context_mut();
218
219 this.assert_target_os(Os::Windows, shim_name);
220 this.check_no_isolation(shim_name)?;
221
222 let filetime = this.deref_pointer(LPFILETIME_op)?;
223
224 let duration = this.system_time_since_windows_epoch(&SystemTime::now())?;
225 let duration_ticks = this.windows_ticks_for(duration)?;
226
227 let dwLowDateTime = u32::try_from(duration_ticks & 0x00000000FFFFFFFF).unwrap();
228 let dwHighDateTime = u32::try_from((duration_ticks & 0xFFFFFFFF00000000) >> 32).unwrap();
229 this.write_int_fields(&[dwLowDateTime.into(), dwHighDateTime.into()], &filetime)?;
230
231 interp_ok(())
232 }
233
234 #[allow(non_snake_case)]
235 fn QueryPerformanceCounter(
236 &mut self,
237 lpPerformanceCount_op: &OpTy<'tcx>,
238 ) -> InterpResult<'tcx, Scalar> {
239 let this = self.eval_context_mut();
240
241 this.assert_target_os(Os::Windows, "QueryPerformanceCounter");
242
243 let duration =
246 this.machine.monotonic_clock.now().duration_since(this.machine.monotonic_clock.epoch());
247 let qpc = i64::try_from(duration.as_nanos()).map_err(|_| {
248 err_unsup_format!("programs running longer than 2^63 nanoseconds are not supported")
249 })?;
250
251 this.write_scalar(Scalar::from_i64(qpc), &this.deref_pointer(lpPerformanceCount_op)?)?;
252 interp_ok(Scalar::from_i32(-1)) }
254
255 #[allow(non_snake_case)]
256 fn QueryPerformanceFrequency(
257 &mut self,
258 lpFrequency_op: &OpTy<'tcx>,
259 ) -> InterpResult<'tcx, Scalar> {
260 let this = self.eval_context_mut();
261
262 this.assert_target_os(Os::Windows, "QueryPerformanceFrequency");
263
264 this.write_scalar(Scalar::from_i64(1_000_000_000), &this.deref_pointer(lpFrequency_op)?)?;
270 interp_ok(Scalar::from_i32(-1)) }
272
273 #[allow(clippy::arithmetic_side_effects)]
274 fn system_time_since_windows_epoch(&self, time: &SystemTime) -> InterpResult<'tcx, Duration> {
275 const SECONDS_TO_UNIX_EPOCH: u64 = 11_644_473_600;
279
280 interp_ok(system_time_to_duration(time)? + Duration::from_secs(SECONDS_TO_UNIX_EPOCH))
281 }
282
283 #[allow(non_snake_case, clippy::arithmetic_side_effects)]
284 fn windows_ticks_for(&self, duration: Duration) -> InterpResult<'tcx, u64> {
285 const NANOS_PER_INTERVAL: u128 = 100;
288
289 let ticks = u64::try_from(duration.as_nanos() / NANOS_PER_INTERVAL)
290 .map_err(|_| err_unsup_format!("programs running more than 2^64 Windows ticks after the Windows epoch are not supported"))?;
291 interp_ok(ticks)
292 }
293
294 fn mach_absolute_time(&self) -> InterpResult<'tcx, Scalar> {
295 let this = self.eval_context_ref();
296
297 this.assert_target_os(Os::MacOs, "mach_absolute_time");
298
299 let duration =
302 this.machine.monotonic_clock.now().duration_since(this.machine.monotonic_clock.epoch());
303 let res = u64::try_from(duration.as_nanos()).map_err(|_| {
304 err_unsup_format!("programs running longer than 2^64 nanoseconds are not supported")
305 })?;
306 interp_ok(Scalar::from_u64(res))
307 }
308
309 fn mach_timebase_info(&mut self, info_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
310 let this = self.eval_context_mut();
311
312 this.assert_target_os(Os::MacOs, "mach_timebase_info");
313
314 let info = this.deref_pointer(info_op)?;
315
316 let (numerator, denom) = (1, 1);
319 this.write_int_fields(&[numerator.into(), denom.into()], &info)?;
320
321 interp_ok(Scalar::from_i32(0)) }
323
324 fn mach_wait_until(&mut self, deadline_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
325 let this = self.eval_context_mut();
326
327 this.assert_target_os(Os::MacOs, "mach_wait_until");
328
329 let deadline = this.read_scalar(deadline_op)?.to_u64()?;
330 let deadline = Duration::from_nanos(deadline);
332 let deadline = this.machine.monotonic_clock.epoch().add_lossy(deadline);
334
335 this.block_thread(
336 BlockReason::Sleep,
337 Some(deadline.into()),
338 callback!(
339 @capture<'tcx> {}
340 |_ecx, unblock: UnblockKind| {
341 assert_eq!(unblock, UnblockKind::TimedOut);
342 interp_ok(())
343 }
344 ),
345 );
346
347 interp_ok(Scalar::from_i32(0)) }
349
350 fn nanosleep(&mut self, duration: &OpTy<'tcx>, rem: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
351 let this = self.eval_context_mut();
352
353 this.assert_target_os_is_unix("nanosleep");
354
355 let duration = this.deref_pointer(duration)?;
356 let _rem = this.read_pointer(rem)?; let Some(duration) = this.read_timespec(&duration)? else {
359 return this.set_errno_and_return_neg1_i32(LibcError("EINVAL"));
360 };
361 let deadline = this.machine.monotonic_clock.now().add_lossy(duration);
362
363 this.block_thread(
364 BlockReason::Sleep,
365 Some(deadline.into()),
366 callback!(
367 @capture<'tcx> {}
368 |_ecx, unblock: UnblockKind| {
369 assert_eq!(unblock, UnblockKind::TimedOut);
370 interp_ok(())
371 }
372 ),
373 );
374 interp_ok(Scalar::from_i32(0))
375 }
376
377 fn clock_nanosleep(
378 &mut self,
379 clock_id: &OpTy<'tcx>,
380 flags: &OpTy<'tcx>,
381 timespec: &OpTy<'tcx>,
382 rem: &OpTy<'tcx>,
383 ) -> InterpResult<'tcx, Scalar> {
384 let this = self.eval_context_mut();
385 let clockid_t_size = this.libc_ty_layout("clockid_t").size;
386
387 let clock_id = this.read_scalar(clock_id)?.to_int(clockid_t_size)?;
388 let timespec = this.deref_pointer(timespec)?;
389 let flags = this.read_scalar(flags)?.to_i32()?;
390 let _rem = this.read_pointer(rem)?; if clock_id != this.eval_libc("CLOCK_MONOTONIC").to_int(clockid_t_size)? {
394 throw_unsup_format!("clock_nanosleep: only CLOCK_MONOTONIC is supported");
395 }
396
397 let Some(duration) = this.read_timespec(×pec)? else {
398 return this.set_errno_and_return_neg1_i32(LibcError("EINVAL"));
399 };
400
401 let timeout_style = if flags == 0 {
402 TimeoutStyle::Relative
405 } else if flags == this.eval_libc_i32("TIMER_ABSTIME") {
406 TimeoutStyle::Absolute
409 } else {
410 throw_unsup_format!(
412 "`clock_nanosleep` unsupported flags {flags}, only no flags or \
413 TIMER_ABSTIME is supported"
414 );
415 };
416 let deadline = this.machine.timeout(TimeoutClock::Monotonic, timeout_style, duration);
417
418 this.block_thread(
419 BlockReason::Sleep,
420 Some(deadline),
421 callback!(
422 @capture<'tcx> {}
423 |_ecx, unblock: UnblockKind| {
424 assert_eq!(unblock, UnblockKind::TimedOut);
425 interp_ok(())
426 }
427 ),
428 );
429 interp_ok(Scalar::from_i32(0))
430 }
431
432 #[allow(non_snake_case)]
433 fn Sleep(&mut self, timeout: &OpTy<'tcx>) -> InterpResult<'tcx> {
434 let this = self.eval_context_mut();
435
436 this.assert_target_os(Os::Windows, "Sleep");
437
438 let timeout_ms = this.read_scalar(timeout)?.to_u32()?;
439
440 let duration = Duration::from_millis(timeout_ms.into());
441 let deadline = this.machine.monotonic_clock.now().add_lossy(duration);
442
443 this.block_thread(
444 BlockReason::Sleep,
445 Some(deadline.into()),
446 callback!(
447 @capture<'tcx> {}
448 |_ecx, unblock: UnblockKind| {
449 assert_eq!(unblock, UnblockKind::TimedOut);
450 interp_ok(())
451 }
452 ),
453 );
454 interp_ok(())
455 }
456
457 fn read_timespec(&self, tp: &MPlaceTy<'tcx>) -> InterpResult<'tcx, Option<Duration>> {
461 let this = self.eval_context_ref();
462 let sec_field = this.project_field_named(tp, "tv_sec")?;
463 let sec = this.read_scalar(&sec_field)?.to_int(sec_field.layout.size)?;
464 let nsec_field = this.project_field_named(tp, "tv_nsec")?;
465 let nsec = this.read_scalar(&nsec_field)?.to_int(nsec_field.layout.size)?;
466
467 if sec < 0 {
470 throw_unsup_format!("timespec with negative tv_sec is not supported");
471 }
472 interp_ok(try {
473 let seconds: u64 = sec.try_into().expect("tv_sec should fit in 64 bits");
474 let nanoseconds: u32 = nsec.try_into().ok()?;
476 if nanoseconds >= 1_000_000_000 {
477 None?
479 }
480 Duration::new(seconds, nanoseconds)
481 })
482 }
483
484 fn read_timeval(&self, tp: &MPlaceTy<'tcx>) -> InterpResult<'tcx, Option<Duration>> {
488 let this = self.eval_context_ref();
489 let sec_field = this.project_field_named(tp, "tv_sec")?;
490 let sec = this.read_scalar(&sec_field)?.to_int(sec_field.layout.size)?;
491
492 let usec_field = this.project_field_named(tp, "tv_usec")?;
493 let usec = this.read_scalar(&usec_field)?.to_int(usec_field.layout.size)?;
494
495 interp_ok(try {
496 let seconds: u64 = sec.try_into().ok()?;
498 let microseconds: u32 = usec.try_into().ok()?;
500 if microseconds >= 1_000_000 {
501 None?
503 }
504 Duration::new(seconds, microseconds.strict_mul(1000))
505 })
506 }
507}