Skip to main content

detcore/syscalls/
time.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 * All rights reserved.
4 *
5 * This source code is licensed under the BSD-style license found in the
6 * LICENSE file in the root directory of this source tree.
7 */
8
9//! System calls for dealing with threads and concurrency.
10use std::time::Duration;
11
12use nix::sys::signal::Signal;
13use reverie::Error;
14use reverie::Guest;
15use reverie::Stack;
16use reverie::syscalls;
17use reverie::syscalls::AddrMut;
18use reverie::syscalls::ClockId;
19use reverie::syscalls::Errno;
20use reverie::syscalls::MemoryAccess;
21use reverie::syscalls::Syscall;
22use reverie::syscalls::Sysno;
23use reverie::syscalls::Timespec;
24use reverie::syscalls::Timeval;
25use reverie::syscalls::family::NanosleepFamily;
26use tracing::error;
27use tracing::info;
28use tracing::trace;
29
30use super::signal::SleepCheck;
31use super::signal::SleepSignal;
32use crate::detlog;
33use crate::record_or_replay::RecordOrReplay;
34use crate::resources::Permission;
35use crate::resources::ResourceID;
36use crate::resources::Resources;
37use crate::scheduler::Priority;
38use crate::scheduler::entropy_to_priority;
39use crate::tool_global::PosixTimerNotification;
40use crate::tool_global::ResumeStatus;
41use crate::tool_global::SigalrmControl;
42use crate::tool_global::posix_timer_thread;
43use crate::tool_global::refuse_sigalrm;
44use crate::tool_global::register_posix_timer;
45use crate::tool_global::thread_observe_time;
46use crate::tool_local::Detcore;
47use crate::types::LogicalTime;
48use crate::types::PosixTimerThread;
49use crate::types::SigWrapper;
50
51/// Whether Linux accepts `clockid` in clock_gettime and clock_getres, as far as
52/// the id alone decides: the fixed clocks 0 to 9 and CLOCK_TAI (11). Linux
53/// answers EINVAL for 10 (CLOCK_SGI_CYCLE, gone since Linux 4.x) and for
54/// every id from 12 up. A negative id names a process's or thread's CPU
55/// clock, or a clock descriptor; whether it is valid depends on the process
56/// or descriptor it names, so it is accepted here as before.
57fn clock_id_is_known(clockid: ClockId) -> bool {
58    use reverie::syscalls::FromToRaw;
59    match clockid.into_raw() as i32 {
60        0..=9 | 11 => true,
61        id => id < 0,
62    }
63}
64
65fn time_from_resources(rsrcs: &Resources) -> Option<LogicalTime> {
66    if rsrcs.resources.len() > 1 {
67        panic!(
68            "time_from_resources: multiple resource ids in resource request: {:?}",
69            rsrcs
70        );
71    }
72    for rs in rsrcs.resources.iter() {
73        if let (ResourceID::SleepUntil(tm), _) = rs {
74            return Some(*tm);
75        }
76    }
77    None
78}
79
80/// Flatten a `timespec` to nanoseconds. Negative fields are not valid for the
81/// timer syscalls we handle; treat them as zero rather than panicking.
82fn timespec_to_ns(ts: libc::timespec) -> u64 {
83    let secs = ts.tv_sec.max(0) as u64;
84    let nsec = ts.tv_nsec.max(0) as u64;
85    secs.saturating_mul(1_000_000_000).saturating_add(nsec)
86}
87
88/// Inverse of [`timespec_to_ns`].
89fn ns_to_timespec(ns: u64) -> libc::timespec {
90    libc::timespec {
91        tv_sec: (ns / 1_000_000_000) as libc::time_t,
92        tv_nsec: (ns % 1_000_000_000) as libc::c_long,
93    }
94}
95
96// AUTONOMOUS-BOT-IMPLEMENTED
97// TODO-HUMAN-REVIEW(PR-857): Query-only timex mode boundary.
98fn timex_mode_is_query(modes: libc::c_uint) -> bool {
99    modes == 0 || modes == libc::ADJ_OFFSET_SS_READ
100}
101
102// AUTONOMOUS-BOT-IMPLEMENTED
103// TODO-HUMAN-REVIEW(PR-857): Host-independent NTP discipline snapshot.
104fn deterministic_timex(now: Timespec) -> libc::timex {
105    // SAFETY: `libc::timex` contains only integer fields and padding; zero is a
106    // valid baseline for the fields not modeled by Hermit.
107    let mut tx: libc::timex = unsafe { std::mem::zeroed() };
108    tx.status = libc::STA_UNSYNC;
109    tx.tick = 10_000;
110    tx.time = libc::timeval {
111        tv_sec: now.tv_sec,
112        tv_usec: now.tv_nsec / 1_000,
113    };
114    tx
115}
116
117// AUTONOMOUS-BOT-IMPLEMENTED
118// TODO-HUMAN-REVIEW(PR-845): Review SaBRe thread-local guest clock reads.
119pub(crate) async fn guest_clock_time<G, T>(guest: &mut G) -> LogicalTime
120where
121    G: Guest<Detcore<T>>,
122    T: RecordOrReplay,
123{
124    let raw = thread_observe_time(guest).await;
125    guest.thread_state().observe_guest_clock(raw)
126}
127
128/// Replacing host time in the `tv` of a `gettimeofday` that failed with EFAULT
129/// could not finish. `tv` may still hold host wall-clock time, so this is a
130/// failed run, not a guest errno.
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132struct TvRepairFailure {
133    /// The word being stored: `tv_sec` or `tv_usec`.
134    field: &'static str,
135    kind: TvRepairFailureKind,
136}
137
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139enum TvRepairFailureKind {
140    /// The backend could not execute the `time(2)` probe. EFAULT is not a
141    /// failure: it means Linux stopped before storing this word.
142    ProbeFailed(Errno),
143    /// After a store probe returned EFAULT, `time(NULL)`, which Linux cannot
144    /// fail, failed too. Something other than the store, such as a seccomp
145    /// filter, produced the EFAULT, so it says nothing about `tv`.
146    ControlProbeFailed(Errno),
147    /// A word at or after the one whose store probe returned EFAULT no longer
148    /// reads as it did before the call, so the original call stored it and the
149    /// EFAULT did not come from the store.
150    StoppedWordChanged,
151    /// A word at or after the one whose store probe returned EFAULT could not
152    /// be read before or after the call, although every byte of it is mapped.
153    /// The read failure may not be a fault: a seccomp filter can deny the
154    /// read while the store went through, so nothing shows the word unstored.
155    StoppedWordUnreadable,
156    /// The guest's memory map, needed to tell an unmapped word from an
157    /// unreadable one, could not be read or was empty.
158    MapsUnavailable,
159    /// The exact overwrite after a successful probe failed. The probe just
160    /// stored host seconds, so the run cannot safely continue.
161    OverwriteFailed(Errno),
162    /// The one-shot overwrite reported a count other than the whole word.
163    OverwriteCount { expected: usize, reported: usize },
164    /// Adding the field offset to the guest's `timeval` address overflowed.
165    AddressOverflow,
166    /// A recorded EFAULT does not prove that this replay execution performed
167    /// the original stores, so live probing would mix replayed and host state.
168    ReplayMode,
169}
170
171impl std::fmt::Display for TvRepairFailure {
172    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
173        write!(
174            f,
175            "replacing host time in the {} of a failed gettimeofday: ",
176            self.field
177        )?;
178        match self.kind {
179            TvRepairFailureKind::ProbeFailed(errno) => {
180                write!(f, "time(2) store probe failed: {errno}")
181            }
182            TvRepairFailureKind::ControlProbeFailed(errno) => write!(
183                f,
184                "time(NULL) control probe failed: {errno}, so the store probe's EFAULT was not a store fault"
185            ),
186            TvRepairFailureKind::StoppedWordChanged => f.write_str(
187                "the word changed during the call although its store probe returned EFAULT",
188            ),
189            TvRepairFailureKind::StoppedWordUnreadable => f.write_str(
190                "the word is mapped but could not be read, so its store probe's EFAULT is unconfirmed",
191            ),
192            TvRepairFailureKind::MapsUnavailable => {
193                f.write_str("the guest's memory map could not be read")
194            }
195            TvRepairFailureKind::OverwriteFailed(errno) => {
196                write!(f, "virtual-time overwrite failed: {errno}")
197            }
198            TvRepairFailureKind::OverwriteCount { expected, reported } => write!(
199                f,
200                "virtual-time overwrite reported {reported} of {expected} bytes"
201            ),
202            TvRepairFailureKind::AddressOverflow => f.write_str("field address overflowed"),
203            TvRepairFailureKind::ReplayMode => {
204                f.write_str("cannot probe a recorded or replayed EFAULT")
205            }
206        }
207    }
208}
209
210impl std::error::Error for TvRepairFailure {}
211
212fn tv_repair_error(field: &'static str, kind: TvRepairFailureKind) -> Error {
213    Error::Tool(anyhow::Error::new(TvRepairFailure { field, kind }))
214}
215
216#[derive(Debug, Clone, Copy, PartialEq, Eq)]
217enum TimeStoreProbe {
218    Stored,
219    Stopped,
220}
221
222fn classify_time_store_probe(
223    field: &'static str,
224    result: Result<i64, Errno>,
225) -> Result<TimeStoreProbe, Error> {
226    match result {
227        Ok(_) => Ok(TimeStoreProbe::Stored),
228        Err(Errno::EFAULT) => Ok(TimeStoreProbe::Stopped),
229        Err(errno) => Err(tv_repair_error(
230            field,
231            TvRepairFailureKind::ProbeFailed(errno),
232        )),
233    }
234}
235
236/// `time(NULL)` stores nothing and cannot fail on Linux, so any error means
237/// the injected `time(2)` never reached the native call.
238fn require_native_time_control_probe(
239    field: &'static str,
240    result: Result<i64, Errno>,
241) -> Result<(), Error> {
242    match result {
243        Ok(_) => Ok(()),
244        Err(errno) => Err(tv_repair_error(
245            field,
246            TvRepairFailureKind::ControlProbeFailed(errno),
247        )),
248    }
249}
250
251/// How a word that Linux did not store reads after the call.
252#[derive(Debug, Clone, Copy, PartialEq, Eq)]
253enum StoppedWord {
254    /// Readable, with the value it held before the call.
255    Unchanged,
256    /// Unreadable both before and after the call. This proves nothing by
257    /// itself; see [`require_unmapped_unreadable_word`].
258    Unreadable,
259}
260
261/// A word Linux did not store keeps both its contents and its readability.
262fn require_unchanged_stopped_word(
263    field: &'static str,
264    before: Result<libc::time_t, Errno>,
265    after: Result<libc::time_t, Errno>,
266) -> Result<StoppedWord, Error> {
267    match (before, after) {
268        (Ok(before), Ok(after)) if before == after => Ok(StoppedWord::Unchanged),
269        (Err(_), Err(_)) => Ok(StoppedWord::Unreadable),
270        _ => Err(tv_repair_error(
271            field,
272            TvRepairFailureKind::StoppedWordChanged,
273        )),
274    }
275}
276
277/// Whether every byte of the `time_t` at `word` lies in one of `ranges`, the
278/// half-open address ranges of the guest's mappings.
279fn time_word_is_fully_mapped(mut ranges: Vec<(u64, u64)>, word: u64) -> bool {
280    let Some(end) = word.checked_add(std::mem::size_of::<libc::time_t>() as u64) else {
281        return false;
282    };
283    ranges.sort_unstable();
284    let mut covered = word;
285    for (start, stop) in ranges {
286        if start <= covered && covered < stop {
287            covered = stop;
288            if covered >= end {
289                return true;
290            }
291        }
292    }
293    false
294}
295
296/// An unreadable word is accepted as unstored only when part of it is
297/// unmapped: Linux's eight-byte `put_user` faults there before storing any
298/// byte. A failed read of a fully mapped word is not evidence of a fault: a
299/// seccomp filter can deny the read while the store succeeds. Ptrace reads use
300/// `FOLL_FORCE`, which bypasses page permissions, but some listed mappings
301/// still refuse the read: file pages beyond end of file, hardware-poisoned
302/// pages, `MADV_GUARD_INSTALL` guard regions, `VM_PFNMAP` mappings without an
303/// `access` operation, missing pages of a userfaultfd region in SIGBUS mode,
304/// and `[vsyscall]` in xonly mode. Backends
305/// that read with `process_vm_readv` also cannot read `PROT_NONE` pages. A
306/// `gettimeofday` whose store faults on any of these ends the run rather than
307/// returning EFAULT. An empty map is refused because a filter that fakes a
308/// successful zero-byte read would otherwise make every word look unmapped.
309fn require_unmapped_unreadable_word(
310    field: &'static str,
311    maps: Result<Vec<(u64, u64)>, Error>,
312    word: u64,
313) -> Result<(), Error> {
314    let ranges = match maps {
315        Ok(ranges) if !ranges.is_empty() => ranges,
316        Ok(_) => {
317            error!("gettimeofday tv repair: the guest's memory map is empty");
318            return Err(tv_repair_error(field, TvRepairFailureKind::MapsUnavailable));
319        }
320        Err(err) => {
321            error!("gettimeofday tv repair: reading the guest's memory map: {err}");
322            return Err(tv_repair_error(field, TvRepairFailureKind::MapsUnavailable));
323        }
324    };
325    if time_word_is_fully_mapped(ranges, word) {
326        Err(tv_repair_error(
327            field,
328            TvRepairFailureKind::StoppedWordUnreadable,
329        ))
330    } else {
331        Ok(())
332    }
333}
334
335/// What Detcore's memory reader returned for `tv_sec` and `tv_usec` before a
336/// `gettimeofday`, with the read error where it failed. Under ptrace the read
337/// ignores page protection and protection keys; backends that read with
338/// `process_vm_readv` respect `VM_READ`.
339type TimevalWordSnapshot = [Result<libc::time_t, Errno>; 2];
340
341const TIMEVAL_WORDS: [(&str, usize); 2] = [
342    ("tv_sec", std::mem::offset_of!(Timeval, tv_sec)),
343    ("tv_usec", std::mem::offset_of!(Timeval, tv_usec)),
344];
345
346fn snapshot_timeval_words<'a, G, T>(
347    guest: &mut G,
348    tv_addr: AddrMut<'a, Timeval>,
349) -> TimevalWordSnapshot
350where
351    G: Guest<Detcore<T>>,
352    T: RecordOrReplay,
353{
354    TIMEVAL_WORDS.map(|(field, offset)| {
355        let addr = timeval_word_addr(field, tv_addr, offset).map_err(|_| Errno::EFAULT)?;
356        guest.memory().read_value(addr)
357    })
358}
359
360fn timeval_word_addr<'a>(
361    field: &'static str,
362    tv_addr: AddrMut<'a, Timeval>,
363    offset: usize,
364) -> Result<AddrMut<'a, libc::time_t>, Error> {
365    tv_addr
366        .as_raw()
367        .checked_add(offset)
368        .and_then(AddrMut::<libc::time_t>::from_raw)
369        .ok_or_else(|| tv_repair_error(field, TvRepairFailureKind::AddressOverflow))
370}
371
372/// The address of `tv`'s word at `offset` for checking that a stopped
373/// `gettimeofday` left it alone, or `None` when the address is past the end of
374/// the address space. No store can reach such a word, so it needs no check.
375/// (A probe needs a real address, so `timeval_word_addr` fails closed instead.)
376fn stopped_timeval_word_addr<'a>(
377    tv_addr: AddrMut<'a, Timeval>,
378    offset: usize,
379) -> Option<AddrMut<'a, libc::time_t>> {
380    tv_addr
381        .as_raw()
382        .checked_add(offset)
383        .and_then(AddrMut::<libc::time_t>::from_raw)
384}
385
386fn require_complete_time_word_overwrite(
387    field: &'static str,
388    expected: usize,
389    result: Result<usize, Errno>,
390) -> Result<(), Error> {
391    match result {
392        Ok(reported) if reported == expected => Ok(()),
393        Ok(reported) => Err(tv_repair_error(
394            field,
395            TvRepairFailureKind::OverwriteCount { expected, reported },
396        )),
397        Err(errno) => Err(tv_repair_error(
398            field,
399            TvRepairFailureKind::OverwriteFailed(errno),
400        )),
401    }
402}
403
404fn require_live_time_store_probe(replay_data_is_some: bool) -> Result<(), Error> {
405    if replay_data_is_some {
406        Err(tv_repair_error("tv", TvRepairFailureKind::ReplayMode))
407    } else {
408        Ok(())
409    }
410}
411
412/// Replaces the host wall-clock time that a `gettimeofday` failing with EFAULT
413/// may have stored in `tv` with virtual time, in exactly the words Linux
414/// stored.
415///
416/// Linux stores `tv_sec`, then `tv_usec`, each with one eight-byte `put_user`,
417/// and only then copies `tz`; the first fault ends the call with EFAULT. A
418/// store that faults on either page it touches commits nothing, so each word
419/// is stored whole or not at all, and nothing after an unstored word is
420/// attempted. `time(2)` uses the same eight-byte `put_user` store for its
421/// `tloc`, so the repair injects it at each word in kernel order. EFAULT means
422/// the original call stopped at that word too. Success means the probe itself
423/// just stored host seconds in those exact bytes; only then does Hermit replace
424/// the word with its virtual value. Other probe errors and overwrite failures
425/// fail closed because host time may remain.
426///
427/// An EFAULT from the probe is only evidence about `tv` if it came from the
428/// store. A seccomp filter can return EFAULT for `time(2)` without running it,
429/// and would otherwise end the repair while host time remains in a writable
430/// `tv`. Two checks therefore confirm every EFAULT before it is trusted.
431/// First, `time(NULL)` is injected: it stores nothing and cannot fail on
432/// Linux, so any error means the probes are not reaching the native call.
433/// Second, every word from the stopped one onward must still read exactly as
434/// it did before the original call: readable with the same value, or
435/// unreadable both times and not fully mapped, so that the store could only
436/// have faulted. A changed word was stored by that call, and an unreadable
437/// word that is fully mapped may have been, because a failed read is not
438/// itself a fault. Each of these failures ends the run, including for the
439/// mapped but unreadable pages listed at `require_unmapped_unreadable_word`.
440///
441/// These checks are observations Detcore makes with its own syscalls, so they
442/// trust those syscalls' results, as every Detcore handler that reads back a
443/// result does. They catch a filter that makes a syscall fail, whether it is
444/// the guest's probe or Detcore's own read. A seccomp filter installed on
445/// Hermit itself can also make one of Detcore's own syscalls report success
446/// without running it, and that is outside this guarantee. A guest cannot
447/// install a filter: Detcore refuses `seccomp(2)` and `PR_SET_SECCOMP`.
448///
449/// The repair never writes a word the kernel could not store, and it does not
450/// test writability by rewriting a word, because a remote write ignores
451/// protection keys that deny the guest's own stores. The pre-call snapshot is
452/// a read only. The host seconds written by a successful
453/// probe exist transiently until the overwrite. Default thread
454/// sequentialization prevents another guest thread from observing that
455/// interval, but another process sharing the page can observe it; such
456/// external shared state is outside Hermit's determinism guarantee.
457/// Standard record/replay disables time virtualization, so this handler is not
458/// used there. A custom configuration that combines replay data with virtual
459/// time fails closed before probing: a recorded EFAULT does not establish that
460/// this execution performed any stores for a live `time(2)` to reproduce.
461///
462/// Every backend runs this repair. The memory map comes from
463/// `Guest::storable_memory_ranges`, which lists `/proc/<pid>/maps` of the
464/// guest by default and the guest's own page record on a backend whose
465/// `pid()` is not the guest (KVM). A backend that executes `gettimeofday` and
466/// `time(2)` itself, as KVM does, stores them as Linux does: each word with an
467/// all-or-nothing store to a writable page, in kernel order.
468async fn overwrite_failed_gettimeofday_tv<'a, G, T>(
469    guest: &mut G,
470    tv_addr: AddrMut<'a, Timeval>,
471    tv: &Timeval,
472    before: &TimevalWordSnapshot,
473) -> Result<(), Error>
474where
475    G: Guest<Detcore<T>>,
476    T: RecordOrReplay,
477{
478    let values = [tv.tv_sec as libc::time_t, tv.tv_usec as libc::time_t];
479    for (index, (field, offset)) in TIMEVAL_WORDS.into_iter().enumerate() {
480        let addr = timeval_word_addr(field, tv_addr, offset)?;
481        let probe = syscalls::Time::new().with_tloc(Some(addr));
482        match classify_time_store_probe(field, guest.inject(probe).await)? {
483            TimeStoreProbe::Stored => {
484                let bytes = values[index].to_ne_bytes();
485                let overwrite = guest
486                    .memory()
487                    .write_with_user_access(addr.cast::<u8>(), &bytes);
488                require_complete_time_word_overwrite(field, bytes.len(), overwrite)?;
489            }
490            TimeStoreProbe::Stopped => {
491                let control = syscalls::Time::new().with_tloc(None);
492                require_native_time_control_probe(field, guest.inject(control).await)?;
493                for (stopped, (field, offset)) in TIMEVAL_WORDS.into_iter().enumerate().skip(index)
494                {
495                    let Some(addr) = stopped_timeval_word_addr(tv_addr, offset) else {
496                        continue;
497                    };
498                    let after = guest.memory().read_value(addr);
499                    match require_unchanged_stopped_word(field, before[stopped], after)? {
500                        StoppedWord::Unchanged => {}
501                        StoppedWord::Unreadable => {
502                            let maps = guest.storable_memory_ranges();
503                            require_unmapped_unreadable_word(field, maps, addr.as_raw() as u64)?;
504                        }
505                    }
506                }
507                break;
508            }
509        }
510    }
511    Ok(())
512}
513
514fn remaining_sleep_duration(target: LogicalTime, now: LogicalTime) -> Duration {
515    if target > now {
516        target.duration_since(now)
517    } else {
518        Duration::ZERO
519    }
520}
521
522impl<T: RecordOrReplay> Detcore<T> {
523    /// Convenience function for constructing a sleep request with a nanosecond offset from "now".
524    pub async fn sleep_request<G: Guest<Self>>(guest: &mut G, ns_delta: Duration) -> Resources {
525        let base_time = thread_observe_time(guest).await;
526        let target_time = base_time + ns_delta;
527        let resource = ResourceID::SleepUntil(target_time);
528        guest.thread_state().mk_request(resource, Permission::W)
529    }
530
531    /// Convenience function for constructing a sleep request with a absolute nanosecond value from the realtime clock.
532    pub async fn sleep_request_abs<G: Guest<Self>>(guest: &mut G, time: LogicalTime) -> Resources {
533        // TODO T124594597 Record-replay case requires better handling of time
534        let resource = ResourceID::SleepUntil(time);
535        guest.thread_state().mk_request(resource, Permission::W)
536    }
537
538    /// Convenience function for constructing a thread yield request.
539    /// Implemented as a sleep ending at the epoch (in the past).
540    pub fn yield_request<G: Guest<Self>>(guest: &mut G) -> Resources {
541        let resource = ResourceID::SleepUntil(LogicalTime::from_nanos(0));
542        guest.thread_state().mk_request(resource, Permission::W)
543    }
544
545    /// Construct a request for a strong, one-turn scheduler yield.
546    pub fn sched_yield_request<G: Guest<Self>>(guest: &mut G) -> Resources {
547        guest
548            .thread_state()
549            .mk_request(ResourceID::SchedYield, Permission::W)
550    }
551
552    /// Construct a random PriorityChangePoint request using the local PRNG.
553    pub fn random_priority_changepoint_request<G: Guest<Self>>(
554        guest: &mut G,
555        change_time: LogicalTime,
556    ) -> Resources {
557        let entropy = guest.thread_state_mut().chaos_prng_next_u64("priority");
558        let new_priority = entropy_to_priority(entropy);
559        Self::priority_changepoint_request(guest, change_time, new_priority)
560    }
561
562    /// Construct a PriorityChangePoint request using the supplied time and priority.
563    pub fn priority_changepoint_request<G: Guest<Self>>(
564        guest: &mut G,
565        change_time: LogicalTime,
566        new_priority: Priority,
567    ) -> Resources {
568        // AUTONOMOUS-BOT-IMPLEMENTED
569        // TODO-HUMAN-REVIEW(PR-1151)
570        let epochs = guest.thread_state_mut().take_pending_chaos_epochs();
571        let rcbs = guest.thread_state().committed_clock_value;
572        let resource = ResourceID::PriorityChangePoint(new_priority, change_time, rcbs, epochs);
573        guest.thread_state().mk_request(resource, Permission::W)
574    }
575
576    /// gettimeofday
577    pub async fn handle_gettimeofday<G: Guest<Self>>(
578        &self,
579        guest: &mut G,
580        call: syscalls::Gettimeofday,
581    ) -> Result<i64, Error> {
582        let time_ns = guest_clock_time(guest).await;
583
584        // What Detcore could read in `tv` before the call; the repair uses it
585        // to confirm which words a failing call left alone.
586        let before = call.tv().map(|tp| snapshot_timeval_words(guest, tp.into()));
587
588        // A call failing with EFAULT may still have stored host wall-clock time
589        // in `tv`, so keep its result until `tv` holds virtual time.
590        let result = self
591            .record_or_replay_preserving_tool_errors(guest, call)
592            .await;
593
594        let tv: Timeval = time_ns.into();
595
596        if let Some(tp) = call.tv() {
597            match (&result, &before) {
598                (Ok(_), _) => guest.memory().write_value(tp, &tv)?,
599                // Linux's gettimeofday fails only with EFAULT, which is taken
600                // to be its own even when a seccomp filter returned it without
601                // running the call. Any other error came from the backend, the
602                // tool, a seccomp filter or a replayed log, and says nothing
603                // about what reached `tv`, so memory is left alone.
604                (Err(Error::Errno(Errno::EFAULT)), Some(before)) => {
605                    require_live_time_store_probe(self.cfg.replay_data.is_some())?;
606                    overwrite_failed_gettimeofday_tv(guest, tp.into(), &tv, before).await?
607                }
608                (Err(_), _) => {}
609            }
610        }
611
612        result
613    }
614
615    /// time
616    pub async fn handle_time<G: Guest<Self>>(
617        &self,
618        guest: &mut G,
619        call: syscalls::Time,
620    ) -> Result<i64, Error> {
621        let time_ns = guest_clock_time(guest).await;
622        let secs = time_ns.as_secs() as i64;
623
624        if let Some(tloc) = call.tloc() {
625            let mut memory = guest.memory();
626            memory.write_value(tloc, &secs)?;
627        }
628
629        Ok(secs)
630    }
631
632    /// clock_gettime
633    pub async fn handle_clock_gettime<G: Guest<Self>>(
634        &self,
635        guest: &mut G,
636        call: syscalls::ClockGettime,
637    ) -> Result<i64, Error> {
638        if !clock_id_is_known(call.clockid()) {
639            return Err(Errno::EINVAL.into());
640        }
641        let time_ns = guest_clock_time(guest).await;
642        trace!("Converting nanoseconds into clock_gettime: {}", time_ns);
643
644        let tp = call.tp().ok_or(Errno::EFAULT)?;
645
646        let t: Timespec = time_ns.into();
647
648        guest.memory().write_value(tp, &t)?;
649
650        Ok(0)
651    }
652
653    /// clock_getres
654    pub async fn handle_clock_getres<G: Guest<Self>>(
655        &self,
656        guest: &mut G,
657        call: syscalls::ClockGetres,
658    ) -> Result<i64, Error> {
659        if !clock_id_is_known(call.clockid()) {
660            return Err(Errno::EINVAL.into());
661        }
662        // A NULL `res` pointer is valid for clock_getres: the kernel validates
663        // the clockid and returns 0 without storing the resolution. GHC's RTS
664        // probes the per-thread CPU clock exactly this way
665        // (clock_getres(clockid, NULL)) in getCurrentThreadCPUTime, so
666        // returning EFAULT here spuriously aborts the guest. Only write the
667        // resolution when the caller supplied a destination.
668        if let Some(res) = call.res() {
669            // For now we report a constant clock res of 10ms:
670            let clock_res = 10;
671
672            let t = Timespec {
673                tv_sec: 0,
674                tv_nsec: 1000 * clock_res as i64,
675            };
676
677            guest.memory().write_value(res, &t)?;
678        }
679
680        Ok(0)
681    }
682
683    // AUTONOMOUS-BOT-IMPLEMENTED
684    // TODO-HUMAN-REVIEW(PR-857): Deterministic adjtimex query/refusal policy.
685    /// Report Hermit's virtual clock with a fixed unsynchronized discipline.
686    /// Adjustment modes are capability-gated host mutations and receive EPERM.
687    pub async fn handle_adjtimex<G: Guest<Self>>(
688        &self,
689        guest: &mut G,
690        call: syscalls::Adjtimex,
691    ) -> Result<i64, Error> {
692        self.write_deterministic_timex(guest, call.buf()).await
693    }
694
695    // AUTONOMOUS-BOT-IMPLEMENTED
696    // TODO-HUMAN-REVIEW(PR-857): Deterministic clock_adjtime query/refusal policy.
697    /// Apply the adjtimex policy to CLOCK_REALTIME. Linux does not permit NTP
698    /// adjustment of the other fixed clock IDs, so reject them with EOPNOTSUPP.
699    pub async fn handle_clock_adjtime<G: Guest<Self>>(
700        &self,
701        guest: &mut G,
702        call: syscalls::ClockAdjtime,
703    ) -> Result<i64, Error> {
704        if call.clockid() != ClockId::CLOCK_REALTIME {
705            return Err(Errno::EOPNOTSUPP.into());
706        }
707        self.write_deterministic_timex(guest, call.buf()).await
708    }
709
710    async fn write_deterministic_timex<G: Guest<Self>>(
711        &self,
712        guest: &mut G,
713        buf: Option<reverie::syscalls::AddrMut<'_, libc::timex>>,
714    ) -> Result<i64, Error> {
715        let buf = buf.ok_or(Errno::EFAULT)?;
716        let request: libc::timex = guest.memory().read_value(buf)?;
717        if !timex_mode_is_query(request.modes) {
718            return Err(Errno::EPERM.into());
719        }
720
721        let now: Timespec = thread_observe_time(guest).await.into();
722        guest.memory().write_value(buf, &deterministic_timex(now))?;
723        Ok(libc::TIME_ERROR as i64)
724    }
725
726    /// Helper function to wait a given period, which may either succeed or be interrupted by a signal.
727    /// Return 0 or EINTR respectively.
728    async fn wait_and_return<R: Guest<Self>>(
729        &self,
730        guest: &mut R,
731        mut request: Resources,
732        call: NanosleepFamily,
733    ) -> Result<i64, Error> {
734        let target_time = time_from_resources(&request).expect("a sleepuntil resource request");
735        // Lets the scheduler end the sleep for a cross-task signal that
736        // interrupts it (`scheduler::sleep_signal`).
737        request.fyi(crate::resources::NANOSLEEP_FYI);
738        let mut claimed = false;
739        loop {
740            // A signal already pending ends the sleep before it parks, and one
741            // still pending after a wake ends it; a wake whose signal was taken
742            // back parks it again with its original absolute deadline
743            // (`super::signal::sleep_signal`).
744            if super::signal::sleep_signal(guest, SleepCheck::BeforePark, false).await?
745                == SleepSignal::Pending
746            {
747                break;
748            }
749            request.in_guest_sleep_sigalrm = self.in_guest_sleep_sigalrm_snapshot(guest).await;
750            match crate::tool_global::parked_wait_request(
751                guest,
752                request.clone(),
753                crate::scheduler::parked::ParkedWaitPolicy::NanosleepNoHandlerRestart {
754                    absolute_deadline: target_time,
755                },
756            )
757            .await
758            {
759                ResumeStatus::InGuestFatalAlarm => {
760                    // The default action terminates the guest. In particular,
761                    // do not observe time or write `rem` after this fatal wake.
762                    self.stage_in_guest_fatal_alarm(guest).await;
763                    return Err(Errno::EINTR.into());
764                }
765                // A sleep never asks for `NothingElseCanRun`.
766                ResumeStatus::Normal | ResumeStatus::NothingElseCanRun => return Ok(0),
767                ResumeStatus::Signaled(signals) => {
768                    match super::signal::sleep_signal(guest, SleepCheck::AfterWake(signals), false)
769                        .await?
770                    {
771                        SleepSignal::Pending | SleepSignal::Held => break,
772                        SleepSignal::Claimed => {
773                            claimed = true;
774                            break;
775                        }
776                        SleepSignal::None => trace!(
777                            "nanosleep woken for a signal no longer pending for it; sleeping again until {}",
778                            target_time
779                        ),
780                    }
781                }
782            }
783        }
784        let now = thread_observe_time(guest).await;
785        let delta = remaining_sleep_duration(target_time, now);
786        // Linux never touches remain for TIMER_ABSTIME, even when
787        // a caught signal interrupts the absolute sleep.
788        let addr2 = if call.flags() & libc::TIMER_ABSTIME == 0 {
789            call.rem()
790        } else {
791            None
792        };
793        if let Some(addr2) = addr2 {
794            info!(
795                "[interrupted] sleep till (until {}), woke up {:?} early, writing into nanosleep rem argument.",
796                target_time, delta
797            );
798            let t = Timespec {
799                tv_sec: delta.as_secs() as i64,
800                tv_nsec: delta.subsec_nanos() as i64,
801            };
802            guest.memory().write_value(addr2, &t)?;
803        } else {
804            info!("[interrupted] nanosleep rem argument is null, not writing it.")
805        }
806        if claimed {
807            // A claimed `SIGCHLD` is held for delivery as the thread resumes
808            // (`SleepSignal::Claimed`): `EINTR` if a handler runs, else the
809            // kernel's restart. As Linux's own `nanosleep`, a relative sleep
810            // returns `ERESTART_RESTARTBLOCK` and keeps its deadline for the
811            // `restart_syscall` the kernel runs only when no handler ran
812            // (`helpers::RestartBlock`, `resume_nanosleep`), so a new call,
813            // from a handler or a retry, cannot take it. An absolute one
814            // returns `ERESTARTNOHAND`: re-executed, it reads the same target.
815            if call.flags() & libc::TIMER_ABSTIME != 0 {
816                return Err(reverie::Error::Errno(Errno::ERESTARTNOHAND));
817            }
818            let result = Err(reverie::Error::Errno(Errno::ERESTART_RESTARTBLOCK));
819            crate::syscalls::helpers::keep_restart_block(
820                guest,
821                &result,
822                crate::syscalls::helpers::RestartCall::Nanosleep(call),
823                Some(target_time),
824            )
825            .await;
826            return result;
827        }
828        Err(reverie::Error::Errno(Errno::EINTR))
829    }
830
831    /// The kernel's `restart_syscall` of a relative `nanosleep` that ended for
832    /// a claimed `SIGCHLD` no handler ran for (`helpers::RestartCall::Nanosleep`).
833    /// Like Linux's restart block, it keeps the deadline it already has and
834    /// does not read the request again, which another thread may have changed.
835    pub(crate) async fn resume_nanosleep<R: Guest<Self>>(
836        &self,
837        guest: &mut R,
838        call: NanosleepFamily,
839        deadline: LogicalTime,
840    ) -> Result<i64, Error> {
841        let request = Self::sleep_request_abs(guest, deadline).await;
842        self.wait_and_return(guest, request, call).await
843    }
844
845    /// clock_nanosleep and nanosleep
846    pub async fn handle_nanosleep_family<R: Guest<Self>>(
847        &self,
848        guest: &mut R,
849        call: NanosleepFamily,
850    ) -> Result<i64, Error> {
851        if call.flags() > libc::TIMER_ABSTIME {
852            trace!("Unhandled clock_nanosleep flags, letting syscall through...");
853            return Ok(guest.inject(Syscall::from(call)).await?);
854        }
855
856        let addr = call.req().ok_or(Errno::EFAULT)?;
857        let t: Timespec = guest.memory().read_value(addr)?;
858
859        // Linux validates the requested interval BEFORE sleeping: nanosleep(2)
860        // and clock_nanosleep(2) both fail EINVAL when tv_nsec is outside
861        // [0, 999999999] or tv_sec is negative.
862        //
863        // Detcore skipped that check and fed the raw fields through `as u64`.
864        // `Timespec` stores both as i64, so `tv_sec = -1` wrapped to
865        // u64::MAX (~1.8e19 seconds) and became `SleepUntil(INDEFINITE)`: the
866        // only guest thread parked with no deadline, the run queue emptied, and
867        // `step2d_handle_empty_queue` deliberately never jumps the clock for an
868        // indefinite waiter (doing so would also wake a `pause(2)`). The
869        // container then died -- exit 1, "Sandbox container exited
870        // unexpectedly" -- where Linux returns an errno and keeps running.
871        //
872        // A past *absolute* deadline is NOT an error and must still return 0,
873        // so this rejects only malformed fields, never an early deadline.
874        if t.tv_sec < 0 || t.tv_nsec < 0 || t.tv_nsec > 999_999_999 {
875            return Err(Errno::EINVAL.into());
876        }
877
878        match call.flags() {
879            0 => {
880                if self.cfg.sequentialize_threads {
881                    let time = Duration::from_secs(t.tv_sec as u64)
882                        + Duration::from_nanos(t.tv_nsec as u64);
883                    let request = Self::sleep_request(guest, time).await;
884                    trace!(
885                        "nanosleep adding delta {:?} to yield request {:?}",
886                        time, &request
887                    );
888                    self.wait_and_return(guest, request, call).await
889                } else {
890                    trace!("Not sequentializing threads, letting nanosleep through...");
891                    Ok(guest.inject(Syscall::from(call)).await?)
892                }
893            }
894            libc::TIMER_ABSTIME => {
895                let target_time = LogicalTime::from_secs(t.tv_sec as u64)
896                    + LogicalTime::from_nanos(t.tv_nsec as u64);
897                if self.cfg.sequentialize_threads {
898                    if self.cfg.virtualize_time {
899                        let request = Self::sleep_request_abs(guest, target_time).await;
900                        trace!(
901                            "nanosleep setting absolute time {:?} to yield request {:?}",
902                            target_time, &request
903                        );
904                        self.wait_and_return(guest, request, call).await
905                    } else {
906                        // TODO T124594597: Record-replay case here, need better ideas to enable proper handling of this case.
907                        error!(
908                            "Sequentializing but not virtualizing, so can't rely on passed abs time, especially when replaying a recording, just yelding"
909                        );
910                        let request = Self::yield_request(guest);
911                        self.wait_and_return(guest, request, call).await
912                    }
913                } else if self.cfg.virtualize_time {
914                    trace!(
915                        "Not sequentializing, but virtualizing so calculating relative time and invoking nanosleep..."
916                    );
917                    let relative_ts = Self::relative_time_from_abs_target(guest, target_time).await;
918                    let mut stack = guest.stack().await;
919                    let req = stack.push(relative_ts);
920                    stack.commit()?;
921                    let modified_call = syscalls::Nanosleep::new().with_req(Some(req));
922                    Ok(guest.inject(modified_call).await?)
923                } else {
924                    trace!(
925                        "Not sequentializing threads not virtualizing, letting nanosleep through..."
926                    );
927                    Ok(guest.inject(Syscall::from(call)).await?)
928                }
929            }
930            _ => unreachable!("Unexpected, unhandled flag value"),
931        }
932    }
933
934    async fn relative_time_from_abs_target<G: Guest<Self>>(
935        guest: &mut G,
936        target_time: LogicalTime,
937    ) -> Timespec {
938        let base_time = thread_observe_time(guest).await;
939
940        // An absolute deadline already in the past is NOT an error on Linux --
941        // clock_nanosleep(TIMER_ABSTIME) simply returns 0 without sleeping.
942        // `LogicalTime`'s `Sub` is a plain subtraction (unlike its `Add` impls,
943        // which saturate deliberately), so `target_time - base_time` underflows
944        // for a past deadline: a debug build panics with "attempt to subtract
945        // with overflow", and a release build wraps to an enormous interval --
946        // the same effectively-indefinite sleep this handler exists to avoid.
947        //
948        // Clamped here rather than by making the shared operator saturate,
949        // because this is the only subtraction of two `LogicalTime`s in the
950        // tree and a silently-saturating operator could hide a real underflow
951        // in some future caller.
952        let relative_logical = if target_time <= base_time {
953            LogicalTime::from_nanos(0)
954        } else {
955            target_time - base_time
956        };
957
958        Timespec {
959            tv_sec: relative_logical.as_secs() as i64,
960            tv_nsec: relative_logical.subsec_nanos() as i64,
961        }
962    }
963
964    /// Whether a POSIX timer notifying with `signo` registers its expirations
965    /// with the scheduler. A standard signal always does. A real-time signal
966    /// (32 to 64; glibc's SIGEV_THREAD timers use one through SIGEV_THREAD_ID)
967    /// cannot be delivered by Detcore, whose signal model carries nix's `Signal`
968    /// (https://github.com/rrnewton/hermit/issues/3893). Creating, arming, reading
969    /// and deleting such a timer still behave as on Linux; only an expiration is
970    /// unserviceable. A fail-closed run registers it anyway, and the scheduler
971    /// refuses the run by name if it ever comes due; a permissive run
972    /// (`--allow-unsupported-syscalls`) leaves it unregistered, so it never fires.
973    fn posix_timer_expiry_is_registered(&self, signo: i32) -> bool {
974        Signal::try_from(signo).is_ok() || self.cfg.panic_on_unsupported_syscalls
975    }
976
977    // AUTONOMOUS-BOT-IMPLEMENTED
978    // TODO-HUMAN-REVIEW(#869)
979    /// timer_create: allocate a per-process POSIX timer and hand back a
980    /// deterministic id, retaining any scheduler-deliverable signal and, for
981    /// `SIGEV_THREAD_ID`, the thread it notifies. The notification is checked
982    /// as Linux's `good_sigevent` does: `SIGEV_SIGNAL` and `SIGEV_THREAD` (which
983    /// the kernel treats alike; libc implements the thread itself) need a
984    /// signal from 1 to 64; `SIGEV_THREAD_ID` needs, first, a thread of the
985    /// caller's own process (<https://github.com/rrnewton/hermit/issues/4164>);
986    /// any other value is EINVAL.
987    pub async fn handle_timer_create<G: Guest<Self>>(
988        &self,
989        guest: &mut G,
990        call: syscalls::TimerCreate,
991    ) -> Result<i64, Error> {
992        // The kernel writes the new timer id here; a null pointer is EFAULT.
993        let timerid_ptr = call.timerid().ok_or(Errno::EFAULT)?;
994        let clockid = call.clockid();
995        let (signo, thread, value) = if let Some(event_ptr) = call.sevp() {
996            // Only the plain fields: `sigevent` holds a pointer, which must not
997            // be kept across the query below. The value is kept as the 64 bits
998            // Linux copies into `si_value`.
999            let (notify, signo, named, value) = {
1000                let event: libc::sigevent = guest.memory().read_value(event_ptr)?;
1001                (
1002                    event.sigev_notify,
1003                    event.sigev_signo,
1004                    event.sigev_notify_thread_id,
1005                    event.sigev_value.sival_ptr as usize as u64,
1006                )
1007            };
1008            let thread = match notify {
1009                libc::SIGEV_NONE => None,
1010                libc::SIGEV_SIGNAL | libc::SIGEV_THREAD => None,
1011                libc::SIGEV_THREAD_ID => match posix_timer_thread(guest, named).await {
1012                    PosixTimerThread::Thread(thread) => Some(thread),
1013                    PosixTimerThread::NotInGroup => return Err(Errno::EINVAL.into()),
1014                    PosixTimerThread::NestedNamespace => {
1015                        tracing::error!(
1016                            "[detcore, dtid {}] timer_create with SIGEV_THREAD_ID is not supported in a nested PID namespace: the thread id is a pid of that namespace, which Detcore does not translate (https://github.com/rrnewton/hermit/issues/4155)",
1017                            guest.thread_state().dettid,
1018                        );
1019                        return self
1020                            .refuse_unserviceable_operation(
1021                                guest,
1022                                Sysno::timer_create,
1023                                Errno::ENOSYS,
1024                            )
1025                            .await;
1026                    }
1027                },
1028                _ => return Err(Errno::EINVAL.into()),
1029            };
1030            if notify == libc::SIGEV_NONE {
1031                (None, None, Some(value))
1032            } else if !(1..=64).contains(&signo) {
1033                return Err(Errno::EINVAL.into());
1034            } else {
1035                (Some(signo), thread, Some(value))
1036            }
1037        } else {
1038            (Some(libc::SIGALRM), None, None)
1039        };
1040        // `None` for a real-time signal (32 to 64): see `handle_timer_settime`.
1041        let signal = signo.and_then(|signo| Signal::try_from(signo).ok());
1042        if signal == Some(Signal::SIGALRM) {
1043            refuse_sigalrm(guest, SigalrmControl::ArmProducer).await?;
1044        }
1045        let id = {
1046            let mut timers = guest.thread_state().posix_timers.lock().unwrap();
1047            timers.create(signo, thread, value)
1048        };
1049        guest
1050            .memory()
1051            .write_value(timerid_ptr, &(id as libc::c_int))?;
1052        // The process has a POSIX timer on this signal from its creation, armed
1053        // or not, which decides how a kept send standing on another sender's
1054        // record is classified (https://github.com/rrnewton/hermit/issues/4262).
1055        if crate::scheduler::discarded_at_send::records(guest.config())
1056            && let Some(signo) = signo
1057            && (1..32).contains(&signo)
1058        {
1059            crate::tool_global::discarded_signal(
1060                guest,
1061                crate::scheduler::discarded_at_send::DiscardedSignalControl::TimerCreated {
1062                    signal: signo,
1063                },
1064            )
1065            .await;
1066        }
1067        detlog!(
1068            "[dtid {}] timer_create(clockid={:?}) => deterministic timer id {}, signal {:?}, thread {:?}",
1069            guest.thread_state().dettid,
1070            clockid,
1071            id,
1072            signal,
1073            thread,
1074        );
1075        Ok(0)
1076    }
1077
1078    // AUTONOMOUS-BOT-IMPLEMENTED
1079    // TODO-HUMAN-REVIEW(#869)
1080    /// timer_settime: arm or disarm a timer against the deterministic virtual
1081    /// clock. The old arming is reported through `old_value` when requested.
1082    pub async fn handle_timer_settime<G: Guest<Self>>(
1083        &self,
1084        guest: &mut G,
1085        call: syscalls::TimerSettime,
1086    ) -> Result<i64, Error> {
1087        let id = call.timerid();
1088        let new_ptr = call.new_value().ok_or(Errno::EINVAL)?;
1089        let new: libc::itimerspec = guest.memory().read_value(new_ptr)?;
1090        let interval_ns = timespec_to_ns(new.it_interval);
1091        let value_ns = timespec_to_ns(new.it_value);
1092
1093        let now = thread_observe_time(guest).await;
1094        let deadline = if value_ns == 0 {
1095            None
1096        } else if call.flags() & libc::TIMER_ABSTIME != 0 {
1097            // Absolute expiration is interpreted against the same virtual clock.
1098            Some(LogicalTime::from_nanos(value_ns))
1099        } else {
1100            Some(now + Duration::from_nanos(value_ns))
1101        };
1102
1103        let (old, signal_number, thread, value) = {
1104            let mut timers = guest.thread_state().posix_timers.lock().unwrap();
1105            let old = timers.settime(id, interval_ns, deadline, now);
1106            let signal = timers.signal(id);
1107            (
1108                old,
1109                signal,
1110                timers.thread(id),
1111                timers.value(id).unwrap_or(0),
1112            )
1113        };
1114        let (mut old_remaining_ns, old_interval_ns) = old.ok_or(Errno::EINVAL)?;
1115        let signal_number = signal_number.ok_or(Errno::EINVAL)?;
1116        // The old value is the timer's remaining time as `timer_gettime`
1117        // reads it now, from the scheduler where it keeps the timer's phase
1118        // (4262 design §5).
1119        if let Some((Some(remaining), _)) = posix_timer_readout(guest, id, now).await {
1120            old_remaining_ns = remaining.as_nanos();
1121        }
1122
1123        // Linux changes the timer, its generation and its overrun before it
1124        // copies the old value out (`do_timer_settime`), and an EFAULT there
1125        // undoes none of it, so the scheduler is told first (the Codex review
1126        // of https://github.com/rrnewton/hermit/pull/4491, P2-2).
1127        if let Some(signo) = signal_number {
1128            if self.posix_timer_expiry_is_registered(signo) {
1129                register_posix_timer(
1130                    guest,
1131                    id,
1132                    deadline,
1133                    LogicalTime::from_nanos(interval_ns),
1134                    PosixTimerNotification {
1135                        sig: SigWrapper(signo),
1136                        thread,
1137                        value,
1138                        deleted: false,
1139                    },
1140                )
1141                .await;
1142            } else if deadline.is_some() {
1143                tracing::error!(
1144                    "[detcore, dtid {}] POSIX timer {} notifies with real-time signal {}, which Detcore does not deliver from a timer; it is armed but will never fire",
1145                    guest.thread_state().dettid,
1146                    id,
1147                    signo,
1148                );
1149            }
1150        }
1151
1152        if let Some(old_ptr) = call.old_value() {
1153            let old_spec = libc::itimerspec {
1154                it_interval: ns_to_timespec(old_interval_ns),
1155                it_value: ns_to_timespec(old_remaining_ns),
1156            };
1157            guest.memory().write_value(old_ptr, &old_spec)?;
1158        }
1159
1160        detlog!(
1161            "[dtid {}] timer_settime(id={}, interval_ns={}, value_ns={}) armed against virtual clock",
1162            guest.thread_state().dettid,
1163            id,
1164            interval_ns,
1165            value_ns,
1166        );
1167        Ok(0)
1168    }
1169
1170    /// timer_gettime: report the time remaining until the next expiration and
1171    /// the reload interval, both computed from the virtual clock.
1172    pub async fn handle_timer_gettime<G: Guest<Self>>(
1173        &self,
1174        guest: &mut G,
1175        call: syscalls::TimerGettime,
1176    ) -> Result<i64, Error> {
1177        let id = call.timerid();
1178        let value_ptr = call.value().ok_or(Errno::EFAULT)?;
1179        let now = thread_observe_time(guest).await;
1180        let cur = {
1181            let timers = guest.thread_state().posix_timers.lock().unwrap();
1182            timers.gettime(id, now)
1183        };
1184        let (mut remaining_ns, interval_ns) = cur.ok_or(Errno::EINVAL)?;
1185        // Where the scheduler coalesces timers, it knows whether this one
1186        // waits for the dequeue of its signal (4262 design §5).
1187        if let Some((Some(remaining), _)) = posix_timer_readout(guest, id, now).await {
1188            remaining_ns = remaining.as_nanos();
1189        }
1190        let spec = libc::itimerspec {
1191            it_interval: ns_to_timespec(interval_ns),
1192            it_value: ns_to_timespec(remaining_ns),
1193        };
1194        guest.memory().write_value(value_ptr, &spec)?;
1195        Ok(0)
1196    }
1197
1198    /// timer_getoverrun: the expirations the timer's last delivered signal
1199    /// missed (`it_overrun_last`), where the scheduler coalesces timers
1200    /// (<https://github.com/rrnewton/hermit/issues/4262>); 0 elsewhere.
1201    pub async fn handle_timer_getoverrun<G: Guest<Self>>(
1202        &self,
1203        guest: &mut G,
1204        call: syscalls::TimerGetoverrun,
1205    ) -> Result<i64, Error> {
1206        let id = call.timerid();
1207        let exists = guest
1208            .thread_state()
1209            .posix_timers
1210            .lock()
1211            .unwrap()
1212            .contains(id);
1213        if !exists {
1214            return Err(Errno::EINVAL.into());
1215        }
1216        // The overrun is the scheduler's record alone, not a function of the
1217        // caller's time, which is not observed here.
1218        Ok(posix_timer_readout(guest, id, LogicalTime::ZERO)
1219            .await
1220            .map_or(0, |(_, overrun)| overrun as i64))
1221    }
1222
1223    // AUTONOMOUS-BOT-IMPLEMENTED
1224    // TODO-HUMAN-REVIEW(#869)
1225    /// timer_delete: destroy a timer created by `timer_create`.
1226    pub async fn handle_timer_delete<G: Guest<Self>>(
1227        &self,
1228        guest: &mut G,
1229        call: syscalls::TimerDelete,
1230    ) -> Result<i64, Error> {
1231        let id = call.timerid();
1232        let signal_number = guest
1233            .thread_state()
1234            .posix_timers
1235            .lock()
1236            .unwrap()
1237            .signal(id)
1238            .ok_or(Errno::EINVAL)?;
1239        let existed = {
1240            let mut timers = guest.thread_state().posix_timers.lock().unwrap();
1241            timers.remove(id)
1242        };
1243        if existed {
1244            if let Some(signo) = signal_number
1245                && self.posix_timer_expiry_is_registered(signo)
1246            {
1247                register_posix_timer(
1248                    guest,
1249                    id,
1250                    None,
1251                    LogicalTime::ZERO,
1252                    PosixTimerNotification {
1253                        sig: SigWrapper(signo),
1254                        thread: None,
1255                        value: 0,
1256                        deleted: true,
1257                    },
1258                )
1259                .await;
1260            }
1261            detlog!(
1262                "[dtid {}] timer_delete(id={})",
1263                guest.thread_state().dettid,
1264                id,
1265            );
1266            Ok(0)
1267        } else {
1268            Err(Errno::EINVAL.into())
1269        }
1270    }
1271}
1272
1273/// The scheduler's remaining time (`None`: the caller's own answer stands)
1274/// and overrun of the calling process's POSIX timer `id` at `now`, where it
1275/// keeps them (`DiscardedSignalControl::TimerReadout`); `None` elsewhere.
1276async fn posix_timer_readout<G: Guest<Detcore<T>>, T: RecordOrReplay>(
1277    guest: &mut G,
1278    id: i32,
1279    now: LogicalTime,
1280) -> Option<(Option<LogicalTime>, i32)> {
1281    use crate::scheduler::discarded_at_send::DiscardedSignalAnswer;
1282    use crate::scheduler::discarded_at_send::DiscardedSignalControl;
1283    if !crate::scheduler::discarded_at_send::records(guest.config()) {
1284        return None;
1285    }
1286    match crate::tool_global::discarded_signal(
1287        guest,
1288        DiscardedSignalControl::TimerReadout { timer: id, now },
1289    )
1290    .await
1291    {
1292        DiscardedSignalAnswer::TimerReadout { remaining, overrun } => Some((remaining, overrun)),
1293        _ => None,
1294    }
1295}
1296
1297#[cfg(test)]
1298mod tests {
1299    use super::*;
1300
1301    #[test]
1302    fn timex_policy_distinguishes_queries_from_mutations() {
1303        assert!(timex_mode_is_query(0));
1304        assert!(timex_mode_is_query(libc::ADJ_OFFSET_SS_READ));
1305        assert!(!timex_mode_is_query(libc::ADJ_OFFSET));
1306        assert!(!timex_mode_is_query(libc::ADJ_FREQUENCY));
1307    }
1308
1309    #[test]
1310    fn timex_snapshot_is_unsynchronized_and_uses_virtual_time() {
1311        let tx = deterministic_timex(Timespec {
1312            tv_sec: 123,
1313            tv_nsec: 456_789_000,
1314        });
1315        assert_eq!(tx.status, libc::STA_UNSYNC);
1316        assert_eq!(tx.tick, 10_000);
1317        assert_eq!(tx.time.tv_sec, 123);
1318        assert_eq!(tx.time.tv_usec, 456_789);
1319    }
1320
1321    #[test]
1322    fn interrupted_sleep_remaining_time_floors_at_zero() {
1323        let target = LogicalTime::from_nanos(1_000);
1324
1325        assert_eq!(
1326            remaining_sleep_duration(target, LogicalTime::from_nanos(750)),
1327            Duration::from_nanos(250)
1328        );
1329        assert_eq!(remaining_sleep_duration(target, target), Duration::ZERO);
1330        assert_eq!(
1331            remaining_sleep_duration(target, LogicalTime::from_nanos(1_250)),
1332            Duration::ZERO
1333        );
1334    }
1335
1336    mod failed_gettimeofday_tv {
1337        use super::*;
1338
1339        fn failure(error: Error) -> TvRepairFailure {
1340            match error {
1341                Error::Tool(error) => *error
1342                    .downcast_ref::<TvRepairFailure>()
1343                    .expect("a typed repair failure"),
1344                other => panic!("expected a Tool error, got {other:?}"),
1345            }
1346        }
1347
1348        #[test]
1349        fn successful_time_store_probe_requires_an_overwrite() {
1350            assert_eq!(
1351                classify_time_store_probe("tv_sec", Ok(1)).unwrap(),
1352                TimeStoreProbe::Stored
1353            );
1354        }
1355
1356        #[test]
1357        fn efault_time_store_probe_stops_without_an_overwrite() {
1358            assert_eq!(
1359                classify_time_store_probe("tv_usec", Err(Errno::EFAULT)).unwrap(),
1360                TimeStoreProbe::Stopped
1361            );
1362        }
1363
1364        #[test]
1365        fn any_control_probe_error_means_the_efault_was_not_a_store_fault() {
1366            require_native_time_control_probe("tv_sec", Ok(1_767_225_600)).unwrap();
1367            for errno in [Errno::EFAULT, Errno::EPERM, Errno::ENOSYS] {
1368                let error = require_native_time_control_probe("tv_usec", Err(errno))
1369                    .expect_err("time(NULL) cannot fail natively");
1370                assert_eq!(
1371                    failure(error),
1372                    TvRepairFailure {
1373                        field: "tv_usec",
1374                        kind: TvRepairFailureKind::ControlProbeFailed(errno),
1375                    }
1376                );
1377            }
1378        }
1379
1380        #[test]
1381        fn a_stopped_word_must_keep_its_contents_and_readability() {
1382            assert_eq!(
1383                require_unchanged_stopped_word("tv_sec", Ok(7), Ok(7)).unwrap(),
1384                StoppedWord::Unchanged
1385            );
1386            for (before, after) in [(Errno::EFAULT, Errno::EFAULT), (Errno::EIO, Errno::EPERM)] {
1387                assert_eq!(
1388                    require_unchanged_stopped_word("tv_sec", Err(before), Err(after)).unwrap(),
1389                    StoppedWord::Unreadable
1390                );
1391            }
1392            for (before, after) in [
1393                (Ok(7), Ok(1_791_041_091)),
1394                (Ok(7), Err(Errno::EFAULT)),
1395                (Err(Errno::EFAULT), Ok(7)),
1396            ] {
1397                let error = require_unchanged_stopped_word("tv_usec", before, after)
1398                    .expect_err("a changed stopped word means the call stored it");
1399                assert_eq!(
1400                    failure(error),
1401                    TvRepairFailure {
1402                        field: "tv_usec",
1403                        kind: TvRepairFailureKind::StoppedWordChanged,
1404                    }
1405                );
1406            }
1407        }
1408
1409        #[test]
1410        fn an_unreadable_word_is_unstored_only_if_part_of_it_is_unmapped() {
1411            const PAGE: u64 = 0x1000;
1412            let two_pages = || Ok(vec![(3 * PAGE, 4 * PAGE), (2 * PAGE, 3 * PAGE)]);
1413            // Outside every mapping, and straddling either end of the mapped pages.
1414            for word in [1, 2 * PAGE - 4, 4 * PAGE - 4, 5 * PAGE, u64::MAX - 3] {
1415                require_unmapped_unreadable_word("tv_sec", two_pages(), word).unwrap();
1416            }
1417            // Inside one page, and across the boundary of two adjacent mappings.
1418            for word in [2 * PAGE, 3 * PAGE - 4, 4 * PAGE - 8] {
1419                let error = require_unmapped_unreadable_word("tv_usec", two_pages(), word)
1420                    .expect_err("a failed read of a mapped word is not a fault");
1421                assert_eq!(
1422                    failure(error),
1423                    TvRepairFailure {
1424                        field: "tv_usec",
1425                        kind: TvRepairFailureKind::StoppedWordUnreadable,
1426                    }
1427                );
1428            }
1429        }
1430
1431        #[test]
1432        fn an_unreadable_word_needs_a_readable_nonempty_map() {
1433            let unreadable = Err(Error::Errno(Errno::EPERM));
1434            for maps in [Ok(Vec::new()), unreadable] {
1435                let error = require_unmapped_unreadable_word("tv_sec", maps, 1)
1436                    .expect_err("without a map an unreadable word proves nothing");
1437                assert_eq!(
1438                    failure(error),
1439                    TvRepairFailure {
1440                        field: "tv_sec",
1441                        kind: TvRepairFailureKind::MapsUnavailable,
1442                    }
1443                );
1444            }
1445        }
1446
1447        #[test]
1448        fn other_time_store_probe_errors_fail_closed() {
1449            for errno in [Errno::ENOSYS, Errno::EPERM, Errno::EIO] {
1450                let error = classify_time_store_probe("tv_sec", Err(errno))
1451                    .expect_err("a non-EFAULT probe error must fail the repair");
1452                assert_eq!(
1453                    failure(error),
1454                    TvRepairFailure {
1455                        field: "tv_sec",
1456                        kind: TvRepairFailureKind::ProbeFailed(errno),
1457                    }
1458                );
1459            }
1460        }
1461
1462        #[test]
1463        fn overwrite_errors_and_nonexact_counts_fail_closed() {
1464            assert_eq!(
1465                failure(
1466                    require_complete_time_word_overwrite("tv_usec", 8, Err(Errno::EFAULT),)
1467                        .unwrap_err()
1468                ),
1469                TvRepairFailure {
1470                    field: "tv_usec",
1471                    kind: TvRepairFailureKind::OverwriteFailed(Errno::EFAULT),
1472                }
1473            );
1474            for reported in [0, 3, 7, 9] {
1475                assert_eq!(
1476                    failure(
1477                        require_complete_time_word_overwrite("tv_sec", 8, Ok(reported))
1478                            .unwrap_err()
1479                    ),
1480                    TvRepairFailure {
1481                        field: "tv_sec",
1482                        kind: TvRepairFailureKind::OverwriteCount {
1483                            expected: 8,
1484                            reported,
1485                        },
1486                    }
1487                );
1488            }
1489            require_complete_time_word_overwrite("tv_sec", 8, Ok(8)).unwrap();
1490
1491            require_live_time_store_probe(false).unwrap();
1492            assert_eq!(
1493                failure(require_live_time_store_probe(true).unwrap_err()),
1494                TvRepairFailure {
1495                    field: "tv",
1496                    kind: TvRepairFailureKind::ReplayMode,
1497                }
1498            );
1499        }
1500
1501        #[test]
1502        fn timeval_word_addresses_follow_kernel_order_and_overflow_fails_closed_only_for_probes() {
1503            assert_eq!(TIMEVAL_WORDS, [("tv_sec", 0), ("tv_usec", 8)]);
1504            let tv_addr = AddrMut::<Timeval>::from_raw(0x10_0000).unwrap();
1505            assert_eq!(
1506                timeval_word_addr("tv_sec", tv_addr, std::mem::offset_of!(Timeval, tv_sec))
1507                    .unwrap()
1508                    .as_raw(),
1509                tv_addr.as_raw()
1510            );
1511            assert_eq!(
1512                timeval_word_addr("tv_usec", tv_addr, std::mem::offset_of!(Timeval, tv_usec))
1513                    .unwrap()
1514                    .as_raw(),
1515                tv_addr.as_raw() + 8
1516            );
1517
1518            let overflowing = AddrMut::<Timeval>::from_raw(usize::MAX - 3).unwrap();
1519            let error = timeval_word_addr("tv_usec", overflowing, 8)
1520                .expect_err("overflowing field address must fail the repair");
1521            assert_eq!(
1522                failure(error),
1523                TvRepairFailure {
1524                    field: "tv_usec",
1525                    kind: TvRepairFailureKind::AddressOverflow,
1526                }
1527            );
1528
1529            // Checking a stopped word needs no probe, so a word past the end of
1530            // the address space is simply one no store reached.
1531            for (_, offset) in TIMEVAL_WORDS {
1532                assert_eq!(
1533                    stopped_timeval_word_addr(tv_addr, offset).map(|addr| addr.as_raw()),
1534                    Some(tv_addr.as_raw() + offset)
1535                );
1536            }
1537            // `gettimeofday((void *)-1, NULL)`: `tv_sec` is the last byte of
1538            // the address space and `tv_usec` has no address at all.
1539            let last = AddrMut::<Timeval>::from_raw(usize::MAX).unwrap();
1540            assert_eq!(
1541                stopped_timeval_word_addr(last, 0).map(|addr| addr.as_raw()),
1542                Some(usize::MAX)
1543            );
1544            assert!(stopped_timeval_word_addr(last, 8).is_none());
1545            assert!(stopped_timeval_word_addr(overflowing, 8).is_none());
1546        }
1547    }
1548}