GDTCORClock.m 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. /*
  2. * Copyright 2018 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "GDTCORLibrary/Public/GDTCORClock.h"
  17. #import <sys/sysctl.h>
  18. // Using a monotonic clock is necessary because CFAbsoluteTimeGetCurrent(), NSDate, and related all
  19. // are subject to drift. That it to say, multiple consecutive calls do not always result in a
  20. // time that is in the future. Clocks may be adjusted by the user, NTP, or any number of external
  21. // factors. This class attempts to determine the wall-clock time at the time of the event by
  22. // capturing the kernel start and time since boot to determine a wallclock time in UTC.
  23. //
  24. // Timezone offsets at the time of a snapshot are also captured in order to provide local-time
  25. // details. Other classes in this library depend on comparing times at some time in the future to
  26. // a time captured in the past, and this class needs to provide a mechanism to do that.
  27. //
  28. // TL;DR: This class attempts to accomplish two things: 1. Provide accurate event times. 2. Provide
  29. // a monotonic clock mechanism to accurately check if some clock snapshot was before or after
  30. // by using a shared reference point (kernel boot time).
  31. //
  32. // Note: Much of the mach time stuff doesn't work properly in the simulator. So this class can be
  33. // difficult to unit test.
  34. /** Returns the kernel boottime property from sysctl.
  35. *
  36. * Inspired by https://stackoverflow.com/a/40497811
  37. *
  38. * @return The KERN_BOOTTIME property from sysctl, in nanoseconds.
  39. */
  40. static int64_t KernelBootTimeInNanoseconds() {
  41. // Caching the result is not possible because clock drift would not be accounted for.
  42. struct timeval boottime;
  43. int mib[2] = {CTL_KERN, KERN_BOOTTIME};
  44. size_t size = sizeof(boottime);
  45. int rc = sysctl(mib, 2, &boottime, &size, NULL, 0);
  46. if (rc != 0) {
  47. return 0;
  48. }
  49. return (int64_t)boottime.tv_sec * NSEC_PER_MSEC + (int64_t)boottime.tv_usec;
  50. }
  51. /** Returns value of gettimeofday, in nanoseconds.
  52. *
  53. * Inspired by https://stackoverflow.com/a/40497811
  54. *
  55. * @return The value of gettimeofday, in nanoseconds.
  56. */
  57. static int64_t UptimeInNanoseconds() {
  58. int64_t before_now;
  59. int64_t after_now;
  60. struct timeval now;
  61. before_now = KernelBootTimeInNanoseconds();
  62. // Addresses a race condition in which the system time has updated, but the boottime has not.
  63. do {
  64. gettimeofday(&now, NULL);
  65. after_now = KernelBootTimeInNanoseconds();
  66. } while (after_now != before_now);
  67. return (int64_t)now.tv_sec * NSEC_PER_MSEC + (int64_t)now.tv_usec - before_now;
  68. }
  69. // TODO: Consider adding a 'trustedTime' property that can be populated by the response from a BE.
  70. @implementation GDTCORClock
  71. - (instancetype)init {
  72. self = [super init];
  73. if (self) {
  74. _kernelBootTime = KernelBootTimeInNanoseconds();
  75. _uptime = UptimeInNanoseconds();
  76. _timeMillis =
  77. (int64_t)((CFAbsoluteTimeGetCurrent() + kCFAbsoluteTimeIntervalSince1970) * NSEC_PER_USEC);
  78. CFTimeZoneRef timeZoneRef = CFTimeZoneCopySystem();
  79. _timezoneOffsetSeconds = CFTimeZoneGetSecondsFromGMT(timeZoneRef, 0);
  80. CFRelease(timeZoneRef);
  81. }
  82. return self;
  83. }
  84. + (GDTCORClock *)snapshot {
  85. return [[GDTCORClock alloc] init];
  86. }
  87. + (instancetype)clockSnapshotInTheFuture:(uint64_t)millisInTheFuture {
  88. GDTCORClock *snapshot = [self snapshot];
  89. snapshot->_timeMillis += millisInTheFuture;
  90. return snapshot;
  91. }
  92. - (BOOL)isAfter:(GDTCORClock *)otherClock {
  93. // These clocks are trivially comparable when they share a kernel boot time.
  94. if (_kernelBootTime == otherClock->_kernelBootTime) {
  95. int64_t timeDiff = (_timeMillis + _timezoneOffsetSeconds) -
  96. (otherClock->_timeMillis + otherClock->_timezoneOffsetSeconds);
  97. return timeDiff > 0;
  98. } else {
  99. int64_t kernelBootTimeDiff = otherClock->_kernelBootTime - _kernelBootTime;
  100. // This isn't a great solution, but essentially, if the other clock's boot time is 'later', NO
  101. // is returned. This can be altered by changing the system time and rebooting.
  102. return kernelBootTimeDiff < 0 ? YES : NO;
  103. }
  104. }
  105. - (NSUInteger)hash {
  106. return [@(_kernelBootTime) hash] ^ [@(_uptime) hash] ^ [@(_timeMillis) hash] ^
  107. [@(_timezoneOffsetSeconds) hash];
  108. }
  109. - (BOOL)isEqual:(id)object {
  110. return [self hash] == [object hash];
  111. }
  112. #pragma mark - NSSecureCoding
  113. /** NSKeyedCoder key for timeMillis property. */
  114. static NSString *const kGDTCORClockTimeMillisKey = @"GDTCORClockTimeMillis";
  115. /** NSKeyedCoder key for timezoneOffsetMillis property. */
  116. static NSString *const kGDTCORClockTimezoneOffsetSeconds = @"GDTCORClockTimezoneOffsetSeconds";
  117. /** NSKeyedCoder key for _kernelBootTime ivar. */
  118. static NSString *const kGDTCORClockKernelBootTime = @"GDTCORClockKernelBootTime";
  119. /** NSKeyedCoder key for _uptime ivar. */
  120. static NSString *const kGDTCORClockUptime = @"GDTCORClockUptime";
  121. + (BOOL)supportsSecureCoding {
  122. return YES;
  123. }
  124. - (instancetype)initWithCoder:(NSCoder *)aDecoder {
  125. self = [super init];
  126. if (self) {
  127. // TODO: If the kernelBootTime is more recent, we need to change the kernel boot time and
  128. // uptimeMillis ivars
  129. _timeMillis = [aDecoder decodeInt64ForKey:kGDTCORClockTimeMillisKey];
  130. _timezoneOffsetSeconds = [aDecoder decodeInt64ForKey:kGDTCORClockTimezoneOffsetSeconds];
  131. _kernelBootTime = [aDecoder decodeInt64ForKey:kGDTCORClockKernelBootTime];
  132. _uptime = [aDecoder decodeInt64ForKey:kGDTCORClockUptime];
  133. }
  134. return self;
  135. }
  136. - (void)encodeWithCoder:(NSCoder *)aCoder {
  137. [aCoder encodeInt64:_timeMillis forKey:kGDTCORClockTimeMillisKey];
  138. [aCoder encodeInt64:_timezoneOffsetSeconds forKey:kGDTCORClockTimezoneOffsetSeconds];
  139. [aCoder encodeInt64:_kernelBootTime forKey:kGDTCORClockKernelBootTime];
  140. [aCoder encodeInt64:_uptime forKey:kGDTCORClockUptime];
  141. }
  142. @end