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