|
| 1 | +/* |
| 2 | +Copyright 2026 The Hyperlight Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | +use hyperlight_guest::error::Result; |
| 17 | +use hyperlight_guest_bin::host_function; |
| 18 | + |
| 19 | +use crate::libc; |
| 20 | + |
| 21 | +fn micros_since_epoch() -> u64 { |
| 22 | + #[host_function("CurrentTimeMicros")] |
| 23 | + fn current_time_micros() -> Result<u64>; |
| 24 | + |
| 25 | + current_time_micros().unwrap_or(1609459200u64 * 1_000_000u64) |
| 26 | +} |
| 27 | + |
| 28 | +#[unsafe(no_mangle)] |
| 29 | +extern "C" fn clock_gettime(clk_id: libc::clockid_t, ts: *mut libc::timespec) -> libc::c_int { |
| 30 | + const CLOCK_REALTIME: libc::clockid_t = libc::CLOCK_REALTIME as libc::clockid_t; |
| 31 | + const CLOCK_MONOTONIC: libc::clockid_t = libc::CLOCK_MONOTONIC as libc::clockid_t; |
| 32 | + |
| 33 | + if clk_id != CLOCK_REALTIME && clk_id != CLOCK_MONOTONIC { |
| 34 | + unsafe { libc::__errno_location().write(libc::EINVAL as _) }; |
| 35 | + return -1; |
| 36 | + } |
| 37 | + let micros = micros_since_epoch(); |
| 38 | + unsafe { |
| 39 | + ts.write(libc::timespec { |
| 40 | + tv_sec: (micros / 1_000_000) as _, |
| 41 | + tv_nsec: ((micros % 1_000_000) * 1000) as _, |
| 42 | + }) |
| 43 | + }; |
| 44 | + 0 |
| 45 | +} |
| 46 | + |
| 47 | +#[unsafe(no_mangle)] |
| 48 | +extern "C" fn gettimeofday(tp: *mut libc::timeval, _tz: *mut libc::c_void) -> libc::c_int { |
| 49 | + let micros = micros_since_epoch(); |
| 50 | + unsafe { |
| 51 | + tp.write(libc::timeval { |
| 52 | + tv_sec: (micros / 1_000_000) as _, |
| 53 | + tv_usec: (micros % 1_000_000) as _, |
| 54 | + }); |
| 55 | + } |
| 56 | + 0 |
| 57 | +} |
0 commit comments