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"
10 #if defined(OS_ANDROID) && !defined(__LP64__)
18 #include "base/basictypes.h"
19 #include "base/logging.h"
20 #include "build/build_config.h"
22 #if defined(OS_ANDROID)
23 #include "base/os_compat_android.h"
24 #elif defined(OS_NACL)
25 #include "base/os_compat_nacl.h"
28 #if !defined(OS_MACOSX)
29 #include "base/lazy_instance.h"
30 #include "base/synchronization/lock.h"
35 #if !defined(OS_MACOSX)
36 // This prevents a crash on traversing the environment global and looking up
37 // the 'TZ' variable in libc. See: crbug.com/390567.
38 base::LazyInstance
<base::Lock
>::Leaky
39 g_sys_time_to_time_struct_lock
= LAZY_INSTANCE_INITIALIZER
;
41 // Define a system-specific SysTime that wraps either to a time_t or
42 // a time64_t depending on the host system, and associated convertion.
43 // See crbug.com/162007
44 #if defined(OS_ANDROID) && !defined(__LP64__)
45 typedef time64_t SysTime
;
47 SysTime
SysTimeFromTimeStruct(struct tm
* timestruct
, bool is_local
) {
48 base::AutoLock
locked(g_sys_time_to_time_struct_lock
.Get());
50 return mktime64(timestruct
);
52 return timegm64(timestruct
);
55 void SysTimeToTimeStruct(SysTime t
, struct tm
* timestruct
, bool is_local
) {
56 base::AutoLock
locked(g_sys_time_to_time_struct_lock
.Get());
58 localtime64_r(&t
, timestruct
);
60 gmtime64_r(&t
, timestruct
);
63 #else // OS_ANDROID && !__LP64__
64 typedef time_t SysTime
;
66 SysTime
SysTimeFromTimeStruct(struct tm
* timestruct
, bool is_local
) {
67 base::AutoLock
locked(g_sys_time_to_time_struct_lock
.Get());
69 return mktime(timestruct
);
71 return timegm(timestruct
);
74 void SysTimeToTimeStruct(SysTime t
, struct tm
* timestruct
, bool is_local
) {
75 base::AutoLock
locked(g_sys_time_to_time_struct_lock
.Get());
77 localtime_r(&t
, timestruct
);
79 gmtime_r(&t
, timestruct
);
83 int64
ConvertTimespecToMicros(const struct timespec
& ts
) {
84 base::CheckedNumeric
<int64
> result(ts
.tv_sec
);
85 result
*= base::Time::kMicrosecondsPerSecond
;
86 result
+= (ts
.tv_nsec
/ base::Time::kNanosecondsPerMicrosecond
);
87 return result
.ValueOrDie();
90 // Helper function to get results from clock_gettime() and convert to a
91 // microsecond timebase. Minimum requirement is MONOTONIC_CLOCK to be supported
92 // on the system. FreeBSD 6 has CLOCK_MONOTONIC but defines
93 // _POSIX_MONOTONIC_CLOCK to -1.
94 #if (defined(OS_POSIX) && \
95 defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0) || \
96 defined(OS_BSD) || defined(OS_ANDROID)
97 int64
ClockNow(clockid_t clk_id
) {
99 if (clock_gettime(clk_id
, &ts
) != 0) {
100 NOTREACHED() << "clock_gettime(" << clk_id
<< ") failed.";
103 return ConvertTimespecToMicros(ts
);
105 #else // _POSIX_MONOTONIC_CLOCK
106 #error No usable tick clock function on this platform.
107 #endif // _POSIX_MONOTONIC_CLOCK
108 #endif // !defined(OS_MACOSX)
114 struct timespec
TimeDelta::ToTimeSpec() const {
115 int64 microseconds
= InMicroseconds();
117 if (microseconds
>= Time::kMicrosecondsPerSecond
) {
118 seconds
= InSeconds();
119 microseconds
-= seconds
* Time::kMicrosecondsPerSecond
;
121 struct timespec result
=
123 static_cast<long>(microseconds
* Time::kNanosecondsPerMicrosecond
)};
127 #if !defined(OS_MACOSX)
128 // The Time routines in this file use standard POSIX routines, or almost-
129 // standard routines in the case of timegm. We need to use a Mach-specific
130 // function for TimeTicks::Now() on Mac OS X.
132 // Time -----------------------------------------------------------------------
134 // Windows uses a Gregorian epoch of 1601. We need to match this internally
135 // so that our time representations match across all platforms. See bug 14734.
136 // irb(main):010:0> Time.at(0).getutc()
137 // => Thu Jan 01 00:00:00 UTC 1970
138 // irb(main):011:0> Time.at(-11644473600).getutc()
139 // => Mon Jan 01 00:00:00 UTC 1601
140 static const int64 kWindowsEpochDeltaSeconds
= INT64_C(11644473600);
143 const int64
Time::kWindowsEpochDeltaMicroseconds
=
144 kWindowsEpochDeltaSeconds
* Time::kMicrosecondsPerSecond
;
146 // Some functions in time.cc use time_t directly, so we provide an offset
147 // to convert from time_t (Unix epoch) and internal (Windows epoch).
149 const int64
Time::kTimeTToMicrosecondsOffset
= kWindowsEpochDeltaMicroseconds
;
154 struct timezone tz
= { 0, 0 }; // UTC
155 if (gettimeofday(&tv
, &tz
) != 0) {
156 DCHECK(0) << "Could not determine time of day";
157 PLOG(ERROR
) << "Call to gettimeofday failed.";
158 // Return null instead of uninitialized |tv| value, which contains random
159 // garbage data. This may result in the crash seen in crbug.com/147570.
162 // Combine seconds and microseconds in a 64-bit field containing microseconds
163 // since the epoch. That's enough for nearly 600 centuries. Adjust from
164 // Unix (1970) to Windows (1601) epoch.
165 return Time((tv
.tv_sec
* kMicrosecondsPerSecond
+ tv
.tv_usec
) +
166 kWindowsEpochDeltaMicroseconds
);
170 Time
Time::NowFromSystemTime() {
171 // Just use Now() because Now() returns the system time.
175 void Time::Explode(bool is_local
, Exploded
* exploded
) const {
176 // Time stores times with microsecond resolution, but Exploded only carries
177 // millisecond resolution, so begin by being lossy. Adjust from Windows
178 // epoch (1601) to Unix epoch (1970);
179 int64 microseconds
= us_
- kWindowsEpochDeltaMicroseconds
;
180 // The following values are all rounded towards -infinity.
181 int64 milliseconds
; // Milliseconds since epoch.
182 SysTime seconds
; // Seconds since epoch.
183 int millisecond
; // Exploded millisecond value (0-999).
184 if (microseconds
>= 0) {
185 // Rounding towards -infinity <=> rounding towards 0, in this case.
186 milliseconds
= microseconds
/ kMicrosecondsPerMillisecond
;
187 seconds
= milliseconds
/ kMillisecondsPerSecond
;
188 millisecond
= milliseconds
% kMillisecondsPerSecond
;
190 // Round these *down* (towards -infinity).
191 milliseconds
= (microseconds
- kMicrosecondsPerMillisecond
+ 1) /
192 kMicrosecondsPerMillisecond
;
193 seconds
= (milliseconds
- kMillisecondsPerSecond
+ 1) /
194 kMillisecondsPerSecond
;
195 // Make this nonnegative (and between 0 and 999 inclusive).
196 millisecond
= milliseconds
% kMillisecondsPerSecond
;
198 millisecond
+= kMillisecondsPerSecond
;
201 struct tm timestruct
;
202 SysTimeToTimeStruct(seconds
, ×truct
, is_local
);
204 exploded
->year
= timestruct
.tm_year
+ 1900;
205 exploded
->month
= timestruct
.tm_mon
+ 1;
206 exploded
->day_of_week
= timestruct
.tm_wday
;
207 exploded
->day_of_month
= timestruct
.tm_mday
;
208 exploded
->hour
= timestruct
.tm_hour
;
209 exploded
->minute
= timestruct
.tm_min
;
210 exploded
->second
= timestruct
.tm_sec
;
211 exploded
->millisecond
= millisecond
;
215 Time
Time::FromExploded(bool is_local
, const Exploded
& exploded
) {
216 struct tm timestruct
;
217 timestruct
.tm_sec
= exploded
.second
;
218 timestruct
.tm_min
= exploded
.minute
;
219 timestruct
.tm_hour
= exploded
.hour
;
220 timestruct
.tm_mday
= exploded
.day_of_month
;
221 timestruct
.tm_mon
= exploded
.month
- 1;
222 timestruct
.tm_year
= exploded
.year
- 1900;
223 timestruct
.tm_wday
= exploded
.day_of_week
; // mktime/timegm ignore this
224 timestruct
.tm_yday
= 0; // mktime/timegm ignore this
225 timestruct
.tm_isdst
= -1; // attempt to figure it out
226 #if !defined(OS_NACL) && !defined(OS_SOLARIS)
227 timestruct
.tm_gmtoff
= 0; // not a POSIX field, so mktime/timegm ignore
228 timestruct
.tm_zone
= NULL
; // not a POSIX field, so mktime/timegm ignore
235 // Certain exploded dates do not really exist due to daylight saving times,
236 // and this causes mktime() to return implementation-defined values when
237 // tm_isdst is set to -1. On Android, the function will return -1, while the
238 // C libraries of other platforms typically return a liberally-chosen value.
239 // Handling this requires the special code below.
241 // SysTimeFromTimeStruct() modifies the input structure, save current value.
242 struct tm timestruct0
= timestruct
;
244 seconds
= SysTimeFromTimeStruct(×truct
, is_local
);
246 // Get the time values with tm_isdst == 0 and 1, then select the closest one
247 // to UTC 00:00:00 that isn't -1.
248 timestruct
= timestruct0
;
249 timestruct
.tm_isdst
= 0;
250 int64 seconds_isdst0
= SysTimeFromTimeStruct(×truct
, is_local
);
252 timestruct
= timestruct0
;
253 timestruct
.tm_isdst
= 1;
254 int64 seconds_isdst1
= SysTimeFromTimeStruct(×truct
, is_local
);
256 // seconds_isdst0 or seconds_isdst1 can be -1 for some timezones.
257 // E.g. "CLST" (Chile Summer Time) returns -1 for 'tm_isdt == 1'.
258 if (seconds_isdst0
< 0)
259 seconds
= seconds_isdst1
;
260 else if (seconds_isdst1
< 0)
261 seconds
= seconds_isdst0
;
263 seconds
= std::min(seconds_isdst0
, seconds_isdst1
);
266 // Handle overflow. Clamping the range to what mktime and timegm might
267 // return is the best that can be done here. It's not ideal, but it's better
268 // than failing here or ignoring the overflow case and treating each time
269 // overflow as one second prior to the epoch.
271 (exploded
.year
< 1969 || exploded
.year
> 1970)) {
272 // If exploded.year is 1969 or 1970, take -1 as correct, with the
273 // time indicating 1 second prior to the epoch. (1970 is allowed to handle
274 // time zone and DST offsets.) Otherwise, return the most future or past
275 // time representable. Assumes the time_t epoch is 1970-01-01 00:00:00 UTC.
277 // The minimum and maximum representible times that mktime and timegm could
278 // return are used here instead of values outside that range to allow for
279 // proper round-tripping between exploded and counter-type time
280 // representations in the presence of possible truncation to time_t by
281 // division and use with other functions that accept time_t.
283 // When representing the most distant time in the future, add in an extra
284 // 999ms to avoid the time being less than any other possible value that
285 // this function can return.
287 // On Android, SysTime is int64, special care must be taken to avoid
289 const int64 min_seconds
= (sizeof(SysTime
) < sizeof(int64
))
290 ? std::numeric_limits
<SysTime
>::min()
291 : std::numeric_limits
<int32_t>::min();
292 const int64 max_seconds
= (sizeof(SysTime
) < sizeof(int64
))
293 ? std::numeric_limits
<SysTime
>::max()
294 : std::numeric_limits
<int32_t>::max();
295 if (exploded
.year
< 1969) {
296 milliseconds
= min_seconds
* kMillisecondsPerSecond
;
298 milliseconds
= max_seconds
* kMillisecondsPerSecond
;
299 milliseconds
+= (kMillisecondsPerSecond
- 1);
302 milliseconds
= seconds
* kMillisecondsPerSecond
+ exploded
.millisecond
;
305 // Adjust from Unix (1970) to Windows (1601) epoch.
306 return Time((milliseconds
* kMicrosecondsPerMillisecond
) +
307 kWindowsEpochDeltaMicroseconds
);
310 // TimeTicks ------------------------------------------------------------------
312 TimeTicks
TimeTicks::Now() {
313 return TimeTicks(ClockNow(CLOCK_MONOTONIC
));
317 bool TimeTicks::IsHighResolution() {
322 ThreadTicks
ThreadTicks::Now() {
323 #if (defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)) || \
325 return ThreadTicks(ClockNow(CLOCK_THREAD_CPUTIME_ID
));
328 return ThreadTicks();
332 // Use the Chrome OS specific system-wide clock.
333 #if defined(OS_CHROMEOS)
335 TraceTicks
TraceTicks::Now() {
337 if (clock_gettime(kClockSystemTrace
, &ts
) != 0) {
338 // NB: fall-back for a chrome os build running on linux
339 return TraceTicks(ClockNow(CLOCK_MONOTONIC
));
341 return TraceTicks(ConvertTimespecToMicros(ts
));
344 #else // !defined(OS_CHROMEOS)
347 TraceTicks
TraceTicks::Now() {
348 return TraceTicks(ClockNow(CLOCK_MONOTONIC
));
351 #endif // defined(OS_CHROMEOS)
356 Time
Time::FromTimeVal(struct timeval t
) {
357 DCHECK_LT(t
.tv_usec
, static_cast<int>(Time::kMicrosecondsPerSecond
));
358 DCHECK_GE(t
.tv_usec
, 0);
359 if (t
.tv_usec
== 0 && t
.tv_sec
== 0)
361 if (t
.tv_usec
== static_cast<suseconds_t
>(Time::kMicrosecondsPerSecond
) - 1 &&
362 t
.tv_sec
== std::numeric_limits
<time_t>::max())
365 (static_cast<int64
>(t
.tv_sec
) * Time::kMicrosecondsPerSecond
) +
367 kTimeTToMicrosecondsOffset
);
370 struct timeval
Time::ToTimeVal() const {
371 struct timeval result
;
378 result
.tv_sec
= std::numeric_limits
<time_t>::max();
379 result
.tv_usec
= static_cast<suseconds_t
>(Time::kMicrosecondsPerSecond
) - 1;
382 int64 us
= us_
- kTimeTToMicrosecondsOffset
;
383 result
.tv_sec
= us
/ Time::kMicrosecondsPerSecond
;
384 result
.tv_usec
= us
% Time::kMicrosecondsPerSecond
;