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