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