Roll src/third_party/WebKit 7764cd0:1eb8b9f (svn 199730:199735)
[chromium-blink-merge.git] / base / time / time_mac.cc
blob1dbbc3370df6ca4c04a34164bc39c39eea73c231
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.
5 #include "base/time/time.h"
7 #include <CoreFoundation/CFDate.h>
8 #include <CoreFoundation/CFTimeZone.h>
9 #include <mach/mach.h>
10 #include <mach/mach_time.h>
11 #include <stdint.h>
12 #include <sys/sysctl.h>
13 #include <sys/time.h>
14 #include <sys/types.h>
15 #include <time.h>
17 #include "base/basictypes.h"
18 #include "base/logging.h"
19 #include "base/mac/mach_logging.h"
20 #include "base/mac/scoped_cftyperef.h"
21 #include "base/mac/scoped_mach_port.h"
22 #include "base/numerics/safe_conversions.h"
24 namespace {
26 int64_t ComputeCurrentTicks() {
27 #if defined(OS_IOS)
28 // On iOS mach_absolute_time stops while the device is sleeping. Instead use
29 // now - KERN_BOOTTIME to get a time difference that is not impacted by clock
30 // changes. KERN_BOOTTIME will be updated by the system whenever the system
31 // clock change.
32 struct timeval boottime;
33 int mib[2] = {CTL_KERN, KERN_BOOTTIME};
34 size_t size = sizeof(boottime);
35 int kr = sysctl(mib, arraysize(mib), &boottime, &size, NULL, 0);
36 DCHECK_EQ(KERN_SUCCESS, kr);
37 base::TimeDelta time_difference = base::Time::Now() -
38 (base::Time::FromTimeT(boottime.tv_sec) +
39 base::TimeDelta::FromMicroseconds(boottime.tv_usec));
40 return time_difference.InMicroseconds();
41 #else
42 static mach_timebase_info_data_t timebase_info;
43 if (timebase_info.denom == 0) {
44 // Zero-initialization of statics guarantees that denom will be 0 before
45 // calling mach_timebase_info. mach_timebase_info will never set denom to
46 // 0 as that would be invalid, so the zero-check can be used to determine
47 // whether mach_timebase_info has already been called. This is
48 // recommended by Apple's QA1398.
49 kern_return_t kr = mach_timebase_info(&timebase_info);
50 MACH_DCHECK(kr == KERN_SUCCESS, kr) << "mach_timebase_info";
53 // mach_absolute_time is it when it comes to ticks on the Mac. Other calls
54 // with less precision (such as TickCount) just call through to
55 // mach_absolute_time.
57 // timebase_info converts absolute time tick units into nanoseconds. Convert
58 // to microseconds up front to stave off overflows.
59 base::CheckedNumeric<uint64_t> result(
60 mach_absolute_time() / base::Time::kNanosecondsPerMicrosecond);
61 result *= timebase_info.numer;
62 result /= timebase_info.denom;
64 // Don't bother with the rollover handling that the Windows version does.
65 // With numer and denom = 1 (the expected case), the 64-bit absolute time
66 // reported in nanoseconds is enough to last nearly 585 years.
67 return base::checked_cast<int64_t>(result.ValueOrDie());
68 #endif // defined(OS_IOS)
71 int64_t ComputeThreadTicks() {
72 #if defined(OS_IOS)
73 NOTREACHED();
74 return 0;
75 #else
76 base::mac::ScopedMachSendRight thread(mach_thread_self());
77 mach_msg_type_number_t thread_info_count = THREAD_BASIC_INFO_COUNT;
78 thread_basic_info_data_t thread_info_data;
80 if (thread.get() == MACH_PORT_NULL) {
81 DLOG(ERROR) << "Failed to get mach_thread_self()";
82 return 0;
85 kern_return_t kr = thread_info(
86 thread,
87 THREAD_BASIC_INFO,
88 reinterpret_cast<thread_info_t>(&thread_info_data),
89 &thread_info_count);
90 MACH_DCHECK(kr == KERN_SUCCESS, kr) << "thread_info";
92 base::CheckedNumeric<int64_t> absolute_micros(
93 thread_info_data.user_time.seconds);
94 absolute_micros *= base::Time::kMicrosecondsPerSecond;
95 absolute_micros += thread_info_data.user_time.microseconds;
96 return absolute_micros.ValueOrDie();
97 #endif // defined(OS_IOS)
100 } // namespace
102 namespace base {
104 // The Time routines in this file use Mach and CoreFoundation APIs, since the
105 // POSIX definition of time_t in Mac OS X wraps around after 2038--and
106 // there are already cookie expiration dates, etc., past that time out in
107 // the field. Using CFDate prevents that problem, and using mach_absolute_time
108 // for TimeTicks gives us nice high-resolution interval timing.
110 // Time -----------------------------------------------------------------------
112 // Core Foundation uses a double second count since 2001-01-01 00:00:00 UTC.
113 // The UNIX epoch is 1970-01-01 00:00:00 UTC.
114 // Windows uses a Gregorian epoch of 1601. We need to match this internally
115 // so that our time representations match across all platforms. See bug 14734.
116 // irb(main):010:0> Time.at(0).getutc()
117 // => Thu Jan 01 00:00:00 UTC 1970
118 // irb(main):011:0> Time.at(-11644473600).getutc()
119 // => Mon Jan 01 00:00:00 UTC 1601
120 static const int64 kWindowsEpochDeltaSeconds = INT64_C(11644473600);
122 // static
123 const int64 Time::kWindowsEpochDeltaMicroseconds =
124 kWindowsEpochDeltaSeconds * Time::kMicrosecondsPerSecond;
126 // Some functions in time.cc use time_t directly, so we provide an offset
127 // to convert from time_t (Unix epoch) and internal (Windows epoch).
128 // static
129 const int64 Time::kTimeTToMicrosecondsOffset = kWindowsEpochDeltaMicroseconds;
131 // static
132 Time Time::Now() {
133 return FromCFAbsoluteTime(CFAbsoluteTimeGetCurrent());
136 // static
137 Time Time::FromCFAbsoluteTime(CFAbsoluteTime t) {
138 COMPILE_ASSERT(std::numeric_limits<CFAbsoluteTime>::has_infinity,
139 numeric_limits_infinity_is_undefined_when_not_has_infinity);
140 if (t == 0)
141 return Time(); // Consider 0 as a null Time.
142 if (t == std::numeric_limits<CFAbsoluteTime>::infinity())
143 return Max();
144 return Time(static_cast<int64>(
145 (t + kCFAbsoluteTimeIntervalSince1970) * kMicrosecondsPerSecond) +
146 kWindowsEpochDeltaMicroseconds);
149 CFAbsoluteTime Time::ToCFAbsoluteTime() const {
150 COMPILE_ASSERT(std::numeric_limits<CFAbsoluteTime>::has_infinity,
151 numeric_limits_infinity_is_undefined_when_not_has_infinity);
152 if (is_null())
153 return 0; // Consider 0 as a null Time.
154 if (is_max())
155 return std::numeric_limits<CFAbsoluteTime>::infinity();
156 return (static_cast<CFAbsoluteTime>(us_ - kWindowsEpochDeltaMicroseconds) /
157 kMicrosecondsPerSecond) - kCFAbsoluteTimeIntervalSince1970;
160 // static
161 Time Time::NowFromSystemTime() {
162 // Just use Now() because Now() returns the system time.
163 return Now();
166 // static
167 Time Time::FromExploded(bool is_local, const Exploded& exploded) {
168 CFGregorianDate date;
169 date.second = exploded.second +
170 exploded.millisecond / static_cast<double>(kMillisecondsPerSecond);
171 date.minute = exploded.minute;
172 date.hour = exploded.hour;
173 date.day = exploded.day_of_month;
174 date.month = exploded.month;
175 date.year = exploded.year;
177 base::ScopedCFTypeRef<CFTimeZoneRef> time_zone(
178 is_local ? CFTimeZoneCopySystem() : NULL);
179 CFAbsoluteTime seconds = CFGregorianDateGetAbsoluteTime(date, time_zone) +
180 kCFAbsoluteTimeIntervalSince1970;
181 return Time(static_cast<int64>(seconds * kMicrosecondsPerSecond) +
182 kWindowsEpochDeltaMicroseconds);
185 void Time::Explode(bool is_local, Exploded* exploded) const {
186 // Avoid rounding issues, by only putting the integral number of seconds
187 // (rounded towards -infinity) into a |CFAbsoluteTime| (which is a |double|).
188 int64 microsecond = us_ % kMicrosecondsPerSecond;
189 if (microsecond < 0)
190 microsecond += kMicrosecondsPerSecond;
191 CFAbsoluteTime seconds = ((us_ - microsecond) / kMicrosecondsPerSecond) -
192 kWindowsEpochDeltaSeconds -
193 kCFAbsoluteTimeIntervalSince1970;
195 base::ScopedCFTypeRef<CFTimeZoneRef> time_zone(
196 is_local ? CFTimeZoneCopySystem() : NULL);
197 CFGregorianDate date = CFAbsoluteTimeGetGregorianDate(seconds, time_zone);
198 // 1 = Monday, ..., 7 = Sunday.
199 int cf_day_of_week = CFAbsoluteTimeGetDayOfWeek(seconds, time_zone);
201 exploded->year = date.year;
202 exploded->month = date.month;
203 exploded->day_of_week = cf_day_of_week % 7;
204 exploded->day_of_month = date.day;
205 exploded->hour = date.hour;
206 exploded->minute = date.minute;
207 // Make sure seconds are rounded down towards -infinity.
208 exploded->second = floor(date.second);
209 // Calculate milliseconds ourselves, since we rounded the |seconds|, making
210 // sure to round towards -infinity.
211 exploded->millisecond =
212 (microsecond >= 0) ? microsecond / kMicrosecondsPerMillisecond :
213 (microsecond - kMicrosecondsPerMillisecond + 1) /
214 kMicrosecondsPerMillisecond;
217 // TimeTicks ------------------------------------------------------------------
219 // static
220 TimeTicks TimeTicks::Now() {
221 return TimeTicks(ComputeCurrentTicks());
224 // static
225 bool TimeTicks::IsHighResolution() {
226 return true;
229 // static
230 ThreadTicks ThreadTicks::Now() {
231 return ThreadTicks(ComputeThreadTicks());
234 // static
235 TraceTicks TraceTicks::Now() {
236 return TraceTicks(ComputeCurrentTicks());
239 } // namespace base