blob: b625af6f912379d13e728c46de4dc1980d9c1368 [file] [log] [blame]
Vitaly Bukacbed2062015-08-17 12:54:05 -07001// 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 <stdint.h>
8#include <sys/time.h>
9#include <time.h>
10#if defined(OS_ANDROID) && !defined(__LP64__)
11#include <time64.h>
12#endif
13#include <unistd.h>
14
15#include <limits>
16#include <ostream>
17
18#include "base/basictypes.h"
Vitaly Buka8750b272015-08-18 18:39:08 -070019#include "base/build/build_config.h"
Vitaly Bukacbed2062015-08-17 12:54:05 -070020#include "base/logging.h"
Vitaly Bukacbed2062015-08-17 12:54:05 -070021
22namespace {
23
24#if !defined(OS_MACOSX)
Vitaly Bukacbed2062015-08-17 12:54:05 -070025// Define a system-specific SysTime that wraps either to a time_t or
26// a time64_t depending on the host system, and associated convertion.
27// See crbug.com/162007
28#if defined(OS_ANDROID) && !defined(__LP64__)
29typedef time64_t SysTime;
30
31SysTime SysTimeFromTimeStruct(struct tm* timestruct, bool is_local) {
Vitaly Bukacbed2062015-08-17 12:54:05 -070032 if (is_local)
33 return mktime64(timestruct);
34 else
35 return timegm64(timestruct);
36}
37
38void SysTimeToTimeStruct(SysTime t, struct tm* timestruct, bool is_local) {
Vitaly Bukacbed2062015-08-17 12:54:05 -070039 if (is_local)
40 localtime64_r(&t, timestruct);
41 else
42 gmtime64_r(&t, timestruct);
43}
44
45#else // OS_ANDROID && !__LP64__
46typedef time_t SysTime;
47
48SysTime SysTimeFromTimeStruct(struct tm* timestruct, bool is_local) {
Vitaly Bukacbed2062015-08-17 12:54:05 -070049 if (is_local)
50 return mktime(timestruct);
51 else
52 return timegm(timestruct);
53}
54
55void SysTimeToTimeStruct(SysTime t, struct tm* timestruct, bool is_local) {
Vitaly Bukacbed2062015-08-17 12:54:05 -070056 if (is_local)
57 localtime_r(&t, timestruct);
58 else
59 gmtime_r(&t, timestruct);
60}
61#endif // OS_ANDROID
62
63int64 ConvertTimespecToMicros(const struct timespec& ts) {
64 base::CheckedNumeric<int64> result(ts.tv_sec);
65 result *= base::Time::kMicrosecondsPerSecond;
66 result += (ts.tv_nsec / base::Time::kNanosecondsPerMicrosecond);
67 return result.ValueOrDie();
68}
69
70// Helper function to get results from clock_gettime() and convert to a
71// microsecond timebase. Minimum requirement is MONOTONIC_CLOCK to be supported
72// on the system. FreeBSD 6 has CLOCK_MONOTONIC but defines
73// _POSIX_MONOTONIC_CLOCK to -1.
74#if (defined(OS_POSIX) && \
75 defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0) || \
76 defined(OS_BSD) || defined(OS_ANDROID)
77int64 ClockNow(clockid_t clk_id) {
78 struct timespec ts;
79 if (clock_gettime(clk_id, &ts) != 0) {
80 NOTREACHED() << "clock_gettime(" << clk_id << ") failed.";
81 return 0;
82 }
83 return ConvertTimespecToMicros(ts);
84}
85#else // _POSIX_MONOTONIC_CLOCK
86#error No usable tick clock function on this platform.
87#endif // _POSIX_MONOTONIC_CLOCK
88#endif // !defined(OS_MACOSX)
89
90} // namespace
91
92namespace base {
93
94struct timespec TimeDelta::ToTimeSpec() const {
95 int64 microseconds = InMicroseconds();
96 time_t seconds = 0;
97 if (microseconds >= Time::kMicrosecondsPerSecond) {
98 seconds = InSeconds();
99 microseconds -= seconds * Time::kMicrosecondsPerSecond;
100 }
101 struct timespec result =
102 {seconds,
103 static_cast<long>(microseconds * Time::kNanosecondsPerMicrosecond)};
104 return result;
105}
106
107#if !defined(OS_MACOSX)
108// The Time routines in this file use standard POSIX routines, or almost-
109// standard routines in the case of timegm. We need to use a Mach-specific
110// function for TimeTicks::Now() on Mac OS X.
111
112// Time -----------------------------------------------------------------------
113
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
120static const int64 kWindowsEpochDeltaSeconds = INT64_C(11644473600);
121
122// static
123const int64 Time::kWindowsEpochDeltaMicroseconds =
124 kWindowsEpochDeltaSeconds * Time::kMicrosecondsPerSecond;
125
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
129const int64 Time::kTimeTToMicrosecondsOffset = kWindowsEpochDeltaMicroseconds;
130
131// static
132Time Time::Now() {
133 struct timeval tv;
134 struct timezone tz = { 0, 0 }; // UTC
135 if (gettimeofday(&tv, &tz) != 0) {
136 DCHECK(0) << "Could not determine time of day";
Vitaly Buka8750b272015-08-18 18:39:08 -0700137 LOG(ERROR) << "Call to gettimeofday failed.";
Vitaly Bukacbed2062015-08-17 12:54:05 -0700138 // Return null instead of uninitialized |tv| value, which contains random
139 // garbage data. This may result in the crash seen in crbug.com/147570.
140 return Time();
141 }
142 // Combine seconds and microseconds in a 64-bit field containing microseconds
143 // since the epoch. That's enough for nearly 600 centuries. Adjust from
144 // Unix (1970) to Windows (1601) epoch.
145 return Time((tv.tv_sec * kMicrosecondsPerSecond + tv.tv_usec) +
146 kWindowsEpochDeltaMicroseconds);
147}
148
149// static
150Time Time::NowFromSystemTime() {
151 // Just use Now() because Now() returns the system time.
152 return Now();
153}
154
155void Time::Explode(bool is_local, Exploded* exploded) const {
156 // Time stores times with microsecond resolution, but Exploded only carries
157 // millisecond resolution, so begin by being lossy. Adjust from Windows
158 // epoch (1601) to Unix epoch (1970);
159 int64 microseconds = us_ - kWindowsEpochDeltaMicroseconds;
160 // The following values are all rounded towards -infinity.
161 int64 milliseconds; // Milliseconds since epoch.
162 SysTime seconds; // Seconds since epoch.
163 int millisecond; // Exploded millisecond value (0-999).
164 if (microseconds >= 0) {
165 // Rounding towards -infinity <=> rounding towards 0, in this case.
166 milliseconds = microseconds / kMicrosecondsPerMillisecond;
167 seconds = milliseconds / kMillisecondsPerSecond;
168 millisecond = milliseconds % kMillisecondsPerSecond;
169 } else {
170 // Round these *down* (towards -infinity).
171 milliseconds = (microseconds - kMicrosecondsPerMillisecond + 1) /
172 kMicrosecondsPerMillisecond;
173 seconds = (milliseconds - kMillisecondsPerSecond + 1) /
174 kMillisecondsPerSecond;
175 // Make this nonnegative (and between 0 and 999 inclusive).
176 millisecond = milliseconds % kMillisecondsPerSecond;
177 if (millisecond < 0)
178 millisecond += kMillisecondsPerSecond;
179 }
180
181 struct tm timestruct;
182 SysTimeToTimeStruct(seconds, &timestruct, is_local);
183
184 exploded->year = timestruct.tm_year + 1900;
185 exploded->month = timestruct.tm_mon + 1;
186 exploded->day_of_week = timestruct.tm_wday;
187 exploded->day_of_month = timestruct.tm_mday;
188 exploded->hour = timestruct.tm_hour;
189 exploded->minute = timestruct.tm_min;
190 exploded->second = timestruct.tm_sec;
191 exploded->millisecond = millisecond;
192}
193
194// static
195Time Time::FromExploded(bool is_local, const Exploded& exploded) {
196 struct tm timestruct;
197 timestruct.tm_sec = exploded.second;
198 timestruct.tm_min = exploded.minute;
199 timestruct.tm_hour = exploded.hour;
200 timestruct.tm_mday = exploded.day_of_month;
201 timestruct.tm_mon = exploded.month - 1;
202 timestruct.tm_year = exploded.year - 1900;
203 timestruct.tm_wday = exploded.day_of_week; // mktime/timegm ignore this
204 timestruct.tm_yday = 0; // mktime/timegm ignore this
205 timestruct.tm_isdst = -1; // attempt to figure it out
206#if !defined(OS_NACL) && !defined(OS_SOLARIS)
207 timestruct.tm_gmtoff = 0; // not a POSIX field, so mktime/timegm ignore
208 timestruct.tm_zone = NULL; // not a POSIX field, so mktime/timegm ignore
209#endif
210
211
212 int64 milliseconds;
213 SysTime seconds;
214
215 // Certain exploded dates do not really exist due to daylight saving times,
216 // and this causes mktime() to return implementation-defined values when
217 // tm_isdst is set to -1. On Android, the function will return -1, while the
218 // C libraries of other platforms typically return a liberally-chosen value.
219 // Handling this requires the special code below.
220
221 // SysTimeFromTimeStruct() modifies the input structure, save current value.
222 struct tm timestruct0 = timestruct;
223
224 seconds = SysTimeFromTimeStruct(&timestruct, is_local);
225 if (seconds == -1) {
226 // Get the time values with tm_isdst == 0 and 1, then select the closest one
227 // to UTC 00:00:00 that isn't -1.
228 timestruct = timestruct0;
229 timestruct.tm_isdst = 0;
230 int64 seconds_isdst0 = SysTimeFromTimeStruct(&timestruct, is_local);
231
232 timestruct = timestruct0;
233 timestruct.tm_isdst = 1;
234 int64 seconds_isdst1 = SysTimeFromTimeStruct(&timestruct, is_local);
235
236 // seconds_isdst0 or seconds_isdst1 can be -1 for some timezones.
237 // E.g. "CLST" (Chile Summer Time) returns -1 for 'tm_isdt == 1'.
238 if (seconds_isdst0 < 0)
239 seconds = seconds_isdst1;
240 else if (seconds_isdst1 < 0)
241 seconds = seconds_isdst0;
242 else
243 seconds = std::min(seconds_isdst0, seconds_isdst1);
244 }
245
246 // Handle overflow. Clamping the range to what mktime and timegm might
247 // return is the best that can be done here. It's not ideal, but it's better
248 // than failing here or ignoring the overflow case and treating each time
249 // overflow as one second prior to the epoch.
250 if (seconds == -1 &&
251 (exploded.year < 1969 || exploded.year > 1970)) {
252 // If exploded.year is 1969 or 1970, take -1 as correct, with the
253 // time indicating 1 second prior to the epoch. (1970 is allowed to handle
254 // time zone and DST offsets.) Otherwise, return the most future or past
255 // time representable. Assumes the time_t epoch is 1970-01-01 00:00:00 UTC.
256 //
257 // The minimum and maximum representible times that mktime and timegm could
258 // return are used here instead of values outside that range to allow for
259 // proper round-tripping between exploded and counter-type time
260 // representations in the presence of possible truncation to time_t by
261 // division and use with other functions that accept time_t.
262 //
263 // When representing the most distant time in the future, add in an extra
264 // 999ms to avoid the time being less than any other possible value that
265 // this function can return.
266
267 // On Android, SysTime is int64, special care must be taken to avoid
268 // overflows.
269 const int64 min_seconds = (sizeof(SysTime) < sizeof(int64))
270 ? std::numeric_limits<SysTime>::min()
271 : std::numeric_limits<int32_t>::min();
272 const int64 max_seconds = (sizeof(SysTime) < sizeof(int64))
273 ? std::numeric_limits<SysTime>::max()
274 : std::numeric_limits<int32_t>::max();
275 if (exploded.year < 1969) {
276 milliseconds = min_seconds * kMillisecondsPerSecond;
277 } else {
278 milliseconds = max_seconds * kMillisecondsPerSecond;
279 milliseconds += (kMillisecondsPerSecond - 1);
280 }
281 } else {
282 milliseconds = seconds * kMillisecondsPerSecond + exploded.millisecond;
283 }
284
285 // Adjust from Unix (1970) to Windows (1601) epoch.
286 return Time((milliseconds * kMicrosecondsPerMillisecond) +
287 kWindowsEpochDeltaMicroseconds);
288}
289
290// TimeTicks ------------------------------------------------------------------
291// static
292TimeTicks TimeTicks::Now() {
293 return TimeTicks(ClockNow(CLOCK_MONOTONIC));
294}
295
296// static
297bool TimeTicks::IsHighResolution() {
298 return true;
299}
300
301// static
302ThreadTicks ThreadTicks::Now() {
303#if (defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)) || \
304 defined(OS_ANDROID)
305 return ThreadTicks(ClockNow(CLOCK_THREAD_CPUTIME_ID));
306#else
307 NOTREACHED();
308 return ThreadTicks();
309#endif
310}
311
312// Use the Chrome OS specific system-wide clock.
313#if defined(OS_CHROMEOS)
314// static
315TraceTicks TraceTicks::Now() {
316 struct timespec ts;
317 if (clock_gettime(kClockSystemTrace, &ts) != 0) {
318 // NB: fall-back for a chrome os build running on linux
319 return TraceTicks(ClockNow(CLOCK_MONOTONIC));
320 }
321 return TraceTicks(ConvertTimespecToMicros(ts));
322}
323
324#else // !defined(OS_CHROMEOS)
325
326// static
327TraceTicks TraceTicks::Now() {
328 return TraceTicks(ClockNow(CLOCK_MONOTONIC));
329}
330
331#endif // defined(OS_CHROMEOS)
332
333#endif // !OS_MACOSX
334
335// static
336Time Time::FromTimeVal(struct timeval t) {
337 DCHECK_LT(t.tv_usec, static_cast<int>(Time::kMicrosecondsPerSecond));
338 DCHECK_GE(t.tv_usec, 0);
339 if (t.tv_usec == 0 && t.tv_sec == 0)
340 return Time();
341 if (t.tv_usec == static_cast<suseconds_t>(Time::kMicrosecondsPerSecond) - 1 &&
342 t.tv_sec == std::numeric_limits<time_t>::max())
343 return Max();
344 return Time(
345 (static_cast<int64>(t.tv_sec) * Time::kMicrosecondsPerSecond) +
346 t.tv_usec +
347 kTimeTToMicrosecondsOffset);
348}
349
350struct timeval Time::ToTimeVal() const {
351 struct timeval result;
352 if (is_null()) {
353 result.tv_sec = 0;
354 result.tv_usec = 0;
355 return result;
356 }
357 if (is_max()) {
358 result.tv_sec = std::numeric_limits<time_t>::max();
359 result.tv_usec = static_cast<suseconds_t>(Time::kMicrosecondsPerSecond) - 1;
360 return result;
361 }
362 int64 us = us_ - kTimeTToMicrosecondsOffset;
363 result.tv_sec = us / Time::kMicrosecondsPerSecond;
364 result.tv_usec = us % Time::kMicrosecondsPerSecond;
365 return result;
366}
367
368} // namespace base