miri/
clock.rs

1use std::cell::Cell;
2use std::time::{Duration, Instant as StdInstant};
3
4/// When using a virtual clock, this defines how many nanoseconds we pretend are passing for each
5/// basic block.
6/// This number is pretty random, but it has been shown to approximately cause
7/// some sample programs to run within an order of magnitude of real time on desktop CPUs.
8/// (See `tests/pass/shims/time-with-isolation*.rs`.)
9const NANOSECONDS_PER_BASIC_BLOCK: u128 = 5000;
10
11#[derive(Debug)]
12pub struct Instant {
13    kind: InstantKind,
14}
15
16#[derive(Debug)]
17enum InstantKind {
18    Host(StdInstant),
19    Virtual { nanoseconds: u128 },
20}
21
22impl Instant {
23    /// Will try to add `duration`, but if that overflows it may add less.
24    pub fn add_lossy(&self, duration: Duration) -> Instant {
25        match self.kind {
26            InstantKind::Host(instant) => {
27                // If this overflows, try adding just 1h and assume that will not overflow.
28                let i = instant
29                    .checked_add(duration)
30                    .unwrap_or_else(|| instant.checked_add(Duration::from_secs(3600)).unwrap());
31                Instant { kind: InstantKind::Host(i) }
32            }
33            InstantKind::Virtual { nanoseconds } => {
34                let n = nanoseconds.saturating_add(duration.as_nanos());
35                Instant { kind: InstantKind::Virtual { nanoseconds: n } }
36            }
37        }
38    }
39
40    pub fn duration_since(&self, earlier: Instant) -> Duration {
41        match (&self.kind, earlier.kind) {
42            (InstantKind::Host(instant), InstantKind::Host(earlier)) =>
43                instant.duration_since(earlier),
44            (
45                InstantKind::Virtual { nanoseconds },
46                InstantKind::Virtual { nanoseconds: earlier },
47            ) => {
48                let duration = nanoseconds.saturating_sub(earlier);
49                // `Duration` does not provide a nice constructor from a `u128` of nanoseconds,
50                // so we have to implement this ourselves.
51                // It is possible for second to overflow because u64::MAX < (u128::MAX / 1e9).
52                // It will be saturated to u64::MAX seconds if the value after division exceeds u64::MAX.
53                let seconds = u64::try_from(duration / 1_000_000_000).unwrap_or(u64::MAX);
54                // It is impossible for nanosecond to overflow because u32::MAX > 1e9.
55                let nanosecond = u32::try_from(duration.wrapping_rem(1_000_000_000)).unwrap();
56                Duration::new(seconds, nanosecond)
57            }
58            _ => panic!("all `Instant` must be of the same kind"),
59        }
60    }
61}
62
63/// A monotone clock used for `Instant` simulation.
64#[derive(Debug)]
65pub struct Clock {
66    kind: ClockKind,
67}
68
69#[derive(Debug)]
70enum ClockKind {
71    Host {
72        /// The "epoch" for this machine's monotone clock:
73        /// the moment we consider to be time = 0.
74        epoch: StdInstant,
75    },
76    Virtual {
77        /// The "current virtual time".
78        nanoseconds: Cell<u128>,
79    },
80}
81
82impl Clock {
83    /// Create a new clock based on the availability of communication with the host.
84    pub fn new(communicate: bool) -> Self {
85        let kind = if communicate {
86            ClockKind::Host { epoch: StdInstant::now() }
87        } else {
88            ClockKind::Virtual { nanoseconds: 0.into() }
89        };
90
91        Self { kind }
92    }
93
94    /// Let the time pass for a small interval.
95    pub fn tick(&self) {
96        match &self.kind {
97            ClockKind::Host { .. } => {
98                // Time will pass without us doing anything.
99            }
100            ClockKind::Virtual { nanoseconds } => {
101                nanoseconds.update(|x| x + NANOSECONDS_PER_BASIC_BLOCK);
102            }
103        }
104    }
105
106    /// Sleep for the desired duration.
107    pub fn sleep(&self, duration: Duration) {
108        match &self.kind {
109            ClockKind::Host { .. } => std::thread::sleep(duration),
110            ClockKind::Virtual { nanoseconds } => {
111                // Just pretend that we have slept for some time.
112                let nanos: u128 = duration.as_nanos();
113                nanoseconds.update(|x| {
114                    x.checked_add(nanos)
115                        .expect("Miri's virtual clock cannot represent an execution this long")
116                });
117            }
118        }
119    }
120
121    /// Return the `epoch` instant (time = 0), to convert between monotone instants and absolute durations.
122    pub fn epoch(&self) -> Instant {
123        match &self.kind {
124            ClockKind::Host { epoch } => Instant { kind: InstantKind::Host(*epoch) },
125            ClockKind::Virtual { .. } => Instant { kind: InstantKind::Virtual { nanoseconds: 0 } },
126        }
127    }
128
129    pub fn now(&self) -> Instant {
130        match &self.kind {
131            ClockKind::Host { .. } => Instant { kind: InstantKind::Host(StdInstant::now()) },
132            ClockKind::Virtual { nanoseconds } =>
133                Instant { kind: InstantKind::Virtual { nanoseconds: nanoseconds.get() } },
134        }
135    }
136}