• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
GetSysTimeToTimeStructLock()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 
SysTimeFromTimeStruct(struct tm * timestruct,bool is_local)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 
SysTimeToTimeStruct(SysTime t,struct tm * timestruct,bool is_local)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 #else  // OS_ANDROID && !__LP64__
65 typedef time_t SysTime;
66 
SysTimeFromTimeStruct(struct tm * timestruct,bool is_local)67 SysTime SysTimeFromTimeStruct(struct tm* timestruct, bool is_local) {
68   base::AutoLock locked(*GetSysTimeToTimeStructLock());
69   if (is_local)
70     return mktime(timestruct);
71   else
72     return timegm(timestruct);
73 }
74 
SysTimeToTimeStruct(SysTime t,struct tm * timestruct,bool is_local)75 void SysTimeToTimeStruct(SysTime t, struct tm* timestruct, bool is_local) {
76   base::AutoLock locked(*GetSysTimeToTimeStructLock());
77   if (is_local)
78     localtime_r(&t, timestruct);
79   else
80     gmtime_r(&t, timestruct);
81 }
82 #endif  // OS_ANDROID
83 
ConvertTimespecToMicros(const struct timespec & ts)84 int64_t ConvertTimespecToMicros(const struct timespec& ts) {
85   // On 32-bit systems, the calculation cannot overflow int64_t.
86   // 2**32 * 1000000 + 2**64 / 1000 < 2**63
87   if (sizeof(ts.tv_sec) <= 4 && sizeof(ts.tv_nsec) <= 8) {
88     int64_t result = ts.tv_sec;
89     result *= base::Time::kMicrosecondsPerSecond;
90     result += (ts.tv_nsec / base::Time::kNanosecondsPerMicrosecond);
91     return result;
92   } else {
93     base::CheckedNumeric<int64_t> result(ts.tv_sec);
94     result *= base::Time::kMicrosecondsPerSecond;
95     result += (ts.tv_nsec / base::Time::kNanosecondsPerMicrosecond);
96     return result.ValueOrDie();
97   }
98 }
99 
100 // Helper function to get results from clock_gettime() and convert to a
101 // microsecond timebase. Minimum requirement is MONOTONIC_CLOCK to be supported
102 // on the system. FreeBSD 6 has CLOCK_MONOTONIC but defines
103 // _POSIX_MONOTONIC_CLOCK to -1.
104 #if (defined(OS_POSIX) &&                                               \
105      defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0) || \
106     defined(OS_BSD) || defined(OS_ANDROID)
ClockNow(clockid_t clk_id)107 int64_t ClockNow(clockid_t clk_id) {
108   struct timespec ts;
109   if (clock_gettime(clk_id, &ts) != 0) {
110     NOTREACHED() << "clock_gettime(" << clk_id << ") failed.";
111     return 0;
112   }
113   return ConvertTimespecToMicros(ts);
114 }
115 #else  // _POSIX_MONOTONIC_CLOCK
116 #error No usable tick clock function on this platform.
117 #endif  // _POSIX_MONOTONIC_CLOCK
118 #endif  // !defined(OS_MACOSX)
119 
120 }  // namespace
121 
122 namespace base {
123 
124 // static
FromTimeSpec(const timespec & ts)125 TimeDelta TimeDelta::FromTimeSpec(const timespec& ts) {
126   return TimeDelta(ts.tv_sec * Time::kMicrosecondsPerSecond +
127                    ts.tv_nsec / Time::kNanosecondsPerMicrosecond);
128 }
129 
ToTimeSpec() const130 struct timespec TimeDelta::ToTimeSpec() const {
131   int64_t microseconds = InMicroseconds();
132   time_t seconds = 0;
133   if (microseconds >= Time::kMicrosecondsPerSecond) {
134     seconds = InSeconds();
135     microseconds -= seconds * Time::kMicrosecondsPerSecond;
136   }
137   struct timespec result =
138       {seconds,
139        static_cast<long>(microseconds * Time::kNanosecondsPerMicrosecond)};
140   return result;
141 }
142 
143 #if !defined(OS_MACOSX)
144 // The Time routines in this file use standard POSIX routines, or almost-
145 // standard routines in the case of timegm.  We need to use a Mach-specific
146 // function for TimeTicks::Now() on Mac OS X.
147 
148 // Time -----------------------------------------------------------------------
149 
150 // Windows uses a Gregorian epoch of 1601.  We need to match this internally
151 // so that our time representations match across all platforms.  See bug 14734.
152 //   irb(main):010:0> Time.at(0).getutc()
153 //   => Thu Jan 01 00:00:00 UTC 1970
154 //   irb(main):011:0> Time.at(-11644473600).getutc()
155 //   => Mon Jan 01 00:00:00 UTC 1601
156 static const int64_t kWindowsEpochDeltaSeconds = INT64_C(11644473600);
157 
158 // static
159 const int64_t Time::kWindowsEpochDeltaMicroseconds =
160     kWindowsEpochDeltaSeconds * Time::kMicrosecondsPerSecond;
161 
162 // Some functions in time.cc use time_t directly, so we provide an offset
163 // to convert from time_t (Unix epoch) and internal (Windows epoch).
164 // static
165 const int64_t Time::kTimeTToMicrosecondsOffset = kWindowsEpochDeltaMicroseconds;
166 
167 // static
Now()168 Time Time::Now() {
169   struct timeval tv;
170   struct timezone tz = { 0, 0 };  // UTC
171   if (gettimeofday(&tv, &tz) != 0) {
172     DCHECK(0) << "Could not determine time of day";
173     PLOG(ERROR) << "Call to gettimeofday failed.";
174     // Return null instead of uninitialized |tv| value, which contains random
175     // garbage data. This may result in the crash seen in crbug.com/147570.
176     return Time();
177   }
178   // Combine seconds and microseconds in a 64-bit field containing microseconds
179   // since the epoch.  That's enough for nearly 600 centuries.  Adjust from
180   // Unix (1970) to Windows (1601) epoch.
181   return Time((tv.tv_sec * kMicrosecondsPerSecond + tv.tv_usec) +
182       kWindowsEpochDeltaMicroseconds);
183 }
184 
185 // static
NowFromSystemTime()186 Time Time::NowFromSystemTime() {
187   // Just use Now() because Now() returns the system time.
188   return Now();
189 }
190 
Explode(bool is_local,Exploded * exploded) const191 void Time::Explode(bool is_local, Exploded* exploded) const {
192   // Time stores times with microsecond resolution, but Exploded only carries
193   // millisecond resolution, so begin by being lossy.  Adjust from Windows
194   // epoch (1601) to Unix epoch (1970);
195   int64_t microseconds = us_ - kWindowsEpochDeltaMicroseconds;
196   // The following values are all rounded towards -infinity.
197   int64_t milliseconds;  // Milliseconds since epoch.
198   SysTime seconds;  // Seconds since epoch.
199   int millisecond;  // Exploded millisecond value (0-999).
200   if (microseconds >= 0) {
201     // Rounding towards -infinity <=> rounding towards 0, in this case.
202     milliseconds = microseconds / kMicrosecondsPerMillisecond;
203     seconds = milliseconds / kMillisecondsPerSecond;
204     millisecond = milliseconds % kMillisecondsPerSecond;
205   } else {
206     // Round these *down* (towards -infinity).
207     milliseconds = (microseconds - kMicrosecondsPerMillisecond + 1) /
208                    kMicrosecondsPerMillisecond;
209     seconds = (milliseconds - kMillisecondsPerSecond + 1) /
210               kMillisecondsPerSecond;
211     // Make this nonnegative (and between 0 and 999 inclusive).
212     millisecond = milliseconds % kMillisecondsPerSecond;
213     if (millisecond < 0)
214       millisecond += kMillisecondsPerSecond;
215   }
216 
217   struct tm timestruct;
218   SysTimeToTimeStruct(seconds, &timestruct, is_local);
219 
220   exploded->year         = timestruct.tm_year + 1900;
221   exploded->month        = timestruct.tm_mon + 1;
222   exploded->day_of_week  = timestruct.tm_wday;
223   exploded->day_of_month = timestruct.tm_mday;
224   exploded->hour         = timestruct.tm_hour;
225   exploded->minute       = timestruct.tm_min;
226   exploded->second       = timestruct.tm_sec;
227   exploded->millisecond  = millisecond;
228 }
229 
230 // static
FromExploded(bool is_local,const Exploded & exploded,Time * time)231 bool Time::FromExploded(bool is_local, const Exploded& exploded, Time* time) {
232   CheckedNumeric<int> month = exploded.month;
233   month--;
234   CheckedNumeric<int> year = exploded.year;
235   year -= 1900;
236   if (!month.IsValid() || !year.IsValid()) {
237     *time = Time(0);
238     return false;
239   }
240 
241   struct tm timestruct;
242   timestruct.tm_sec = exploded.second;
243   timestruct.tm_min = exploded.minute;
244   timestruct.tm_hour = exploded.hour;
245   timestruct.tm_mday = exploded.day_of_month;
246   timestruct.tm_mon = month.ValueOrDie();
247   timestruct.tm_year = year.ValueOrDie();
248   timestruct.tm_wday = exploded.day_of_week;  // mktime/timegm ignore this
249   timestruct.tm_yday = 0;                     // mktime/timegm ignore this
250   timestruct.tm_isdst = -1;                   // attempt to figure it out
251 #if !defined(OS_NACL) && !defined(OS_SOLARIS)
252   timestruct.tm_gmtoff = 0;   // not a POSIX field, so mktime/timegm ignore
253   timestruct.tm_zone = NULL;  // not a POSIX field, so mktime/timegm ignore
254 #endif
255 
256   SysTime seconds;
257 
258   // Certain exploded dates do not really exist due to daylight saving times,
259   // and this causes mktime() to return implementation-defined values when
260   // tm_isdst is set to -1. On Android, the function will return -1, while the
261   // C libraries of other platforms typically return a liberally-chosen value.
262   // Handling this requires the special code below.
263 
264   // SysTimeFromTimeStruct() modifies the input structure, save current value.
265   struct tm timestruct0 = timestruct;
266 
267   seconds = SysTimeFromTimeStruct(&timestruct, is_local);
268   if (seconds == -1) {
269     // Get the time values with tm_isdst == 0 and 1, then select the closest one
270     // to UTC 00:00:00 that isn't -1.
271     timestruct = timestruct0;
272     timestruct.tm_isdst = 0;
273     int64_t seconds_isdst0 = SysTimeFromTimeStruct(&timestruct, is_local);
274 
275     timestruct = timestruct0;
276     timestruct.tm_isdst = 1;
277     int64_t seconds_isdst1 = SysTimeFromTimeStruct(&timestruct, is_local);
278 
279     // seconds_isdst0 or seconds_isdst1 can be -1 for some timezones.
280     // E.g. "CLST" (Chile Summer Time) returns -1 for 'tm_isdt == 1'.
281     if (seconds_isdst0 < 0)
282       seconds = seconds_isdst1;
283     else if (seconds_isdst1 < 0)
284       seconds = seconds_isdst0;
285     else
286       seconds = std::min(seconds_isdst0, seconds_isdst1);
287   }
288 
289   // Handle overflow.  Clamping the range to what mktime and timegm might
290   // return is the best that can be done here.  It's not ideal, but it's better
291   // than failing here or ignoring the overflow case and treating each time
292   // overflow as one second prior to the epoch.
293   int64_t milliseconds = 0;
294   if (seconds == -1 &&
295       (exploded.year < 1969 || exploded.year > 1970)) {
296     // If exploded.year is 1969 or 1970, take -1 as correct, with the
297     // time indicating 1 second prior to the epoch.  (1970 is allowed to handle
298     // time zone and DST offsets.)  Otherwise, return the most future or past
299     // time representable.  Assumes the time_t epoch is 1970-01-01 00:00:00 UTC.
300     //
301     // The minimum and maximum representible times that mktime and timegm could
302     // return are used here instead of values outside that range to allow for
303     // proper round-tripping between exploded and counter-type time
304     // representations in the presence of possible truncation to time_t by
305     // division and use with other functions that accept time_t.
306     //
307     // When representing the most distant time in the future, add in an extra
308     // 999ms to avoid the time being less than any other possible value that
309     // this function can return.
310 
311     // On Android, SysTime is int64_t, special care must be taken to avoid
312     // overflows.
313     const int64_t min_seconds = (sizeof(SysTime) < sizeof(int64_t))
314                                     ? std::numeric_limits<SysTime>::min()
315                                     : std::numeric_limits<int32_t>::min();
316     const int64_t max_seconds = (sizeof(SysTime) < sizeof(int64_t))
317                                     ? std::numeric_limits<SysTime>::max()
318                                     : std::numeric_limits<int32_t>::max();
319     if (exploded.year < 1969) {
320       milliseconds = min_seconds * kMillisecondsPerSecond;
321     } else {
322       milliseconds = max_seconds * kMillisecondsPerSecond;
323       milliseconds += (kMillisecondsPerSecond - 1);
324     }
325   } else {
326     base::CheckedNumeric<int64_t> checked_millis = seconds;
327     checked_millis *= kMillisecondsPerSecond;
328     checked_millis += exploded.millisecond;
329     if (!checked_millis.IsValid()) {
330       *time = base::Time(0);
331       return false;
332     }
333     milliseconds = checked_millis.ValueOrDie();
334   }
335 
336   // Adjust from Unix (1970) to Windows (1601) epoch avoiding overflows.
337   base::CheckedNumeric<int64_t> checked_microseconds_win_epoch = milliseconds;
338   checked_microseconds_win_epoch *= kMicrosecondsPerMillisecond;
339   checked_microseconds_win_epoch += kWindowsEpochDeltaMicroseconds;
340   if (!checked_microseconds_win_epoch.IsValid()) {
341     *time = base::Time(0);
342     return false;
343   }
344   base::Time converted_time(checked_microseconds_win_epoch.ValueOrDie());
345 
346   // If |exploded.day_of_month| is set to 31 on a 28-30 day month, it will
347   // return the first day of the next month. Thus round-trip the time and
348   // compare the initial |exploded| with |utc_to_exploded| time.
349   base::Time::Exploded to_exploded;
350   if (!is_local)
351     converted_time.UTCExplode(&to_exploded);
352   else
353     converted_time.LocalExplode(&to_exploded);
354 
355   if (ExplodedMostlyEquals(to_exploded, exploded)) {
356     *time = converted_time;
357     return true;
358   }
359 
360   *time = Time(0);
361   return false;
362 }
363 
364 // TimeTicks ------------------------------------------------------------------
365 // static
Now()366 TimeTicks TimeTicks::Now() {
367   return TimeTicks(ClockNow(CLOCK_MONOTONIC));
368 }
369 
370 // static
GetClock()371 TimeTicks::Clock TimeTicks::GetClock() {
372   return Clock::LINUX_CLOCK_MONOTONIC;
373 }
374 
375 // static
IsHighResolution()376 bool TimeTicks::IsHighResolution() {
377   return true;
378 }
379 
380 // static
IsConsistentAcrossProcesses()381 bool TimeTicks::IsConsistentAcrossProcesses() {
382   return true;
383 }
384 
385 // static
Now()386 ThreadTicks ThreadTicks::Now() {
387 #if (defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)) || \
388     defined(OS_ANDROID)
389   return ThreadTicks(ClockNow(CLOCK_THREAD_CPUTIME_ID));
390 #else
391   NOTREACHED();
392   return ThreadTicks();
393 #endif
394 }
395 
396 #endif  // !OS_MACOSX
397 
398 // static
FromTimeVal(struct timeval t)399 Time Time::FromTimeVal(struct timeval t) {
400   DCHECK_LT(t.tv_usec, static_cast<int>(Time::kMicrosecondsPerSecond));
401   DCHECK_GE(t.tv_usec, 0);
402   if (t.tv_usec == 0 && t.tv_sec == 0)
403     return Time();
404   if (t.tv_usec == static_cast<suseconds_t>(Time::kMicrosecondsPerSecond) - 1 &&
405       t.tv_sec == std::numeric_limits<time_t>::max())
406     return Max();
407   return Time((static_cast<int64_t>(t.tv_sec) * Time::kMicrosecondsPerSecond) +
408               t.tv_usec + kTimeTToMicrosecondsOffset);
409 }
410 
ToTimeVal() const411 struct timeval Time::ToTimeVal() const {
412   struct timeval result;
413   if (is_null()) {
414     result.tv_sec = 0;
415     result.tv_usec = 0;
416     return result;
417   }
418   if (is_max()) {
419     result.tv_sec = std::numeric_limits<time_t>::max();
420     result.tv_usec = static_cast<suseconds_t>(Time::kMicrosecondsPerSecond) - 1;
421     return result;
422   }
423   int64_t us = us_ - kTimeTToMicrosecondsOffset;
424   result.tv_sec = us / Time::kMicrosecondsPerSecond;
425   result.tv_usec = us % Time::kMicrosecondsPerSecond;
426   return result;
427 }
428 
429 }  // namespace base
430