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.
6 #include <linux/futex.h>
7 #include <sys/syscall.h>
11 #include "components/nacl/loader/nonsfi/irt_interfaces.h"
12 #include "components/nacl/loader/nonsfi/irt_util.h"
13 #include "native_client/src/trusted/service_runtime/include/sys/time.h"
19 // Converts a pair of NaCl's timespec of absolute time and host's timespec of
20 // the current time to host's timespec of the relative time between them.
21 // Note that assuming tv_nsec for the both input structs are non-negative,
22 // the returned reltime's tv_nsec is also always non-negative.
23 // (I.e., for -0.1 sec, {tv_sec: -1, tv_nsec: 900000000} will be returned).
24 void NaClAbsTimeToRelTime(const struct nacl_abi_timespec
& nacl_abstime
,
25 const struct timespec
& now
,
26 struct timespec
* reltime
) {
27 reltime
->tv_sec
= nacl_abstime
.tv_sec
- now
.tv_sec
;
28 reltime
->tv_nsec
= nacl_abstime
.tv_nsec
- now
.tv_nsec
;
29 if (reltime
->tv_nsec
< 0) {
31 reltime
->tv_nsec
+= 1000000000;
35 int IrtFutexWaitAbs(volatile int* addr
, int value
,
36 const struct nacl_abi_timespec
* abstime
) {
37 struct timespec timeout
;
38 struct timespec
* timeout_ptr
= NULL
;
40 // futex syscall takes relative timeout, but the ABI for IRT's
41 // futex_wait_abs is absolute timeout. So, here we convert it.
43 if (clock_gettime(CLOCK_REALTIME
, &now
))
45 NaClAbsTimeToRelTime(*abstime
, now
, &timeout
);
47 // Linux's FUTEX_WAIT returns EINVAL for negative timeout, but an absolute
48 // time that is in the past is a valid argument to irt_futex_wait_abs(),
49 // and a caller expects ETIMEDOUT.
50 // Here check only tv_sec since we assume time_t is signed. See also
51 // the comment for NaClAbsTimeToRelTime.
52 if (timeout
.tv_sec
< 0)
54 timeout_ptr
= &timeout
;
57 syscall(SYS_futex
, addr
, FUTEX_WAIT_PRIVATE
, value
, timeout_ptr
, 0, 0));
60 int IrtFutexWake(volatile int* addr
, int nwake
, int* count
) {
61 return CheckErrorWithResult(
62 syscall(SYS_futex
, addr
, FUTEX_WAKE_PRIVATE
, nwake
, 0, 0, 0), count
);
67 // For futex_wait_abs, the argument type should be nacl_abi_timespec. However,
68 // the definition uses its host type, struct timespec. So, here we need to cast
70 const nacl_irt_futex kIrtFutex
= {
71 reinterpret_cast<int(*)(volatile int*, int, const struct timespec
*)>(