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