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 ecx = self.eval_context_ref();
26
27 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 match &ecx.tcx.sess.target.os {
36 Os::Linux | Os::FreeBsd | Os::Android => {
37 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)] Os::MacOs => {
48 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 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 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 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 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 let dt: DateTime<Tz> = dt_utc.with_timezone(&tz);
156
157 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 if !matches!(&ecx.tcx.sess.target.os, Os::Solaris | Os::Illumos) {
180 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 tm_zone.push('\0');
200
201 let tm_zone_ptr = ecx.allocate_bytes_dedup(tm_zone.as_bytes())?;
203
204 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 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)) }
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 ecx.write_scalar(Scalar::from_i64(1_000_000_000), &ecx.deref_pointer(lpFrequency_op)?)?;
269 interp_ok(Scalar::from_i32(-1)) }
271
272 #[allow(clippy::arithmetic_side_effects)]
273 fn system_time_since_windows_epoch(&self, time: &SystemTime) -> InterpResult<'tcx, Duration> {
274 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 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 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 let (numerator, denom) = (1, 1);
318 ecx.write_int_fields(&[numerator.into(), denom.into()], &info)?;
319
320 interp_ok(Scalar::from_i32(0)) }
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 let deadline = Duration::from_nanos(deadline);
331 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)) }
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)?; 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)?; 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(×pec)? else {
396 return ecx.set_errno_and_return_neg1_i32(LibcError("EINVAL"));
397 };
398
399 let timeout_style = if flags == 0 {
400 TimeoutStyle::Relative
403 } else if flags == ecx.eval_libc_i32("TIMER_ABSTIME") {
404 TimeoutStyle::Absolute
407 } else {
408 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 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 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 let nanoseconds: u32 = nsec.try_into().ok()?;
475 if nanoseconds >= 1_000_000_000 {
476 None?
478 }
479 Duration::new(seconds, nanoseconds)
480 })
481 }
482
483 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 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 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}