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