OLD | NEW |
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. | 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 | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 | 4 |
5 #include "base/time/time.h" | 5 #include "base/time/time.h" |
6 | 6 |
7 #include <stdint.h> | 7 #include <stdint.h> |
8 #include <sys/time.h> | 8 #include <sys/time.h> |
9 #include <time.h> | 9 #include <time.h> |
10 #if defined(OS_ANDROID) && !defined(__LP64__) | 10 #if defined(OS_ANDROID) && !defined(__LP64__) |
11 #include <time64.h> | 11 #include <time64.h> |
12 #endif | 12 #endif |
13 #include <unistd.h> | 13 #include <unistd.h> |
14 | 14 |
15 #include <limits> | 15 #include <limits> |
16 #include <ostream> | |
17 | 16 |
18 #include "base/logging.h" | |
19 #include "base/numerics/safe_math.h" | 17 #include "base/numerics/safe_math.h" |
| 18 #include "base/synchronization/lock.h" |
20 #include "build/build_config.h" | 19 #include "build/build_config.h" |
21 | 20 |
22 #if defined(OS_ANDROID) | 21 #if defined(OS_ANDROID) |
23 #include "base/os_compat_android.h" | 22 #include "base/os_compat_android.h" |
24 #elif defined(OS_NACL) | 23 #elif defined(OS_NACL) |
25 #include "base/os_compat_nacl.h" | 24 #include "base/os_compat_nacl.h" |
26 #endif | 25 #endif |
27 | 26 |
28 #if !defined(OS_MACOSX) | 27 // Ensure the Mac build does not include this module. Instead, non-POSIX |
29 #include "base/synchronization/lock.h" | 28 // implementation is used to support Time::Exploded. |
| 29 #if defined(OS_MACOSX) |
| 30 #error "This implementation is for POSIX platforms other than Mac." |
30 #endif | 31 #endif |
31 | 32 |
32 namespace { | 33 namespace { |
33 | 34 |
34 #if !defined(OS_MACOSX) | |
35 // This prevents a crash on traversing the environment global and looking up | 35 // This prevents a crash on traversing the environment global and looking up |
36 // the 'TZ' variable in libc. See: crbug.com/390567. | 36 // the 'TZ' variable in libc. See: crbug.com/390567. |
37 base::Lock* GetSysTimeToTimeStructLock() { | 37 base::Lock* GetSysTimeToTimeStructLock() { |
38 static auto* lock = new base::Lock(); | 38 static auto* lock = new base::Lock(); |
39 return lock; | 39 return lock; |
40 } | 40 } |
41 | 41 |
42 // Define a system-specific SysTime that wraps either to a time_t or | 42 // Define a system-specific SysTime that wraps either to a time_t or |
43 // a time64_t depending on the host system, and associated convertion. | 43 // a time64_t depending on the host system, and associated convertion. |
44 // See crbug.com/162007 | 44 // See crbug.com/162007 |
(...skipping 51 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
96 } | 96 } |
97 | 97 |
98 void SysTimeToTimeStruct(SysTime t, struct tm* timestruct, bool is_local) { | 98 void SysTimeToTimeStruct(SysTime t, struct tm* timestruct, bool is_local) { |
99 base::AutoLock locked(*GetSysTimeToTimeStructLock()); | 99 base::AutoLock locked(*GetSysTimeToTimeStructLock()); |
100 if (is_local) | 100 if (is_local) |
101 localtime_r(&t, timestruct); | 101 localtime_r(&t, timestruct); |
102 else | 102 else |
103 gmtime_r(&t, timestruct); | 103 gmtime_r(&t, timestruct); |
104 } | 104 } |
105 | 105 |
106 #else // OS_ANDROID && !__LP64__ | 106 #else // OS_ANDROID && !__LP64__ |
107 typedef time_t SysTime; | 107 typedef time_t SysTime; |
108 | 108 |
109 SysTime SysTimeFromTimeStruct(struct tm* timestruct, bool is_local) { | 109 SysTime SysTimeFromTimeStruct(struct tm* timestruct, bool is_local) { |
110 base::AutoLock locked(*GetSysTimeToTimeStructLock()); | 110 base::AutoLock locked(*GetSysTimeToTimeStructLock()); |
111 if (is_local) | 111 if (is_local) |
112 return mktime(timestruct); | 112 return mktime(timestruct); |
113 else | 113 else |
114 return timegm(timestruct); | 114 return timegm(timestruct); |
115 } | 115 } |
116 | 116 |
117 void SysTimeToTimeStruct(SysTime t, struct tm* timestruct, bool is_local) { | 117 void SysTimeToTimeStruct(SysTime t, struct tm* timestruct, bool is_local) { |
118 base::AutoLock locked(*GetSysTimeToTimeStructLock()); | 118 base::AutoLock locked(*GetSysTimeToTimeStructLock()); |
119 if (is_local) | 119 if (is_local) |
120 localtime_r(&t, timestruct); | 120 localtime_r(&t, timestruct); |
121 else | 121 else |
122 gmtime_r(&t, timestruct); | 122 gmtime_r(&t, timestruct); |
123 } | 123 } |
124 #endif // OS_ANDROID | 124 #endif // OS_ANDROID |
125 | 125 |
126 int64_t ConvertTimespecToMicros(const struct timespec& ts) { | |
127 // On 32-bit systems, the calculation cannot overflow int64_t. | |
128 // 2**32 * 1000000 + 2**64 / 1000 < 2**63 | |
129 if (sizeof(ts.tv_sec) <= 4 && sizeof(ts.tv_nsec) <= 8) { | |
130 int64_t result = ts.tv_sec; | |
131 result *= base::Time::kMicrosecondsPerSecond; | |
132 result += (ts.tv_nsec / base::Time::kNanosecondsPerMicrosecond); | |
133 return result; | |
134 } else { | |
135 base::CheckedNumeric<int64_t> result(ts.tv_sec); | |
136 result *= base::Time::kMicrosecondsPerSecond; | |
137 result += (ts.tv_nsec / base::Time::kNanosecondsPerMicrosecond); | |
138 return result.ValueOrDie(); | |
139 } | |
140 } | |
141 | |
142 // Helper function to get results from clock_gettime() and convert to a | |
143 // microsecond timebase. Minimum requirement is MONOTONIC_CLOCK to be supported | |
144 // on the system. FreeBSD 6 has CLOCK_MONOTONIC but defines | |
145 // _POSIX_MONOTONIC_CLOCK to -1. | |
146 #if (defined(OS_POSIX) && \ | |
147 defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0) || \ | |
148 defined(OS_BSD) || defined(OS_ANDROID) | |
149 int64_t ClockNow(clockid_t clk_id) { | |
150 struct timespec ts; | |
151 if (clock_gettime(clk_id, &ts) != 0) { | |
152 NOTREACHED() << "clock_gettime(" << clk_id << ") failed."; | |
153 return 0; | |
154 } | |
155 return ConvertTimespecToMicros(ts); | |
156 } | |
157 #else // _POSIX_MONOTONIC_CLOCK | |
158 #error No usable tick clock function on this platform. | |
159 #endif // _POSIX_MONOTONIC_CLOCK | |
160 #endif // !defined(OS_MACOSX) | |
161 | |
162 } // namespace | 126 } // namespace |
163 | 127 |
164 namespace base { | 128 namespace base { |
165 | 129 |
166 // static | |
167 TimeDelta TimeDelta::FromTimeSpec(const timespec& ts) { | |
168 return TimeDelta(ts.tv_sec * Time::kMicrosecondsPerSecond + | |
169 ts.tv_nsec / Time::kNanosecondsPerMicrosecond); | |
170 } | |
171 | |
172 struct timespec TimeDelta::ToTimeSpec() const { | |
173 int64_t microseconds = InMicroseconds(); | |
174 time_t seconds = 0; | |
175 if (microseconds >= Time::kMicrosecondsPerSecond) { | |
176 seconds = InSeconds(); | |
177 microseconds -= seconds * Time::kMicrosecondsPerSecond; | |
178 } | |
179 struct timespec result = | |
180 {seconds, | |
181 static_cast<long>(microseconds * Time::kNanosecondsPerMicrosecond)}; | |
182 return result; | |
183 } | |
184 | |
185 #if !defined(OS_MACOSX) | |
186 // The Time routines in this file use standard POSIX routines, or almost- | |
187 // standard routines in the case of timegm. We need to use a Mach-specific | |
188 // function for TimeTicks::Now() on Mac OS X. | |
189 | |
190 // Time ----------------------------------------------------------------------- | |
191 | |
192 // Windows uses a Gregorian epoch of 1601. We need to match this internally | |
193 // so that our time representations match across all platforms. See bug 14734. | |
194 // irb(main):010:0> Time.at(0).getutc() | |
195 // => Thu Jan 01 00:00:00 UTC 1970 | |
196 // irb(main):011:0> Time.at(-11644473600).getutc() | |
197 // => Mon Jan 01 00:00:00 UTC 1601 | |
198 static const int64_t kWindowsEpochDeltaSeconds = INT64_C(11644473600); | |
199 | |
200 // static | |
201 const int64_t Time::kWindowsEpochDeltaMicroseconds = | |
202 kWindowsEpochDeltaSeconds * Time::kMicrosecondsPerSecond; | |
203 | |
204 // Some functions in time.cc use time_t directly, so we provide an offset | |
205 // to convert from time_t (Unix epoch) and internal (Windows epoch). | |
206 // static | |
207 const int64_t Time::kTimeTToMicrosecondsOffset = kWindowsEpochDeltaMicroseconds; | |
208 | |
209 // static | |
210 Time Time::Now() { | |
211 struct timeval tv; | |
212 struct timezone tz = { 0, 0 }; // UTC | |
213 if (gettimeofday(&tv, &tz) != 0) { | |
214 DCHECK(0) << "Could not determine time of day"; | |
215 PLOG(ERROR) << "Call to gettimeofday failed."; | |
216 // Return null instead of uninitialized |tv| value, which contains random | |
217 // garbage data. This may result in the crash seen in crbug.com/147570. | |
218 return Time(); | |
219 } | |
220 // Combine seconds and microseconds in a 64-bit field containing microseconds | |
221 // since the epoch. That's enough for nearly 600 centuries. Adjust from | |
222 // Unix (1970) to Windows (1601) epoch. | |
223 return Time((tv.tv_sec * kMicrosecondsPerSecond + tv.tv_usec) + | |
224 kWindowsEpochDeltaMicroseconds); | |
225 } | |
226 | |
227 // static | |
228 Time Time::NowFromSystemTime() { | |
229 // Just use Now() because Now() returns the system time. | |
230 return Now(); | |
231 } | |
232 | |
233 void Time::Explode(bool is_local, Exploded* exploded) const { | 130 void Time::Explode(bool is_local, Exploded* exploded) const { |
234 // Time stores times with microsecond resolution, but Exploded only carries | 131 // Time stores times with microsecond resolution, but Exploded only carries |
235 // millisecond resolution, so begin by being lossy. Adjust from Windows | 132 // millisecond resolution, so begin by being lossy. Adjust from Windows |
236 // epoch (1601) to Unix epoch (1970); | 133 // epoch (1601) to Unix epoch (1970); |
237 int64_t microseconds = us_ - kWindowsEpochDeltaMicroseconds; | 134 int64_t microseconds = us_ - kTimeTToMicrosecondsOffset; |
238 // The following values are all rounded towards -infinity. | 135 // The following values are all rounded towards -infinity. |
239 int64_t milliseconds; // Milliseconds since epoch. | 136 int64_t milliseconds; // Milliseconds since epoch. |
240 SysTime seconds; // Seconds since epoch. | 137 SysTime seconds; // Seconds since epoch. |
241 int millisecond; // Exploded millisecond value (0-999). | 138 int millisecond; // Exploded millisecond value (0-999). |
242 if (microseconds >= 0) { | 139 if (microseconds >= 0) { |
243 // Rounding towards -infinity <=> rounding towards 0, in this case. | 140 // Rounding towards -infinity <=> rounding towards 0, in this case. |
244 milliseconds = microseconds / kMicrosecondsPerMillisecond; | 141 milliseconds = microseconds / kMicrosecondsPerMillisecond; |
245 seconds = milliseconds / kMillisecondsPerSecond; | 142 seconds = milliseconds / kMillisecondsPerSecond; |
246 millisecond = milliseconds % kMillisecondsPerSecond; | 143 millisecond = milliseconds % kMillisecondsPerSecond; |
247 } else { | 144 } else { |
248 // Round these *down* (towards -infinity). | 145 // Round these *down* (towards -infinity). |
249 milliseconds = (microseconds - kMicrosecondsPerMillisecond + 1) / | 146 milliseconds = (microseconds - kMicrosecondsPerMillisecond + 1) / |
250 kMicrosecondsPerMillisecond; | 147 kMicrosecondsPerMillisecond; |
251 seconds = (milliseconds - kMillisecondsPerSecond + 1) / | 148 seconds = |
252 kMillisecondsPerSecond; | 149 (milliseconds - kMillisecondsPerSecond + 1) / kMillisecondsPerSecond; |
253 // Make this nonnegative (and between 0 and 999 inclusive). | 150 // Make this nonnegative (and between 0 and 999 inclusive). |
254 millisecond = milliseconds % kMillisecondsPerSecond; | 151 millisecond = milliseconds % kMillisecondsPerSecond; |
255 if (millisecond < 0) | 152 if (millisecond < 0) |
256 millisecond += kMillisecondsPerSecond; | 153 millisecond += kMillisecondsPerSecond; |
257 } | 154 } |
258 | 155 |
259 struct tm timestruct; | 156 struct tm timestruct; |
260 SysTimeToTimeStruct(seconds, ×truct, is_local); | 157 SysTimeToTimeStruct(seconds, ×truct, is_local); |
261 | 158 |
262 exploded->year = timestruct.tm_year + 1900; | 159 exploded->year = timestruct.tm_year + 1900; |
263 exploded->month = timestruct.tm_mon + 1; | 160 exploded->month = timestruct.tm_mon + 1; |
264 exploded->day_of_week = timestruct.tm_wday; | 161 exploded->day_of_week = timestruct.tm_wday; |
265 exploded->day_of_month = timestruct.tm_mday; | 162 exploded->day_of_month = timestruct.tm_mday; |
266 exploded->hour = timestruct.tm_hour; | 163 exploded->hour = timestruct.tm_hour; |
267 exploded->minute = timestruct.tm_min; | 164 exploded->minute = timestruct.tm_min; |
268 exploded->second = timestruct.tm_sec; | 165 exploded->second = timestruct.tm_sec; |
269 exploded->millisecond = millisecond; | 166 exploded->millisecond = millisecond; |
270 } | 167 } |
271 | 168 |
272 // static | 169 // static |
273 bool Time::FromExploded(bool is_local, const Exploded& exploded, Time* time) { | 170 bool Time::FromExploded(bool is_local, const Exploded& exploded, Time* time) { |
274 CheckedNumeric<int> month = exploded.month; | 171 CheckedNumeric<int> month = exploded.month; |
275 month--; | 172 month--; |
276 CheckedNumeric<int> year = exploded.year; | 173 CheckedNumeric<int> year = exploded.year; |
277 year -= 1900; | 174 year -= 1900; |
278 if (!month.IsValid() || !year.IsValid()) { | 175 if (!month.IsValid() || !year.IsValid()) { |
279 *time = Time(0); | 176 *time = Time(0); |
(...skipping 46 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
326 seconds = seconds_isdst0; | 223 seconds = seconds_isdst0; |
327 else | 224 else |
328 seconds = std::min(seconds_isdst0, seconds_isdst1); | 225 seconds = std::min(seconds_isdst0, seconds_isdst1); |
329 } | 226 } |
330 | 227 |
331 // Handle overflow. Clamping the range to what mktime and timegm might | 228 // Handle overflow. Clamping the range to what mktime and timegm might |
332 // return is the best that can be done here. It's not ideal, but it's better | 229 // return is the best that can be done here. It's not ideal, but it's better |
333 // than failing here or ignoring the overflow case and treating each time | 230 // than failing here or ignoring the overflow case and treating each time |
334 // overflow as one second prior to the epoch. | 231 // overflow as one second prior to the epoch. |
335 int64_t milliseconds = 0; | 232 int64_t milliseconds = 0; |
336 if (seconds == -1 && | 233 if (seconds == -1 && (exploded.year < 1969 || exploded.year > 1970)) { |
337 (exploded.year < 1969 || exploded.year > 1970)) { | |
338 // If exploded.year is 1969 or 1970, take -1 as correct, with the | 234 // If exploded.year is 1969 or 1970, take -1 as correct, with the |
339 // time indicating 1 second prior to the epoch. (1970 is allowed to handle | 235 // time indicating 1 second prior to the epoch. (1970 is allowed to handle |
340 // time zone and DST offsets.) Otherwise, return the most future or past | 236 // time zone and DST offsets.) Otherwise, return the most future or past |
341 // time representable. Assumes the time_t epoch is 1970-01-01 00:00:00 UTC. | 237 // time representable. Assumes the time_t epoch is 1970-01-01 00:00:00 UTC. |
342 // | 238 // |
343 // The minimum and maximum representible times that mktime and timegm could | 239 // The minimum and maximum representible times that mktime and timegm could |
344 // return are used here instead of values outside that range to allow for | 240 // return are used here instead of values outside that range to allow for |
345 // proper round-tripping between exploded and counter-type time | 241 // proper round-tripping between exploded and counter-type time |
346 // representations in the presence of possible truncation to time_t by | 242 // representations in the presence of possible truncation to time_t by |
347 // division and use with other functions that accept time_t. | 243 // division and use with other functions that accept time_t. |
(...skipping 23 matching lines...) Expand all Loading... |
371 if (!checked_millis.IsValid()) { | 267 if (!checked_millis.IsValid()) { |
372 *time = base::Time(0); | 268 *time = base::Time(0); |
373 return false; | 269 return false; |
374 } | 270 } |
375 milliseconds = checked_millis.ValueOrDie(); | 271 milliseconds = checked_millis.ValueOrDie(); |
376 } | 272 } |
377 | 273 |
378 // Adjust from Unix (1970) to Windows (1601) epoch avoiding overflows. | 274 // Adjust from Unix (1970) to Windows (1601) epoch avoiding overflows. |
379 base::CheckedNumeric<int64_t> checked_microseconds_win_epoch = milliseconds; | 275 base::CheckedNumeric<int64_t> checked_microseconds_win_epoch = milliseconds; |
380 checked_microseconds_win_epoch *= kMicrosecondsPerMillisecond; | 276 checked_microseconds_win_epoch *= kMicrosecondsPerMillisecond; |
381 checked_microseconds_win_epoch += kWindowsEpochDeltaMicroseconds; | 277 checked_microseconds_win_epoch += kTimeTToMicrosecondsOffset; |
382 if (!checked_microseconds_win_epoch.IsValid()) { | 278 if (!checked_microseconds_win_epoch.IsValid()) { |
383 *time = base::Time(0); | 279 *time = base::Time(0); |
384 return false; | 280 return false; |
385 } | 281 } |
386 base::Time converted_time(checked_microseconds_win_epoch.ValueOrDie()); | 282 base::Time converted_time(checked_microseconds_win_epoch.ValueOrDie()); |
387 | 283 |
388 // If |exploded.day_of_month| is set to 31 on a 28-30 day month, it will | 284 // If |exploded.day_of_month| is set to 31 on a 28-30 day month, it will |
389 // return the first day of the next month. Thus round-trip the time and | 285 // return the first day of the next month. Thus round-trip the time and |
390 // compare the initial |exploded| with |utc_to_exploded| time. | 286 // compare the initial |exploded| with |utc_to_exploded| time. |
391 base::Time::Exploded to_exploded; | 287 base::Time::Exploded to_exploded; |
392 if (!is_local) | 288 if (!is_local) |
393 converted_time.UTCExplode(&to_exploded); | 289 converted_time.UTCExplode(&to_exploded); |
394 else | 290 else |
395 converted_time.LocalExplode(&to_exploded); | 291 converted_time.LocalExplode(&to_exploded); |
396 | 292 |
397 if (ExplodedMostlyEquals(to_exploded, exploded)) { | 293 if (ExplodedMostlyEquals(to_exploded, exploded)) { |
398 *time = converted_time; | 294 *time = converted_time; |
399 return true; | 295 return true; |
400 } | 296 } |
401 | 297 |
402 *time = Time(0); | 298 *time = Time(0); |
403 return false; | 299 return false; |
404 } | 300 } |
405 | 301 |
406 // TimeTicks ------------------------------------------------------------------ | |
407 // static | |
408 TimeTicks TimeTicks::Now() { | |
409 return TimeTicks(ClockNow(CLOCK_MONOTONIC)); | |
410 } | |
411 | |
412 // static | |
413 TimeTicks::Clock TimeTicks::GetClock() { | |
414 return Clock::LINUX_CLOCK_MONOTONIC; | |
415 } | |
416 | |
417 // static | |
418 bool TimeTicks::IsHighResolution() { | |
419 return true; | |
420 } | |
421 | |
422 // static | |
423 bool TimeTicks::IsConsistentAcrossProcesses() { | |
424 return true; | |
425 } | |
426 | |
427 // static | |
428 ThreadTicks ThreadTicks::Now() { | |
429 #if (defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)) || \ | |
430 defined(OS_ANDROID) | |
431 return ThreadTicks(ClockNow(CLOCK_THREAD_CPUTIME_ID)); | |
432 #else | |
433 NOTREACHED(); | |
434 return ThreadTicks(); | |
435 #endif | |
436 } | |
437 | |
438 #endif // !OS_MACOSX | |
439 | |
440 // static | |
441 Time Time::FromTimeVal(struct timeval t) { | |
442 DCHECK_LT(t.tv_usec, static_cast<int>(Time::kMicrosecondsPerSecond)); | |
443 DCHECK_GE(t.tv_usec, 0); | |
444 if (t.tv_usec == 0 && t.tv_sec == 0) | |
445 return Time(); | |
446 if (t.tv_usec == static_cast<suseconds_t>(Time::kMicrosecondsPerSecond) - 1 && | |
447 t.tv_sec == std::numeric_limits<time_t>::max()) | |
448 return Max(); | |
449 return Time((static_cast<int64_t>(t.tv_sec) * Time::kMicrosecondsPerSecond) + | |
450 t.tv_usec + kTimeTToMicrosecondsOffset); | |
451 } | |
452 | |
453 struct timeval Time::ToTimeVal() const { | |
454 struct timeval result; | |
455 if (is_null()) { | |
456 result.tv_sec = 0; | |
457 result.tv_usec = 0; | |
458 return result; | |
459 } | |
460 if (is_max()) { | |
461 result.tv_sec = std::numeric_limits<time_t>::max(); | |
462 result.tv_usec = static_cast<suseconds_t>(Time::kMicrosecondsPerSecond) - 1; | |
463 return result; | |
464 } | |
465 int64_t us = us_ - kTimeTToMicrosecondsOffset; | |
466 result.tv_sec = us / Time::kMicrosecondsPerSecond; | |
467 result.tv_usec = us % Time::kMicrosecondsPerSecond; | |
468 return result; | |
469 } | |
470 | |
471 } // namespace base | 302 } // namespace base |
OLD | NEW |