Skip to main content

detcore/syscalls/
sysinfo.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
9use procfs::process::Process;
10use reverie::Error;
11use reverie::Guest;
12use reverie::syscalls;
13use reverie::syscalls::Errno;
14use reverie::syscalls::MemoryAccess;
15use reverie::syscalls::Sysno;
16
17use crate::Detcore;
18use crate::RecordOrReplay;
19use crate::tool_global::thread_observe_time;
20use crate::tool_local::ResourceLimit;
21
22// Linux exposes USER_HZ, not the kernel's configurable scheduler HZ, through times(2).
23const CLOCK_TICKS_PER_SECOND: u64 = 100;
24const NANOS_PER_CLOCK_TICK: u64 = 1_000_000_000 / CLOCK_TICKS_PER_SECOND;
25
26fn clock_ticks(duration: crate::types::LogicalTime) -> u64 {
27    duration.as_nanos() / NANOS_PER_CLOCK_TICK
28}
29
30fn clock_t_from_ticks(ticks: u64) -> libc::clock_t {
31    ticks as libc::clock_t
32}
33
34const NANOS_PER_SECOND: u64 = 1_000_000_000;
35const NANOS_PER_MICROSECOND: u64 = 1_000;
36
37/// Render a logical CPU duration as the `timeval` `getrusage(2)` reports.
38///
39/// Linux truncates rusage CPU times to microsecond granularity, so the sub-microsecond
40/// remainder of the logical duration is discarded rather than rounded. Truncation (not
41/// rounding) is what keeps the value monotonic: a duration that grows by less than a
42/// microsecond must never make the reported total go backwards, and rounding-to-nearest
43/// on a shrinking remainder can do exactly that.
44fn timeval_from_logical(duration: crate::types::LogicalTime) -> libc::timeval {
45    let nanos = duration.as_nanos();
46    libc::timeval {
47        tv_sec: (nanos / NANOS_PER_SECOND) as libc::time_t,
48        tv_usec: ((nanos % NANOS_PER_SECOND) / NANOS_PER_MICROSECOND) as libc::suseconds_t,
49    }
50}
51
52fn logical_clock_ticks(
53    now: crate::types::LogicalTime,
54    boot: crate::types::LogicalTime,
55    uptime_offset_seconds: u64,
56) -> libc::clock_t {
57    let ticks = uptime_offset_seconds
58        .wrapping_mul(CLOCK_TICKS_PER_SECOND)
59        .wrapping_add(clock_ticks(now - boot));
60    clock_t_from_ticks(ticks)
61}
62
63/// Project elapsed logical time into Linux's integer `sysinfo(2)` uptime.
64///
65/// Linux rounds a positive fractional boottime up to the next second. Subtract
66/// the exact internal epoch first so its calendar fraction cannot affect the
67/// result. This projection does not alter the underlying logical clock.
68fn sysinfo_uptime_seconds(
69    now: crate::types::LogicalTime,
70    epoch: crate::types::LogicalTime,
71    uptime_offset_seconds: u64,
72) -> Result<u64, Error> {
73    let now_ns = now.as_nanos();
74    let epoch_ns = epoch.as_nanos();
75    let elapsed_ns = now_ns.checked_sub(epoch_ns).ok_or_else(|| {
76        Error::Tool(anyhow::anyhow!(
77            "sysinfo observed logical time {now_ns} ns before epoch {epoch_ns} ns"
78        ))
79    })?;
80    // Divide before rounding: adding NANOS_PER_SECOND - 1 to elapsed_ns can
81    // overflow. The rounded quotient of any u64 nanosecond duration fits u64.
82    let seconds =
83        elapsed_ns / NANOS_PER_SECOND + u64::from(!elapsed_ns.is_multiple_of(NANOS_PER_SECOND));
84    // Config accepts the full u64 offset; preserve its existing release-build
85    // wrapping extension, including the subsequent SysInfo -> c_long ABI cast.
86    // Ordinary Linux uptime semantics apply within the nonnegative c_long range.
87    Ok(uptime_offset_seconds.wrapping_add(seconds))
88}
89
90/// Render the whole-second part of `/proc/uptime` from an absolute logical clock.
91///
92/// Linux's `uptime_proc_show` prints `tv_sec` followed by truncated
93/// centiseconds, so the integer part is the floor of the elapsed time.
94/// Subtract before truncating. Truncating `now` and `boot` separately makes a
95/// sub-second run appear one second old whenever it crosses an absolute-second
96/// boundary, even though less than one logical second elapsed.
97fn procfs_uptime_seconds(
98    now: crate::types::LogicalTime,
99    boot: crate::types::LogicalTime,
100    uptime_offset_seconds: u64,
101) -> u64 {
102    uptime_offset_seconds + (now - boot).as_secs()
103}
104
105/// Render `/proc/stat`'s `btime` from the logical boot instant.
106///
107/// Linux's `show_stat` prints the seconds of `getboottime64`, a fixed instant
108/// that moves only when the realtime clock or time-namespace offset changes.
109/// Derive it from the boot instant itself, never as `floor(now) - uptime`: for
110/// a fractional boot those two floors round independently, so ordinary
111/// elapsed time would move `btime` back and forth by one second.
112///
113/// Config accepts every u64 offset, and an offset above `i64::MAX` can still
114/// place the boot instant inside time64_t. Subtract in i128, where every such
115/// difference is exact, and range-check only the result. `None` means the
116/// boot instant itself precedes `i64::MIN` seconds.
117fn procfs_boot_time_seconds(
118    boot: crate::types::LogicalTime,
119    uptime_offset_seconds: u64,
120) -> Option<i64> {
121    i64::try_from(i128::from(boot.as_secs()) - i128::from(uptime_offset_seconds)).ok()
122}
123
124fn prlimit_targets_current_process(
125    target_pid: i32,
126    deterministic_pid: Option<i32>,
127    physical_pid: i32,
128) -> bool {
129    target_pid == 0 || target_pid == deterministic_pid.unwrap_or(physical_pid)
130}
131
132fn validate_resource_limit_mutation(
133    resource: u32,
134    previous: ResourceLimit,
135    requested: ResourceLimit,
136) -> Result<(), Errno> {
137    if requested.current > requested.maximum {
138        return Err(Errno::EINVAL);
139    }
140    // Linux accepts an exact no-op for every valid resource, including limits
141    // that an unprivileged process could not otherwise change. Recognize that
142    // case before applying Detcore's narrower virtual-mutation policy.
143    if requested == previous {
144        return Ok(());
145    }
146    // CORE is virtual compatibility state too: changing it cannot enable host
147    // core dumps, while Linux sanitizers routinely lower its soft limit.
148    if resource != libc::RLIMIT_STACK
149        && resource != libc::RLIMIT_NOFILE
150        && resource != libc::RLIMIT_CORE
151    {
152        return Err(Errno::EPERM);
153    }
154    if requested.maximum > previous.maximum {
155        return Err(Errno::EPERM);
156    }
157    Ok(())
158}
159
160/// The record of a resource-limit read that a loader served before post-exec
161/// ([`crate::random::EarlyRequest::LimitRead`]), emitted by post-exec. It is
162/// the record [`Detcore::handle_prlimit64`] emits for the same read, from the
163/// same module; a `getrlimit` read records nothing, as in `handle_getrlimit`.
164pub(crate) fn record_early_limit_read(
165    call: crate::random::LimitReadCall,
166    resource: u32,
167    current: u64,
168    maximum: u64,
169) {
170    if let crate::random::LimitReadCall::Prlimit64 { pid } = call {
171        crate::detlog!(
172            "prlimit64: pid={pid}, resource={resource}, mutation=false, old={current}:{maximum}"
173        );
174    }
175}
176
177impl<T: RecordOrReplay> Detcore<T> {
178    // AUTONOMOUS-BOT-IMPLEMENTED
179    // TODO-HUMAN-REVIEW(#663)
180    /// Return one deterministic process resource limit through the legacy ABI.
181    pub async fn handle_getrlimit<G: Guest<Self>>(
182        &self,
183        guest: &mut G,
184        call: syscalls::Getrlimit,
185    ) -> Result<i64, Error> {
186        let resource = u32::try_from(call.resource()).map_err(|_| Errno::EINVAL)?;
187        let address = call.rlim().ok_or(Errno::EFAULT)?;
188        let limit = guest
189            .thread_state()
190            .resource_limits
191            .lock()
192            .expect("resource limits mutex poisoned")
193            .get(resource)
194            .ok_or(Errno::EINVAL)?;
195        let result = libc::rlimit {
196            rlim_cur: limit.current,
197            rlim_max: limit.maximum,
198        };
199        guest.memory().write_value(address, &result)?;
200        Ok(0)
201    }
202
203    // AUTONOMOUS-BOT-IMPLEMENTED
204    // TODO-HUMAN-REVIEW(#663)
205    /// Update one virtual process resource limit through the legacy ABI.
206    pub async fn handle_setrlimit<G: Guest<Self>>(
207        &self,
208        guest: &mut G,
209        call: syscalls::Setrlimit,
210    ) -> Result<i64, Error> {
211        let resource = u32::try_from(call.resource()).map_err(|_| Errno::EINVAL)?;
212        let address = call.rlim().ok_or(Errno::EFAULT)?;
213        let requested: libc::rlimit = guest.memory().read_value(address)?;
214        let requested = ResourceLimit {
215            current: requested.rlim_cur,
216            maximum: requested.rlim_max,
217        };
218        let resource_limits = guest.thread_state().resource_limits.clone();
219        let mut limits = resource_limits
220            .lock()
221            .expect("resource limits mutex poisoned");
222        let previous = limits.get(resource).ok_or(Errno::EINVAL)?;
223        validate_resource_limit_mutation(resource, previous, requested)?;
224        if requested != previous {
225            limits.set(resource, requested);
226        }
227        Ok(0)
228    }
229
230    /// Virtualize `prlimit64(2)` for the current guest process.
231    ///
232    /// Queries return process-local deterministic values. Exact no-op updates
233    /// succeed for every valid resource, as on Linux. Changes are kept virtual
234    /// and restricted to limits that do not grant access to host resources or
235    /// affect host scheduling. Accepted changes update only guest-observable
236    /// compatibility state; they are not a sandbox boundary and do not ask the
237    /// host kernel to enforce the virtual limit.
238    // AUTONOMOUS-BOT-IMPLEMENTED
239    // TODO-HUMAN-REVIEW(#534)
240    pub async fn handle_prlimit64<G: Guest<Self>>(
241        &self,
242        guest: &mut G,
243        call: syscalls::Prlimit64,
244    ) -> Result<i64, Error> {
245        let resource = call.resource();
246        let resource_limits = guest.thread_state().resource_limits.clone();
247        if resource_limits
248            .lock()
249            .expect("resource limits mutex poisoned")
250            .get(resource)
251            .is_none()
252        {
253            return Err(Errno::EINVAL.into());
254        }
255
256        let requested = if let Some(address) = call.new_rlim() {
257            let limit: libc::rlimit64 = guest.memory().read_value(address)?;
258            Some(ResourceLimit {
259                current: limit.rlim_cur,
260                maximum: limit.rlim_max,
261            })
262        } else {
263            None
264        };
265
266        // A nested caller names its process by its own namespace's pid
267        // (https://github.com/rrnewton/hermit/issues/4155); a pid no task of
268        // that namespace has is ESRCH, as Linux's `find_task_by_vpid` answers.
269        let pid = if call.pid() > 0 && guest.thread_state().nested_pid_namespace {
270            match crate::tool_global::guest_pid(guest, call.pid()).await {
271                crate::scheduler::pid_namespaces::GuestPidAnswer::Task { task, .. } => {
272                    task.as_raw()
273                }
274                crate::scheduler::pid_namespaces::GuestPidAnswer::NoSuchPid => {
275                    return Err(Errno::ESRCH.into());
276                }
277                crate::scheduler::pid_namespaces::GuestPidAnswer::Untranslatable(reason) => {
278                    tracing::error!(
279                        "[detcore, dtid {}] prlimit64 from a nested PID namespace is not supported: {} (https://github.com/rrnewton/hermit/issues/4155)",
280                        guest.thread_state().dettid,
281                        reason,
282                    );
283                    return self
284                        .refuse_unserviceable_operation(guest, Sysno::prlimit64, Errno::ENOSYS)
285                        .await;
286                }
287            }
288        } else {
289            call.pid()
290        };
291        let deterministic_pid = guest.thread_state().detpid.map(|detpid| detpid.as_raw());
292        if !prlimit_targets_current_process(pid, deterministic_pid, guest.pid().as_raw()) {
293            return Err(Errno::EPERM.into());
294        }
295
296        let previous = {
297            let mut limits = resource_limits
298                .lock()
299                .expect("resource limits mutex poisoned");
300            let previous = limits
301                .get(resource)
302                .expect("resource validity changed while handling prlimit64");
303
304            if let Some(requested) = requested {
305                validate_resource_limit_mutation(resource, previous, requested)?;
306                if requested != previous {
307                    limits.set(resource, requested);
308                }
309            }
310
311            previous
312        };
313
314        if let Some(address) = call.old_rlim() {
315            let previous = libc::rlimit64 {
316                rlim_cur: previous.current,
317                rlim_max: previous.maximum,
318            };
319            guest.memory().write_value(address, &previous)?;
320        }
321
322        crate::detlog!(
323            "prlimit64: pid={pid}, resource={resource}, mutation={}, old={}:{}",
324            requested.is_some(),
325            previous.current,
326            previous.maximum
327        );
328        Ok(0)
329    }
330    /// Return a deterministic resource-usage snapshot.
331    ///
332    /// `ru_utime`/`ru_stime` come from the SAME logical CPU accounting that backs `times(2)`
333    /// (see [`Self::handle_times`]), not from host scheduler counters. Reporting them as zero,
334    /// as this did previously, was both a fidelity bug and an internal contradiction: a guest
335    /// that called `times(2)` saw advancing CPU time while `getrusage(2)` insisted the same
336    /// process had consumed none. Deriving both from `ProcessCpuSnapshot` makes the two
337    /// syscalls agree by construction rather than by coincidence.
338    ///
339    /// The `who` values report different aggregates, matching Linux:
340    /// - `RUSAGE_SELF` — this process, summed across its threads.
341    /// - `RUSAGE_THREAD` — the calling thread alone. This reads the thread's own logical CPU
342    ///   counters rather than the process totals; substituting the process aggregate would
343    ///   over-report for every multithreaded guest.
344    /// - `RUSAGE_CHILDREN` — reaped children only, which is exactly what the `children_*`
345    ///   fields accumulate on `wait`.
346    ///
347    /// `ru_maxrss` is populated for the process/thread cases with the guest's peak resident set
348    /// size so that programs which require a positive maximum RSS (e.g. rr's `rusage` test)
349    /// behave like they do on Linux. This remains a best-effort host-procfs observation on
350    /// backends where [`Guest::pid`] names a host process; it is separate from the configured
351    /// system-wide memory reported by `sysinfo(2)` and virtual `/proc/meminfo`.
352    ///
353    /// Page-fault and context-switch counts remain zero: Detcore does not model them, and
354    /// synthesizing a plausible-looking number would be worse than reporting none.
355    pub async fn handle_getrusage<G: Guest<Self>>(
356        &self,
357        guest: &mut G,
358        call: syscalls::Getrusage,
359    ) -> Result<i64, Error> {
360        let who = call.who();
361        match who {
362            libc::RUSAGE_SELF | libc::RUSAGE_CHILDREN | libc::RUSAGE_THREAD => {}
363            _ => return Err(Errno::EINVAL.into()),
364        }
365
366        let usage_addr = call.usage().ok_or(Errno::EFAULT)?;
367
368        // SAFETY: `libc::rusage` is a plain-old-data C struct that is valid when zero-initialized.
369        let mut usage: libc::rusage = unsafe { std::mem::zeroed() };
370
371        let (user, system) = match who {
372            libc::RUSAGE_THREAD => guest.thread_state_mut().thread_cpu_time(),
373            libc::RUSAGE_CHILDREN => {
374                let cpu = guest.thread_state_mut().process_cpu_time();
375                (cpu.children_user, cpu.children_system)
376            }
377            // RUSAGE_SELF
378            _ => {
379                let cpu = guest.thread_state_mut().process_cpu_time();
380                (cpu.user, cpu.system)
381            }
382        };
383        usage.ru_utime = timeval_from_logical(user);
384        usage.ru_stime = timeval_from_logical(system);
385
386        // RUSAGE_SELF/RUSAGE_THREAD report this process's peak RSS. RUSAGE_CHILDREN aggregates
387        // terminated children only; with no such accounting we leave it zero, matching Linux when
388        // no child has exited.
389        if matches!(who, libc::RUSAGE_SELF | libc::RUSAGE_THREAD) {
390            usage.ru_maxrss = self.guest_peak_rss_kb(guest) as libc::c_long;
391        }
392
393        guest.memory().write_value(usage_addr, &usage)?;
394        Ok(0)
395    }
396
397    // AUTONOMOUS-BOT-IMPLEMENTED
398    // TODO-HUMAN-REVIEW(#797): Review logical elapsed and process CPU accounting semantics.
399    /// Return deterministic elapsed ticks and process CPU accounting for `times(2)`.
400    ///
401    /// Linux's host boot epoch and scheduler CPU counters are nondeterministic. Detcore instead
402    /// derives the return value from its global logical clock. Per-process logical CPU accounting
403    /// aggregates user instruction and syscall-system time across threads; forked processes start
404    /// fresh counters and contribute their totals to the parent's child counters when reaped.
405    pub async fn handle_times<G: Guest<Self>>(
406        &self,
407        guest: &mut G,
408        call: syscalls::Times,
409    ) -> Result<i64, Error> {
410        let now = thread_observe_time(guest).await;
411        let boot = crate::types::DetTime::new(&self.cfg).as_nanos();
412        let ticks = logical_clock_ticks(now, boot, self.cfg.sysinfo_uptime_offset);
413        let cpu = guest.thread_state_mut().process_cpu_time();
414
415        if let Some(address) = call.buf() {
416            let usage = libc::tms {
417                tms_utime: clock_t_from_ticks(clock_ticks(cpu.user)),
418                tms_stime: clock_t_from_ticks(clock_ticks(cpu.system)),
419                tms_cutime: clock_t_from_ticks(clock_ticks(cpu.children_user)),
420                tms_cstime: clock_t_from_ticks(clock_ticks(cpu.children_system)),
421            };
422            guest.memory().write_value(address, &usage)?;
423        }
424
425        Ok(ticks as i64)
426    }
427
428    /// The guest's peak resident set size ("high water mark") in kibibytes, matching the units of
429    /// Linux `getrusage`'s `ru_maxrss`. This reads host procfs through [`Guest::pid`], which only
430    /// identifies the guest process on backends where it names a host process; always returns a
431    /// positive value so guests can rely on a nonzero maximum RSS even if the read fails.
432    fn guest_peak_rss_kb<G: Guest<Self>>(&self, guest: &G) -> u64 {
433        Process::new(guest.pid().as_raw())
434            .and_then(|process| process.status())
435            .ok()
436            .and_then(|status| status.vmhwm.or(status.vmrss))
437            .unwrap_or(0)
438            .max(1)
439    }
440
441    /// handle sysinfo syscall
442    pub async fn handle_sysinfo<G: Guest<Self>>(
443        &self,
444        guest: &mut G,
445        call: syscalls::Sysinfo,
446    ) -> Result<i64, Error> {
447        let info_addr = call.info().ok_or(Errno::EFAULT)?;
448        let sys_info = self.collect_sysinfo(guest).await?;
449        let mut memory = guest.memory();
450
451        memory.write_value(info_addr, &sys_info.into())?;
452        Ok(0)
453    }
454
455    /// Whole-second `/proc/uptime` value (floor of elapsed logical time).
456    pub(super) async fn calculate_procfs_uptime<G: Guest<Self>>(
457        &self,
458        guest: &mut G,
459    ) -> Result<u64, Error> {
460        let global_time = thread_observe_time(guest).await;
461        Ok(procfs_uptime_seconds(
462            global_time,
463            crate::types::DetTime::new(&self.cfg).as_nanos(),
464            self.cfg.sysinfo_uptime_offset,
465        ))
466    }
467
468    /// Whole-second `/proc/stat` `btime`, fixed for the life of the run.
469    ///
470    /// `EOVERFLOW` only when the boot instant precedes `i64::MIN` seconds.
471    /// Only snapshots that render `btime` may ask, so that refusal stays
472    /// local to `/proc/stat`.
473    pub(super) fn calculate_procfs_boot_time(&self) -> Result<i64, Error> {
474        procfs_boot_time_seconds(
475            crate::types::DetTime::new(&self.cfg).as_nanos(),
476            self.cfg.sysinfo_uptime_offset,
477        )
478        .ok_or_else(|| Errno::EOVERFLOW.into())
479    }
480
481    async fn collect_sysinfo<G: Guest<Self>>(
482        &self,
483        guest: &mut G,
484    ) -> Result<syscalls::SysInfo, Error> {
485        let memory = configured_memory(crate::machine::MachineDescription::of(&self.cfg).memory);
486        let now = thread_observe_time(guest).await;
487        let epoch = crate::types::DetTime::new(&self.cfg).as_nanos();
488        Ok(syscalls::SysInfo {
489            uptime: sysinfo_uptime_seconds(now, epoch, self.cfg.sysinfo_uptime_offset)?,
490            loads_1: 1,
491            loads_5: 1,
492            loads_15: 1,
493            total_ram: memory.total_ram,
494            free_ram: memory.free_ram,
495            buffer_ram: memory.buffer_ram,
496            shared_ram: memory.shared_ram,
497            total_swap: memory.total_swap,
498            free_swap: memory.free_swap,
499            procs: 1,
500            total_high: memory.total_high,
501            free_high: memory.free_high,
502            mem_unit: memory.mem_unit,
503        })
504    }
505}
506
507// AUTONOMOUS-BOT-IMPLEMENTED
508// TODO-HUMAN-REVIEW(PR-2979): Deterministic free-memory accounting for sysinfo(2).
509#[derive(Debug, PartialEq, Eq)]
510struct ConfiguredMemory {
511    total_ram: u64,
512    free_ram: u64,
513    buffer_ram: u64,
514    shared_ram: u64,
515    total_swap: u64,
516    free_swap: u64,
517    total_high: u64,
518    free_high: u64,
519    mem_unit: u32,
520}
521
522/// Report the configured guest memory consistently with virtual `/proc/meminfo`.
523///
524/// Linux `sysinfo(2)` describes system-wide memory, not one process's virtual
525/// mappings. Detcore does not model allocation pressure within its configured
526/// memory limit, so all configured memory remains available and the other
527/// modeled memory categories remain empty.
528fn configured_memory(memory: u64) -> ConfiguredMemory {
529    ConfiguredMemory {
530        total_ram: memory,
531        free_ram: memory,
532        buffer_ram: 0,
533        shared_ram: 0,
534        total_swap: 0,
535        free_swap: 0,
536        total_high: 0,
537        free_high: 0,
538        mem_unit: 1,
539    }
540}
541
542#[cfg(test)]
543mod tests {
544    use super::*;
545    use crate::types::LogicalTime;
546
547    #[test]
548    fn logical_clock_ticks_include_boot_offset_and_fractional_seconds() {
549        let boot = LogicalTime::from_secs(1_000);
550        let now = boot + LogicalTime::from_millis(25);
551
552        assert_eq!(logical_clock_ticks(now, boot, 120), 12_002);
553    }
554
555    #[test]
556    fn sysinfo_uptime_rounds_positive_elapsed_up() {
557        let epoch = LogicalTime::from_nanos(1_000_000_000_000);
558        for (elapsed_ns, expected_zero, expected_offset) in [
559            (0, 0, 120),
560            (1, 1, 121),
561            (999_999_999, 1, 121),
562            (1_000_000_000, 1, 121),
563            (1_000_000_001, 2, 122),
564            (1_200_000_000, 2, 122),
565        ] {
566            let now = epoch + LogicalTime::from_nanos(elapsed_ns);
567            assert_eq!(
568                sysinfo_uptime_seconds(now, epoch, 0).unwrap(),
569                expected_zero,
570                "elapsed {elapsed_ns} ns without boot offset"
571            );
572            assert_eq!(
573                sysinfo_uptime_seconds(now, epoch, 120).unwrap(),
574                expected_offset,
575                "elapsed {elapsed_ns} ns with boot offset"
576            );
577        }
578    }
579
580    #[test]
581    fn sysinfo_uptime_ignores_epoch_fraction() {
582        for fraction_ns in [0, 1, 1_000, 999_999_000, 999_999_999] {
583            let epoch = LogicalTime::from_nanos(1_000_000_000_000 + fraction_ns);
584            for (elapsed_ns, expected) in [
585                (0, 120),
586                (1, 121),
587                (999_999_999, 121),
588                (1_000_000_000, 121),
589                (1_000_000_001, 122),
590                (1_200_000_000, 122),
591            ] {
592                let now = epoch + LogicalTime::from_nanos(elapsed_ns);
593                assert_eq!(
594                    sysinfo_uptime_seconds(now, epoch, 120).unwrap(),
595                    expected,
596                    "epoch fraction {fraction_ns} ns, elapsed {elapsed_ns} ns"
597                );
598            }
599        }
600    }
601
602    #[test]
603    fn sysinfo_uptime_rounds_maximum_duration_without_overflow() {
604        let epoch = LogicalTime::from_nanos(0);
605        assert_eq!(
606            sysinfo_uptime_seconds(LogicalTime::MAX, epoch, 0).unwrap(),
607            18_446_744_074
608        );
609        assert_eq!(
610            sysinfo_uptime_seconds(
611                LogicalTime::from_nanos(18_446_744_073_000_000_000),
612                epoch,
613                120,
614            )
615            .unwrap(),
616            18_446_744_193
617        );
618        // An absolute timestamp at the representation limit need not have a
619        // large elapsed duration; subtraction must precede the projection.
620        assert_eq!(
621            sysinfo_uptime_seconds(LogicalTime::MAX, LogicalTime::from_nanos(u64::MAX - 1), 120,)
622                .unwrap(),
623            121
624        );
625    }
626
627    #[test]
628    fn sysinfo_uptime_preserves_wrapping_offset_extension() {
629        let epoch = LogicalTime::from_nanos(0);
630        for (elapsed_ns, offset, expected) in [
631            (0, u64::MAX, u64::MAX),
632            (1, u64::MAX, 0),
633            (1_000_000_000, u64::MAX, 0),
634            (1_000_000_001, u64::MAX, 1),
635            (1, u64::MAX - 1, u64::MAX),
636            (1_000_000_001, u64::MAX - 1, 0),
637        ] {
638            assert_eq!(
639                sysinfo_uptime_seconds(LogicalTime::from_nanos(elapsed_ns), epoch, offset).unwrap(),
640                expected,
641                "elapsed {elapsed_ns} ns, offset {offset}"
642            );
643        }
644    }
645
646    #[test]
647    fn sysinfo_uptime_preserves_signed_abi_conversion() {
648        let epoch = LogicalTime::from_nanos(0);
649        for (elapsed_ns, offset, expected) in [
650            (0, i64::MAX as u64, i64::MAX),
651            (1, i64::MAX as u64, i64::MIN),
652            (0, u64::MAX, -1),
653            (1, u64::MAX, 0),
654        ] {
655            let uptime =
656                sysinfo_uptime_seconds(LogicalTime::from_nanos(elapsed_ns), epoch, offset).unwrap();
657            let info: libc::sysinfo = syscalls::SysInfo {
658                uptime,
659                loads_1: 0,
660                loads_5: 0,
661                loads_15: 0,
662                total_ram: 0,
663                free_ram: 0,
664                shared_ram: 0,
665                buffer_ram: 0,
666                total_swap: 0,
667                free_swap: 0,
668                procs: 0,
669                total_high: 0,
670                free_high: 0,
671                mem_unit: 1,
672            }
673            .into();
674            assert_eq!(info.uptime, expected);
675        }
676    }
677
678    #[test]
679    fn sysinfo_uptime_rejects_time_before_epoch() {
680        let error = sysinfo_uptime_seconds(
681            LogicalTime::from_nanos(999),
682            LogicalTime::from_nanos(1_000),
683            120,
684        )
685        .unwrap_err();
686        let Error::Tool(error) = error else {
687            panic!("an impossible clock must be a tool failure, got {error:?}");
688        };
689        assert_eq!(
690            error.to_string(),
691            "sysinfo observed logical time 999 ns before epoch 1000 ns"
692        );
693    }
694
695    #[test]
696    fn procfs_uptime_subtracts_fractional_boot_before_truncating() {
697        let boot = LogicalTime::from_nanos(1_000_999_999_999);
698
699        assert_eq!(
700            procfs_uptime_seconds(boot + LogicalTime::from_nanos(1), boot, 120),
701            120
702        );
703        assert_eq!(
704            procfs_uptime_seconds(boot + LogicalTime::from_secs(1), boot, 120),
705            121
706        );
707    }
708
709    #[test]
710    fn procfs_boot_time_is_the_boot_instant_not_now_minus_uptime() {
711        // The reviewed reproducer: boot 1000.75s, offset 120s. Linux reports
712        // the seconds of the fixed boot instant, 880, for every sample.
713        let boot = LogicalTime::from_nanos(1_000_750_000_000);
714        assert_eq!(procfs_boot_time_seconds(boot, 120), Some(880));
715
716        // `floor(now) - uptime` is what the fix replaced: at these samples it
717        // yields 880, 881, 880. Pin that the old derivation really did move,
718        // so this test keeps meaning something if the helpers change.
719        let old_btime =
720            |now: LogicalTime| now.as_secs() as i64 - procfs_uptime_seconds(now, boot, 120) as i64;
721        let samples = [100, 400, 1_100].map(|millis| boot + LogicalTime::from_millis(millis));
722        assert_eq!(samples.map(old_btime), [880, 881, 880]);
723
724        // For an integral boot the two derivations agree, so whole-second
725        // epochs render exactly what they rendered before.
726        let integral_boot = LogicalTime::from_secs(1_000);
727        let integral_now = integral_boot + LogicalTime::from_millis(1_400);
728        assert_eq!(
729            procfs_boot_time_seconds(integral_boot, 120),
730            Some(
731                integral_now.as_secs() as i64
732                    - procfs_uptime_seconds(integral_now, integral_boot, 120) as i64
733            )
734        );
735
736        assert_eq!(procfs_boot_time_seconds(boot, u64::MAX), None);
737    }
738
739    #[test]
740    fn procfs_boot_time_is_exact_for_every_offset_whose_result_fits() {
741        // Config accepts every u64 offset. 2026-01-01T00:00:00Z minus 2^63 s
742        // is -9223372035087550208, which time64_t represents even though the
743        // offset alone exceeds i64::MAX.
744        let boot = LogicalTime::from_secs(1_767_225_600);
745        assert_eq!(procfs_boot_time_seconds(boot, 0), Some(1_767_225_600));
746        assert_eq!(
747            procfs_boot_time_seconds(boot, 1 << 63),
748            Some(-9_223_372_035_087_550_208)
749        );
750        // The result, not the offset, bounds the domain: exactly i64::MIN is
751        // representable and one second earlier is not.
752        assert_eq!(
753            procfs_boot_time_seconds(boot, 1_767_225_600 + (1 << 63)),
754            Some(i64::MIN)
755        );
756        assert_eq!(
757            procfs_boot_time_seconds(boot, 1_767_225_600 + (1 << 63) + 1),
758            None
759        );
760        assert_eq!(procfs_boot_time_seconds(boot, u64::MAX), None);
761    }
762
763    #[test]
764    fn sysinfo_uptime_rounds_fractional_elapsed_up_like_linux() {
765        // A boot instant with a fractional absolute second: rounding must see
766        // only the elapsed time, never the absolute boundary crossing.
767        let boot = LogicalTime::from_nanos(1_000_999_999_999);
768
769        assert_eq!(sysinfo_uptime_seconds(boot, boot, 120).unwrap(), 120);
770        assert_eq!(
771            sysinfo_uptime_seconds(boot + LogicalTime::from_nanos(1), boot, 120).unwrap(),
772            121
773        );
774        assert_eq!(
775            sysinfo_uptime_seconds(boot + LogicalTime::from_millis(999), boot, 120).unwrap(),
776            121
777        );
778        assert_eq!(
779            sysinfo_uptime_seconds(boot + LogicalTime::from_secs(1), boot, 120).unwrap(),
780            121
781        );
782        assert_eq!(
783            sysinfo_uptime_seconds(
784                boot + LogicalTime::from_secs(1) + LogicalTime::from_nanos(1),
785                boot,
786                120
787            )
788            .unwrap(),
789            122
790        );
791        // The floor-based procfs value differs exactly on fractional elapsed.
792        let fractional = boot + LogicalTime::from_millis(1_500);
793        assert_eq!(procfs_uptime_seconds(fractional, boot, 120), 121);
794        assert_eq!(sysinfo_uptime_seconds(fractional, boot, 120).unwrap(), 122);
795    }
796
797    #[test]
798    fn sysinfo_memory_matches_configured_memory() {
799        assert_eq!(
800            configured_memory(1_000_000_000),
801            ConfiguredMemory {
802                total_ram: 1_000_000_000,
803                free_ram: 1_000_000_000,
804                buffer_ram: 0,
805                shared_ram: 0,
806                total_swap: 0,
807                free_swap: 0,
808                total_high: 0,
809                free_high: 0,
810                mem_unit: 1,
811            },
812        );
813    }
814
815    #[test]
816    fn prlimit_self_target_prefers_deterministic_process_identity() {
817        assert!(prlimit_targets_current_process(3, Some(3), 10_003));
818        assert!(prlimit_targets_current_process(0, Some(3), 10_003));
819        assert!(!prlimit_targets_current_process(10_003, Some(3), 10_003));
820        assert!(!prlimit_targets_current_process(4, Some(3), 10_003));
821    }
822
823    #[test]
824    fn prlimit_self_target_falls_back_to_physical_identity_before_init() {
825        assert!(prlimit_targets_current_process(10_003, None, 10_003));
826        assert!(!prlimit_targets_current_process(3, None, 10_003));
827    }
828
829    #[test]
830    fn prlimit_accepts_exact_noop_for_restricted_resource() {
831        let limit = ResourceLimit {
832            current: 0,
833            maximum: 0,
834        };
835        assert_eq!(
836            validate_resource_limit_mutation(libc::RLIMIT_CPU, limit, limit),
837            Ok(())
838        );
839    }
840
841    #[test]
842    fn prlimit_accepts_core_soft_limit_change() {
843        let previous = ResourceLimit {
844            current: 1,
845            maximum: 1,
846        };
847        let requested = ResourceLimit {
848            current: 0,
849            maximum: 1,
850        };
851        assert_eq!(
852            validate_resource_limit_mutation(libc::RLIMIT_CORE, previous, requested),
853            Ok(())
854        );
855    }
856
857    #[test]
858    fn prlimit_rejects_actual_change_to_restricted_resource() {
859        let previous = ResourceLimit {
860            current: 1,
861            maximum: 1,
862        };
863        let requested = ResourceLimit {
864            current: 0,
865            maximum: 1,
866        };
867        assert_eq!(
868            validate_resource_limit_mutation(libc::RLIMIT_CPU, previous, requested),
869            Err(Errno::EPERM)
870        );
871    }
872
873    #[test]
874    fn prlimit_rejects_invalid_soft_limit_before_noop_policy() {
875        let previous = ResourceLimit {
876            current: 1,
877            maximum: 1,
878        };
879        let requested = ResourceLimit {
880            current: 2,
881            maximum: 1,
882        };
883        assert_eq!(
884            validate_resource_limit_mutation(libc::RLIMIT_CORE, previous, requested),
885            Err(Errno::EINVAL)
886        );
887    }
888
889    #[test]
890    fn prlimit_rejects_core_hard_limit_raise() {
891        let previous = ResourceLimit {
892            current: 1,
893            maximum: 1,
894        };
895        let requested = ResourceLimit {
896            current: 1,
897            maximum: 2,
898        };
899        assert_eq!(
900            validate_resource_limit_mutation(libc::RLIMIT_CORE, previous, requested),
901            Err(Errno::EPERM)
902        );
903    }
904
905    #[test]
906    fn logical_cpu_ticks_exclude_boot_epoch() {
907        assert_eq!(clock_ticks(LogicalTime::from_millis(25)), 2);
908    }
909
910    #[test]
911    fn rusage_timeval_splits_seconds_and_microseconds() {
912        let tv = timeval_from_logical(LogicalTime::from_millis(2_500));
913        assert_eq!(tv.tv_sec, 2);
914        assert_eq!(tv.tv_usec, 500_000);
915    }
916
917    #[test]
918    fn rusage_timeval_truncates_sub_microsecond_rather_than_rounding() {
919        // 1_999 ns is a hair under 2us. Truncating yields 1us; rounding to nearest would
920        // yield 2us and could make a later, larger duration report a SMALLER value once its
921        // remainder shrank -- i.e. CPU time going backwards. Pin truncation explicitly.
922        let tv = timeval_from_logical(LogicalTime::from_nanos(1_999));
923        assert_eq!(tv.tv_sec, 0);
924        assert_eq!(tv.tv_usec, 1);
925    }
926
927    #[test]
928    fn rusage_timeval_is_monotonic_in_the_logical_duration() {
929        // The property that matters to a guest: CPU time never goes backwards. Walk a range
930        // of nanosecond durations across microsecond and second boundaries and assert the
931        // rendered timeval is non-decreasing at every step.
932        let mut previous = (0_i64, 0_i64);
933        for nanos in (0..3_000_000u64).step_by(997) {
934            let tv = timeval_from_logical(LogicalTime::from_nanos(nanos));
935            let current = (tv.tv_sec, tv.tv_usec);
936            assert!(
937                current >= previous,
938                "rusage timeval went backwards at {nanos}ns: {previous:?} -> {current:?}"
939            );
940            previous = current;
941        }
942    }
943
944    #[test]
945    fn rusage_zero_cpu_time_renders_as_zero() {
946        let tv = timeval_from_logical(LogicalTime::ZERO);
947        assert_eq!(tv.tv_sec, 0);
948        assert_eq!(tv.tv_usec, 0);
949    }
950
951    #[test]
952    fn rusage_and_times_agree_within_one_clock_tick() {
953        // Both syscalls project the same logical duration, but times(2) is
954        // quantized to USER_HZ while getrusage(2) retains microseconds.
955        for nanos in [0u64, 1_000_000, 300_484_000, 7_000_000_000, 12_345_678_901] {
956            let duration = LogicalTime::from_nanos(nanos);
957            let tv = timeval_from_logical(duration);
958            let rusage_micros = tv.tv_sec as u64 * 1_000_000 + tv.tv_usec as u64;
959            let times_micros = clock_ticks(duration) * (NANOS_PER_CLOCK_TICK / 1_000);
960
961            assert!(rusage_micros >= times_micros);
962            assert!(rusage_micros - times_micros < NANOS_PER_CLOCK_TICK / 1_000);
963
964            // A tick-ALIGNED duration must agree EXACTLY, not merely to within
965            // one tick. The bounds above are satisfied at every sample by an
966            // implementation carrying a constant sub-tick offset, so without
967            // this the suite cannot distinguish that from a correct one.
968            if nanos % NANOS_PER_CLOCK_TICK == 0 {
969                assert_eq!(rusage_micros, times_micros);
970            }
971        }
972    }
973
974    #[test]
975    fn logical_clock_ticks_wrap_configured_offset_like_linux_clock_t() {
976        let boot = LogicalTime::from_secs(1_000);
977        let before = logical_clock_ticks(boot, boot, u64::MAX);
978        let after = logical_clock_ticks(boot + LogicalTime::from_millis(10), boot, u64::MAX);
979
980        assert_eq!(before, -100);
981        assert_eq!(after, -99);
982    }
983}