Path: blob/main/e2e_tests/guest_under_test/rootfs/readclock/src/lib.rs
5394 views
// Copyright 2024 The ChromiumOS Authors1// Use of this source code is governed by a BSD-style license that can be2// found in the LICENSE file.34//! A helper binary for reading CLOCK_BOOTTIME and CLOCK_MONOTONIC5//! to verify the virtio-pvclock behavior.6//! This program is used by corresponding e2e_tests.78use std::time::Duration;910use serde::Deserialize;11use serde::Serialize;1213#[cfg(any(target_os = "linux", target_os = "android"))]14fn clock_gettime_nanos(clock_id: i32) -> u64 {15let mut ts = libc::timespec {16tv_sec: 0,17tv_nsec: 0,18};19// SAFETY: This is safe since clock_gettime will succeed always20// and will not break Rust's assumption on data structures21// because it is called with valid parameters.22assert_eq!(unsafe { libc::clock_gettime(clock_id, &mut ts) }, 0);23ts.tv_sec as u64 * 1_000_000_000u64 + ts.tv_nsec as u6424}2526#[cfg(any(target_os = "linux", target_os = "android"))]27fn clock_monotonic_now() -> Duration {28Duration::from_nanos(clock_gettime_nanos(libc::CLOCK_MONOTONIC))29}3031#[cfg(any(target_os = "linux", target_os = "android"))]32fn clock_boottime_now() -> Duration {33Duration::from_nanos(clock_gettime_nanos(libc::CLOCK_BOOTTIME))34}3536/// ClockValues hold the values read out from the kernel37/// via clock_gettime syscall.38#[derive(Serialize, Deserialize, Debug)]39pub struct ClockValues {40pub clock_monotonic: Duration,41pub clock_boottime: Duration,42}43impl ClockValues {44#[cfg(any(target_os = "linux", target_os = "android"))]45pub fn now() -> Self {46Self {47clock_monotonic: clock_monotonic_now(),48clock_boottime: clock_boottime_now(),49}50}51pub fn clock_monotonic(&self) -> Duration {52self.clock_monotonic53}54pub fn clock_boottime(&self) -> Duration {55self.clock_boottime56}57}585960