2 * Copyright 2016 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include <folly/ClockGettimeWrappers.h>
18 #include <folly/Likely.h>
19 #include <folly/portability/Time.h>
33 static int64_t clock_gettime_ns_fallback(clockid_t clock) {
35 int r = clock_gettime(clock, &ts);
36 if (UNLIKELY(r != 0)) {
37 // Mimic what __clock_gettime_ns does (even though this can be a legit
41 std::chrono::nanoseconds result =
42 std::chrono::seconds(ts.tv_sec) + std::chrono::nanoseconds(ts.tv_nsec);
43 return result.count();
46 // Initialize with default behavior, which we might override on Linux hosts
48 int (*clock_gettime)(clockid_t, timespec* ts) = &::clock_gettime;
49 int64_t (*clock_gettime_ns)(clockid_t) = &clock_gettime_ns_fallback;
55 struct VdsoInitializer {
57 m_handle = dlopen("linux-vdso.so.1", RTLD_LAZY | RTLD_LOCAL | RTLD_NOLOAD);
62 void* p = dlsym(m_handle, "__vdso_clock_gettime");
64 folly::chrono::clock_gettime = (int (*)(clockid_t, timespec*))p;
66 p = dlsym(m_handle, "__vdso_clock_gettime_ns");
68 folly::chrono::clock_gettime_ns = (int64_t(*)(clockid_t))p;
74 clock_gettime = &::clock_gettime;
75 clock_gettime_ns = &clock_gettime_ns_fallback;
84 static const VdsoInitializer vdso_initializer;