time_exploded_posix.cc 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. #include <stdint.h>
  5. #include <sys/time.h>
  6. #include <time.h>
  7. #include "base/time/time.h"
  8. #include "build/build_config.h"
  9. #if BUILDFLAG(IS_ANDROID) && !defined(__LP64__)
  10. #include <time64.h>
  11. #endif
  12. #include <unistd.h>
  13. #include <limits>
  14. #include "base/no_destructor.h"
  15. #include "base/numerics/safe_math.h"
  16. #include "base/synchronization/lock.h"
  17. #include "build/build_config.h"
  18. #include "build/chromecast_buildflags.h"
  19. #if BUILDFLAG(IS_NACL)
  20. #include "base/os_compat_nacl.h"
  21. #endif
  22. namespace {
  23. // This prevents a crash on traversing the environment global and looking up
  24. // the 'TZ' variable in libc. See: crbug.com/390567.
  25. base::Lock* GetSysTimeToTimeStructLock() {
  26. static base::NoDestructor<base::Lock> lock;
  27. return lock.get();
  28. }
  29. // Define a system-specific SysTime that wraps either to a time_t or
  30. // a time64_t depending on the host system, and associated convertion.
  31. // See crbug.com/162007
  32. #if BUILDFLAG(IS_ANDROID) && !defined(__LP64__)
  33. typedef time64_t SysTime;
  34. SysTime SysTimeFromTimeStruct(struct tm* timestruct, bool is_local) {
  35. base::AutoLock locked(*GetSysTimeToTimeStructLock());
  36. if (is_local)
  37. return mktime64(timestruct);
  38. else
  39. return timegm64(timestruct);
  40. }
  41. void SysTimeToTimeStruct(SysTime t, struct tm* timestruct, bool is_local) {
  42. base::AutoLock locked(*GetSysTimeToTimeStructLock());
  43. if (is_local)
  44. localtime64_r(&t, timestruct);
  45. else
  46. gmtime64_r(&t, timestruct);
  47. }
  48. #elif BUILDFLAG(IS_AIX)
  49. // The function timegm is not available on AIX.
  50. time_t aix_timegm(struct tm* tm) {
  51. time_t ret;
  52. char* tz;
  53. tz = getenv("TZ");
  54. if (tz) {
  55. tz = strdup(tz);
  56. }
  57. setenv("TZ", "GMT0", 1);
  58. tzset();
  59. ret = mktime(tm);
  60. if (tz) {
  61. setenv("TZ", tz, 1);
  62. free(tz);
  63. } else {
  64. unsetenv("TZ");
  65. }
  66. tzset();
  67. return ret;
  68. }
  69. typedef time_t SysTime;
  70. SysTime SysTimeFromTimeStruct(struct tm* timestruct, bool is_local) {
  71. base::AutoLock locked(*GetSysTimeToTimeStructLock());
  72. if (is_local)
  73. return mktime(timestruct);
  74. else
  75. return aix_timegm(timestruct);
  76. }
  77. void SysTimeToTimeStruct(SysTime t, struct tm* timestruct, bool is_local) {
  78. base::AutoLock locked(*GetSysTimeToTimeStructLock());
  79. if (is_local)
  80. localtime_r(&t, timestruct);
  81. else
  82. gmtime_r(&t, timestruct);
  83. }
  84. #else // MacOS (and iOS 64-bit), Linux/ChromeOS, or any other POSIX-compliant.
  85. typedef time_t SysTime;
  86. SysTime SysTimeFromTimeStruct(struct tm* timestruct, bool is_local) {
  87. base::AutoLock locked(*GetSysTimeToTimeStructLock());
  88. return is_local ? mktime(timestruct) : timegm(timestruct);
  89. }
  90. void SysTimeToTimeStruct(SysTime t, struct tm* timestruct, bool is_local) {
  91. base::AutoLock locked(*GetSysTimeToTimeStructLock());
  92. if (is_local)
  93. localtime_r(&t, timestruct);
  94. else
  95. gmtime_r(&t, timestruct);
  96. }
  97. #endif // BUILDFLAG(IS_ANDROID) && !defined(__LP64__)
  98. } // namespace
  99. namespace base {
  100. void Time::Explode(bool is_local, Exploded* exploded) const {
  101. const int64_t millis_since_unix_epoch =
  102. ToRoundedDownMillisecondsSinceUnixEpoch();
  103. // For systems with a Y2038 problem, use ICU as the Explode() implementation.
  104. if (sizeof(SysTime) < 8) {
  105. // TODO(b/167763382) Find an alternate solution for Chromecast devices, since
  106. // adding the icui18n dep significantly increases the binary size.
  107. #if !BUILDFLAG(IS_CASTOS) && !BUILDFLAG(IS_CAST_ANDROID)
  108. ExplodeUsingIcu(millis_since_unix_epoch, is_local, exploded);
  109. return;
  110. #endif // !BUILDFLAG(IS_CASTOS) && !BUILDFLAG(IS_CAST_ANDROID)
  111. }
  112. // Split the |millis_since_unix_epoch| into separate seconds and millisecond
  113. // components because the platform calendar-explode operates at one-second
  114. // granularity.
  115. SysTime seconds = millis_since_unix_epoch / Time::kMillisecondsPerSecond;
  116. int64_t millisecond = millis_since_unix_epoch % Time::kMillisecondsPerSecond;
  117. if (millisecond < 0) {
  118. // Make the the |millisecond| component positive, within the range [0,999],
  119. // by transferring 1000 ms from |seconds|.
  120. --seconds;
  121. millisecond += Time::kMillisecondsPerSecond;
  122. }
  123. struct tm timestruct;
  124. SysTimeToTimeStruct(seconds, &timestruct, is_local);
  125. exploded->year = timestruct.tm_year + 1900;
  126. exploded->month = timestruct.tm_mon + 1;
  127. exploded->day_of_week = timestruct.tm_wday;
  128. exploded->day_of_month = timestruct.tm_mday;
  129. exploded->hour = timestruct.tm_hour;
  130. exploded->minute = timestruct.tm_min;
  131. exploded->second = timestruct.tm_sec;
  132. exploded->millisecond = static_cast<int>(millisecond);
  133. }
  134. // static
  135. bool Time::FromExploded(bool is_local, const Exploded& exploded, Time* time) {
  136. CheckedNumeric<int> month = exploded.month;
  137. month--;
  138. CheckedNumeric<int> year = exploded.year;
  139. year -= 1900;
  140. if (!month.IsValid() || !year.IsValid()) {
  141. *time = Time(0);
  142. return false;
  143. }
  144. struct tm timestruct;
  145. timestruct.tm_sec = exploded.second;
  146. timestruct.tm_min = exploded.minute;
  147. timestruct.tm_hour = exploded.hour;
  148. timestruct.tm_mday = exploded.day_of_month;
  149. timestruct.tm_mon = month.ValueOrDie();
  150. timestruct.tm_year = year.ValueOrDie();
  151. timestruct.tm_wday = exploded.day_of_week; // mktime/timegm ignore this
  152. timestruct.tm_yday = 0; // mktime/timegm ignore this
  153. timestruct.tm_isdst = -1; // attempt to figure it out
  154. #if !BUILDFLAG(IS_NACL) && !BUILDFLAG(IS_SOLARIS) && !BUILDFLAG(IS_AIX)
  155. timestruct.tm_gmtoff = 0; // not a POSIX field, so mktime/timegm ignore
  156. timestruct.tm_zone = nullptr; // not a POSIX field, so mktime/timegm ignore
  157. #endif
  158. int64_t seconds;
  159. // Certain exploded dates do not really exist due to daylight saving times,
  160. // and this causes mktime() to return implementation-defined values when
  161. // tm_isdst is set to -1. On Android, the function will return -1, while the
  162. // C libraries of other platforms typically return a liberally-chosen value.
  163. // Handling this requires the special code below.
  164. // SysTimeFromTimeStruct() modifies the input structure, save current value.
  165. struct tm timestruct0 = timestruct;
  166. seconds = SysTimeFromTimeStruct(&timestruct, is_local);
  167. if (seconds == -1) {
  168. // Get the time values with tm_isdst == 0 and 1, then select the closest one
  169. // to UTC 00:00:00 that isn't -1.
  170. timestruct = timestruct0;
  171. timestruct.tm_isdst = 0;
  172. int64_t seconds_isdst0 = SysTimeFromTimeStruct(&timestruct, is_local);
  173. timestruct = timestruct0;
  174. timestruct.tm_isdst = 1;
  175. int64_t seconds_isdst1 = SysTimeFromTimeStruct(&timestruct, is_local);
  176. // seconds_isdst0 or seconds_isdst1 can be -1 for some timezones.
  177. // E.g. "CLST" (Chile Summer Time) returns -1 for 'tm_isdt == 1'.
  178. if (seconds_isdst0 < 0)
  179. seconds = seconds_isdst1;
  180. else if (seconds_isdst1 < 0)
  181. seconds = seconds_isdst0;
  182. else
  183. seconds = std::min(seconds_isdst0, seconds_isdst1);
  184. }
  185. // Handle overflow. Clamping the range to what mktime and timegm might
  186. // return is the best that can be done here. It's not ideal, but it's better
  187. // than failing here or ignoring the overflow case and treating each time
  188. // overflow as one second prior to the epoch.
  189. int64_t milliseconds = 0;
  190. if (seconds == -1 && (exploded.year < 1969 || exploded.year > 1970)) {
  191. // If exploded.year is 1969 or 1970, take -1 as correct, with the
  192. // time indicating 1 second prior to the epoch. (1970 is allowed to handle
  193. // time zone and DST offsets.) Otherwise, return the most future or past
  194. // time representable. Assumes the time_t epoch is 1970-01-01 00:00:00 UTC.
  195. //
  196. // The minimum and maximum representible times that mktime and timegm could
  197. // return are used here instead of values outside that range to allow for
  198. // proper round-tripping between exploded and counter-type time
  199. // representations in the presence of possible truncation to time_t by
  200. // division and use with other functions that accept time_t.
  201. //
  202. // When representing the most distant time in the future, add in an extra
  203. // 999ms to avoid the time being less than any other possible value that
  204. // this function can return.
  205. // On Android, SysTime is int64_t, special care must be taken to avoid
  206. // overflows.
  207. const int64_t min_seconds = (sizeof(SysTime) < sizeof(int64_t))
  208. ? std::numeric_limits<SysTime>::min()
  209. : std::numeric_limits<int32_t>::min();
  210. const int64_t max_seconds = (sizeof(SysTime) < sizeof(int64_t))
  211. ? std::numeric_limits<SysTime>::max()
  212. : std::numeric_limits<int32_t>::max();
  213. if (exploded.year < 1969) {
  214. milliseconds = min_seconds * kMillisecondsPerSecond;
  215. } else {
  216. milliseconds = max_seconds * kMillisecondsPerSecond;
  217. milliseconds += (kMillisecondsPerSecond - 1);
  218. }
  219. } else {
  220. CheckedNumeric<int64_t> checked_millis = seconds;
  221. checked_millis *= kMillisecondsPerSecond;
  222. checked_millis += exploded.millisecond;
  223. if (!checked_millis.IsValid()) {
  224. *time = Time(0);
  225. return false;
  226. }
  227. milliseconds = checked_millis.ValueOrDie();
  228. }
  229. Time converted_time;
  230. if (!FromMillisecondsSinceUnixEpoch(milliseconds, &converted_time)) {
  231. *time = base::Time(0);
  232. return false;
  233. }
  234. // If |exploded.day_of_month| is set to 31 on a 28-30 day month, it will
  235. // return the first day of the next month. Thus round-trip the time and
  236. // compare the initial |exploded| with |utc_to_exploded| time.
  237. Time::Exploded to_exploded;
  238. if (!is_local)
  239. converted_time.UTCExplode(&to_exploded);
  240. else
  241. converted_time.LocalExplode(&to_exploded);
  242. if (ExplodedMostlyEquals(to_exploded, exploded)) {
  243. *time = converted_time;
  244. return true;
  245. }
  246. *time = Time(0);
  247. return false;
  248. }
  249. } // namespace base