Home | History | Annotate | Download | only in time
      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 <CoreFoundation/CFDate.h>
      8 #include <CoreFoundation/CFTimeZone.h>
      9 #include <mach/mach.h>
     10 #include <mach/mach_time.h>
     11 #include <stddef.h>
     12 #include <stdint.h>
     13 #include <sys/sysctl.h>
     14 #include <sys/time.h>
     15 #include <sys/types.h>
     16 #include <time.h>
     17 
     18 #include "base/logging.h"
     19 #include "base/mac/mach_logging.h"
     20 #include "base/mac/scoped_cftyperef.h"
     21 #include "base/mac/scoped_mach_port.h"
     22 #include "base/macros.h"
     23 #include "base/numerics/safe_conversions.h"
     24 #include "build/build_config.h"
     25 
     26 namespace {
     27 
     28 int64_t ComputeCurrentTicks() {
     29 #if defined(OS_IOS)
     30   // On iOS mach_absolute_time stops while the device is sleeping. Instead use
     31   // now - KERN_BOOTTIME to get a time difference that is not impacted by clock
     32   // changes. KERN_BOOTTIME will be updated by the system whenever the system
     33   // clock change.
     34   struct timeval boottime;
     35   int mib[2] = {CTL_KERN, KERN_BOOTTIME};
     36   size_t size = sizeof(boottime);
     37   int kr = sysctl(mib, arraysize(mib), &boottime, &size, nullptr, 0);
     38   DCHECK_EQ(KERN_SUCCESS, kr);
     39   base::TimeDelta time_difference = base::Time::Now() -
     40       (base::Time::FromTimeT(boottime.tv_sec) +
     41        base::TimeDelta::FromMicroseconds(boottime.tv_usec));
     42   return time_difference.InMicroseconds();
     43 #else
     44   static mach_timebase_info_data_t timebase_info;
     45   if (timebase_info.denom == 0) {
     46     // Zero-initialization of statics guarantees that denom will be 0 before
     47     // calling mach_timebase_info.  mach_timebase_info will never set denom to
     48     // 0 as that would be invalid, so the zero-check can be used to determine
     49     // whether mach_timebase_info has already been called.  This is
     50     // recommended by Apple's QA1398.
     51     kern_return_t kr = mach_timebase_info(&timebase_info);
     52     MACH_DCHECK(kr == KERN_SUCCESS, kr) << "mach_timebase_info";
     53   }
     54 
     55   // mach_absolute_time is it when it comes to ticks on the Mac.  Other calls
     56   // with less precision (such as TickCount) just call through to
     57   // mach_absolute_time.
     58 
     59   // timebase_info converts absolute time tick units into nanoseconds.  Convert
     60   // to microseconds up front to stave off overflows.
     61   base::CheckedNumeric<uint64_t> result(
     62       mach_absolute_time() / base::Time::kNanosecondsPerMicrosecond);
     63   result *= timebase_info.numer;
     64   result /= timebase_info.denom;
     65 
     66   // Don't bother with the rollover handling that the Windows version does.
     67   // With numer and denom = 1 (the expected case), the 64-bit absolute time
     68   // reported in nanoseconds is enough to last nearly 585 years.
     69   return base::checked_cast<int64_t>(result.ValueOrDie());
     70 #endif  // defined(OS_IOS)
     71 }
     72 
     73 int64_t ComputeThreadTicks() {
     74 #if defined(OS_IOS)
     75   NOTREACHED();
     76   return 0;
     77 #else
     78   base::mac::ScopedMachSendRight thread(mach_thread_self());
     79   mach_msg_type_number_t thread_info_count = THREAD_BASIC_INFO_COUNT;
     80   thread_basic_info_data_t thread_info_data;
     81 
     82   if (thread.get() == MACH_PORT_NULL) {
     83     DLOG(ERROR) << "Failed to get mach_thread_self()";
     84     return 0;
     85   }
     86 
     87   kern_return_t kr = thread_info(
     88       thread.get(),
     89       THREAD_BASIC_INFO,
     90       reinterpret_cast<thread_info_t>(&thread_info_data),
     91       &thread_info_count);
     92   MACH_DCHECK(kr == KERN_SUCCESS, kr) << "thread_info";
     93 
     94   base::CheckedNumeric<int64_t> absolute_micros(
     95       thread_info_data.user_time.seconds +
     96       thread_info_data.system_time.seconds);
     97   absolute_micros *= base::Time::kMicrosecondsPerSecond;
     98   absolute_micros += (thread_info_data.user_time.microseconds +
     99                       thread_info_data.system_time.microseconds);
    100   return absolute_micros.ValueOrDie();
    101 #endif  // defined(OS_IOS)
    102 }
    103 
    104 }  // namespace
    105 
    106 namespace base {
    107 
    108 // The Time routines in this file use Mach and CoreFoundation APIs, since the
    109 // POSIX definition of time_t in Mac OS X wraps around after 2038--and
    110 // there are already cookie expiration dates, etc., past that time out in
    111 // the field.  Using CFDate prevents that problem, and using mach_absolute_time
    112 // for TimeTicks gives us nice high-resolution interval timing.
    113 
    114 // Time -----------------------------------------------------------------------
    115 
    116 // Core Foundation uses a double second count since 2001-01-01 00:00:00 UTC.
    117 // The UNIX epoch is 1970-01-01 00:00:00 UTC.
    118 // Windows uses a Gregorian epoch of 1601.  We need to match this internally
    119 // so that our time representations match across all platforms.  See bug 14734.
    120 //   irb(main):010:0> Time.at(0).getutc()
    121 //   => Thu Jan 01 00:00:00 UTC 1970
    122 //   irb(main):011:0> Time.at(-11644473600).getutc()
    123 //   => Mon Jan 01 00:00:00 UTC 1601
    124 static const int64_t kWindowsEpochDeltaSeconds = INT64_C(11644473600);
    125 
    126 // static
    127 const int64_t Time::kWindowsEpochDeltaMicroseconds =
    128     kWindowsEpochDeltaSeconds * Time::kMicrosecondsPerSecond;
    129 
    130 // Some functions in time.cc use time_t directly, so we provide an offset
    131 // to convert from time_t (Unix epoch) and internal (Windows epoch).
    132 // static
    133 const int64_t Time::kTimeTToMicrosecondsOffset = kWindowsEpochDeltaMicroseconds;
    134 
    135 // static
    136 Time Time::Now() {
    137   return FromCFAbsoluteTime(CFAbsoluteTimeGetCurrent());
    138 }
    139 
    140 // static
    141 Time Time::FromCFAbsoluteTime(CFAbsoluteTime t) {
    142   static_assert(std::numeric_limits<CFAbsoluteTime>::has_infinity,
    143                 "CFAbsoluteTime must have an infinity value");
    144   if (t == 0)
    145     return Time();  // Consider 0 as a null Time.
    146   if (t == std::numeric_limits<CFAbsoluteTime>::infinity())
    147     return Max();
    148   return Time(static_cast<int64_t>((t + kCFAbsoluteTimeIntervalSince1970) *
    149                                    kMicrosecondsPerSecond) +
    150               kWindowsEpochDeltaMicroseconds);
    151 }
    152 
    153 CFAbsoluteTime Time::ToCFAbsoluteTime() const {
    154   static_assert(std::numeric_limits<CFAbsoluteTime>::has_infinity,
    155                 "CFAbsoluteTime must have an infinity value");
    156   if (is_null())
    157     return 0;  // Consider 0 as a null Time.
    158   if (is_max())
    159     return std::numeric_limits<CFAbsoluteTime>::infinity();
    160   return (static_cast<CFAbsoluteTime>(us_ - kWindowsEpochDeltaMicroseconds) /
    161       kMicrosecondsPerSecond) - kCFAbsoluteTimeIntervalSince1970;
    162 }
    163 
    164 // static
    165 Time Time::NowFromSystemTime() {
    166   // Just use Now() because Now() returns the system time.
    167   return Now();
    168 }
    169 
    170 // static
    171 bool Time::FromExploded(bool is_local, const Exploded& exploded, Time* time) {
    172   base::ScopedCFTypeRef<CFTimeZoneRef> time_zone(
    173       is_local
    174           ? CFTimeZoneCopySystem()
    175           : CFTimeZoneCreateWithTimeIntervalFromGMT(kCFAllocatorDefault, 0));
    176   base::ScopedCFTypeRef<CFCalendarRef> gregorian(CFCalendarCreateWithIdentifier(
    177       kCFAllocatorDefault, kCFGregorianCalendar));
    178   CFCalendarSetTimeZone(gregorian, time_zone);
    179   CFAbsoluteTime absolute_time;
    180   // 'S' is not defined in componentDesc in Apple documentation, but can be
    181   // found at http://www.opensource.apple.com/source/CF/CF-855.17/CFCalendar.c
    182   CFCalendarComposeAbsoluteTime(
    183       gregorian, &absolute_time, "yMdHmsS", exploded.year, exploded.month,
    184       exploded.day_of_month, exploded.hour, exploded.minute, exploded.second,
    185       exploded.millisecond);
    186   CFAbsoluteTime seconds = absolute_time + kCFAbsoluteTimeIntervalSince1970;
    187 
    188   base::Time converted_time =
    189       Time(static_cast<int64_t>(seconds * kMicrosecondsPerSecond) +
    190            kWindowsEpochDeltaMicroseconds);
    191 
    192   // If |exploded.day_of_month| is set to 31
    193   // on a 28-30 day month, it will return the first day of the next month.
    194   // Thus round-trip the time and compare the initial |exploded| with
    195   // |utc_to_exploded| time.
    196   base::Time::Exploded to_exploded;
    197   if (!is_local)
    198     converted_time.UTCExplode(&to_exploded);
    199   else
    200     converted_time.LocalExplode(&to_exploded);
    201 
    202   if (ExplodedMostlyEquals(to_exploded, exploded)) {
    203     *time = converted_time;
    204     return true;
    205   }
    206 
    207   *time = Time(0);
    208   return false;
    209 }
    210 
    211 void Time::Explode(bool is_local, Exploded* exploded) const {
    212   // Avoid rounding issues, by only putting the integral number of seconds
    213   // (rounded towards -infinity) into a |CFAbsoluteTime| (which is a |double|).
    214   int64_t microsecond = us_ % kMicrosecondsPerSecond;
    215   if (microsecond < 0)
    216     microsecond += kMicrosecondsPerSecond;
    217   CFAbsoluteTime seconds = ((us_ - microsecond) / kMicrosecondsPerSecond) -
    218                            kWindowsEpochDeltaSeconds -
    219                            kCFAbsoluteTimeIntervalSince1970;
    220 
    221   base::ScopedCFTypeRef<CFTimeZoneRef> time_zone(
    222       is_local
    223           ? CFTimeZoneCopySystem()
    224           : CFTimeZoneCreateWithTimeIntervalFromGMT(kCFAllocatorDefault, 0));
    225   base::ScopedCFTypeRef<CFCalendarRef> gregorian(CFCalendarCreateWithIdentifier(
    226       kCFAllocatorDefault, kCFGregorianCalendar));
    227   CFCalendarSetTimeZone(gregorian, time_zone);
    228   int second, day_of_week;
    229   // 'E' sets the day of week, but is not defined in componentDesc in Apple
    230   // documentation. It can be found in open source code here:
    231   // http://www.opensource.apple.com/source/CF/CF-855.17/CFCalendar.c
    232   CFCalendarDecomposeAbsoluteTime(gregorian, seconds, "yMdHmsE",
    233                                   &exploded->year, &exploded->month,
    234                                   &exploded->day_of_month, &exploded->hour,
    235                                   &exploded->minute, &second, &day_of_week);
    236   // Make sure seconds are rounded down towards -infinity.
    237   exploded->second = floor(second);
    238   // |Exploded|'s convention for day of week is 0 = Sunday, i.e. different
    239   // from CF's 1 = Sunday.
    240   exploded->day_of_week = (day_of_week - 1) % 7;
    241   // Calculate milliseconds ourselves, since we rounded the |seconds|, making
    242   // sure to round towards -infinity.
    243   exploded->millisecond =
    244       (microsecond >= 0) ? microsecond / kMicrosecondsPerMillisecond :
    245                            (microsecond - kMicrosecondsPerMillisecond + 1) /
    246                                kMicrosecondsPerMillisecond;
    247 }
    248 
    249 // TimeTicks ------------------------------------------------------------------
    250 
    251 // static
    252 TimeTicks TimeTicks::Now() {
    253   return TimeTicks(ComputeCurrentTicks());
    254 }
    255 
    256 // static
    257 bool TimeTicks::IsHighResolution() {
    258   return true;
    259 }
    260 
    261 // static
    262 TimeTicks::Clock TimeTicks::GetClock() {
    263 #if defined(OS_IOS)
    264   return Clock::IOS_CF_ABSOLUTE_TIME_MINUS_KERN_BOOTTIME;
    265 #else
    266   return Clock::MAC_MACH_ABSOLUTE_TIME;
    267 #endif  // defined(OS_IOS)
    268 }
    269 
    270 // static
    271 ThreadTicks ThreadTicks::Now() {
    272   return ThreadTicks(ComputeThreadTicks());
    273 }
    274 
    275 }  // namespace base
    276