xref: /freebsd/contrib/llvm-project/libcxx/src/chrono.cpp (revision bc7512cc58af2e8bbe5bbf5ca0059b1daa1da897)
1 //===----------------------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #if defined(__MVS__)
10 // As part of monotonic clock support on z/OS we need macro _LARGE_TIME_API
11 // to be defined before any system header to include definition of struct timespec64.
12 #define _LARGE_TIME_API
13 #endif
14 
15 #include "chrono"
16 #include "cerrno"        // errno
17 #include "system_error"  // __throw_system_error
18 
19 #if defined(__MVS__)
20 #include <__support/ibm/gettod_zos.h> // gettimeofdayMonotonic
21 #endif
22 
23 #include <time.h>        // clock_gettime and CLOCK_{MONOTONIC,REALTIME,MONOTONIC_RAW}
24 #include "include/apple_availability.h"
25 
26 #if __has_include(<unistd.h>)
27 # include <unistd.h>
28 #endif
29 
30 #if __has_include(<sys/time.h>)
31 # include <sys/time.h> // for gettimeofday and timeval
32 #endif
33 
34 #if !defined(__APPLE__) && defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0
35 # define _LIBCPP_USE_CLOCK_GETTIME
36 #endif
37 
38 #if defined(_LIBCPP_WIN32API)
39 #  define WIN32_LEAN_AND_MEAN
40 #  define VC_EXTRA_LEAN
41 #  include <windows.h>
42 #  if _WIN32_WINNT >= _WIN32_WINNT_WIN8
43 #    include <winapifamily.h>
44 #  endif
45 #endif // defined(_LIBCPP_WIN32API)
46 
47 #if defined(__Fuchsia__)
48 #  include <zircon/syscalls.h>
49 #endif
50 
51 #if __has_include(<mach/mach_time.h>)
52 # include <mach/mach_time.h>
53 #endif
54 
55 #if defined(__ELF__) && defined(_LIBCPP_LINK_RT_LIB)
56 #  pragma comment(lib, "rt")
57 #endif
58 
59 _LIBCPP_BEGIN_NAMESPACE_STD
60 
61 namespace chrono
62 {
63 
64 //
65 // system_clock
66 //
67 
68 #if defined(_LIBCPP_WIN32API)
69 
70 #if _WIN32_WINNT < _WIN32_WINNT_WIN8
71 
72 namespace {
73 
74 typedef void(WINAPI *GetSystemTimeAsFileTimePtr)(LPFILETIME);
75 
76 class GetSystemTimeInit {
77 public:
78   GetSystemTimeInit() {
79     fp = (GetSystemTimeAsFileTimePtr)GetProcAddress(
80         GetModuleHandleW(L"kernel32.dll"), "GetSystemTimePreciseAsFileTime");
81     if (fp == nullptr)
82       fp = GetSystemTimeAsFileTime;
83   }
84   GetSystemTimeAsFileTimePtr fp;
85 };
86 
87 // Pretend we're inside a system header so the compiler doesn't flag the use of the init_priority
88 // attribute with a value that's reserved for the implementation (we're the implementation).
89 #include "chrono_system_time_init.h"
90 } // namespace
91 
92 #endif
93 
94 static system_clock::time_point __libcpp_system_clock_now() {
95   // FILETIME is in 100ns units
96   using filetime_duration =
97       _VSTD::chrono::duration<__int64,
98                               _VSTD::ratio_multiply<_VSTD::ratio<100, 1>,
99                                                     nanoseconds::period>>;
100 
101   // The Windows epoch is Jan 1 1601, the Unix epoch Jan 1 1970.
102   static _LIBCPP_CONSTEXPR const seconds nt_to_unix_epoch{11644473600};
103 
104   FILETIME ft;
105 #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8 && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)) || \
106     (_WIN32_WINNT >= _WIN32_WINNT_WIN10)
107   GetSystemTimePreciseAsFileTime(&ft);
108 #elif !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
109   GetSystemTimeAsFileTime(&ft);
110 #else
111   GetSystemTimeAsFileTimeFunc.fp(&ft);
112 #endif
113 
114   filetime_duration d{(static_cast<__int64>(ft.dwHighDateTime) << 32) |
115                        static_cast<__int64>(ft.dwLowDateTime)};
116   return system_clock::time_point(duration_cast<system_clock::duration>(d - nt_to_unix_epoch));
117 }
118 
119 #elif defined(CLOCK_REALTIME) && defined(_LIBCPP_USE_CLOCK_GETTIME)
120 
121 static system_clock::time_point __libcpp_system_clock_now() {
122   struct timespec tp;
123   if (0 != clock_gettime(CLOCK_REALTIME, &tp))
124     __throw_system_error(errno, "clock_gettime(CLOCK_REALTIME) failed");
125   return system_clock::time_point(seconds(tp.tv_sec) + microseconds(tp.tv_nsec / 1000));
126 }
127 
128 #else
129 
130 static system_clock::time_point __libcpp_system_clock_now() {
131     timeval tv;
132     gettimeofday(&tv, 0);
133     return system_clock::time_point(seconds(tv.tv_sec) + microseconds(tv.tv_usec));
134 }
135 
136 #endif
137 
138 const bool system_clock::is_steady;
139 
140 system_clock::time_point
141 system_clock::now() noexcept
142 {
143     return __libcpp_system_clock_now();
144 }
145 
146 time_t
147 system_clock::to_time_t(const time_point& t) noexcept
148 {
149     return time_t(duration_cast<seconds>(t.time_since_epoch()).count());
150 }
151 
152 system_clock::time_point
153 system_clock::from_time_t(time_t t) noexcept
154 {
155     return system_clock::time_point(seconds(t));
156 }
157 
158 //
159 // steady_clock
160 //
161 // Warning:  If this is not truly steady, then it is non-conforming.  It is
162 //  better for it to not exist and have the rest of libc++ use system_clock
163 //  instead.
164 //
165 
166 #ifndef _LIBCPP_HAS_NO_MONOTONIC_CLOCK
167 
168 #if defined(__APPLE__)
169 
170 // TODO(ldionne):
171 // This old implementation of steady_clock is retained until Chrome drops supports
172 // for macOS < 10.12. The issue is that they link libc++ statically into their
173 // application, which means that libc++ must support being built for such deployment
174 // targets. See https://llvm.org/D74489 for details.
175 #if (defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 101200) || \
176     (defined(__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ < 100000) || \
177     (defined(__ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__ < 100000) || \
178     (defined(__ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__ < 30000)
179 # define _LIBCPP_USE_OLD_MACH_ABSOLUTE_TIME
180 #endif
181 
182 #if defined(_LIBCPP_USE_OLD_MACH_ABSOLUTE_TIME)
183 
184 //   mach_absolute_time() * MachInfo.numer / MachInfo.denom is the number of
185 //   nanoseconds since the computer booted up.  MachInfo.numer and MachInfo.denom
186 //   are run time constants supplied by the OS.  This clock has no relationship
187 //   to the Gregorian calendar.  It's main use is as a high resolution timer.
188 
189 // MachInfo.numer / MachInfo.denom is often 1 on the latest equipment.  Specialize
190 //   for that case as an optimization.
191 
192 static steady_clock::rep steady_simplified() {
193     return static_cast<steady_clock::rep>(mach_absolute_time());
194 }
195 static double compute_steady_factor() {
196     mach_timebase_info_data_t MachInfo;
197     mach_timebase_info(&MachInfo);
198     return static_cast<double>(MachInfo.numer) / MachInfo.denom;
199 }
200 
201 static steady_clock::rep steady_full() {
202     static const double factor = compute_steady_factor();
203     return static_cast<steady_clock::rep>(mach_absolute_time() * factor);
204 }
205 
206 typedef steady_clock::rep (*FP)();
207 
208 static FP init_steady_clock() {
209     mach_timebase_info_data_t MachInfo;
210     mach_timebase_info(&MachInfo);
211     if (MachInfo.numer == MachInfo.denom)
212         return &steady_simplified;
213     return &steady_full;
214 }
215 
216 static steady_clock::time_point __libcpp_steady_clock_now() {
217     static FP fp = init_steady_clock();
218     return steady_clock::time_point(steady_clock::duration(fp()));
219 }
220 
221 #else // vvvvv default behavior for Apple platforms  vvvvv
222 
223 // On Apple platforms, only CLOCK_UPTIME_RAW, CLOCK_MONOTONIC_RAW or
224 // mach_absolute_time are able to time functions in the nanosecond range.
225 // Furthermore, only CLOCK_MONOTONIC_RAW is truly monotonic, because it
226 // also counts cycles when the system is asleep. Thus, it is the only
227 // acceptable implementation of steady_clock.
228 static steady_clock::time_point __libcpp_steady_clock_now() {
229     struct timespec tp;
230     if (0 != clock_gettime(CLOCK_MONOTONIC_RAW, &tp))
231         __throw_system_error(errno, "clock_gettime(CLOCK_MONOTONIC_RAW) failed");
232     return steady_clock::time_point(seconds(tp.tv_sec) + nanoseconds(tp.tv_nsec));
233 }
234 
235 #endif
236 
237 #elif defined(_LIBCPP_WIN32API)
238 
239 // https://msdn.microsoft.com/en-us/library/windows/desktop/ms644905(v=vs.85).aspx says:
240 //    If the function fails, the return value is zero. <snip>
241 //    On systems that run Windows XP or later, the function will always succeed
242 //      and will thus never return zero.
243 
244 static LARGE_INTEGER
245 __QueryPerformanceFrequency()
246 {
247     LARGE_INTEGER val;
248     (void) QueryPerformanceFrequency(&val);
249     return val;
250 }
251 
252 static steady_clock::time_point __libcpp_steady_clock_now() {
253   static const LARGE_INTEGER freq = __QueryPerformanceFrequency();
254 
255   LARGE_INTEGER counter;
256   (void) QueryPerformanceCounter(&counter);
257   auto seconds = counter.QuadPart / freq.QuadPart;
258   auto fractions = counter.QuadPart % freq.QuadPart;
259   auto dur = seconds * nano::den + fractions * nano::den / freq.QuadPart;
260   return steady_clock::time_point(steady_clock::duration(dur));
261 }
262 
263 #elif defined(__MVS__)
264 
265 static steady_clock::time_point __libcpp_steady_clock_now() {
266   struct timespec64 ts;
267   if (0 != gettimeofdayMonotonic(&ts))
268     __throw_system_error(errno, "failed to obtain time of day");
269 
270   return steady_clock::time_point(seconds(ts.tv_sec) + nanoseconds(ts.tv_nsec));
271 }
272 
273 #  elif defined(__Fuchsia__)
274 
275 static steady_clock::time_point __libcpp_steady_clock_now() noexcept {
276   // Implicitly link against the vDSO system call ABI without
277   // requiring the final link to specify -lzircon explicitly when
278   // statically linking libc++.
279 #    pragma comment(lib, "zircon")
280 
281   return steady_clock::time_point(nanoseconds(_zx_clock_get_monotonic()));
282 }
283 
284 #  elif defined(CLOCK_MONOTONIC)
285 
286 static steady_clock::time_point __libcpp_steady_clock_now() {
287     struct timespec tp;
288     if (0 != clock_gettime(CLOCK_MONOTONIC, &tp))
289         __throw_system_error(errno, "clock_gettime(CLOCK_MONOTONIC) failed");
290     return steady_clock::time_point(seconds(tp.tv_sec) + nanoseconds(tp.tv_nsec));
291 }
292 
293 #  else
294 #    error "Monotonic clock not implemented on this platform"
295 #  endif
296 
297 const bool steady_clock::is_steady;
298 
299 steady_clock::time_point
300 steady_clock::now() noexcept
301 {
302     return __libcpp_steady_clock_now();
303 }
304 
305 #endif // !_LIBCPP_HAS_NO_MONOTONIC_CLOCK
306 
307 }
308 
309 _LIBCPP_END_NAMESPACE_STD
310