OLD | NEW |
| (Empty) |
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 <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/logging.h" | |
19 #include "base/numerics/safe_math.h" | |
20 #include "build/build_config.h" | |
21 | |
22 #if defined(OS_ANDROID) | |
23 #include "base/os_compat_android.h" | |
24 #elif defined(OS_NACL) | |
25 #include "base/os_compat_nacl.h" | |
26 #endif | |
27 | |
28 #if !defined(OS_MACOSX) | |
29 #include "base/synchronization/lock.h" | |
30 #endif | |
31 | |
32 namespace { | |
33 | |
34 #if !defined(OS_MACOSX) | |
35 // This prevents a crash on traversing the environment global and looking up | |
36 // the 'TZ' variable in libc. See: crbug.com/390567. | |
37 base::Lock* GetSysTimeToTimeStructLock() { | |
38 static auto* lock = new base::Lock(); | |
39 return lock; | |
40 } | |
41 | |
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. | |
44 // See crbug.com/162007 | |
45 #if defined(OS_ANDROID) && !defined(__LP64__) | |
46 typedef time64_t SysTime; | |
47 | |
48 SysTime SysTimeFromTimeStruct(struct tm* timestruct, bool is_local) { | |
49 base::AutoLock locked(*GetSysTimeToTimeStructLock()); | |
50 if (is_local) | |
51 return mktime64(timestruct); | |
52 else | |
53 return timegm64(timestruct); | |
54 } | |
55 | |
56 void SysTimeToTimeStruct(SysTime t, struct tm* timestruct, bool is_local) { | |
57 base::AutoLock locked(*GetSysTimeToTimeStructLock()); | |
58 if (is_local) | |
59 localtime64_r(&t, timestruct); | |
60 else | |
61 gmtime64_r(&t, timestruct); | |
62 } | |
63 | |
64 #elif defined(OS_AIX) | |
65 | |
66 // The function timegm is not available on AIX. | |
67 time_t aix_timegm(struct tm* tm) { | |
68 time_t ret; | |
69 char* tz; | |
70 | |
71 tz = getenv("TZ"); | |
72 if (tz) { | |
73 tz = strdup(tz); | |
74 } | |
75 setenv("TZ", "GMT0", 1); | |
76 tzset(); | |
77 ret = mktime(tm); | |
78 if (tz) { | |
79 setenv("TZ", tz, 1); | |
80 free(tz); | |
81 } else { | |
82 unsetenv("TZ"); | |
83 } | |
84 tzset(); | |
85 return ret; | |
86 } | |
87 | |
88 typedef time_t SysTime; | |
89 | |
90 SysTime SysTimeFromTimeStruct(struct tm* timestruct, bool is_local) { | |
91 base::AutoLock locked(*GetSysTimeToTimeStructLock()); | |
92 if (is_local) | |
93 return mktime(timestruct); | |
94 else | |
95 return aix_timegm(timestruct); | |
96 } | |
97 | |
98 void SysTimeToTimeStruct(SysTime t, struct tm* timestruct, bool is_local) { | |
99 base::AutoLock locked(*GetSysTimeToTimeStructLock()); | |
100 if (is_local) | |
101 localtime_r(&t, timestruct); | |
102 else | |
103 gmtime_r(&t, timestruct); | |
104 } | |
105 | |
106 #else // OS_ANDROID && !__LP64__ | |
107 typedef time_t SysTime; | |
108 | |
109 SysTime SysTimeFromTimeStruct(struct tm* timestruct, bool is_local) { | |
110 base::AutoLock locked(*GetSysTimeToTimeStructLock()); | |
111 if (is_local) | |
112 return mktime(timestruct); | |
113 else | |
114 return timegm(timestruct); | |
115 } | |
116 | |
117 void SysTimeToTimeStruct(SysTime t, struct tm* timestruct, bool is_local) { | |
118 base::AutoLock locked(*GetSysTimeToTimeStructLock()); | |
119 if (is_local) | |
120 localtime_r(&t, timestruct); | |
121 else | |
122 gmtime_r(&t, timestruct); | |
123 } | |
124 #endif // OS_ANDROID | |
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 | |
163 | |
164 namespace base { | |
165 | |
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 { | |
234 // Time stores times with microsecond resolution, but Exploded only carries | |
235 // millisecond resolution, so begin by being lossy. Adjust from Windows | |
236 // epoch (1601) to Unix epoch (1970); | |
237 int64_t microseconds = us_ - kWindowsEpochDeltaMicroseconds; | |
238 // The following values are all rounded towards -infinity. | |
239 int64_t milliseconds; // Milliseconds since epoch. | |
240 SysTime seconds; // Seconds since epoch. | |
241 int millisecond; // Exploded millisecond value (0-999). | |
242 if (microseconds >= 0) { | |
243 // Rounding towards -infinity <=> rounding towards 0, in this case. | |
244 milliseconds = microseconds / kMicrosecondsPerMillisecond; | |
245 seconds = milliseconds / kMillisecondsPerSecond; | |
246 millisecond = milliseconds % kMillisecondsPerSecond; | |
247 } else { | |
248 // Round these *down* (towards -infinity). | |
249 milliseconds = (microseconds - kMicrosecondsPerMillisecond + 1) / | |
250 kMicrosecondsPerMillisecond; | |
251 seconds = (milliseconds - kMillisecondsPerSecond + 1) / | |
252 kMillisecondsPerSecond; | |
253 // Make this nonnegative (and between 0 and 999 inclusive). | |
254 millisecond = milliseconds % kMillisecondsPerSecond; | |
255 if (millisecond < 0) | |
256 millisecond += kMillisecondsPerSecond; | |
257 } | |
258 | |
259 struct tm timestruct; | |
260 SysTimeToTimeStruct(seconds, ×truct, is_local); | |
261 | |
262 exploded->year = timestruct.tm_year + 1900; | |
263 exploded->month = timestruct.tm_mon + 1; | |
264 exploded->day_of_week = timestruct.tm_wday; | |
265 exploded->day_of_month = timestruct.tm_mday; | |
266 exploded->hour = timestruct.tm_hour; | |
267 exploded->minute = timestruct.tm_min; | |
268 exploded->second = timestruct.tm_sec; | |
269 exploded->millisecond = millisecond; | |
270 } | |
271 | |
272 // static | |
273 bool Time::FromExploded(bool is_local, const Exploded& exploded, Time* time) { | |
274 CheckedNumeric<int> month = exploded.month; | |
275 month--; | |
276 CheckedNumeric<int> year = exploded.year; | |
277 year -= 1900; | |
278 if (!month.IsValid() || !year.IsValid()) { | |
279 *time = Time(0); | |
280 return false; | |
281 } | |
282 | |
283 struct tm timestruct; | |
284 timestruct.tm_sec = exploded.second; | |
285 timestruct.tm_min = exploded.minute; | |
286 timestruct.tm_hour = exploded.hour; | |
287 timestruct.tm_mday = exploded.day_of_month; | |
288 timestruct.tm_mon = month.ValueOrDie(); | |
289 timestruct.tm_year = year.ValueOrDie(); | |
290 timestruct.tm_wday = exploded.day_of_week; // mktime/timegm ignore this | |
291 timestruct.tm_yday = 0; // mktime/timegm ignore this | |
292 timestruct.tm_isdst = -1; // attempt to figure it out | |
293 #if !defined(OS_NACL) && !defined(OS_SOLARIS) && !defined(OS_AIX) | |
294 timestruct.tm_gmtoff = 0; // not a POSIX field, so mktime/timegm ignore | |
295 timestruct.tm_zone = NULL; // not a POSIX field, so mktime/timegm ignore | |
296 #endif | |
297 | |
298 SysTime seconds; | |
299 | |
300 // Certain exploded dates do not really exist due to daylight saving times, | |
301 // and this causes mktime() to return implementation-defined values when | |
302 // tm_isdst is set to -1. On Android, the function will return -1, while the | |
303 // C libraries of other platforms typically return a liberally-chosen value. | |
304 // Handling this requires the special code below. | |
305 | |
306 // SysTimeFromTimeStruct() modifies the input structure, save current value. | |
307 struct tm timestruct0 = timestruct; | |
308 | |
309 seconds = SysTimeFromTimeStruct(×truct, is_local); | |
310 if (seconds == -1) { | |
311 // Get the time values with tm_isdst == 0 and 1, then select the closest one | |
312 // to UTC 00:00:00 that isn't -1. | |
313 timestruct = timestruct0; | |
314 timestruct.tm_isdst = 0; | |
315 int64_t seconds_isdst0 = SysTimeFromTimeStruct(×truct, is_local); | |
316 | |
317 timestruct = timestruct0; | |
318 timestruct.tm_isdst = 1; | |
319 int64_t seconds_isdst1 = SysTimeFromTimeStruct(×truct, is_local); | |
320 | |
321 // seconds_isdst0 or seconds_isdst1 can be -1 for some timezones. | |
322 // E.g. "CLST" (Chile Summer Time) returns -1 for 'tm_isdt == 1'. | |
323 if (seconds_isdst0 < 0) | |
324 seconds = seconds_isdst1; | |
325 else if (seconds_isdst1 < 0) | |
326 seconds = seconds_isdst0; | |
327 else | |
328 seconds = std::min(seconds_isdst0, seconds_isdst1); | |
329 } | |
330 | |
331 // 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 | |
333 // than failing here or ignoring the overflow case and treating each time | |
334 // overflow as one second prior to the epoch. | |
335 int64_t milliseconds = 0; | |
336 if (seconds == -1 && | |
337 (exploded.year < 1969 || exploded.year > 1970)) { | |
338 // 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 | |
340 // 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. | |
342 // | |
343 // 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 | |
345 // proper round-tripping between exploded and counter-type time | |
346 // representations in the presence of possible truncation to time_t by | |
347 // division and use with other functions that accept time_t. | |
348 // | |
349 // When representing the most distant time in the future, add in an extra | |
350 // 999ms to avoid the time being less than any other possible value that | |
351 // this function can return. | |
352 | |
353 // On Android, SysTime is int64_t, special care must be taken to avoid | |
354 // overflows. | |
355 const int64_t min_seconds = (sizeof(SysTime) < sizeof(int64_t)) | |
356 ? std::numeric_limits<SysTime>::min() | |
357 : std::numeric_limits<int32_t>::min(); | |
358 const int64_t max_seconds = (sizeof(SysTime) < sizeof(int64_t)) | |
359 ? std::numeric_limits<SysTime>::max() | |
360 : std::numeric_limits<int32_t>::max(); | |
361 if (exploded.year < 1969) { | |
362 milliseconds = min_seconds * kMillisecondsPerSecond; | |
363 } else { | |
364 milliseconds = max_seconds * kMillisecondsPerSecond; | |
365 milliseconds += (kMillisecondsPerSecond - 1); | |
366 } | |
367 } else { | |
368 base::CheckedNumeric<int64_t> checked_millis = seconds; | |
369 checked_millis *= kMillisecondsPerSecond; | |
370 checked_millis += exploded.millisecond; | |
371 if (!checked_millis.IsValid()) { | |
372 *time = base::Time(0); | |
373 return false; | |
374 } | |
375 milliseconds = checked_millis.ValueOrDie(); | |
376 } | |
377 | |
378 // Adjust from Unix (1970) to Windows (1601) epoch avoiding overflows. | |
379 base::CheckedNumeric<int64_t> checked_microseconds_win_epoch = milliseconds; | |
380 checked_microseconds_win_epoch *= kMicrosecondsPerMillisecond; | |
381 checked_microseconds_win_epoch += kWindowsEpochDeltaMicroseconds; | |
382 if (!checked_microseconds_win_epoch.IsValid()) { | |
383 *time = base::Time(0); | |
384 return false; | |
385 } | |
386 base::Time converted_time(checked_microseconds_win_epoch.ValueOrDie()); | |
387 | |
388 // 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 | |
390 // compare the initial |exploded| with |utc_to_exploded| time. | |
391 base::Time::Exploded to_exploded; | |
392 if (!is_local) | |
393 converted_time.UTCExplode(&to_exploded); | |
394 else | |
395 converted_time.LocalExplode(&to_exploded); | |
396 | |
397 if (ExplodedMostlyEquals(to_exploded, exploded)) { | |
398 *time = converted_time; | |
399 return true; | |
400 } | |
401 | |
402 *time = Time(0); | |
403 return false; | |
404 } | |
405 | |
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 | |
OLD | NEW |