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