1 //===------------------------- chrono.cpp ---------------------------------===//
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 __has_include(<mach/mach_time.h>)
48 # include <mach/mach_time.h>
49 #endif
50 
51 #if defined(__ELF__) && defined(_LIBCPP_LINK_RT_LIB)
52 #  pragma comment(lib, "rt")
53 #endif
54 
55 _LIBCPP_BEGIN_NAMESPACE_STD
56 
57 namespace chrono
58 {
59 
60 //
61 // system_clock
62 //
63 
64 #if defined(_LIBCPP_WIN32API)
65 
66 static system_clock::time_point __libcpp_system_clock_now() {
67   // FILETIME is in 100ns units
68   using filetime_duration =
69       _VSTD::chrono::duration<__int64,
70                               _VSTD::ratio_multiply<_VSTD::ratio<100, 1>,
71                                                     nanoseconds::period>>;
72 
73   // The Windows epoch is Jan 1 1601, the Unix epoch Jan 1 1970.
74   static _LIBCPP_CONSTEXPR const seconds nt_to_unix_epoch{11644473600};
75 
76   FILETIME ft;
77 #if _WIN32_WINNT >= _WIN32_WINNT_WIN8 && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
78   GetSystemTimePreciseAsFileTime(&ft);
79 #else
80   GetSystemTimeAsFileTime(&ft);
81 #endif
82 
83   filetime_duration d{(static_cast<__int64>(ft.dwHighDateTime) << 32) |
84                        static_cast<__int64>(ft.dwLowDateTime)};
85   return system_clock::time_point(duration_cast<system_clock::duration>(d - nt_to_unix_epoch));
86 }
87 
88 #elif defined(CLOCK_REALTIME) && defined(_LIBCPP_USE_CLOCK_GETTIME)
89 
90 static system_clock::time_point __libcpp_system_clock_now() {
91   struct timespec tp;
92   if (0 != clock_gettime(CLOCK_REALTIME, &tp))
93     __throw_system_error(errno, "clock_gettime(CLOCK_REALTIME) failed");
94   return system_clock::time_point(seconds(tp.tv_sec) + microseconds(tp.tv_nsec / 1000));
95 }
96 
97 #else
98 
99 static system_clock::time_point __libcpp_system_clock_now() {
100     timeval tv;
101     gettimeofday(&tv, 0);
102     return system_clock::time_point(seconds(tv.tv_sec) + microseconds(tv.tv_usec));
103 }
104 
105 #endif
106 
107 const bool system_clock::is_steady;
108 
109 system_clock::time_point
110 system_clock::now() noexcept
111 {
112     return __libcpp_system_clock_now();
113 }
114 
115 time_t
116 system_clock::to_time_t(const time_point& t) noexcept
117 {
118     return time_t(duration_cast<seconds>(t.time_since_epoch()).count());
119 }
120 
121 system_clock::time_point
122 system_clock::from_time_t(time_t t) noexcept
123 {
124     return system_clock::time_point(seconds(t));
125 }
126 
127 //
128 // steady_clock
129 //
130 // Warning:  If this is not truly steady, then it is non-conforming.  It is
131 //  better for it to not exist and have the rest of libc++ use system_clock
132 //  instead.
133 //
134 
135 #ifndef _LIBCPP_HAS_NO_MONOTONIC_CLOCK
136 
137 #if defined(__APPLE__)
138 
139 // TODO(ldionne):
140 // This old implementation of steady_clock is retained until Chrome drops supports
141 // for macOS < 10.12. The issue is that they link libc++ statically into their
142 // application, which means that libc++ must support being built for such deployment
143 // targets. See https://llvm.org/D74489 for details.
144 #if (defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 101200) || \
145     (defined(__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ < 100000) || \
146     (defined(__ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__ < 100000) || \
147     (defined(__ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__ < 30000)
148 # define _LIBCPP_USE_OLD_MACH_ABSOLUTE_TIME
149 #endif
150 
151 #if defined(_LIBCPP_USE_OLD_MACH_ABSOLUTE_TIME)
152 
153 //   mach_absolute_time() * MachInfo.numer / MachInfo.denom is the number of
154 //   nanoseconds since the computer booted up.  MachInfo.numer and MachInfo.denom
155 //   are run time constants supplied by the OS.  This clock has no relationship
156 //   to the Gregorian calendar.  It's main use is as a high resolution timer.
157 
158 // MachInfo.numer / MachInfo.denom is often 1 on the latest equipment.  Specialize
159 //   for that case as an optimization.
160 
161 static steady_clock::rep steady_simplified() {
162     return static_cast<steady_clock::rep>(mach_absolute_time());
163 }
164 static double compute_steady_factor() {
165     mach_timebase_info_data_t MachInfo;
166     mach_timebase_info(&MachInfo);
167     return static_cast<double>(MachInfo.numer) / MachInfo.denom;
168 }
169 
170 static steady_clock::rep steady_full() {
171     static const double factor = compute_steady_factor();
172     return static_cast<steady_clock::rep>(mach_absolute_time() * factor);
173 }
174 
175 typedef steady_clock::rep (*FP)();
176 
177 static FP init_steady_clock() {
178     mach_timebase_info_data_t MachInfo;
179     mach_timebase_info(&MachInfo);
180     if (MachInfo.numer == MachInfo.denom)
181         return &steady_simplified;
182     return &steady_full;
183 }
184 
185 static steady_clock::time_point __libcpp_steady_clock_now() {
186     static FP fp = init_steady_clock();
187     return steady_clock::time_point(steady_clock::duration(fp()));
188 }
189 
190 #else // vvvvv default behavior for Apple platforms  vvvvv
191 
192 // On Apple platforms, only CLOCK_UPTIME_RAW, CLOCK_MONOTONIC_RAW or
193 // mach_absolute_time are able to time functions in the nanosecond range.
194 // Furthermore, only CLOCK_MONOTONIC_RAW is truly monotonic, because it
195 // also counts cycles when the system is asleep. Thus, it is the only
196 // acceptable implementation of steady_clock.
197 static steady_clock::time_point __libcpp_steady_clock_now() {
198     struct timespec tp;
199     if (0 != clock_gettime(CLOCK_MONOTONIC_RAW, &tp))
200         __throw_system_error(errno, "clock_gettime(CLOCK_MONOTONIC_RAW) failed");
201     return steady_clock::time_point(seconds(tp.tv_sec) + nanoseconds(tp.tv_nsec));
202 }
203 
204 #endif
205 
206 #elif defined(_LIBCPP_WIN32API)
207 
208 // https://msdn.microsoft.com/en-us/library/windows/desktop/ms644905(v=vs.85).aspx says:
209 //    If the function fails, the return value is zero. <snip>
210 //    On systems that run Windows XP or later, the function will always succeed
211 //      and will thus never return zero.
212 
213 static LARGE_INTEGER
214 __QueryPerformanceFrequency()
215 {
216     LARGE_INTEGER val;
217     (void) QueryPerformanceFrequency(&val);
218     return val;
219 }
220 
221 static steady_clock::time_point __libcpp_steady_clock_now() {
222   static const LARGE_INTEGER freq = __QueryPerformanceFrequency();
223 
224   LARGE_INTEGER counter;
225   (void) QueryPerformanceCounter(&counter);
226   auto seconds = counter.QuadPart / freq.QuadPart;
227   auto fractions = counter.QuadPart % freq.QuadPart;
228   auto dur = seconds * nano::den + fractions * nano::den / freq.QuadPart;
229   return steady_clock::time_point(steady_clock::duration(dur));
230 }
231 
232 #elif defined(__MVS__)
233 
234 static steady_clock::time_point __libcpp_steady_clock_now() {
235   struct timespec64 ts;
236   if (0 != gettimeofdayMonotonic(&ts))
237     __throw_system_error(errno, "failed to obtain time of day");
238 
239   return steady_clock::time_point(seconds(ts.tv_sec) + nanoseconds(ts.tv_nsec));
240 }
241 
242 #elif defined(CLOCK_MONOTONIC)
243 
244 static steady_clock::time_point __libcpp_steady_clock_now() {
245     struct timespec tp;
246     if (0 != clock_gettime(CLOCK_MONOTONIC, &tp))
247         __throw_system_error(errno, "clock_gettime(CLOCK_MONOTONIC) failed");
248     return steady_clock::time_point(seconds(tp.tv_sec) + nanoseconds(tp.tv_nsec));
249 }
250 
251 #else
252 #   error "Monotonic clock not implemented on this platform"
253 #endif
254 
255 const bool steady_clock::is_steady;
256 
257 steady_clock::time_point
258 steady_clock::now() noexcept
259 {
260     return __libcpp_steady_clock_now();
261 }
262 
263 #endif // !_LIBCPP_HAS_NO_MONOTONIC_CLOCK
264 
265 }
266 
267 _LIBCPP_END_NAMESPACE_STD
268