xref: /freebsd/contrib/llvm-project/libcxx/src/chrono.cpp (revision 5b56413d04e608379c9a306373554a8e4d321bc0)
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 <__system_error/system_error.h>
16 #include <cerrno> // errno
17 #include <chrono>
18 
19 #if defined(__MVS__)
20 #  include <__support/ibm/gettod_zos.h> // gettimeofdayMonotonic
21 #endif
22 
23 #include "include/apple_availability.h"
24 #include <time.h> // clock_gettime and CLOCK_{MONOTONIC,REALTIME,MONOTONIC_RAW}
25 
26 #if __has_include(<unistd.h>)
27 #  include <unistd.h> // _POSIX_TIMERS
28 #endif
29 
30 #if __has_include(<sys/time.h>)
31 #  include <sys/time.h> // for gettimeofday and timeval
32 #endif
33 
34 // OpenBSD does not have a fully conformant suite of POSIX timers, but
35 // it does have clock_gettime and CLOCK_MONOTONIC which is all we need.
36 #if defined(__APPLE__) || defined(__gnu_hurd__) || defined(__OpenBSD__) || (defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0)
37 #  define _LIBCPP_HAS_CLOCK_GETTIME
38 #endif
39 
40 #if defined(_LIBCPP_WIN32API)
41 #  define WIN32_LEAN_AND_MEAN
42 #  define VC_EXTRA_LEAN
43 #  include <windows.h>
44 #  if _WIN32_WINNT >= _WIN32_WINNT_WIN8
45 #    include <winapifamily.h>
46 #  endif
47 #endif // defined(_LIBCPP_WIN32API)
48 
49 #if defined(__Fuchsia__)
50 #  include <zircon/syscalls.h>
51 #endif
52 
53 #if __has_include(<mach/mach_time.h>)
54 #  include <mach/mach_time.h>
55 #endif
56 
57 #if defined(__ELF__) && defined(_LIBCPP_LINK_RT_LIB)
58 #  pragma comment(lib, "rt")
59 #endif
60 
61 _LIBCPP_BEGIN_NAMESPACE_STD
62 
63 namespace chrono {
64 
65 //
66 // system_clock
67 //
68 
69 #if defined(_LIBCPP_WIN32API)
70 
71 #  if _WIN32_WINNT < _WIN32_WINNT_WIN8
72 
73 namespace {
74 
75 typedef void(WINAPI* GetSystemTimeAsFileTimePtr)(LPFILETIME);
76 
77 class GetSystemTimeInit {
78 public:
79   GetSystemTimeInit() {
80     fp =
81         (GetSystemTimeAsFileTimePtr)GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "GetSystemTimePreciseAsFileTime");
82     if (fp == nullptr)
83       fp = GetSystemTimeAsFileTime;
84   }
85   GetSystemTimeAsFileTimePtr fp;
86 };
87 
88 // Pretend we're inside a system header so the compiler doesn't flag the use of the init_priority
89 // attribute with a value that's reserved for the implementation (we're the implementation).
90 #    include "chrono_system_time_init.h"
91 } // namespace
92 
93 #  endif
94 
95 static system_clock::time_point __libcpp_system_clock_now() {
96   // FILETIME is in 100ns units
97   using filetime_duration =
98       std::chrono::duration<__int64, std::ratio_multiply<std::ratio<100, 1>, nanoseconds::period>>;
99 
100   // The Windows epoch is Jan 1 1601, the Unix epoch Jan 1 1970.
101   static constexpr const seconds nt_to_unix_epoch{11644473600};
102 
103   FILETIME ft;
104 #  if (_WIN32_WINNT >= _WIN32_WINNT_WIN8 && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)) ||                      \
105       (_WIN32_WINNT >= _WIN32_WINNT_WIN10)
106   GetSystemTimePreciseAsFileTime(&ft);
107 #  elif !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
108   GetSystemTimeAsFileTime(&ft);
109 #  else
110   GetSystemTimeAsFileTimeFunc.fp(&ft);
111 #  endif
112 
113   filetime_duration d{(static_cast<__int64>(ft.dwHighDateTime) << 32) | static_cast<__int64>(ft.dwLowDateTime)};
114   return system_clock::time_point(duration_cast<system_clock::duration>(d - nt_to_unix_epoch));
115 }
116 
117 #elif defined(_LIBCPP_HAS_CLOCK_GETTIME)
118 
119 static system_clock::time_point __libcpp_system_clock_now() {
120   struct timespec tp;
121   if (0 != clock_gettime(CLOCK_REALTIME, &tp))
122     __throw_system_error(errno, "clock_gettime(CLOCK_REALTIME) failed");
123   return system_clock::time_point(seconds(tp.tv_sec) + microseconds(tp.tv_nsec / 1000));
124 }
125 
126 #else
127 
128 static system_clock::time_point __libcpp_system_clock_now() {
129   timeval tv;
130   gettimeofday(&tv, 0);
131   return system_clock::time_point(seconds(tv.tv_sec) + microseconds(tv.tv_usec));
132 }
133 
134 #endif
135 
136 const bool system_clock::is_steady;
137 
138 system_clock::time_point system_clock::now() noexcept { return __libcpp_system_clock_now(); }
139 
140 time_t system_clock::to_time_t(const time_point& t) noexcept {
141   return time_t(duration_cast<seconds>(t.time_since_epoch()).count());
142 }
143 
144 system_clock::time_point system_clock::from_time_t(time_t t) noexcept { return system_clock::time_point(seconds(t)); }
145 
146 //
147 // steady_clock
148 //
149 // Warning:  If this is not truly steady, then it is non-conforming.  It is
150 //  better for it to not exist and have the rest of libc++ use system_clock
151 //  instead.
152 //
153 
154 #ifndef _LIBCPP_HAS_NO_MONOTONIC_CLOCK
155 
156 #  if defined(__APPLE__)
157 
158 // On Apple platforms, only CLOCK_UPTIME_RAW, CLOCK_MONOTONIC_RAW or
159 // mach_absolute_time are able to time functions in the nanosecond range.
160 // Furthermore, only CLOCK_MONOTONIC_RAW is truly monotonic, because it
161 // also counts cycles when the system is asleep. Thus, it is the only
162 // acceptable implementation of steady_clock.
163 static steady_clock::time_point __libcpp_steady_clock_now() {
164   struct timespec tp;
165   if (0 != clock_gettime(CLOCK_MONOTONIC_RAW, &tp))
166     __throw_system_error(errno, "clock_gettime(CLOCK_MONOTONIC_RAW) failed");
167   return steady_clock::time_point(seconds(tp.tv_sec) + nanoseconds(tp.tv_nsec));
168 }
169 
170 #  elif defined(_LIBCPP_WIN32API)
171 
172 // https://msdn.microsoft.com/en-us/library/windows/desktop/ms644905(v=vs.85).aspx says:
173 //    If the function fails, the return value is zero. <snip>
174 //    On systems that run Windows XP or later, the function will always succeed
175 //      and will thus never return zero.
176 
177 static LARGE_INTEGER __QueryPerformanceFrequency() {
178   LARGE_INTEGER val;
179   (void)QueryPerformanceFrequency(&val);
180   return val;
181 }
182 
183 static steady_clock::time_point __libcpp_steady_clock_now() {
184   static const LARGE_INTEGER freq = __QueryPerformanceFrequency();
185 
186   LARGE_INTEGER counter;
187   (void)QueryPerformanceCounter(&counter);
188   auto seconds   = counter.QuadPart / freq.QuadPart;
189   auto fractions = counter.QuadPart % freq.QuadPart;
190   auto dur       = seconds * nano::den + fractions * nano::den / freq.QuadPart;
191   return steady_clock::time_point(steady_clock::duration(dur));
192 }
193 
194 #  elif defined(__MVS__)
195 
196 static steady_clock::time_point __libcpp_steady_clock_now() {
197   struct timespec64 ts;
198   if (0 != gettimeofdayMonotonic(&ts))
199     __throw_system_error(errno, "failed to obtain time of day");
200 
201   return steady_clock::time_point(seconds(ts.tv_sec) + nanoseconds(ts.tv_nsec));
202 }
203 
204 #  elif defined(__Fuchsia__)
205 
206 static steady_clock::time_point __libcpp_steady_clock_now() noexcept {
207   // Implicitly link against the vDSO system call ABI without
208   // requiring the final link to specify -lzircon explicitly when
209   // statically linking libc++.
210 #    pragma comment(lib, "zircon")
211 
212   return steady_clock::time_point(nanoseconds(_zx_clock_get_monotonic()));
213 }
214 
215 #  elif defined(_LIBCPP_HAS_CLOCK_GETTIME)
216 
217 static steady_clock::time_point __libcpp_steady_clock_now() {
218   struct timespec tp;
219   if (0 != clock_gettime(CLOCK_MONOTONIC, &tp))
220     __throw_system_error(errno, "clock_gettime(CLOCK_MONOTONIC) failed");
221   return steady_clock::time_point(seconds(tp.tv_sec) + nanoseconds(tp.tv_nsec));
222 }
223 
224 #  else
225 #    error "Monotonic clock not implemented on this platform"
226 #  endif
227 
228 const bool steady_clock::is_steady;
229 
230 steady_clock::time_point steady_clock::now() noexcept { return __libcpp_steady_clock_now(); }
231 
232 #endif // !_LIBCPP_HAS_NO_MONOTONIC_CLOCK
233 
234 } // namespace chrono
235 
236 _LIBCPP_END_NAMESPACE_STD
237