• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2013 The Android Open Source Project
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 
17 #include <time.h>
18 
19 #include <errno.h>
20 #include <gtest/gtest.h>
21 #include <pthread.h>
22 #include <signal.h>
23 #include <sys/cdefs.h>
24 #include <sys/syscall.h>
25 #include <sys/types.h>
26 #include <sys/wait.h>
27 #include <unistd.h>
28 
29 #include <atomic>
30 #include <chrono>
31 #include <thread>
32 
33 #include "SignalUtils.h"
34 #include "android-base/file.h"
35 #include "android-base/strings.h"
36 #include "utils.h"
37 
38 using namespace std::chrono_literals;
39 
TEST(time,time)40 TEST(time, time) {
41   // Acquire time
42   time_t p1, t1 = time(&p1);
43   // valid?
44   ASSERT_NE(static_cast<time_t>(0), t1);
45   ASSERT_NE(static_cast<time_t>(-1), t1);
46   ASSERT_EQ(p1, t1);
47 
48   // Acquire time one+ second later
49   usleep(1010000);
50   time_t p2, t2 = time(&p2);
51   // valid?
52   ASSERT_NE(static_cast<time_t>(0), t2);
53   ASSERT_NE(static_cast<time_t>(-1), t2);
54   ASSERT_EQ(p2, t2);
55 
56   // Expect time progression
57   ASSERT_LT(p1, p2);
58   ASSERT_LE(t2 - t1, static_cast<time_t>(2));
59 
60   // Expect nullptr call to produce same results
61   ASSERT_LE(t2, time(nullptr));
62   ASSERT_LE(time(nullptr) - t2, static_cast<time_t>(1));
63 }
64 
TEST(time,gmtime)65 TEST(time, gmtime) {
66   time_t t = 0;
67   tm* broken_down = gmtime(&t);
68   ASSERT_TRUE(broken_down != nullptr);
69   ASSERT_EQ(0, broken_down->tm_sec);
70   ASSERT_EQ(0, broken_down->tm_min);
71   ASSERT_EQ(0, broken_down->tm_hour);
72   ASSERT_EQ(1, broken_down->tm_mday);
73   ASSERT_EQ(0, broken_down->tm_mon);
74   ASSERT_EQ(1970, broken_down->tm_year + 1900);
75 }
76 
TEST(time,gmtime_r)77 TEST(time, gmtime_r) {
78   struct tm tm = {};
79   time_t t = 0;
80   struct tm* broken_down = gmtime_r(&t, &tm);
81   ASSERT_EQ(broken_down, &tm);
82   ASSERT_EQ(0, broken_down->tm_sec);
83   ASSERT_EQ(0, broken_down->tm_min);
84   ASSERT_EQ(0, broken_down->tm_hour);
85   ASSERT_EQ(1, broken_down->tm_mday);
86   ASSERT_EQ(0, broken_down->tm_mon);
87   ASSERT_EQ(1970, broken_down->tm_year + 1900);
88 }
89 
TEST(time,mktime_TZ_as_UTC_and_offset)90 TEST(time, mktime_TZ_as_UTC_and_offset) {
91   struct tm tm = {.tm_year = 70, .tm_mon = 0, .tm_mday = 1};
92 
93   // This TZ value is not a valid Olson ID and is not present in tzdata file,
94   // but is a valid TZ string according to POSIX standard.
95   setenv("TZ", "UTC+08:00:00", 1);
96   tzset();
97   ASSERT_EQ(static_cast<time_t>(8 * 60 * 60), mktime(&tm));
98 }
99 
gmtime_no_stack_overflow_14313703_fn(void *)100 static void* gmtime_no_stack_overflow_14313703_fn(void*) {
101   const char* original_tz = getenv("TZ");
102   // Ensure we'll actually have to enter tzload by using a timezone that doesn't exist.
103   setenv("TZ", "gmtime_stack_overflow_14313703", 1);
104   tzset();
105   if (original_tz != nullptr) {
106     setenv("TZ", original_tz, 1);
107   }
108   tzset();
109   return nullptr;
110 }
111 
TEST(time,gmtime_no_stack_overflow_14313703)112 TEST(time, gmtime_no_stack_overflow_14313703) {
113   // Is it safe to call tzload on a thread with a small stack?
114   // http://b/14313703
115   // https://code.google.com/p/android/issues/detail?id=61130
116   pthread_attr_t a;
117   ASSERT_EQ(0, pthread_attr_init(&a));
118   ASSERT_EQ(0, pthread_attr_setstacksize(&a, PTHREAD_STACK_MIN));
119 
120   pthread_t t;
121   ASSERT_EQ(0, pthread_create(&t, &a, gmtime_no_stack_overflow_14313703_fn, nullptr));
122   ASSERT_EQ(0, pthread_join(t, nullptr));
123 }
124 
TEST(time,mktime_empty_TZ)125 TEST(time, mktime_empty_TZ) {
126   // tzcode used to have a bug where it didn't reinitialize some internal state.
127 
128   // Choose a time where DST is set.
129   struct tm t = {};
130   t.tm_year = 1980 - 1900;
131   t.tm_mon = 6;
132   t.tm_mday = 2;
133 
134   setenv("TZ", "America/Los_Angeles", 1);
135   tzset();
136   ASSERT_EQ(static_cast<time_t>(331372800U), mktime(&t));
137 
138   t = {};
139   t.tm_year = 1980 - 1900;
140   t.tm_mon = 6;
141   t.tm_mday = 2;
142 
143   setenv("TZ", "", 1); // Implies UTC.
144   tzset();
145   ASSERT_EQ(static_cast<time_t>(331344000U), mktime(&t));
146 }
147 
TEST(time,mktime_10310929)148 TEST(time, mktime_10310929) {
149   struct tm tm = {.tm_year = 2100 - 1900, .tm_mon = 2, .tm_mday = 10};
150 
151 #if !defined(__LP64__)
152   // 32-bit bionic has a signed 32-bit time_t.
153   ASSERT_EQ(-1, mktime(&tm));
154   ASSERT_ERRNO(EOVERFLOW);
155 #else
156   // Everyone else should be using a signed 64-bit time_t.
157   ASSERT_GE(sizeof(time_t) * 8, 64U);
158 
159   setenv("TZ", "America/Los_Angeles", 1);
160   tzset();
161   errno = 0;
162 
163   // On the date/time specified by tm America/Los_Angeles
164   // follows DST. But tm_isdst is set to 0, which forces
165   // mktime to interpret that time as local standard, hence offset
166   // is 8 hours, not 7.
167   ASSERT_EQ(static_cast<time_t>(4108348800U), mktime(&tm));
168   ASSERT_ERRNO(0);
169 #endif
170 }
171 
TEST(time,mktime_EOVERFLOW)172 TEST(time, mktime_EOVERFLOW) {
173   setenv("TZ", "UTC", 1);
174 
175   struct tm t = {};
176 
177   // LP32 year range is 1901-2038, so this year is guaranteed not to overflow.
178   t.tm_year = 2016 - 1900;
179 
180   t.tm_mon = 2;
181   t.tm_mday = 10;
182 
183   errno = 0;
184   ASSERT_NE(static_cast<time_t>(-1), mktime(&t));
185   ASSERT_ERRNO(0);
186 
187   // This will overflow for LP32.
188   t.tm_year = INT_MAX;
189 
190   errno = 0;
191 #if !defined(__LP64__)
192   ASSERT_EQ(static_cast<time_t>(-1), mktime(&t));
193   ASSERT_ERRNO(EOVERFLOW);
194 #else
195   ASSERT_EQ(static_cast<time_t>(67768036166016000U), mktime(&t));
196   ASSERT_ERRNO(0);
197 #endif
198 
199   // This will overflow for LP32 or LP64.
200   // tm_year is int, this t struct points to INT_MAX + 1 no matter what TZ is.
201   t.tm_year = INT_MAX;
202   t.tm_mon = 11;
203   t.tm_mday = 45;
204 
205   errno = 0;
206   ASSERT_EQ(static_cast<time_t>(-1), mktime(&t));
207   ASSERT_ERRNO(EOVERFLOW);
208 }
209 
TEST(time,mktime_invalid_tm_TZ_combination)210 TEST(time, mktime_invalid_tm_TZ_combination) {
211   setenv("TZ", "UTC", 1);
212 
213   struct tm t = {};
214   t.tm_year = 2022 - 1900;
215   t.tm_mon = 11;
216   t.tm_mday = 31;
217   // UTC does not observe DST
218   t.tm_isdst = 1;
219 
220   errno = 0;
221 
222   EXPECT_EQ(static_cast<time_t>(-1), mktime(&t));
223   // mktime sets errno to EOVERFLOW if result is unrepresentable.
224   EXPECT_ERRNO(EOVERFLOW);
225 }
226 
227 // Transitions in the tzdata file are generated up to the year 2100. Testing
228 // that dates beyond that are handled properly too.
TEST(time,mktime_after_2100)229 TEST(time, mktime_after_2100) {
230   struct tm tm = {.tm_year = 2150 - 1900, .tm_mon = 2, .tm_mday = 10, .tm_isdst = -1};
231 
232 #if !defined(__LP64__)
233   // 32-bit bionic has a signed 32-bit time_t.
234   ASSERT_EQ(-1, mktime(&tm));
235   ASSERT_ERRNO(EOVERFLOW);
236 #else
237   setenv("TZ", "Europe/London", 1);
238   tzset();
239   errno = 0;
240   ASSERT_EQ(static_cast<time_t>(5686156800U), mktime(&tm));
241   ASSERT_ERRNO(0);
242 #endif
243 }
244 
TEST(time,strftime)245 TEST(time, strftime) {
246   setenv("TZ", "UTC", 1);
247 
248   struct tm t = {};
249   t.tm_year = 200;
250   t.tm_mon = 2;
251   t.tm_mday = 10;
252 
253   char buf[64];
254 
255   // Seconds since the epoch.
256 #if defined(__BIONIC__) || defined(__LP64__) // Not 32-bit glibc.
257   EXPECT_EQ(10U, strftime(buf, sizeof(buf), "%s", &t));
258   EXPECT_STREQ("4108320000", buf);
259 #endif
260 
261   // Date and time as text.
262   EXPECT_EQ(24U, strftime(buf, sizeof(buf), "%c", &t));
263   EXPECT_STREQ("Sun Mar 10 00:00:00 2100", buf);
264 }
265 
TEST(time,strftime_second_before_epoch)266 TEST(time, strftime_second_before_epoch) {
267   setenv("TZ", "UTC", 1);
268 
269   struct tm t = {};
270   t.tm_year = 1969 - 1900;
271   t.tm_mon = 11;
272   t.tm_mday = 31;
273   t.tm_hour = 23;
274   t.tm_min = 59;
275   t.tm_sec = 59;
276 
277   char buf[64];
278 
279   EXPECT_EQ(2U, strftime(buf, sizeof(buf), "%s", &t));
280   EXPECT_STREQ("-1", buf);
281 }
282 
TEST(time,strftime_Z_null_tm_zone)283 TEST(time, strftime_Z_null_tm_zone) {
284   // Netflix on Nexus Player wouldn't start (http://b/25170306).
285   struct tm t = {};
286   char buf[64];
287 
288   setenv("TZ", "America/Los_Angeles", 1);
289   tzset();
290 
291   t.tm_isdst = 0; // "0 if Daylight Savings Time is not in effect".
292   EXPECT_EQ(5U, strftime(buf, sizeof(buf), "<%Z>", &t));
293   EXPECT_STREQ("<PST>", buf);
294 
295 #if defined(__BIONIC__) // glibc 2.19 only copes with tm_isdst being 0 and 1.
296   t.tm_isdst = 2; // "positive if Daylight Savings Time is in effect"
297   EXPECT_EQ(5U, strftime(buf, sizeof(buf), "<%Z>", &t));
298   EXPECT_STREQ("<PDT>", buf);
299 
300   t.tm_isdst = -123; // "and negative if the information is not available".
301   EXPECT_EQ(2U, strftime(buf, sizeof(buf), "<%Z>", &t));
302   EXPECT_STREQ("<>", buf);
303 #endif
304 
305   setenv("TZ", "UTC", 1);
306   tzset();
307 
308   t.tm_isdst = 0;
309   EXPECT_EQ(5U, strftime(buf, sizeof(buf), "<%Z>", &t));
310   EXPECT_STREQ("<UTC>", buf);
311 
312 #if defined(__BIONIC__) // glibc 2.19 thinks UTC DST is "UTC".
313   t.tm_isdst = 1; // UTC has no DST.
314   EXPECT_EQ(2U, strftime(buf, sizeof(buf), "<%Z>", &t));
315   EXPECT_STREQ("<>", buf);
316 #endif
317 }
318 
319 // According to C language specification the only tm struct field needed to
320 // find out replacement for %z and %Z in strftime is tm_isdst. Which is
321 // wrong, as timezones change their standard offset and even DST savings.
322 // tzcode deviates from C language specification and requires tm struct either
323 // to be output of localtime-like functions or to be modified by mktime call
324 // before passing to strftime. See tz mailing discussion for more details
325 // https://mm.icann.org/pipermail/tz/2022-July/031674.html
326 // But we are testing case when tm.tm_zone is null, which means that tm struct
327 // is not coming from localtime and is neither modified by mktime. That's why
328 // we are comparing against +0000, even though America/Los_Angeles never
329 // observes it.
TEST(time,strftime_z_null_tm_zone)330 TEST(time, strftime_z_null_tm_zone) {
331   char str[64];
332   struct tm tm = {.tm_year = 109, .tm_mon = 4, .tm_mday = 2, .tm_isdst = 0};
333 
334   setenv("TZ", "America/Los_Angeles", 1);
335   tzset();
336 
337   tm.tm_zone = NULL;
338 
339   size_t result = strftime(str, sizeof(str), "%z", &tm);
340 
341   EXPECT_EQ(5U, result);
342   EXPECT_STREQ("+0000", str);
343 
344   tm.tm_isdst = 1;
345 
346   result = strftime(str, sizeof(str), "%z", &tm);
347 
348   EXPECT_EQ(5U, result);
349   EXPECT_STREQ("+0000", str);
350 
351   setenv("TZ", "UTC", 1);
352   tzset();
353 
354   tm.tm_isdst = 0;
355 
356   result = strftime(str, sizeof(str), "%z", &tm);
357 
358   EXPECT_EQ(5U, result);
359   EXPECT_STREQ("+0000", str);
360 
361   tm.tm_isdst = 1;
362 
363   result = strftime(str, sizeof(str), "%z", &tm);
364 
365   EXPECT_EQ(5U, result);
366   EXPECT_STREQ("+0000", str);
367 }
368 
TEST(time,strftime_z_Europe_Lisbon)369 TEST(time, strftime_z_Europe_Lisbon) {
370   char str[64];
371   // During 1992-1996 Europe/Lisbon standard offset was 1 hour.
372   // tm_isdst is not set as it will be overridden by mktime call anyway.
373   struct tm tm = {.tm_year = 1996 - 1900, .tm_mon = 2, .tm_mday = 13};
374 
375   setenv("TZ", "Europe/Lisbon", 1);
376   tzset();
377 
378   // tzcode's strftime implementation for %z relies on prior mktime call.
379   // At the moment of writing %z value is taken from tm_gmtoff. So without
380   // mktime call %z is replaced with +0000.
381   // See https://mm.icann.org/pipermail/tz/2022-July/031674.html
382   mktime(&tm);
383 
384   size_t result = strftime(str, sizeof(str), "%z", &tm);
385 
386   EXPECT_EQ(5U, result);
387   EXPECT_STREQ("+0100", str);
388 
389   // Now standard offset is 0.
390   tm = {.tm_year = 2022 - 1900, .tm_mon = 2, .tm_mday = 13};
391 
392   mktime(&tm);
393   result = strftime(str, sizeof(str), "%z", &tm);
394 
395   EXPECT_EQ(5U, result);
396   EXPECT_STREQ("+0000", str);
397 }
398 
TEST(time,strftime_l)399 TEST(time, strftime_l) {
400   locale_t cloc = newlocale(LC_ALL, "C.UTF-8", nullptr);
401   locale_t old_locale = uselocale(cloc);
402 
403   setenv("TZ", "UTC", 1);
404 
405   struct tm t = {};
406   t.tm_year = 200;
407   t.tm_mon = 2;
408   t.tm_mday = 10;
409 
410   // Date and time as text.
411   char buf[64];
412   EXPECT_EQ(24U, strftime_l(buf, sizeof(buf), "%c", &t, cloc));
413   EXPECT_STREQ("Sun Mar 10 00:00:00 2100", buf);
414 
415   uselocale(old_locale);
416   freelocale(cloc);
417 }
418 
TEST(time,strptime)419 TEST(time, strptime) {
420   setenv("TZ", "UTC", 1);
421 
422   struct tm t = {};
423   char buf[64];
424 
425   strptime("11:14", "%R", &t);
426   strftime(buf, sizeof(buf), "%H:%M", &t);
427   EXPECT_STREQ("11:14", buf);
428 
429   t = {};
430   strptime("09:41:53", "%T", &t);
431   strftime(buf, sizeof(buf), "%H:%M:%S", &t);
432   EXPECT_STREQ("09:41:53", buf);
433 }
434 
TEST(time,strptime_l)435 TEST(time, strptime_l) {
436 #if !defined(ANDROID_HOST_MUSL)
437   setenv("TZ", "UTC", 1);
438 
439   struct tm t = {};
440   char buf[64];
441 
442   strptime_l("11:14", "%R", &t, LC_GLOBAL_LOCALE);
443   strftime_l(buf, sizeof(buf), "%H:%M", &t, LC_GLOBAL_LOCALE);
444   EXPECT_STREQ("11:14", buf);
445 
446   t = {};
447   strptime_l("09:41:53", "%T", &t, LC_GLOBAL_LOCALE);
448   strftime_l(buf, sizeof(buf), "%H:%M:%S", &t, LC_GLOBAL_LOCALE);
449   EXPECT_STREQ("09:41:53", buf);
450 #else
451   GTEST_SKIP() << "musl doesn't support strptime_l";
452 #endif
453 }
454 
TEST(time,strptime_F)455 TEST(time, strptime_F) {
456   setenv("TZ", "UTC", 1);
457 
458   struct tm tm = {};
459   ASSERT_EQ('\0', *strptime("2019-03-26", "%F", &tm));
460   EXPECT_EQ(119, tm.tm_year);
461   EXPECT_EQ(2, tm.tm_mon);
462   EXPECT_EQ(26, tm.tm_mday);
463 }
464 
TEST(time,strptime_P_p)465 TEST(time, strptime_P_p) {
466   setenv("TZ", "UTC", 1);
467 
468   // For parsing, %P and %p are the same: case doesn't matter.
469 
470   struct tm tm = {.tm_hour = 12};
471   ASSERT_EQ('\0', *strptime("AM", "%p", &tm));
472   EXPECT_EQ(0, tm.tm_hour);
473 
474   tm = {.tm_hour = 12};
475   ASSERT_EQ('\0', *strptime("am", "%p", &tm));
476   EXPECT_EQ(0, tm.tm_hour);
477 
478   tm = {.tm_hour = 12};
479   ASSERT_EQ('\0', *strptime("AM", "%P", &tm));
480   EXPECT_EQ(0, tm.tm_hour);
481 
482   tm = {.tm_hour = 12};
483   ASSERT_EQ('\0', *strptime("am", "%P", &tm));
484   EXPECT_EQ(0, tm.tm_hour);
485 }
486 
TEST(time,strptime_u)487 TEST(time, strptime_u) {
488   setenv("TZ", "UTC", 1);
489 
490   struct tm tm = {};
491   ASSERT_EQ('\0', *strptime("2", "%u", &tm));
492   EXPECT_EQ(2, tm.tm_wday);
493 }
494 
TEST(time,strptime_v)495 TEST(time, strptime_v) {
496   setenv("TZ", "UTC", 1);
497 
498   struct tm tm = {};
499   ASSERT_EQ('\0', *strptime("26-Mar-1980", "%v", &tm));
500   EXPECT_EQ(80, tm.tm_year);
501   EXPECT_EQ(2, tm.tm_mon);
502   EXPECT_EQ(26, tm.tm_mday);
503 }
504 
TEST(time,strptime_V_G_g)505 TEST(time, strptime_V_G_g) {
506   setenv("TZ", "UTC", 1);
507 
508   // %V (ISO-8601 week number), %G (year of week number, without century), and
509   // %g (year of week number) have no effect when parsed, and are supported
510   // solely so that it's possible for strptime(3) to parse everything that
511   // strftime(3) can output.
512   struct tm tm = {};
513   ASSERT_EQ('\0', *strptime("1 2 3", "%V %G %g", &tm));
514   struct tm zero = {};
515   EXPECT_TRUE(memcmp(&tm, &zero, sizeof(tm)) == 0);
516 }
517 
TEST(time,strptime_Z)518 TEST(time, strptime_Z) {
519 #if defined(__BIONIC__)
520   // glibc doesn't handle %Z at all.
521   // The BSDs only handle hard-coded "GMT" and "UTC", plus whatever two strings
522   // are in the global `tzname` (which correspond to the current $TZ).
523   struct tm tm;
524   setenv("TZ", "Europe/Berlin", 1);
525 
526   // "GMT" always works.
527   tm = {};
528   ASSERT_EQ('\0', *strptime("GMT", "%Z", &tm));
529   EXPECT_STREQ("GMT", tm.tm_zone);
530   EXPECT_EQ(0, tm.tm_isdst);
531   EXPECT_EQ(0, tm.tm_gmtoff);
532 
533   // As does "UTC".
534   tm = {};
535   ASSERT_EQ('\0', *strptime("UTC", "%Z", &tm));
536   EXPECT_STREQ("UTC", tm.tm_zone);
537   EXPECT_EQ(0, tm.tm_isdst);
538   EXPECT_EQ(0, tm.tm_gmtoff);
539 
540   // Europe/Berlin is known as "CET" when there's no DST.
541   tm = {};
542   ASSERT_EQ('\0', *strptime("CET", "%Z", &tm));
543   EXPECT_STREQ("CET", tm.tm_zone);
544   EXPECT_EQ(0, tm.tm_isdst);
545   EXPECT_EQ(3600, tm.tm_gmtoff);
546 
547   // Europe/Berlin is known as "CEST" when there's no DST.
548   tm = {};
549   ASSERT_EQ('\0', *strptime("CEST", "%Z", &tm));
550   EXPECT_STREQ("CEST", tm.tm_zone);
551   EXPECT_EQ(1, tm.tm_isdst);
552   EXPECT_EQ(3600, tm.tm_gmtoff);
553 
554   // And as long as we're in Europe/Berlin, those are the only timezone
555   // abbreviations that are recognized.
556   tm = {};
557   ASSERT_TRUE(strptime("PDT", "%Z", &tm) == nullptr);
558 #endif
559 }
560 
TEST(time,strptime_z)561 TEST(time, strptime_z) {
562   struct tm tm;
563   setenv("TZ", "Europe/Berlin", 1);
564 
565   // "UT" is what RFC822 called UTC.
566   tm = {};
567   ASSERT_EQ('\0', *strptime("UT", "%z", &tm));
568   EXPECT_STREQ("UTC", tm.tm_zone);
569   EXPECT_EQ(0, tm.tm_isdst);
570   EXPECT_EQ(0, tm.tm_gmtoff);
571   // "GMT" is RFC822's other name for UTC.
572   tm = {};
573   ASSERT_EQ('\0', *strptime("GMT", "%z", &tm));
574   EXPECT_STREQ("UTC", tm.tm_zone);
575   EXPECT_EQ(0, tm.tm_isdst);
576   EXPECT_EQ(0, tm.tm_gmtoff);
577 
578   // "Z" ("Zulu") is a synonym for UTC.
579   tm = {};
580   ASSERT_EQ('\0', *strptime("Z", "%z", &tm));
581   EXPECT_STREQ("UTC", tm.tm_zone);
582   EXPECT_EQ(0, tm.tm_isdst);
583   EXPECT_EQ(0, tm.tm_gmtoff);
584 
585   // "PST"/"PDT" and the other common US zone abbreviations are all supported.
586   tm = {};
587   ASSERT_EQ('\0', *strptime("PST", "%z", &tm));
588   EXPECT_STREQ("PST", tm.tm_zone);
589   EXPECT_EQ(0, tm.tm_isdst);
590   EXPECT_EQ(-28800, tm.tm_gmtoff);
591   tm = {};
592   ASSERT_EQ('\0', *strptime("PDT", "%z", &tm));
593   EXPECT_STREQ("PDT", tm.tm_zone);
594   EXPECT_EQ(1, tm.tm_isdst);
595   EXPECT_EQ(-25200, tm.tm_gmtoff);
596 
597   // +-hh
598   tm = {};
599   ASSERT_EQ('\0', *strptime("+01", "%z", &tm));
600   EXPECT_EQ(3600, tm.tm_gmtoff);
601   EXPECT_TRUE(tm.tm_zone == nullptr);
602   EXPECT_EQ(0, tm.tm_isdst);
603   // +-hhmm
604   tm = {};
605   ASSERT_EQ('\0', *strptime("+0130", "%z", &tm));
606   EXPECT_EQ(5400, tm.tm_gmtoff);
607   EXPECT_TRUE(tm.tm_zone == nullptr);
608   EXPECT_EQ(0, tm.tm_isdst);
609   // +-hh:mm
610   tm = {};
611   ASSERT_EQ('\0', *strptime("+01:30", "%z", &tm));
612   EXPECT_EQ(5400, tm.tm_gmtoff);
613   EXPECT_TRUE(tm.tm_zone == nullptr);
614   EXPECT_EQ(0, tm.tm_isdst);
615 }
616 
SetTime(timer_t t,time_t value_s,time_t value_ns,time_t interval_s,time_t interval_ns)617 void SetTime(timer_t t, time_t value_s, time_t value_ns, time_t interval_s, time_t interval_ns) {
618   itimerspec ts;
619   ts.it_value.tv_sec = value_s;
620   ts.it_value.tv_nsec = value_ns;
621   ts.it_interval.tv_sec = interval_s;
622   ts.it_interval.tv_nsec = interval_ns;
623   ASSERT_EQ(0, timer_settime(t, 0, &ts, nullptr));
624 }
625 
NoOpNotifyFunction(sigval)626 static void NoOpNotifyFunction(sigval) {
627 }
628 
TEST(time,timer_create)629 TEST(time, timer_create) {
630   sigevent se = {};
631   se.sigev_notify = SIGEV_THREAD;
632   se.sigev_notify_function = NoOpNotifyFunction;
633   timer_t timer_id;
634   ASSERT_EQ(0, timer_create(CLOCK_MONOTONIC, &se, &timer_id));
635 
636   pid_t pid = fork();
637   ASSERT_NE(-1, pid) << strerror(errno);
638 
639   if (pid == 0) {
640     // Timers are not inherited by the child.
641     ASSERT_EQ(-1, timer_delete(timer_id));
642     ASSERT_ERRNO(EINVAL);
643     _exit(0);
644   }
645 
646   AssertChildExited(pid, 0);
647 
648   ASSERT_EQ(0, timer_delete(timer_id));
649 }
650 
651 static int timer_create_SIGEV_SIGNAL_signal_handler_invocation_count;
timer_create_SIGEV_SIGNAL_signal_handler(int signal_number)652 static void timer_create_SIGEV_SIGNAL_signal_handler(int signal_number) {
653   ++timer_create_SIGEV_SIGNAL_signal_handler_invocation_count;
654   ASSERT_EQ(SIGUSR1, signal_number);
655 }
656 
TEST(time,timer_create_SIGEV_SIGNAL)657 TEST(time, timer_create_SIGEV_SIGNAL) {
658   sigevent se = {};
659   se.sigev_notify = SIGEV_SIGNAL;
660   se.sigev_signo = SIGUSR1;
661 
662   timer_t timer_id;
663   ASSERT_EQ(0, timer_create(CLOCK_MONOTONIC, &se, &timer_id));
664 
665   timer_create_SIGEV_SIGNAL_signal_handler_invocation_count = 0;
666   ScopedSignalHandler ssh(SIGUSR1, timer_create_SIGEV_SIGNAL_signal_handler);
667 
668   ASSERT_EQ(0, timer_create_SIGEV_SIGNAL_signal_handler_invocation_count);
669 
670   itimerspec ts;
671   ts.it_value.tv_sec =  0;
672   ts.it_value.tv_nsec = 1;
673   ts.it_interval.tv_sec = 0;
674   ts.it_interval.tv_nsec = 0;
675   ASSERT_EQ(0, timer_settime(timer_id, 0, &ts, nullptr));
676 
677   usleep(500000);
678   ASSERT_EQ(1, timer_create_SIGEV_SIGNAL_signal_handler_invocation_count);
679 }
680 
681 struct Counter {
682  private:
683   std::atomic<int> value;
684   timer_t timer_id;
685   sigevent se;
686   bool timer_valid;
687 
CreateCounter688   void Create() {
689     ASSERT_FALSE(timer_valid);
690     ASSERT_EQ(0, timer_create(CLOCK_REALTIME, &se, &timer_id));
691     timer_valid = true;
692   }
693 
694  public:
CounterCounter695   explicit Counter(void (*fn)(sigval)) : value(0), timer_valid(false) {
696     se = {.sigev_notify = SIGEV_THREAD, .sigev_notify_function = fn, .sigev_value.sival_ptr = this};
697     Create();
698   }
DeleteTimerCounter699   void DeleteTimer() {
700     ASSERT_TRUE(timer_valid);
701     ASSERT_EQ(0, timer_delete(timer_id));
702     timer_valid = false;
703   }
704 
~CounterCounter705   ~Counter() {
706     if (timer_valid) {
707       DeleteTimer();
708     }
709   }
710 
ValueCounter711   int Value() const {
712     return value;
713   }
714 
SetTimeCounter715   void SetTime(time_t value_s, time_t value_ns, time_t interval_s, time_t interval_ns) {
716     ::SetTime(timer_id, value_s, value_ns, interval_s, interval_ns);
717   }
718 
ValueUpdatedCounter719   bool ValueUpdated() {
720     int current_value = value;
721     time_t start = time(nullptr);
722     while (current_value == value && (time(nullptr) - start) < 5) {
723     }
724     return current_value != value;
725   }
726 
CountNotifyFunctionCounter727   static void CountNotifyFunction(sigval value) {
728     Counter* cd = reinterpret_cast<Counter*>(value.sival_ptr);
729     ++cd->value;
730   }
731 
CountAndDisarmNotifyFunctionCounter732   static void CountAndDisarmNotifyFunction(sigval value) {
733     Counter* cd = reinterpret_cast<Counter*>(value.sival_ptr);
734     ++cd->value;
735 
736     // Setting the initial expiration time to 0 disarms the timer.
737     cd->SetTime(0, 0, 1, 0);
738   }
739 };
740 
TEST(time,timer_settime_0)741 TEST(time, timer_settime_0) {
742   Counter counter(Counter::CountAndDisarmNotifyFunction);
743   ASSERT_EQ(0, counter.Value());
744 
745   counter.SetTime(0, 500000000, 1, 0);
746   sleep(1);
747 
748   // The count should just be 1 because we disarmed the timer the first time it fired.
749   ASSERT_EQ(1, counter.Value());
750 }
751 
TEST(time,timer_settime_repeats)752 TEST(time, timer_settime_repeats) {
753   Counter counter(Counter::CountNotifyFunction);
754   ASSERT_EQ(0, counter.Value());
755 
756   counter.SetTime(0, 1, 0, 10);
757   ASSERT_TRUE(counter.ValueUpdated());
758   ASSERT_TRUE(counter.ValueUpdated());
759   ASSERT_TRUE(counter.ValueUpdated());
760   counter.DeleteTimer();
761   // Add a sleep as other threads may be calling the callback function when the timer is deleted.
762   usleep(500000);
763 }
764 
765 static int timer_create_NULL_signal_handler_invocation_count;
timer_create_NULL_signal_handler(int signal_number)766 static void timer_create_NULL_signal_handler(int signal_number) {
767   ++timer_create_NULL_signal_handler_invocation_count;
768   ASSERT_EQ(SIGALRM, signal_number);
769 }
770 
TEST(time,timer_create_NULL)771 TEST(time, timer_create_NULL) {
772   // A NULL sigevent* is equivalent to asking for SIGEV_SIGNAL for SIGALRM.
773   timer_t timer_id;
774   ASSERT_EQ(0, timer_create(CLOCK_MONOTONIC, nullptr, &timer_id));
775 
776   timer_create_NULL_signal_handler_invocation_count = 0;
777   ScopedSignalHandler ssh(SIGALRM, timer_create_NULL_signal_handler);
778 
779   ASSERT_EQ(0, timer_create_NULL_signal_handler_invocation_count);
780 
781   SetTime(timer_id, 0, 1, 0, 0);
782   usleep(500000);
783 
784   ASSERT_EQ(1, timer_create_NULL_signal_handler_invocation_count);
785 }
786 
GetThreadCount()787 static int GetThreadCount() {
788   std::string status;
789   if (android::base::ReadFileToString("/proc/self/status", &status)) {
790     for (const auto& line : android::base::Split(status, "\n")) {
791       int thread_count;
792       if (sscanf(line.c_str(), "Threads: %d", &thread_count) == 1) {
793         return thread_count;
794       }
795     }
796   }
797   return -1;
798 }
799 
TEST(time,timer_create_EINVAL)800 TEST(time, timer_create_EINVAL) {
801   const clockid_t kInvalidClock = 16;
802 
803   // A SIGEV_SIGNAL timer failure is easy; that's the kernel's problem.
804   timer_t timer_id;
805   ASSERT_EQ(-1, timer_create(kInvalidClock, nullptr, &timer_id));
806   ASSERT_ERRNO(EINVAL);
807 
808   // A SIGEV_THREAD timer failure is more interesting because we have a thread
809   // to clean up (https://issuetracker.google.com/340125671).
810   sigevent se = {};
811   se.sigev_notify = SIGEV_THREAD;
812   se.sigev_notify_function = NoOpNotifyFunction;
813   ASSERT_EQ(-1, timer_create(kInvalidClock, &se, &timer_id));
814   ASSERT_ERRNO(EINVAL);
815 
816   // timer_create() doesn't guarantee that the thread will be dead _before_
817   // it returns because that would require extra synchronization that's
818   // unnecessary in the normal (successful) case. A timeout here means we
819   // leaked a thread.
820   while (GetThreadCount() > 1) {
821   }
822 }
823 
TEST(time,timer_create_multiple)824 TEST(time, timer_create_multiple) {
825   Counter counter1(Counter::CountNotifyFunction);
826   Counter counter2(Counter::CountNotifyFunction);
827   Counter counter3(Counter::CountNotifyFunction);
828 
829   ASSERT_EQ(0, counter1.Value());
830   ASSERT_EQ(0, counter2.Value());
831   ASSERT_EQ(0, counter3.Value());
832 
833   counter2.SetTime(0, 500000000, 0, 0);
834   sleep(1);
835 
836   EXPECT_EQ(0, counter1.Value());
837   EXPECT_EQ(1, counter2.Value());
838   EXPECT_EQ(0, counter3.Value());
839 }
840 
841 // Test to verify that disarming a repeatable timer disables the callbacks.
TEST(time,timer_disarm_terminates)842 TEST(time, timer_disarm_terminates) {
843   Counter counter(Counter::CountNotifyFunction);
844   ASSERT_EQ(0, counter.Value());
845 
846   counter.SetTime(0, 1, 0, 1);
847   ASSERT_TRUE(counter.ValueUpdated());
848   ASSERT_TRUE(counter.ValueUpdated());
849   ASSERT_TRUE(counter.ValueUpdated());
850 
851   counter.SetTime(0, 0, 0, 0);
852   // Add a sleep as the kernel may have pending events when the timer is disarmed.
853   usleep(500000);
854   int value = counter.Value();
855   usleep(500000);
856 
857   // Verify the counter has not been incremented.
858   ASSERT_EQ(value, counter.Value());
859 }
860 
861 // Test to verify that deleting a repeatable timer disables the callbacks.
TEST(time,timer_delete_terminates)862 TEST(time, timer_delete_terminates) {
863   Counter counter(Counter::CountNotifyFunction);
864   ASSERT_EQ(0, counter.Value());
865 
866   counter.SetTime(0, 1, 0, 1);
867   ASSERT_TRUE(counter.ValueUpdated());
868   ASSERT_TRUE(counter.ValueUpdated());
869   ASSERT_TRUE(counter.ValueUpdated());
870 
871   counter.DeleteTimer();
872   // Add a sleep as other threads may be calling the callback function when the timer is deleted.
873   usleep(500000);
874   int value = counter.Value();
875   usleep(500000);
876 
877   // Verify the counter has not been incremented.
878   ASSERT_EQ(value, counter.Value());
879 }
880 
881 struct TimerDeleteData {
882   timer_t timer_id;
883   pid_t tid;
884   volatile bool complete;
885 };
886 
TimerDeleteCallback(sigval value)887 static void TimerDeleteCallback(sigval value) {
888   TimerDeleteData* tdd = reinterpret_cast<TimerDeleteData*>(value.sival_ptr);
889 
890   tdd->tid = gettid();
891   timer_delete(tdd->timer_id);
892   tdd->complete = true;
893 }
894 
TEST(time,timer_delete_from_timer_thread)895 TEST(time, timer_delete_from_timer_thread) {
896   TimerDeleteData tdd;
897   sigevent se = {};
898   se.sigev_notify = SIGEV_THREAD;
899   se.sigev_notify_function = TimerDeleteCallback;
900   se.sigev_value.sival_ptr = &tdd;
901 
902   tdd.complete = false;
903   ASSERT_EQ(0, timer_create(CLOCK_REALTIME, &se, &tdd.timer_id));
904 
905   itimerspec ts;
906   ts.it_value.tv_sec = 1;
907   ts.it_value.tv_nsec = 0;
908   ts.it_interval.tv_sec = 0;
909   ts.it_interval.tv_nsec = 0;
910   ASSERT_EQ(0, timer_settime(tdd.timer_id, 0, &ts, nullptr));
911 
912   time_t cur_time = time(nullptr);
913   while (!tdd.complete && (time(nullptr) - cur_time) < 5);
914   ASSERT_TRUE(tdd.complete);
915 
916 #if defined(__BIONIC__)
917   // Since bionic timers are implemented by creating a thread to handle the
918   // callback, verify that the thread actually completes.
919   cur_time = time(NULL);
920   while ((kill(tdd.tid, 0) != -1 || errno != ESRCH) && (time(NULL) - cur_time) < 5);
921   ASSERT_EQ(-1, kill(tdd.tid, 0));
922   ASSERT_ERRNO(ESRCH);
923 #endif
924 }
925 
926 // Musl doesn't define __NR_clock_gettime on 32-bit architectures.
927 #if !defined(__NR_clock_gettime)
928 #define __NR_clock_gettime __NR_clock_gettime32
929 #endif
930 
TEST(time,clock_gettime)931 TEST(time, clock_gettime) {
932   // Try to ensure that our vdso clock_gettime is working.
933   timespec ts0;
934   timespec ts1;
935   timespec ts2;
936   ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts0));
937   ASSERT_EQ(0, syscall(__NR_clock_gettime, CLOCK_MONOTONIC, &ts1));
938   ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts2));
939 
940   // Check we have a nice monotonic timestamp sandwich.
941   ASSERT_LE(ts0.tv_sec, ts1.tv_sec);
942   if (ts0.tv_sec == ts1.tv_sec) {
943     ASSERT_LE(ts0.tv_nsec, ts1.tv_nsec);
944   }
945   ASSERT_LE(ts1.tv_sec, ts2.tv_sec);
946   if (ts1.tv_sec == ts2.tv_sec) {
947     ASSERT_LE(ts1.tv_nsec, ts2.tv_nsec);
948   }
949 }
950 
TEST(time,clock_gettime_CLOCK_REALTIME)951 TEST(time, clock_gettime_CLOCK_REALTIME) {
952   timespec ts;
953   ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
954 }
955 
TEST(time,clock_gettime_CLOCK_MONOTONIC)956 TEST(time, clock_gettime_CLOCK_MONOTONIC) {
957   timespec ts;
958   ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
959 }
960 
TEST(time,clock_gettime_CLOCK_PROCESS_CPUTIME_ID)961 TEST(time, clock_gettime_CLOCK_PROCESS_CPUTIME_ID) {
962   timespec ts;
963   ASSERT_EQ(0, clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts));
964 }
965 
TEST(time,clock_gettime_CLOCK_THREAD_CPUTIME_ID)966 TEST(time, clock_gettime_CLOCK_THREAD_CPUTIME_ID) {
967   timespec ts;
968   ASSERT_EQ(0, clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts));
969 }
970 
TEST(time,clock_gettime_CLOCK_BOOTTIME)971 TEST(time, clock_gettime_CLOCK_BOOTTIME) {
972   timespec ts;
973   ASSERT_EQ(0, clock_gettime(CLOCK_BOOTTIME, &ts));
974 }
975 
TEST(time,clock_gettime_unknown)976 TEST(time, clock_gettime_unknown) {
977   errno = 0;
978   timespec ts;
979   ASSERT_EQ(-1, clock_gettime(-1, &ts));
980   ASSERT_ERRNO(EINVAL);
981 }
982 
TEST(time,clock_getres_CLOCK_REALTIME)983 TEST(time, clock_getres_CLOCK_REALTIME) {
984   timespec ts;
985   ASSERT_EQ(0, clock_getres(CLOCK_REALTIME, &ts));
986   ASSERT_EQ(1, ts.tv_nsec);
987   ASSERT_EQ(0, ts.tv_sec);
988 }
989 
TEST(time,clock_getres_CLOCK_MONOTONIC)990 TEST(time, clock_getres_CLOCK_MONOTONIC) {
991   timespec ts;
992   ASSERT_EQ(0, clock_getres(CLOCK_MONOTONIC, &ts));
993   ASSERT_EQ(1, ts.tv_nsec);
994   ASSERT_EQ(0, ts.tv_sec);
995 }
996 
TEST(time,clock_getres_CLOCK_PROCESS_CPUTIME_ID)997 TEST(time, clock_getres_CLOCK_PROCESS_CPUTIME_ID) {
998   timespec ts;
999   ASSERT_EQ(0, clock_getres(CLOCK_PROCESS_CPUTIME_ID, &ts));
1000 }
1001 
TEST(time,clock_getres_CLOCK_THREAD_CPUTIME_ID)1002 TEST(time, clock_getres_CLOCK_THREAD_CPUTIME_ID) {
1003   timespec ts;
1004   ASSERT_EQ(0, clock_getres(CLOCK_THREAD_CPUTIME_ID, &ts));
1005 }
1006 
TEST(time,clock_getres_CLOCK_BOOTTIME)1007 TEST(time, clock_getres_CLOCK_BOOTTIME) {
1008   timespec ts;
1009   ASSERT_EQ(0, clock_getres(CLOCK_BOOTTIME, &ts));
1010   ASSERT_EQ(1, ts.tv_nsec);
1011   ASSERT_EQ(0, ts.tv_sec);
1012 }
1013 
TEST(time,clock_getres_unknown)1014 TEST(time, clock_getres_unknown) {
1015   errno = 0;
1016   timespec ts = { -1, -1 };
1017   ASSERT_EQ(-1, clock_getres(-1, &ts));
1018   ASSERT_ERRNO(EINVAL);
1019   ASSERT_EQ(-1, ts.tv_nsec);
1020   ASSERT_EQ(-1, ts.tv_sec);
1021 }
1022 
TEST(time,clock_getres_null_resolution)1023 TEST(time, clock_getres_null_resolution) {
1024   ASSERT_EQ(0, clock_getres(CLOCK_REALTIME, nullptr));
1025 }
1026 
TEST(time,clock)1027 TEST(time, clock) {
1028   // clock(3) is hard to test, but a 1s sleep should cost less than 10ms on average.
1029   static const clock_t N = 5;
1030   static const clock_t mean_limit_ms = 10;
1031   clock_t t0 = clock();
1032   for (size_t i = 0; i < N; ++i) {
1033     sleep(1);
1034   }
1035   clock_t t1 = clock();
1036   ASSERT_LT(t1 - t0, N * mean_limit_ms * (CLOCKS_PER_SEC / 1000));
1037 }
1038 
GetInvalidPid()1039 static pid_t GetInvalidPid() {
1040   std::unique_ptr<FILE, decltype(&fclose)> fp{fopen("/proc/sys/kernel/pid_max", "r"), fclose};
1041   long pid_max;
1042   fscanf(fp.get(), "%ld", &pid_max);
1043   return static_cast<pid_t>(pid_max + 1);
1044 }
1045 
TEST(time,clock_getcpuclockid_current)1046 TEST(time, clock_getcpuclockid_current) {
1047   clockid_t clockid;
1048   ASSERT_EQ(0, clock_getcpuclockid(getpid(), &clockid));
1049   timespec ts;
1050   ASSERT_EQ(0, clock_gettime(clockid, &ts));
1051 }
1052 
TEST(time,clock_getcpuclockid_parent)1053 TEST(time, clock_getcpuclockid_parent) {
1054   clockid_t clockid;
1055   ASSERT_EQ(0, clock_getcpuclockid(getppid(), &clockid));
1056   timespec ts;
1057   ASSERT_EQ(0, clock_gettime(clockid, &ts));
1058 }
1059 
TEST(time,clock_getcpuclockid_ESRCH)1060 TEST(time, clock_getcpuclockid_ESRCH) {
1061   // We can't use -1 for invalid pid here, because clock_getcpuclockid() can't detect it.
1062   errno = 0;
1063   // If this fails, your kernel needs commit e1b6b6ce to be backported.
1064   clockid_t clockid;
1065   ASSERT_EQ(ESRCH, clock_getcpuclockid(GetInvalidPid(), &clockid)) << "\n"
1066     << "Please ensure that the following kernel patches or their replacements have been applied:\n"
1067     << "* https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/"
1068     << "commit/?id=e1b6b6ce55a0a25c8aa8af019095253b2133a41a\n"
1069     << "* https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/"
1070     << "commit/?id=c80ed088a519da53f27b798a69748eaabc66aadf\n";
1071   ASSERT_ERRNO(0);
1072 }
1073 
TEST(time,clock_settime)1074 TEST(time, clock_settime) {
1075   errno = 0;
1076   timespec ts;
1077   ASSERT_EQ(-1, clock_settime(-1, &ts));
1078   ASSERT_ERRNO(EINVAL);
1079 }
1080 
TEST(time,clock_nanosleep_EINVAL)1081 TEST(time, clock_nanosleep_EINVAL) {
1082   timespec in;
1083   timespec out;
1084   ASSERT_EQ(EINVAL, clock_nanosleep(-1, 0, &in, &out));
1085 }
1086 
TEST(time,clock_nanosleep_thread_cputime_id)1087 TEST(time, clock_nanosleep_thread_cputime_id) {
1088   timespec in;
1089   in.tv_sec = 1;
1090   in.tv_nsec = 0;
1091   ASSERT_EQ(EINVAL, clock_nanosleep(CLOCK_THREAD_CPUTIME_ID, 0, &in, nullptr));
1092 }
1093 
TEST(time,clock_nanosleep)1094 TEST(time, clock_nanosleep) {
1095   auto t0 = std::chrono::steady_clock::now();
1096   const timespec ts = {.tv_nsec = 5000000};
1097   ASSERT_EQ(0, clock_nanosleep(CLOCK_MONOTONIC, 0, &ts, nullptr));
1098   auto t1 = std::chrono::steady_clock::now();
1099   ASSERT_GE(t1-t0, 5000000ns);
1100 }
1101 
TEST(time,nanosleep)1102 TEST(time, nanosleep) {
1103   auto t0 = std::chrono::steady_clock::now();
1104   const timespec ts = {.tv_nsec = 5000000};
1105   ASSERT_EQ(0, nanosleep(&ts, nullptr));
1106   auto t1 = std::chrono::steady_clock::now();
1107   ASSERT_GE(t1-t0, 5000000ns);
1108 }
1109 
TEST(time,nanosleep_EINVAL)1110 TEST(time, nanosleep_EINVAL) {
1111   timespec ts = {.tv_sec = -1};
1112   errno = 0;
1113   ASSERT_EQ(-1, nanosleep(&ts, nullptr));
1114   ASSERT_ERRNO(EINVAL);
1115 }
1116 
TEST(time,bug_31938693)1117 TEST(time, bug_31938693) {
1118   // User-visible symptoms in N:
1119   // http://b/31938693
1120   // https://code.google.com/p/android/issues/detail?id=225132
1121 
1122   // Actual underlying bug (the code change, not the tzdata upgrade that first exposed the bug):
1123   // http://b/31848040
1124 
1125   // This isn't a great test, because very few timezones were actually affected, and there's
1126   // no real logic to which ones were affected: it was just a coincidence of the data that came
1127   // after them in the tzdata file.
1128 
1129   time_t t = 1475619727;
1130   struct tm tm;
1131 
1132   setenv("TZ", "America/Los_Angeles", 1);
1133   tzset();
1134   ASSERT_TRUE(localtime_r(&t, &tm) != nullptr);
1135   EXPECT_EQ(15, tm.tm_hour);
1136 
1137   setenv("TZ", "Europe/London", 1);
1138   tzset();
1139   ASSERT_TRUE(localtime_r(&t, &tm) != nullptr);
1140   EXPECT_EQ(23, tm.tm_hour);
1141 
1142   setenv("TZ", "America/Atka", 1);
1143   tzset();
1144   ASSERT_TRUE(localtime_r(&t, &tm) != nullptr);
1145   EXPECT_EQ(13, tm.tm_hour);
1146 
1147   setenv("TZ", "Pacific/Apia", 1);
1148   tzset();
1149   ASSERT_TRUE(localtime_r(&t, &tm) != nullptr);
1150   EXPECT_EQ(12, tm.tm_hour);
1151 
1152   setenv("TZ", "Pacific/Honolulu", 1);
1153   tzset();
1154   ASSERT_TRUE(localtime_r(&t, &tm) != nullptr);
1155   EXPECT_EQ(12, tm.tm_hour);
1156 
1157   setenv("TZ", "Asia/Magadan", 1);
1158   tzset();
1159   ASSERT_TRUE(localtime_r(&t, &tm) != nullptr);
1160   EXPECT_EQ(9, tm.tm_hour);
1161 }
1162 
TEST(time,bug_31339449)1163 TEST(time, bug_31339449) {
1164   // POSIX says localtime acts as if it calls tzset.
1165   // tzset does two things:
1166   //  1. it sets the timezone ctime/localtime/mktime/strftime will use.
1167   //  2. it sets the global `tzname`.
1168   // POSIX says localtime_r need not set `tzname` (2).
1169   // Q: should localtime_r set the timezone (1)?
1170   // Upstream tzcode (and glibc) answer "no", everyone else answers "yes".
1171 
1172   // Pick a time, any time...
1173   time_t t = 1475619727;
1174 
1175   // Call tzset with a specific timezone.
1176   setenv("TZ", "America/Atka", 1);
1177   tzset();
1178 
1179   // If we change the timezone and call localtime, localtime should use the new timezone.
1180   setenv("TZ", "America/Los_Angeles", 1);
1181   struct tm* tm_p = localtime(&t);
1182   EXPECT_EQ(15, tm_p->tm_hour);
1183 
1184   // Reset the timezone back.
1185   setenv("TZ", "America/Atka", 1);
1186   tzset();
1187 
1188 #if defined(__BIONIC__)
1189   // If we change the timezone again and call localtime_r, localtime_r should use the new timezone.
1190   setenv("TZ", "America/Los_Angeles", 1);
1191   struct tm tm = {};
1192   localtime_r(&t, &tm);
1193   EXPECT_EQ(15, tm.tm_hour);
1194 #else
1195   // The BSDs agree with us, but glibc gets this wrong.
1196 #endif
1197 }
1198 
TEST(time,asctime)1199 TEST(time, asctime) {
1200   const struct tm tm = {};
1201   ASSERT_STREQ("Sun Jan  0 00:00:00 1900\n", asctime(&tm));
1202 }
1203 
TEST(time,asctime_r)1204 TEST(time, asctime_r) {
1205   const struct tm tm = {};
1206   char buf[256];
1207   ASSERT_EQ(buf, asctime_r(&tm, buf));
1208   ASSERT_STREQ("Sun Jan  0 00:00:00 1900\n", buf);
1209 }
1210 
TEST(time,ctime)1211 TEST(time, ctime) {
1212   setenv("TZ", "UTC", 1);
1213   const time_t t = 0;
1214   ASSERT_STREQ("Thu Jan  1 00:00:00 1970\n", ctime(&t));
1215 }
1216 
TEST(time,ctime_r)1217 TEST(time, ctime_r) {
1218   setenv("TZ", "UTC", 1);
1219   const time_t t = 0;
1220   char buf[256];
1221   ASSERT_EQ(buf, ctime_r(&t, buf));
1222   ASSERT_STREQ("Thu Jan  1 00:00:00 1970\n", buf);
1223 }
1224 
1225 // https://issuetracker.google.com/37128336
TEST(time,strftime_strptime_s)1226 TEST(time, strftime_strptime_s) {
1227   char buf[32];
1228   const struct tm tm0 = { .tm_year = 1982-1900, .tm_mon = 0, .tm_mday = 1 };
1229 
1230   setenv("TZ", "America/Los_Angeles", 1);
1231   strftime(buf, sizeof(buf), "<%s>", &tm0);
1232   EXPECT_STREQ("<378720000>", buf);
1233 
1234   setenv("TZ", "UTC", 1);
1235   strftime(buf, sizeof(buf), "<%s>", &tm0);
1236   EXPECT_STREQ("<378691200>", buf);
1237 
1238   setenv("TZ", "America/Los_Angeles", 1);
1239   tzset();
1240   struct tm tm = {};
1241   char* p = strptime("378720000x", "%s", &tm);
1242   ASSERT_EQ('x', *p);
1243   EXPECT_EQ(0, tm.tm_sec);
1244   EXPECT_EQ(0, tm.tm_min);
1245   EXPECT_EQ(0, tm.tm_hour);
1246   EXPECT_EQ(1, tm.tm_mday);
1247   EXPECT_EQ(0, tm.tm_mon);
1248   EXPECT_EQ(82, tm.tm_year);
1249   EXPECT_EQ(5, tm.tm_wday);
1250   EXPECT_EQ(0, tm.tm_yday);
1251   EXPECT_EQ(0, tm.tm_isdst);
1252 
1253   setenv("TZ", "UTC", 1);
1254   tzset();
1255   tm = {};
1256   p = strptime("378691200x", "%s", &tm);
1257   ASSERT_EQ('x', *p);
1258   EXPECT_EQ(0, tm.tm_sec);
1259   EXPECT_EQ(0, tm.tm_min);
1260   EXPECT_EQ(0, tm.tm_hour);
1261   EXPECT_EQ(1, tm.tm_mday);
1262   EXPECT_EQ(0, tm.tm_mon);
1263   EXPECT_EQ(82, tm.tm_year);
1264   EXPECT_EQ(5, tm.tm_wday);
1265   EXPECT_EQ(0, tm.tm_yday);
1266   EXPECT_EQ(0, tm.tm_isdst);
1267 }
1268 
TEST(time,strptime_s_nothing)1269 TEST(time, strptime_s_nothing) {
1270   struct tm tm;
1271   ASSERT_EQ(nullptr, strptime("x", "%s", &tm));
1272 }
1273 
TEST(time,timespec_get)1274 TEST(time, timespec_get) {
1275 #if defined(__BIONIC__)
1276   timespec ts = {};
1277   ASSERT_EQ(TIME_UTC, timespec_get(&ts, TIME_UTC));
1278   ASSERT_EQ(TIME_MONOTONIC, timespec_get(&ts, TIME_MONOTONIC));
1279   ASSERT_EQ(TIME_ACTIVE, timespec_get(&ts, TIME_ACTIVE));
1280   ASSERT_EQ(TIME_THREAD_ACTIVE, timespec_get(&ts, TIME_THREAD_ACTIVE));
1281 #else
1282   GTEST_SKIP() << "glibc doesn't have timespec_get until 2.21";
1283 #endif
1284 }
1285 
TEST(time,timespec_get_invalid)1286 TEST(time, timespec_get_invalid) {
1287 #if defined(__BIONIC__)
1288   timespec ts = {};
1289   ASSERT_EQ(0, timespec_get(&ts, 123));
1290 #else
1291   GTEST_SKIP() << "glibc doesn't have timespec_get until 2.21";
1292 #endif
1293 }
1294 
TEST(time,timespec_getres)1295 TEST(time, timespec_getres) {
1296 #if defined(__BIONIC__)
1297   timespec ts = {};
1298   ASSERT_EQ(TIME_UTC, timespec_getres(&ts, TIME_UTC));
1299   ASSERT_EQ(1, ts.tv_nsec);
1300   ASSERT_EQ(0, ts.tv_sec);
1301 #else
1302   GTEST_SKIP() << "glibc doesn't have timespec_get until 2.21";
1303 #endif
1304 }
1305 
TEST(time,timespec_getres_invalid)1306 TEST(time, timespec_getres_invalid) {
1307 #if defined(__BIONIC__)
1308   timespec ts = {};
1309   ASSERT_EQ(0, timespec_getres(&ts, 123));
1310 #else
1311   GTEST_SKIP() << "glibc doesn't have timespec_get until 2.21";
1312 #endif
1313 }
1314 
TEST(time,difftime)1315 TEST(time, difftime) {
1316   ASSERT_EQ(1.0, difftime(1, 0));
1317   ASSERT_EQ(-1.0, difftime(0, 1));
1318 }
1319 
TEST(time,tzfree_null)1320 TEST(time, tzfree_null) {
1321 #if defined(__BIONIC__)
1322   tzfree(nullptr);
1323 #else
1324   GTEST_SKIP() << "glibc doesn't have timezone_t";
1325 #endif
1326 }
1327 
TEST(time,localtime_rz)1328 TEST(time, localtime_rz) {
1329 #if defined(__BIONIC__)
1330   setenv("TZ", "America/Los_Angeles", 1);
1331   tzset();
1332 
1333   auto AssertTmEq = [](const struct tm& rhs, int hour) {
1334     ASSERT_EQ(93, rhs.tm_year);
1335     ASSERT_EQ(0, rhs.tm_mon);
1336     ASSERT_EQ(1, rhs.tm_mday);
1337     ASSERT_EQ(hour, rhs.tm_hour);
1338     ASSERT_EQ(0, rhs.tm_min);
1339     ASSERT_EQ(0, rhs.tm_sec);
1340   };
1341 
1342   const time_t t = 725875200;
1343 
1344   // Spam localtime_r() while we use localtime_rz().
1345   std::atomic<bool> done = false;
1346   std::thread thread{[&] {
1347     while (!done) {
1348       struct tm tm {};
1349       ASSERT_EQ(&tm, localtime_r(&t, &tm));
1350       AssertTmEq(tm, 0);
1351     }
1352   }};
1353 
1354   struct tm tm;
1355 
1356   timezone_t london{tzalloc("Europe/London")};
1357   tm = {};
1358   ASSERT_EQ(&tm, localtime_rz(london, &t, &tm));
1359   AssertTmEq(tm, 8);
1360 
1361   timezone_t seoul{tzalloc("Asia/Seoul")};
1362   tm = {};
1363   ASSERT_EQ(&tm, localtime_rz(seoul, &t, &tm));
1364   AssertTmEq(tm, 17);
1365 
1366   // Just check that mktime()'s timezone didn't change.
1367   tm = {};
1368   ASSERT_EQ(&tm, localtime_r(&t, &tm));
1369   ASSERT_EQ(0, tm.tm_hour);
1370   AssertTmEq(tm, 0);
1371 
1372   done = true;
1373   thread.join();
1374 
1375   tzfree(london);
1376   tzfree(seoul);
1377 #else
1378   GTEST_SKIP() << "glibc doesn't have timezone_t";
1379 #endif
1380 }
1381 
TEST(time,mktime_z)1382 TEST(time, mktime_z) {
1383 #if defined(__BIONIC__)
1384   setenv("TZ", "America/Los_Angeles", 1);
1385   tzset();
1386 
1387   // Spam mktime() while we use mktime_z().
1388   std::atomic<bool> done = false;
1389   std::thread thread{[&done] {
1390     while (!done) {
1391       struct tm tm {
1392         .tm_year = 93, .tm_mday = 1
1393       };
1394       ASSERT_EQ(725875200, mktime(&tm));
1395     }
1396   }};
1397 
1398   struct tm tm;
1399 
1400   timezone_t london{tzalloc("Europe/London")};
1401   tm = {.tm_year = 93, .tm_mday = 1};
1402   ASSERT_EQ(725846400, mktime_z(london, &tm));
1403 
1404   timezone_t seoul{tzalloc("Asia/Seoul")};
1405   tm = {.tm_year = 93, .tm_mday = 1};
1406   ASSERT_EQ(725814000, mktime_z(seoul, &tm));
1407 
1408   // Just check that mktime()'s timezone didn't change.
1409   tm = {.tm_year = 93, .tm_mday = 1};
1410   ASSERT_EQ(725875200, mktime(&tm));
1411 
1412   done = true;
1413   thread.join();
1414 
1415   tzfree(london);
1416   tzfree(seoul);
1417 #else
1418   GTEST_SKIP() << "glibc doesn't have timezone_t";
1419 #endif
1420 }
1421 
TEST(time,tzalloc_nullptr)1422 TEST(time, tzalloc_nullptr) {
1423 #if defined(__BIONIC__)
1424   // tzalloc(nullptr) returns the system timezone.
1425   timezone_t default_tz = tzalloc(nullptr);
1426   ASSERT_NE(nullptr, default_tz);
1427 
1428   // Check that mktime_z() with the default timezone matches mktime().
1429   // This assumes that the system timezone doesn't change during the test,
1430   // but that should be unlikely, and we don't have much choice if we
1431   // want to write a test at all.
1432   // We unset $TZ before calling mktime() because mktime() honors $TZ.
1433   unsetenv("TZ");
1434   struct tm tm = {.tm_year = 93, .tm_mday = 1};
1435   time_t t = mktime(&tm);
1436   ASSERT_EQ(t, mktime_z(default_tz, &tm));
1437 
1438   // Check that changing $TZ doesn't affect the tzalloc() default in
1439   // the same way it would the mktime() default.
1440   setenv("TZ", "America/Los_Angeles", 1);
1441   tzset();
1442   ASSERT_EQ(t, mktime_z(default_tz, &tm));
1443 
1444   setenv("TZ", "Europe/London", 1);
1445   tzset();
1446   ASSERT_EQ(t, mktime_z(default_tz, &tm));
1447 
1448   setenv("TZ", "Asia/Seoul", 1);
1449   tzset();
1450   ASSERT_EQ(t, mktime_z(default_tz, &tm));
1451 
1452   tzfree(default_tz);
1453 #else
1454   GTEST_SKIP() << "glibc doesn't have timezone_t";
1455 #endif
1456 }
1457 
TEST(time,tzalloc_unique_ptr)1458 TEST(time, tzalloc_unique_ptr) {
1459 #if defined(__BIONIC__)
1460   std::unique_ptr<std::remove_pointer_t<timezone_t>, decltype(&tzfree)> tz{tzalloc("Asia/Seoul"),
1461                                                                            tzfree};
1462 #else
1463   GTEST_SKIP() << "glibc doesn't have timezone_t";
1464 #endif
1465 }
1466