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::from_nanos_u128(duration)
50            }
51            _ => panic!("all `Instant` must be of the same kind"),
52        }
53    }
54}
55
56/// A monotone clock used for `Instant` simulation.
57#[derive(Debug)]
58pub struct MonotonicClock {
59    kind: MonotonicClockKind,
60}
61
62#[derive(Debug)]
63enum MonotonicClockKind {
64    Host {
65        /// The "epoch" for this machine's monotone clock:
66        /// the moment we consider to be time = 0.
67        epoch: StdInstant,
68    },
69    Virtual {
70        /// The "current virtual time".
71        nanoseconds: Cell<u128>,
72    },
73}
74
75impl MonotonicClock {
76    /// Create a new clock based on the availability of communication with the host.
77    pub fn new(communicate: bool) -> Self {
78        let kind = if communicate {
79            MonotonicClockKind::Host { epoch: StdInstant::now() }
80        } else {
81            MonotonicClockKind::Virtual { nanoseconds: 0.into() }
82        };
83
84        Self { kind }
85    }
86
87    /// Let the time pass for a small interval.
88    pub fn tick(&self) {
89        match &self.kind {
90            MonotonicClockKind::Host { .. } => {
91                // Time will pass without us doing anything.
92            }
93            MonotonicClockKind::Virtual { nanoseconds } => {
94                nanoseconds.update(|x| x + NANOSECONDS_PER_BASIC_BLOCK);
95            }
96        }
97    }
98
99    /// Sleep for the desired duration.
100    pub fn sleep(&self, duration: Duration) {
101        match &self.kind {
102            MonotonicClockKind::Host { .. } => std::thread::sleep(duration),
103            MonotonicClockKind::Virtual { nanoseconds } => {
104                // Just pretend that we have slept for some time.
105                let nanos: u128 = duration.as_nanos();
106                nanoseconds.update(|x| {
107                    x.checked_add(nanos)
108                        .expect("Miri's virtual clock cannot represent an execution this long")
109                });
110            }
111        }
112    }
113
114    /// Return the `epoch` instant (time = 0), to convert between monotone instants and absolute durations.
115    pub fn epoch(&self) -> Instant {
116        match &self.kind {
117            MonotonicClockKind::Host { epoch } => Instant { kind: InstantKind::Host(*epoch) },
118            MonotonicClockKind::Virtual { .. } =>
119                Instant { kind: InstantKind::Virtual { nanoseconds: 0 } },
120        }
121    }
122
123    pub fn now(&self) -> Instant {
124        match &self.kind {
125            MonotonicClockKind::Host { .. } =>
126                Instant { kind: InstantKind::Host(StdInstant::now()) },
127            MonotonicClockKind::Virtual { nanoseconds } =>
128                Instant { kind: InstantKind::Virtual { nanoseconds: nanoseconds.get() } },
129        }
130    }
131}