1 #include <time.h>
2 #include <errno.h>
3 #include <stdint.h>
4 #include "syscall.h"
5 #include "libc.h"
6 #include "atomic.h"
7 
8 #ifdef VDSO_CGT_SYM
9 
10 void *__vdsosym(const char *, const char *);
11 
12 static void *volatile vdso_func;
13 
cgt_init(clockid_t clk,struct timespec * ts)14 static int cgt_init(clockid_t clk, struct timespec *ts)
15 {
16 	void *p = __vdsosym(VDSO_CGT_VER, VDSO_CGT_SYM);
17 	int (*f)(clockid_t, struct timespec *) =
18 		(int (*)(clockid_t, struct timespec *))p;
19 	a_cas_p(&vdso_func, (void *)cgt_init, p);
20 	return f ? f(clk, ts) : -ENOSYS;
21 }
22 
23 static void *volatile vdso_func = (void *)cgt_init;
24 
25 #endif
26 
27 #if __EMSCRIPTEN__
28 _Static_assert(CLOCK_REALTIME == __WASI_CLOCKID_REALTIME, "monotonic clock must match");
29 _Static_assert(CLOCK_MONOTONIC == __WASI_CLOCKID_MONOTONIC, "monotonic clock must match");
30 
__clock_gettime(clockid_t clk,struct timespec * ts)31 int __clock_gettime(clockid_t clk, struct timespec *ts) {
32 	__wasi_timestamp_t timestamp;
33 	if (__wasi_syscall_ret(__wasi_clock_time_get(clk, 1, &timestamp))) {
34 		return -1;
35 	}
36   *ts = __wasi_timestamp_to_timespec(timestamp);
37 	return 0;
38 }
39 #else // __EMSCRIPTEN__
__clock_gettime(clockid_t clk,struct timespec * ts)40 int __clock_gettime(clockid_t clk, struct timespec *ts)
41 {
42 	int r;
43 
44 #ifdef VDSO_CGT_SYM
45 	int (*f)(clockid_t, struct timespec *) =
46 		(int (*)(clockid_t, struct timespec *))vdso_func;
47 	if (f) {
48 		r = f(clk, ts);
49 		if (!r) return r;
50 		if (r == -EINVAL) return __syscall_ret(r);
51 		/* Fall through on errors other than EINVAL. Some buggy
52 		 * vdso implementations return ENOSYS for clocks they
53 		 * can't handle, rather than making the syscall. This
54 		 * also handles the case where cgt_init fails to find
55 		 * a vdso function to use. */
56 	}
57 #endif
58 
59 	r = __syscall(SYS_clock_gettime, clk, ts);
60 	if (r == -ENOSYS) {
61 		if (clk == CLOCK_REALTIME) {
62 			__syscall(SYS_gettimeofday, ts, 0);
63 			ts->tv_nsec = (int)ts->tv_nsec * 1000;
64 			return 0;
65 		}
66 		r = -EINVAL;
67 	}
68 	return __syscall_ret(r);
69 }
70 #endif //__EMSCRIPTEN__
71 
72 weak_alias(__clock_gettime, clock_gettime);
73