Make certificate viewer a tab-modal dialog.
[chromium-blink-merge.git] / base / time_posix.cc
blob288c646309f9682335e1ef9496b1d632fbf88948
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.h"
7 #include <sys/time.h>
8 #include <time.h>
9 #if defined(OS_ANDROID)
10 #include <time64.h>
11 #endif
12 #include <unistd.h>
14 #include <limits>
16 #include "base/basictypes.h"
17 #include "base/logging.h"
19 #if defined(OS_ANDROID)
20 #include "base/os_compat_android.h"
21 #elif defined(OS_NACL)
22 #include "base/os_compat_nacl.h"
23 #endif
25 namespace {
27 // Define a system-specific SysTime that wraps either to a time_t or
28 // a time64_t depending on the host system, and associated convertion.
29 // See crbug.com/162007
30 #if defined(OS_ANDROID)
31 typedef time64_t SysTime;
33 SysTime SysTimeFromTimeStruct(struct tm* timestruct, bool is_local) {
34 if (is_local)
35 return mktime64(timestruct);
36 else
37 return timegm64(timestruct);
40 void SysTimeToTimeStruct(SysTime t, struct tm* timestruct, bool is_local) {
41 if (is_local)
42 localtime64_r(&t, timestruct);
43 else
44 gmtime64_r(&t, timestruct);
47 #else // OS_ANDROID
48 typedef time_t SysTime;
50 SysTime SysTimeFromTimeStruct(struct tm* timestruct, bool is_local) {
51 if (is_local)
52 return mktime(timestruct);
53 else
54 return timegm(timestruct);
57 void SysTimeToTimeStruct(SysTime t, struct tm* timestruct, bool is_local) {
58 if (is_local)
59 localtime_r(&t, timestruct);
60 else
61 gmtime_r(&t, timestruct);
63 #endif // OS_ANDROID
65 } // namespace
67 namespace base {
69 struct timespec TimeDelta::ToTimeSpec() const {
70 int64 microseconds = InMicroseconds();
71 time_t seconds = 0;
72 if (microseconds >= Time::kMicrosecondsPerSecond) {
73 seconds = InSeconds();
74 microseconds -= seconds * Time::kMicrosecondsPerSecond;
76 struct timespec result =
77 {seconds,
78 static_cast<long>(microseconds * Time::kNanosecondsPerMicrosecond)};
79 return result;
82 #if !defined(OS_MACOSX)
83 // The Time routines in this file use standard POSIX routines, or almost-
84 // standard routines in the case of timegm. We need to use a Mach-specific
85 // function for TimeTicks::Now() on Mac OS X.
87 // Time -----------------------------------------------------------------------
89 // Windows uses a Gregorian epoch of 1601. We need to match this internally
90 // so that our time representations match across all platforms. See bug 14734.
91 // irb(main):010:0> Time.at(0).getutc()
92 // => Thu Jan 01 00:00:00 UTC 1970
93 // irb(main):011:0> Time.at(-11644473600).getutc()
94 // => Mon Jan 01 00:00:00 UTC 1601
95 static const int64 kWindowsEpochDeltaSeconds = GG_INT64_C(11644473600);
96 static const int64 kWindowsEpochDeltaMilliseconds =
97 kWindowsEpochDeltaSeconds * Time::kMillisecondsPerSecond;
99 // static
100 const int64 Time::kWindowsEpochDeltaMicroseconds =
101 kWindowsEpochDeltaSeconds * Time::kMicrosecondsPerSecond;
103 // Some functions in time.cc use time_t directly, so we provide an offset
104 // to convert from time_t (Unix epoch) and internal (Windows epoch).
105 // static
106 const int64 Time::kTimeTToMicrosecondsOffset = kWindowsEpochDeltaMicroseconds;
108 // static
109 Time Time::Now() {
110 struct timeval tv;
111 struct timezone tz = { 0, 0 }; // UTC
112 if (gettimeofday(&tv, &tz) != 0) {
113 DCHECK(0) << "Could not determine time of day";
114 LOG_ERRNO(ERROR) << "Call to gettimeofday failed.";
115 // Return null instead of uninitialized |tv| value, which contains random
116 // garbage data. This may result in the crash seen in crbug.com/147570.
117 return Time();
119 // Combine seconds and microseconds in a 64-bit field containing microseconds
120 // since the epoch. That's enough for nearly 600 centuries. Adjust from
121 // Unix (1970) to Windows (1601) epoch.
122 return Time((tv.tv_sec * kMicrosecondsPerSecond + tv.tv_usec) +
123 kWindowsEpochDeltaMicroseconds);
126 // static
127 Time Time::NowFromSystemTime() {
128 // Just use Now() because Now() returns the system time.
129 return Now();
132 void Time::Explode(bool is_local, Exploded* exploded) const {
133 // Time stores times with microsecond resolution, but Exploded only carries
134 // millisecond resolution, so begin by being lossy. Adjust from Windows
135 // epoch (1601) to Unix epoch (1970);
136 int64 microseconds = us_ - kWindowsEpochDeltaMicroseconds;
137 // The following values are all rounded towards -infinity.
138 int64 milliseconds; // Milliseconds since epoch.
139 SysTime seconds; // Seconds since epoch.
140 int millisecond; // Exploded millisecond value (0-999).
141 if (microseconds >= 0) {
142 // Rounding towards -infinity <=> rounding towards 0, in this case.
143 milliseconds = microseconds / kMicrosecondsPerMillisecond;
144 seconds = milliseconds / kMillisecondsPerSecond;
145 millisecond = milliseconds % kMillisecondsPerSecond;
146 } else {
147 // Round these *down* (towards -infinity).
148 milliseconds = (microseconds - kMicrosecondsPerMillisecond + 1) /
149 kMicrosecondsPerMillisecond;
150 seconds = (milliseconds - kMillisecondsPerSecond + 1) /
151 kMillisecondsPerSecond;
152 // Make this nonnegative (and between 0 and 999 inclusive).
153 millisecond = milliseconds % kMillisecondsPerSecond;
154 if (millisecond < 0)
155 millisecond += kMillisecondsPerSecond;
158 struct tm timestruct;
159 SysTimeToTimeStruct(seconds, &timestruct, is_local);
161 exploded->year = timestruct.tm_year + 1900;
162 exploded->month = timestruct.tm_mon + 1;
163 exploded->day_of_week = timestruct.tm_wday;
164 exploded->day_of_month = timestruct.tm_mday;
165 exploded->hour = timestruct.tm_hour;
166 exploded->minute = timestruct.tm_min;
167 exploded->second = timestruct.tm_sec;
168 exploded->millisecond = millisecond;
171 // static
172 Time Time::FromExploded(bool is_local, const Exploded& exploded) {
173 struct tm timestruct;
174 timestruct.tm_sec = exploded.second;
175 timestruct.tm_min = exploded.minute;
176 timestruct.tm_hour = exploded.hour;
177 timestruct.tm_mday = exploded.day_of_month;
178 timestruct.tm_mon = exploded.month - 1;
179 timestruct.tm_year = exploded.year - 1900;
180 timestruct.tm_wday = exploded.day_of_week; // mktime/timegm ignore this
181 timestruct.tm_yday = 0; // mktime/timegm ignore this
182 timestruct.tm_isdst = -1; // attempt to figure it out
183 #if !defined(OS_NACL) && !defined(OS_SOLARIS)
184 timestruct.tm_gmtoff = 0; // not a POSIX field, so mktime/timegm ignore
185 timestruct.tm_zone = NULL; // not a POSIX field, so mktime/timegm ignore
186 #endif
188 SysTime seconds = SysTimeFromTimeStruct(&timestruct, is_local);
190 int64 milliseconds;
191 // Handle overflow. Clamping the range to what mktime and timegm might
192 // return is the best that can be done here. It's not ideal, but it's better
193 // than failing here or ignoring the overflow case and treating each time
194 // overflow as one second prior to the epoch.
195 if (seconds == -1 &&
196 (exploded.year < 1969 || exploded.year > 1970)) {
197 // If exploded.year is 1969 or 1970, take -1 as correct, with the
198 // time indicating 1 second prior to the epoch. (1970 is allowed to handle
199 // time zone and DST offsets.) Otherwise, return the most future or past
200 // time representable. Assumes the time_t epoch is 1970-01-01 00:00:00 UTC.
202 // The minimum and maximum representible times that mktime and timegm could
203 // return are used here instead of values outside that range to allow for
204 // proper round-tripping between exploded and counter-type time
205 // representations in the presence of possible truncation to time_t by
206 // division and use with other functions that accept time_t.
208 // When representing the most distant time in the future, add in an extra
209 // 999ms to avoid the time being less than any other possible value that
210 // this function can return.
211 if (exploded.year < 1969) {
212 milliseconds = std::numeric_limits<SysTime>::min() *
213 kMillisecondsPerSecond;
214 } else {
215 milliseconds = (std::numeric_limits<SysTime>::max() *
216 kMillisecondsPerSecond) +
217 kMillisecondsPerSecond - 1;
219 } else {
220 milliseconds = seconds * kMillisecondsPerSecond + exploded.millisecond;
223 // Adjust from Unix (1970) to Windows (1601) epoch.
224 return Time((milliseconds * kMicrosecondsPerMillisecond) +
225 kWindowsEpochDeltaMicroseconds);
228 // TimeTicks ------------------------------------------------------------------
229 // FreeBSD 6 has CLOCK_MONOLITHIC but defines _POSIX_MONOTONIC_CLOCK to -1.
230 #if (defined(OS_POSIX) && \
231 defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0) || \
232 defined(OS_BSD) || defined(OS_ANDROID)
234 // static
235 TimeTicks TimeTicks::Now() {
236 uint64_t absolute_micro;
238 struct timespec ts;
239 if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
240 NOTREACHED() << "clock_gettime(CLOCK_MONOTONIC) failed.";
241 return TimeTicks();
244 absolute_micro =
245 (static_cast<int64>(ts.tv_sec) * Time::kMicrosecondsPerSecond) +
246 (static_cast<int64>(ts.tv_nsec) / Time::kNanosecondsPerMicrosecond);
248 return TimeTicks(absolute_micro);
250 #else // _POSIX_MONOTONIC_CLOCK
251 #error No usable tick clock function on this platform.
252 #endif // _POSIX_MONOTONIC_CLOCK
254 // static
255 TimeTicks TimeTicks::HighResNow() {
256 return Now();
259 #if defined(OS_CHROMEOS)
260 // Force definition of the system trace clock; it is a chromeos-only api
261 // at the moment and surfacing it in the right place requires mucking
262 // with glibc et al.
263 #define CLOCK_SYSTEM_TRACE 11
265 // static
266 TimeTicks TimeTicks::NowFromSystemTraceTime() {
267 uint64_t absolute_micro;
269 struct timespec ts;
270 if (clock_gettime(CLOCK_SYSTEM_TRACE, &ts) != 0) {
271 // NB: fall-back for a chrome os build running on linux
272 return HighResNow();
275 absolute_micro =
276 (static_cast<int64>(ts.tv_sec) * Time::kMicrosecondsPerSecond) +
277 (static_cast<int64>(ts.tv_nsec) / Time::kNanosecondsPerMicrosecond);
279 return TimeTicks(absolute_micro);
282 #else // !defined(OS_CHROMEOS)
284 // static
285 TimeTicks TimeTicks::NowFromSystemTraceTime() {
286 return HighResNow();
289 #endif // defined(OS_CHROMEOS)
291 #endif // !OS_MACOSX
293 // static
294 Time Time::FromTimeVal(struct timeval t) {
295 DCHECK_LT(t.tv_usec, static_cast<int>(Time::kMicrosecondsPerSecond));
296 DCHECK_GE(t.tv_usec, 0);
297 if (t.tv_usec == 0 && t.tv_sec == 0)
298 return Time();
299 if (t.tv_usec == static_cast<suseconds_t>(Time::kMicrosecondsPerSecond) - 1 &&
300 t.tv_sec == std::numeric_limits<time_t>::max())
301 return Max();
302 return Time(
303 (static_cast<int64>(t.tv_sec) * Time::kMicrosecondsPerSecond) +
304 t.tv_usec +
305 kTimeTToMicrosecondsOffset);
308 struct timeval Time::ToTimeVal() const {
309 struct timeval result;
310 if (is_null()) {
311 result.tv_sec = 0;
312 result.tv_usec = 0;
313 return result;
315 if (is_max()) {
316 result.tv_sec = std::numeric_limits<time_t>::max();
317 result.tv_usec = static_cast<suseconds_t>(Time::kMicrosecondsPerSecond) - 1;
318 return result;
320 int64 us = us_ - kTimeTToMicrosecondsOffset;
321 result.tv_sec = us / Time::kMicrosecondsPerSecond;
322 result.tv_usec = us % Time::kMicrosecondsPerSecond;
323 return result;
326 } // namespace base