1 | /* |
2 | * Copyright (c) Facebook, Inc. and its affiliates. |
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 | |
17 | #include <folly/ClockGettimeWrappers.h> |
18 | #include <folly/CPortability.h> |
19 | #include <folly/Likely.h> |
20 | #include <folly/portability/Time.h> |
21 | |
22 | #include <chrono> |
23 | |
24 | #include <ctime> |
25 | |
26 | #ifndef _WIN32 |
27 | #define _GNU_SOURCE 1 |
28 | #include <dlfcn.h> |
29 | #endif |
30 | |
31 | namespace folly { |
32 | namespace chrono { |
33 | |
34 | static int64_t clock_gettime_ns_fallback(clockid_t clock) { |
35 | struct timespec ts; |
36 | int r = clock_gettime(clock, &ts); |
37 | if (UNLIKELY(r != 0)) { |
38 | // Mimic what __clock_gettime_ns does (even though this can be a legit |
39 | // value). |
40 | return -1; |
41 | } |
42 | std::chrono::nanoseconds result = |
43 | std::chrono::seconds(ts.tv_sec) + std::chrono::nanoseconds(ts.tv_nsec); |
44 | return result.count(); |
45 | } |
46 | |
47 | // Initialize with default behavior, which we might override on Linux hosts |
48 | // with VDSO support. |
49 | int (*clock_gettime)(clockid_t, timespec* ts) = &::clock_gettime; |
50 | int64_t (*clock_gettime_ns)(clockid_t) = &clock_gettime_ns_fallback; |
51 | |
52 | // In MSAN mode use glibc's versions as they are intercepted by the MSAN |
53 | // runtime which properly tracks memory initialization. |
54 | #if defined(FOLLY_HAVE_LINUX_VDSO) && !defined(FOLLY_SANITIZE_MEMORY) |
55 | |
56 | namespace { |
57 | |
58 | struct VdsoInitializer { |
59 | VdsoInitializer() { |
60 | m_handle = dlopen("linux-vdso.so.1" , RTLD_LAZY | RTLD_LOCAL | RTLD_NOLOAD); |
61 | if (!m_handle) { |
62 | return; |
63 | } |
64 | |
65 | void* p = dlsym(m_handle, "__vdso_clock_gettime" ); |
66 | if (p) { |
67 | folly::chrono::clock_gettime = (int (*)(clockid_t, timespec*))p; |
68 | } |
69 | p = dlsym(m_handle, "__vdso_clock_gettime_ns" ); |
70 | if (p) { |
71 | folly::chrono::clock_gettime_ns = (int64_t(*)(clockid_t))p; |
72 | } |
73 | } |
74 | |
75 | ~VdsoInitializer() { |
76 | if (m_handle) { |
77 | clock_gettime = &::clock_gettime; |
78 | clock_gettime_ns = &clock_gettime_ns_fallback; |
79 | dlclose(m_handle); |
80 | } |
81 | } |
82 | |
83 | private: |
84 | void* m_handle; |
85 | }; |
86 | |
87 | const VdsoInitializer vdso_initializer; |
88 | } // namespace |
89 | |
90 | #endif |
91 | } // namespace chrono |
92 | } // namespace folly |
93 | |