api_impl/
time.rs

1// Copyright 2024 The Fuchsia Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// Implementation of TEE Internal Core API Specification 7 Time API
6// Functions return specific error codes where applicable and panic on all other errors.
7
8use tee_internal::binding::{TEE_Time, TEE_TIMEOUT_INFINITE};
9use tee_internal::Result;
10
11fn nanos_to_time(nanos: i64) -> TEE_Time {
12    const NANOSECONDS_PER_MILLISECOND: i64 = 1000 * 1000;
13    const MILLISECONDS_PER_SECOND: i64 = 1000;
14    const NANOSECONDS_PER_SECOND: i64 = NANOSECONDS_PER_MILLISECOND * MILLISECONDS_PER_SECOND;
15
16    let seconds = nanos / NANOSECONDS_PER_SECOND;
17    let nanos_remainder = nanos - seconds * NANOSECONDS_PER_SECOND;
18    let millis = nanos_remainder / NANOSECONDS_PER_MILLISECOND;
19    TEE_Time { seconds: seconds as u32, millis: millis as u32 }
20}
21
22pub fn get_system_time() -> TEE_Time {
23    inspect_stubs::track_stub!(TODO("https://fxbug.dev/384101082"), "get_system_time");
24    let now_utc = fuchsia_runtime::utc_time();
25    nanos_to_time(now_utc.into_nanos())
26}
27
28pub fn wait(timeout: u32) -> Result {
29    inspect_stubs::track_stub!(TODO("https://fxbug.dev/370103570"), "wait should be cancelable");
30    if timeout == TEE_TIMEOUT_INFINITE {
31        std::thread::sleep(std::time::Duration::MAX);
32    } else {
33        std::thread::sleep(std::time::Duration::from_millis(timeout as u64));
34    }
35    Ok(())
36}
37
38pub fn get_ta_persistent_time() -> Result<TEE_Time> {
39    inspect_stubs::track_stub!(TODO("https://fxbug.dev/384101082"), "get_ta_persistent_time");
40    // For now, just return our system time.
41    Ok(get_system_time())
42}
43
44pub fn set_ta_persistent_time(_time: &TEE_Time) -> Result {
45    inspect_stubs::track_stub!(TODO("https://fxbug.dev/384101082"), "set_ta_persistent_time");
46    // For now, ignore.
47    Ok(())
48}
49
50pub fn get_ree_time() -> TEE_Time {
51    inspect_stubs::track_stub!(TODO("https://fxbug.dev/384101082"), "get_ree_time");
52    // For now, just return our system time.
53    get_system_time()
54}