1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/time/time.h"
6 
7 #include <CoreFoundation/CFDate.h>
8 #include <mach/mach.h>
9 #include <mach/mach_time.h>
10 #include <stddef.h>
11 #include <stdint.h>
12 #include <sys/sysctl.h>
13 #include <sys/time.h>
14 #include <sys/types.h>
15 #include <time.h>
16 
17 #include "base/logging.h"
18 #include "base/mac/mach_logging.h"
19 #include "base/mac/scoped_cftyperef.h"
20 #include "base/mac/scoped_mach_port.h"
21 #include "base/notreached.h"
22 #include "base/numerics/safe_conversions.h"
23 #include "base/stl_util.h"
24 #include "base/time/time_override.h"
25 #include "build/build_config.h"
26 
27 #if defined(OS_IOS)
28 #include <time.h>
29 #include "base/ios/ios_util.h"
30 #endif
31 
32 namespace {
33 
34 #if defined(OS_MAC)
MachTimeToMicroseconds(uint64_t mach_time)35 int64_t MachTimeToMicroseconds(uint64_t mach_time) {
36   static mach_timebase_info_data_t timebase_info;
37   if (timebase_info.denom == 0) {
38     // Zero-initialization of statics guarantees that denom will be 0 before
39     // calling mach_timebase_info.  mach_timebase_info will never set denom to
40     // 0 as that would be invalid, so the zero-check can be used to determine
41     // whether mach_timebase_info has already been called.  This is
42     // recommended by Apple's QA1398.
43     kern_return_t kr = mach_timebase_info(&timebase_info);
44     MACH_DCHECK(kr == KERN_SUCCESS, kr) << "mach_timebase_info";
45   }
46 
47   // timebase_info converts absolute time tick units into nanoseconds.  Convert
48   // to microseconds up front to stave off overflows.
49   base::CheckedNumeric<uint64_t> result(mach_time /
50                                         base::Time::kNanosecondsPerMicrosecond);
51   result *= timebase_info.numer;
52   result /= timebase_info.denom;
53 
54   // Don't bother with the rollover handling that the Windows version does.
55   // With numer and denom = 1 (the expected case), the 64-bit absolute time
56   // reported in nanoseconds is enough to last nearly 585 years.
57   return base::checked_cast<int64_t>(result.ValueOrDie());
58 }
59 #endif  // defined(OS_MAC)
60 
61 // Returns monotonically growing number of ticks in microseconds since some
62 // unspecified starting point.
ComputeCurrentTicks()63 int64_t ComputeCurrentTicks() {
64 #if defined(OS_IOS)
65   // iOS 10 supports clock_gettime(CLOCK_MONOTONIC, ...), which is
66   // around 15 times faster than sysctl() call. Use it if possible;
67   // otherwise, fall back to sysctl().
68   if (__builtin_available(iOS 10, *)) {
69     struct timespec tp;
70     if (clock_gettime(CLOCK_MONOTONIC, &tp) == 0) {
71       return (int64_t)tp.tv_sec * 1000000 + tp.tv_nsec / 1000;
72     }
73   }
74 
75   // On iOS mach_absolute_time stops while the device is sleeping. Instead use
76   // now - KERN_BOOTTIME to get a time difference that is not impacted by clock
77   // changes. KERN_BOOTTIME will be updated by the system whenever the system
78   // clock change.
79   struct timeval boottime;
80   int mib[2] = {CTL_KERN, KERN_BOOTTIME};
81   size_t size = sizeof(boottime);
82   int kr = sysctl(mib, base::size(mib), &boottime, &size, nullptr, 0);
83   DCHECK_EQ(KERN_SUCCESS, kr);
84   base::TimeDelta time_difference =
85       base::subtle::TimeNowIgnoringOverride() -
86       (base::Time::FromTimeT(boottime.tv_sec) +
87        base::TimeDelta::FromMicroseconds(boottime.tv_usec));
88   return time_difference.InMicroseconds();
89 #else
90   // mach_absolute_time is it when it comes to ticks on the Mac.  Other calls
91   // with less precision (such as TickCount) just call through to
92   // mach_absolute_time.
93   return MachTimeToMicroseconds(mach_absolute_time());
94 #endif  // defined(OS_IOS)
95 }
96 
ComputeThreadTicks()97 int64_t ComputeThreadTicks() {
98 #if defined(OS_IOS)
99   NOTREACHED();
100   return 0;
101 #else
102   // The pthreads library keeps a cached reference to the thread port, which
103   // does not have to be released like mach_thread_self() does.
104   mach_port_t thread_port = pthread_mach_thread_np(pthread_self());
105   if (thread_port == MACH_PORT_NULL) {
106     DLOG(ERROR) << "Failed to get pthread_mach_thread_np()";
107     return 0;
108   }
109 
110   mach_msg_type_number_t thread_info_count = THREAD_BASIC_INFO_COUNT;
111   thread_basic_info_data_t thread_info_data;
112 
113   kern_return_t kr = thread_info(
114       thread_port,
115       THREAD_BASIC_INFO,
116       reinterpret_cast<thread_info_t>(&thread_info_data),
117       &thread_info_count);
118   MACH_DCHECK(kr == KERN_SUCCESS, kr) << "thread_info";
119 
120   base::CheckedNumeric<int64_t> absolute_micros(
121       thread_info_data.user_time.seconds +
122       thread_info_data.system_time.seconds);
123   absolute_micros *= base::Time::kMicrosecondsPerSecond;
124   absolute_micros += (thread_info_data.user_time.microseconds +
125                       thread_info_data.system_time.microseconds);
126   return absolute_micros.ValueOrDie();
127 #endif  // defined(OS_IOS)
128 }
129 
130 }  // namespace
131 
132 namespace base {
133 
134 // The Time routines in this file use Mach and CoreFoundation APIs, since the
135 // POSIX definition of time_t in Mac OS X wraps around after 2038--and
136 // there are already cookie expiration dates, etc., past that time out in
137 // the field.  Using CFDate prevents that problem, and using mach_absolute_time
138 // for TimeTicks gives us nice high-resolution interval timing.
139 
140 // Time -----------------------------------------------------------------------
141 
142 namespace subtle {
TimeNowIgnoringOverride()143 Time TimeNowIgnoringOverride() {
144   return Time::FromCFAbsoluteTime(CFAbsoluteTimeGetCurrent());
145 }
146 
TimeNowFromSystemTimeIgnoringOverride()147 Time TimeNowFromSystemTimeIgnoringOverride() {
148   // Just use TimeNowIgnoringOverride() because it returns the system time.
149   return TimeNowIgnoringOverride();
150 }
151 }  // namespace subtle
152 
153 // static
FromCFAbsoluteTime(CFAbsoluteTime t)154 Time Time::FromCFAbsoluteTime(CFAbsoluteTime t) {
155   static_assert(std::numeric_limits<CFAbsoluteTime>::has_infinity,
156                 "CFAbsoluteTime must have an infinity value");
157   if (t == 0)
158     return Time();  // Consider 0 as a null Time.
159   return (t == std::numeric_limits<CFAbsoluteTime>::infinity())
160              ? Max()
161              : (UnixEpoch() + TimeDelta::FromSecondsD(double{
162                                   t + kCFAbsoluteTimeIntervalSince1970}));
163 }
164 
ToCFAbsoluteTime() const165 CFAbsoluteTime Time::ToCFAbsoluteTime() const {
166   static_assert(std::numeric_limits<CFAbsoluteTime>::has_infinity,
167                 "CFAbsoluteTime must have an infinity value");
168   if (is_null())
169     return 0;  // Consider 0 as a null Time.
170   return is_max() ? std::numeric_limits<CFAbsoluteTime>::infinity()
171                   : (CFAbsoluteTime{(*this - UnixEpoch()).InSecondsF()} -
172                      kCFAbsoluteTimeIntervalSince1970);
173 }
174 
175 // TimeDelta ------------------------------------------------------------------
176 
177 #if defined(OS_MAC)
178 // static
FromMachTime(uint64_t mach_time)179 TimeDelta TimeDelta::FromMachTime(uint64_t mach_time) {
180   return TimeDelta::FromMicroseconds(MachTimeToMicroseconds(mach_time));
181 }
182 #endif  // defined(OS_MAC)
183 
184 // TimeTicks ------------------------------------------------------------------
185 
186 namespace subtle {
TimeTicksNowIgnoringOverride()187 TimeTicks TimeTicksNowIgnoringOverride() {
188   return TimeTicks() + TimeDelta::FromMicroseconds(ComputeCurrentTicks());
189 }
190 }  // namespace subtle
191 
192 // static
IsHighResolution()193 bool TimeTicks::IsHighResolution() {
194   return true;
195 }
196 
197 // static
IsConsistentAcrossProcesses()198 bool TimeTicks::IsConsistentAcrossProcesses() {
199   return true;
200 }
201 
202 #if defined(OS_MAC)
203 // static
FromMachAbsoluteTime(uint64_t mach_absolute_time)204 TimeTicks TimeTicks::FromMachAbsoluteTime(uint64_t mach_absolute_time) {
205   return TimeTicks(MachTimeToMicroseconds(mach_absolute_time));
206 }
207 #endif  // defined(OS_MAC)
208 
209 // static
GetClock()210 TimeTicks::Clock TimeTicks::GetClock() {
211 #if defined(OS_IOS)
212   return Clock::IOS_CF_ABSOLUTE_TIME_MINUS_KERN_BOOTTIME;
213 #else
214   return Clock::MAC_MACH_ABSOLUTE_TIME;
215 #endif  // defined(OS_IOS)
216 }
217 
218 // ThreadTicks ----------------------------------------------------------------
219 
220 namespace subtle {
ThreadTicksNowIgnoringOverride()221 ThreadTicks ThreadTicksNowIgnoringOverride() {
222   return ThreadTicks() + TimeDelta::FromMicroseconds(ComputeThreadTicks());
223 }
224 }  // namespace subtle
225 
226 }  // namespace base
227