1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include <errno.h>
6 #include <time.h>
7
8 #include "components/nacl/loader/nonsfi/abi_conversion.h"
9 #include "components/nacl/loader/nonsfi/irt_interfaces.h"
10 #include "native_client/src/trusted/service_runtime/include/sys/time.h"
11
12 namespace nacl {
13 namespace nonsfi {
14 namespace {
15
NaClAbiClockIdToClockId(nacl_irt_clockid_t nacl_clk_id,clockid_t * host_clk_id)16 bool NaClAbiClockIdToClockId(nacl_irt_clockid_t nacl_clk_id,
17 clockid_t* host_clk_id) {
18 switch (nacl_clk_id) {
19 case NACL_ABI_CLOCK_REALTIME:
20 *host_clk_id = CLOCK_REALTIME;
21 break;
22 case NACL_ABI_CLOCK_MONOTONIC:
23 *host_clk_id = CLOCK_MONOTONIC;
24 break;
25 case NACL_ABI_CLOCK_PROCESS_CPUTIME_ID:
26 *host_clk_id = CLOCK_PROCESS_CPUTIME_ID;
27 break;
28 case NACL_ABI_CLOCK_THREAD_CPUTIME_ID:
29 *host_clk_id = CLOCK_THREAD_CPUTIME_ID;
30 break;
31 default:
32 // Unknown clock id.
33 return false;
34 }
35 return true;
36 }
37
IrtClockGetRes(nacl_irt_clockid_t clk_id,struct nacl_abi_timespec * res)38 int IrtClockGetRes(nacl_irt_clockid_t clk_id, struct nacl_abi_timespec* res) {
39 clockid_t host_clk_id;
40 if (!NaClAbiClockIdToClockId(clk_id, &host_clk_id))
41 return EINVAL;
42
43 struct timespec host_res;
44 if (clock_getres(host_clk_id, &host_res))
45 return errno;
46
47 // clock_getres() requires a NULL check but clock_gettime() doesn't.
48 if (res)
49 TimeSpecToNaClAbiTimeSpec(host_res, res);
50 return 0;
51 }
52
IrtClockGetTime(nacl_irt_clockid_t clk_id,struct nacl_abi_timespec * tp)53 int IrtClockGetTime(nacl_irt_clockid_t clk_id, struct nacl_abi_timespec* tp) {
54 clockid_t host_clk_id;
55 if (!NaClAbiClockIdToClockId(clk_id, &host_clk_id))
56 return EINVAL;
57
58 struct timespec host_tp;
59 if (clock_gettime(host_clk_id, &host_tp))
60 return errno;
61
62 TimeSpecToNaClAbiTimeSpec(host_tp, tp);
63 return 0;
64 }
65
66 } // namespace
67
68 // Cast away the distinction between host types and NaCl ABI types.
69 const nacl_irt_clock kIrtClock = {
70 reinterpret_cast<int(*)(nacl_irt_clockid_t, struct timespec*)>(
71 IrtClockGetRes),
72 reinterpret_cast<int(*)(nacl_irt_clockid_t, struct timespec*)>(
73 IrtClockGetTime),
74 };
75
76 } // namespace nonsfi
77 } // namespace nacl
78