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 <stdint.h>
8 #include <sys/time.h>
9 #include <time.h>
10 #if defined(OS_ANDROID) && !defined(__LP64__)
11 #include <time64.h>
12 #endif
13 #include <unistd.h>
14
15 #include <limits>
16
17 #include "base/numerics/safe_math.h"
18 #include "base/synchronization/lock.h"
19 #include "build/build_config.h"
20
21 #if defined(OS_ANDROID)
22 #include "base/os_compat_android.h"
23 #elif defined(OS_NACL)
24 #include "base/os_compat_nacl.h"
25 #endif
26
27 #if defined(OS_MACOSX) || defined(OS_IOS)
28 static_assert(sizeof(time_t) >= 8, "Y2038 problem!");
29 #endif
30
31 namespace {
32
33 // This prevents a crash on traversing the environment global and looking up
34 // the 'TZ' variable in libc. See: crbug.com/390567.
GetSysTimeToTimeStructLock()35 base::Lock* GetSysTimeToTimeStructLock() {
36 static auto* lock = new base::Lock();
37 return lock;
38 }
39
40 // Define a system-specific SysTime that wraps either to a time_t or
41 // a time64_t depending on the host system, and associated convertion.
42 // See crbug.com/162007
43 #if defined(OS_ANDROID) && !defined(__LP64__)
44 typedef time64_t SysTime;
45
SysTimeFromTimeStruct(struct tm * timestruct,bool is_local)46 SysTime SysTimeFromTimeStruct(struct tm* timestruct, bool is_local) {
47 base::AutoLock locked(*GetSysTimeToTimeStructLock());
48 if (is_local)
49 return mktime64(timestruct);
50 else
51 return timegm64(timestruct);
52 }
53
SysTimeToTimeStruct(SysTime t,struct tm * timestruct,bool is_local)54 void SysTimeToTimeStruct(SysTime t, struct tm* timestruct, bool is_local) {
55 base::AutoLock locked(*GetSysTimeToTimeStructLock());
56 if (is_local)
57 localtime64_r(&t, timestruct);
58 else
59 gmtime64_r(&t, timestruct);
60 }
61 #elif defined(OS_AIX)
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
SysTimeToTimeStruct(SysTime t,struct tm * timestruct,bool is_local)94 void SysTimeToTimeStruct(SysTime t, struct tm* timestruct, bool is_local) {
95 base::AutoLock locked(*GetSysTimeToTimeStructLock());
96 if (is_local)
97 localtime_r(&t, timestruct);
98 else
99 gmtime_r(&t, timestruct);
100 }
101
102 #else
103 typedef time_t SysTime;
104
SysTimeFromTimeStruct(struct tm * timestruct,bool is_local)105 SysTime SysTimeFromTimeStruct(struct tm* timestruct, bool is_local) {
106 base::AutoLock locked(*GetSysTimeToTimeStructLock());
107 return is_local ? mktime(timestruct) : timegm(timestruct);
108 }
109
SysTimeToTimeStruct(SysTime t,struct tm * timestruct,bool is_local)110 void SysTimeToTimeStruct(SysTime t, struct tm* timestruct, bool is_local) {
111 base::AutoLock locked(*GetSysTimeToTimeStructLock());
112 if (is_local)
113 localtime_r(&t, timestruct);
114 else
115 gmtime_r(&t, timestruct);
116 }
117 #endif // defined(OS_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 // The following values are all rounded towards -infinity.
125 int64_t milliseconds = ToRoundedDownMillisecondsSinceUnixEpoch();
126 SysTime seconds; // Seconds since epoch.
127 int millisecond; // Exploded millisecond value (0-999).
128
129 // If the microseconds were negative, the rounded down milliseconds will also
130 // be negative. For example, -1 us becomes -1 ms.
131 if (milliseconds >= 0) {
132 // Rounding towards -infinity <=> rounding towards 0, in this case.
133 seconds = milliseconds / kMillisecondsPerSecond;
134 millisecond = milliseconds % kMillisecondsPerSecond;
135 } else {
136 // Round these *down* (towards -infinity).
137 seconds =
138 (milliseconds - kMillisecondsPerSecond + 1) / kMillisecondsPerSecond;
139 // Make this nonnegative (and between 0 and 999 inclusive).
140 millisecond = milliseconds % kMillisecondsPerSecond;
141 if (millisecond < 0)
142 millisecond += kMillisecondsPerSecond;
143 }
144
145 struct tm timestruct;
146 SysTimeToTimeStruct(seconds, ×truct, is_local);
147
148 exploded->year = timestruct.tm_year + 1900;
149 exploded->month = timestruct.tm_mon + 1;
150 exploded->day_of_week = timestruct.tm_wday;
151 exploded->day_of_month = timestruct.tm_mday;
152 exploded->hour = timestruct.tm_hour;
153 exploded->minute = timestruct.tm_min;
154 exploded->second = timestruct.tm_sec;
155 exploded->millisecond = millisecond;
156 }
157
158 // static
FromExploded(bool is_local,const Exploded & exploded,Time * time)159 bool Time::FromExploded(bool is_local, const Exploded& exploded, Time* time) {
160 CheckedNumeric<int> month = exploded.month;
161 month--;
162 CheckedNumeric<int> year = exploded.year;
163 year -= 1900;
164 if (!month.IsValid() || !year.IsValid()) {
165 *time = Time(0);
166 return false;
167 }
168
169 struct tm timestruct;
170 timestruct.tm_sec = exploded.second;
171 timestruct.tm_min = exploded.minute;
172 timestruct.tm_hour = exploded.hour;
173 timestruct.tm_mday = exploded.day_of_month;
174 timestruct.tm_mon = month.ValueOrDie();
175 timestruct.tm_year = year.ValueOrDie();
176 timestruct.tm_wday = exploded.day_of_week; // mktime/timegm ignore this
177 timestruct.tm_yday = 0; // mktime/timegm ignore this
178 timestruct.tm_isdst = -1; // attempt to figure it out
179 #if !defined(OS_NACL) && !defined(OS_SOLARIS) && !defined(OS_AIX)
180 timestruct.tm_gmtoff = 0; // not a POSIX field, so mktime/timegm ignore
181 timestruct.tm_zone = nullptr; // not a POSIX field, so mktime/timegm ignore
182 #endif
183
184 SysTime seconds;
185
186 // Certain exploded dates do not really exist due to daylight saving times,
187 // and this causes mktime() to return implementation-defined values when
188 // tm_isdst is set to -1. On Android, the function will return -1, while the
189 // C libraries of other platforms typically return a liberally-chosen value.
190 // Handling this requires the special code below.
191
192 // SysTimeFromTimeStruct() modifies the input structure, save current value.
193 struct tm timestruct0 = timestruct;
194
195 seconds = SysTimeFromTimeStruct(×truct, is_local);
196 if (seconds == -1) {
197 // Get the time values with tm_isdst == 0 and 1, then select the closest one
198 // to UTC 00:00:00 that isn't -1.
199 timestruct = timestruct0;
200 timestruct.tm_isdst = 0;
201 int64_t seconds_isdst0 = SysTimeFromTimeStruct(×truct, is_local);
202
203 timestruct = timestruct0;
204 timestruct.tm_isdst = 1;
205 int64_t seconds_isdst1 = SysTimeFromTimeStruct(×truct, is_local);
206
207 // seconds_isdst0 or seconds_isdst1 can be -1 for some timezones.
208 // E.g. "CLST" (Chile Summer Time) returns -1 for 'tm_isdt == 1'.
209 if (seconds_isdst0 < 0)
210 seconds = seconds_isdst1;
211 else if (seconds_isdst1 < 0)
212 seconds = seconds_isdst0;
213 else
214 seconds = std::min(seconds_isdst0, seconds_isdst1);
215 }
216
217 // Handle overflow. Clamping the range to what mktime and timegm might
218 // return is the best that can be done here. It's not ideal, but it's better
219 // than failing here or ignoring the overflow case and treating each time
220 // overflow as one second prior to the epoch.
221 int64_t milliseconds = 0;
222 if (seconds == -1 && (exploded.year < 1969 || exploded.year > 1970)) {
223 // If exploded.year is 1969 or 1970, take -1 as correct, with the
224 // time indicating 1 second prior to the epoch. (1970 is allowed to handle
225 // time zone and DST offsets.) Otherwise, return the most future or past
226 // time representable. Assumes the time_t epoch is 1970-01-01 00:00:00 UTC.
227 //
228 // The minimum and maximum representible times that mktime and timegm could
229 // return are used here instead of values outside that range to allow for
230 // proper round-tripping between exploded and counter-type time
231 // representations in the presence of possible truncation to time_t by
232 // division and use with other functions that accept time_t.
233 //
234 // When representing the most distant time in the future, add in an extra
235 // 999ms to avoid the time being less than any other possible value that
236 // this function can return.
237
238 // On Android, SysTime is int64_t, special care must be taken to avoid
239 // overflows.
240 const int64_t min_seconds = (sizeof(SysTime) < sizeof(int64_t))
241 ? std::numeric_limits<SysTime>::min()
242 : std::numeric_limits<int32_t>::min();
243 const int64_t max_seconds = (sizeof(SysTime) < sizeof(int64_t))
244 ? std::numeric_limits<SysTime>::max()
245 : std::numeric_limits<int32_t>::max();
246 if (exploded.year < 1969) {
247 milliseconds = min_seconds * kMillisecondsPerSecond;
248 } else {
249 milliseconds = max_seconds * kMillisecondsPerSecond;
250 milliseconds += (kMillisecondsPerSecond - 1);
251 }
252 } else {
253 CheckedNumeric<int64_t> checked_millis = seconds;
254 checked_millis *= kMillisecondsPerSecond;
255 checked_millis += exploded.millisecond;
256 if (!checked_millis.IsValid()) {
257 *time = Time(0);
258 return false;
259 }
260 milliseconds = checked_millis.ValueOrDie();
261 }
262
263 Time converted_time;
264 if (!FromMillisecondsSinceUnixEpoch(milliseconds, &converted_time)) {
265 *time = base::Time(0);
266 return false;
267 }
268
269 // If |exploded.day_of_month| is set to 31 on a 28-30 day month, it will
270 // return the first day of the next month. Thus round-trip the time and
271 // compare the initial |exploded| with |utc_to_exploded| time.
272 Time::Exploded to_exploded;
273 if (!is_local)
274 converted_time.UTCExplode(&to_exploded);
275 else
276 converted_time.LocalExplode(&to_exploded);
277
278 if (ExplodedMostlyEquals(to_exploded, exploded)) {
279 *time = converted_time;
280 return true;
281 }
282
283 *time = Time(0);
284 return false;
285 }
286
287 } // namespace base
288