• 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/syscall.h>
24 #include <sys/types.h>
25 #include <sys/wait.h>
26 #include <unistd.h>
27 #include <atomic>
28 
29 #include "SignalUtils.h"
30 #include "utils.h"
31 
32 #include "private/bionic_constants.h"
33 
TEST(time,time)34 TEST(time, time) {
35   // Acquire time
36   time_t p1, t1 = time(&p1);
37   // valid?
38   ASSERT_NE(static_cast<time_t>(0), t1);
39   ASSERT_NE(static_cast<time_t>(-1), t1);
40   ASSERT_EQ(p1, t1);
41 
42   // Acquire time one+ second later
43   usleep(1010000);
44   time_t p2, t2 = time(&p2);
45   // valid?
46   ASSERT_NE(static_cast<time_t>(0), t2);
47   ASSERT_NE(static_cast<time_t>(-1), t2);
48   ASSERT_EQ(p2, t2);
49 
50   // Expect time progression
51   ASSERT_LT(p1, p2);
52   ASSERT_LE(t2 - t1, static_cast<time_t>(2));
53 
54   // Expect nullptr call to produce same results
55   ASSERT_LE(t2, time(nullptr));
56   ASSERT_LE(time(nullptr) - t2, static_cast<time_t>(1));
57 }
58 
TEST(time,gmtime)59 TEST(time, gmtime) {
60   time_t t = 0;
61   tm* broken_down = gmtime(&t);
62   ASSERT_TRUE(broken_down != nullptr);
63   ASSERT_EQ(0, broken_down->tm_sec);
64   ASSERT_EQ(0, broken_down->tm_min);
65   ASSERT_EQ(0, broken_down->tm_hour);
66   ASSERT_EQ(1, broken_down->tm_mday);
67   ASSERT_EQ(0, broken_down->tm_mon);
68   ASSERT_EQ(1970, broken_down->tm_year + 1900);
69 }
70 
TEST(time,gmtime_r)71 TEST(time, gmtime_r) {
72   struct tm tm = {};
73   time_t t = 0;
74   struct tm* broken_down = gmtime_r(&t, &tm);
75   ASSERT_EQ(broken_down, &tm);
76   ASSERT_EQ(0, broken_down->tm_sec);
77   ASSERT_EQ(0, broken_down->tm_min);
78   ASSERT_EQ(0, broken_down->tm_hour);
79   ASSERT_EQ(1, broken_down->tm_mday);
80   ASSERT_EQ(0, broken_down->tm_mon);
81   ASSERT_EQ(1970, broken_down->tm_year + 1900);
82 }
83 
gmtime_no_stack_overflow_14313703_fn(void *)84 static void* gmtime_no_stack_overflow_14313703_fn(void*) {
85   const char* original_tz = getenv("TZ");
86   // Ensure we'll actually have to enter tzload by using a time zone that doesn't exist.
87   setenv("TZ", "gmtime_stack_overflow_14313703", 1);
88   tzset();
89   if (original_tz != nullptr) {
90     setenv("TZ", original_tz, 1);
91   }
92   tzset();
93   return nullptr;
94 }
95 
TEST(time,gmtime_no_stack_overflow_14313703)96 TEST(time, gmtime_no_stack_overflow_14313703) {
97   // Is it safe to call tzload on a thread with a small stack?
98   // http://b/14313703
99   // https://code.google.com/p/android/issues/detail?id=61130
100   pthread_attr_t a;
101   ASSERT_EQ(0, pthread_attr_init(&a));
102   ASSERT_EQ(0, pthread_attr_setstacksize(&a, PTHREAD_STACK_MIN));
103 
104   pthread_t t;
105   ASSERT_EQ(0, pthread_create(&t, &a, gmtime_no_stack_overflow_14313703_fn, nullptr));
106   ASSERT_EQ(0, pthread_join(t, nullptr));
107 }
108 
TEST(time,mktime_empty_TZ)109 TEST(time, mktime_empty_TZ) {
110   // tzcode used to have a bug where it didn't reinitialize some internal state.
111 
112   // Choose a time where DST is set.
113   struct tm t;
114   memset(&t, 0, sizeof(tm));
115   t.tm_year = 1980 - 1900;
116   t.tm_mon = 6;
117   t.tm_mday = 2;
118 
119   setenv("TZ", "America/Los_Angeles", 1);
120   tzset();
121   ASSERT_EQ(static_cast<time_t>(331372800U), mktime(&t));
122 
123   memset(&t, 0, sizeof(tm));
124   t.tm_year = 1980 - 1900;
125   t.tm_mon = 6;
126   t.tm_mday = 2;
127 
128   setenv("TZ", "", 1); // Implies UTC.
129   tzset();
130   ASSERT_EQ(static_cast<time_t>(331344000U), mktime(&t));
131 }
132 
TEST(time,mktime_10310929)133 TEST(time, mktime_10310929) {
134   struct tm t;
135   memset(&t, 0, sizeof(tm));
136   t.tm_year = 200;
137   t.tm_mon = 2;
138   t.tm_mday = 10;
139 
140 #if !defined(__LP64__)
141   // 32-bit bionic stupidly had a signed 32-bit time_t.
142   ASSERT_EQ(-1, mktime(&t));
143   ASSERT_EQ(EOVERFLOW, errno);
144 #else
145   // Everyone else should be using a signed 64-bit time_t.
146   ASSERT_GE(sizeof(time_t) * 8, 64U);
147 
148   setenv("TZ", "America/Los_Angeles", 1);
149   tzset();
150   errno = 0;
151   ASSERT_EQ(static_cast<time_t>(4108348800U), mktime(&t));
152   ASSERT_EQ(0, errno);
153 
154   setenv("TZ", "UTC", 1);
155   tzset();
156   errno = 0;
157   ASSERT_EQ(static_cast<time_t>(4108320000U), mktime(&t));
158   ASSERT_EQ(0, errno);
159 #endif
160 }
161 
TEST(time,mktime_EOVERFLOW)162 TEST(time, mktime_EOVERFLOW) {
163   struct tm t;
164   memset(&t, 0, sizeof(tm));
165 
166   // LP32 year range is 1901-2038, so this year is guaranteed not to overflow.
167   t.tm_year = 2016 - 1900;
168 
169   t.tm_mon = 2;
170   t.tm_mday = 10;
171 
172   errno = 0;
173   ASSERT_NE(static_cast<time_t>(-1), mktime(&t));
174   ASSERT_EQ(0, errno);
175 
176   // This will overflow for LP32 or LP64.
177   t.tm_year = INT_MAX;
178 
179   errno = 0;
180   ASSERT_EQ(static_cast<time_t>(-1), mktime(&t));
181   ASSERT_EQ(EOVERFLOW, errno);
182 }
183 
TEST(time,strftime)184 TEST(time, strftime) {
185   setenv("TZ", "UTC", 1);
186 
187   struct tm t;
188   memset(&t, 0, sizeof(tm));
189   t.tm_year = 200;
190   t.tm_mon = 2;
191   t.tm_mday = 10;
192 
193   char buf[64];
194 
195   // Seconds since the epoch.
196 #if defined(__BIONIC__) || defined(__LP64__) // Not 32-bit glibc.
197   EXPECT_EQ(10U, strftime(buf, sizeof(buf), "%s", &t));
198   EXPECT_STREQ("4108320000", buf);
199 #endif
200 
201   // Date and time as text.
202   EXPECT_EQ(24U, strftime(buf, sizeof(buf), "%c", &t));
203   EXPECT_STREQ("Sun Mar 10 00:00:00 2100", buf);
204 }
205 
TEST(time,strftime_null_tm_zone)206 TEST(time, strftime_null_tm_zone) {
207   // Netflix on Nexus Player wouldn't start (http://b/25170306).
208   struct tm t;
209   memset(&t, 0, sizeof(tm));
210 
211   char buf[64];
212 
213   setenv("TZ", "America/Los_Angeles", 1);
214   tzset();
215 
216   t.tm_isdst = 0; // "0 if Daylight Savings Time is not in effect".
217   EXPECT_EQ(5U, strftime(buf, sizeof(buf), "<%Z>", &t));
218   EXPECT_STREQ("<PST>", buf);
219 
220 #if defined(__BIONIC__) // glibc 2.19 only copes with tm_isdst being 0 and 1.
221   t.tm_isdst = 2; // "positive if Daylight Savings Time is in effect"
222   EXPECT_EQ(5U, strftime(buf, sizeof(buf), "<%Z>", &t));
223   EXPECT_STREQ("<PDT>", buf);
224 
225   t.tm_isdst = -123; // "and negative if the information is not available".
226   EXPECT_EQ(2U, strftime(buf, sizeof(buf), "<%Z>", &t));
227   EXPECT_STREQ("<>", buf);
228 #endif
229 
230   setenv("TZ", "UTC", 1);
231   tzset();
232 
233   t.tm_isdst = 0;
234   EXPECT_EQ(5U, strftime(buf, sizeof(buf), "<%Z>", &t));
235   EXPECT_STREQ("<UTC>", buf);
236 
237 #if defined(__BIONIC__) // glibc 2.19 thinks UTC DST is "UTC".
238   t.tm_isdst = 1; // UTC has no DST.
239   EXPECT_EQ(2U, strftime(buf, sizeof(buf), "<%Z>", &t));
240   EXPECT_STREQ("<>", buf);
241 #endif
242 }
243 
TEST(time,strftime_l)244 TEST(time, strftime_l) {
245   locale_t cloc = newlocale(LC_ALL, "C.UTF-8", nullptr);
246   locale_t old_locale = uselocale(cloc);
247 
248   setenv("TZ", "UTC", 1);
249 
250   struct tm t;
251   memset(&t, 0, sizeof(tm));
252   t.tm_year = 200;
253   t.tm_mon = 2;
254   t.tm_mday = 10;
255 
256   // Date and time as text.
257   char buf[64];
258   EXPECT_EQ(24U, strftime_l(buf, sizeof(buf), "%c", &t, cloc));
259   EXPECT_STREQ("Sun Mar 10 00:00:00 2100", buf);
260 
261   uselocale(old_locale);
262   freelocale(cloc);
263 }
264 
TEST(time,strptime)265 TEST(time, strptime) {
266   setenv("TZ", "UTC", 1);
267 
268   struct tm t;
269   char buf[64];
270 
271   memset(&t, 0, sizeof(t));
272   strptime("11:14", "%R", &t);
273   strftime(buf, sizeof(buf), "%H:%M", &t);
274   EXPECT_STREQ("11:14", buf);
275 
276   memset(&t, 0, sizeof(t));
277   strptime("09:41:53", "%T", &t);
278   strftime(buf, sizeof(buf), "%H:%M:%S", &t);
279   EXPECT_STREQ("09:41:53", buf);
280 }
281 
TEST(time,strptime_l)282 TEST(time, strptime_l) {
283   setenv("TZ", "UTC", 1);
284 
285   struct tm t;
286   char buf[64];
287 
288   memset(&t, 0, sizeof(t));
289   strptime_l("11:14", "%R", &t, LC_GLOBAL_LOCALE);
290   strftime_l(buf, sizeof(buf), "%H:%M", &t, LC_GLOBAL_LOCALE);
291   EXPECT_STREQ("11:14", buf);
292 
293   memset(&t, 0, sizeof(t));
294   strptime_l("09:41:53", "%T", &t, LC_GLOBAL_LOCALE);
295   strftime_l(buf, sizeof(buf), "%H:%M:%S", &t, LC_GLOBAL_LOCALE);
296   EXPECT_STREQ("09:41:53", buf);
297 }
298 
TEST(time,strptime_F)299 TEST(time, strptime_F) {
300   setenv("TZ", "UTC", 1);
301 
302   struct tm tm = {};
303   ASSERT_EQ('\0', *strptime("2019-03-26", "%F", &tm));
304   EXPECT_EQ(119, tm.tm_year);
305   EXPECT_EQ(2, tm.tm_mon);
306   EXPECT_EQ(26, tm.tm_mday);
307 }
308 
TEST(time,strptime_P_p)309 TEST(time, strptime_P_p) {
310   setenv("TZ", "UTC", 1);
311 
312   // For parsing, %P and %p are the same: case doesn't matter.
313 
314   struct tm tm = {.tm_hour = 12};
315   ASSERT_EQ('\0', *strptime("AM", "%p", &tm));
316   EXPECT_EQ(0, tm.tm_hour);
317 
318   tm = {.tm_hour = 12};
319   ASSERT_EQ('\0', *strptime("am", "%p", &tm));
320   EXPECT_EQ(0, tm.tm_hour);
321 
322   tm = {.tm_hour = 12};
323   ASSERT_EQ('\0', *strptime("AM", "%P", &tm));
324   EXPECT_EQ(0, tm.tm_hour);
325 
326   tm = {.tm_hour = 12};
327   ASSERT_EQ('\0', *strptime("am", "%P", &tm));
328   EXPECT_EQ(0, tm.tm_hour);
329 }
330 
TEST(time,strptime_u)331 TEST(time, strptime_u) {
332   setenv("TZ", "UTC", 1);
333 
334   struct tm tm = {};
335   ASSERT_EQ('\0', *strptime("2", "%u", &tm));
336   EXPECT_EQ(2, tm.tm_wday);
337 }
338 
TEST(time,strptime_v)339 TEST(time, strptime_v) {
340   setenv("TZ", "UTC", 1);
341 
342   struct tm tm = {};
343   ASSERT_EQ('\0', *strptime("26-Mar-1980", "%v", &tm));
344   EXPECT_EQ(80, tm.tm_year);
345   EXPECT_EQ(2, tm.tm_mon);
346   EXPECT_EQ(26, tm.tm_mday);
347 }
348 
TEST(time,strptime_V_G_g)349 TEST(time, strptime_V_G_g) {
350   setenv("TZ", "UTC", 1);
351 
352   // %V (ISO-8601 week number), %G (year of week number, without century), and
353   // %g (year of week number) have no effect when parsed, and are supported
354   // solely so that it's possible for strptime(3) to parse everything that
355   // strftime(3) can output.
356   struct tm tm = {};
357   ASSERT_EQ('\0', *strptime("1 2 3", "%V %G %g", &tm));
358   struct tm zero = {};
359   EXPECT_TRUE(memcmp(&tm, &zero, sizeof(tm)) == 0);
360 }
361 
SetTime(timer_t t,time_t value_s,time_t value_ns,time_t interval_s,time_t interval_ns)362 void SetTime(timer_t t, time_t value_s, time_t value_ns, time_t interval_s, time_t interval_ns) {
363   itimerspec ts;
364   ts.it_value.tv_sec = value_s;
365   ts.it_value.tv_nsec = value_ns;
366   ts.it_interval.tv_sec = interval_s;
367   ts.it_interval.tv_nsec = interval_ns;
368   ASSERT_EQ(0, timer_settime(t, 0, &ts, nullptr));
369 }
370 
NoOpNotifyFunction(sigval_t)371 static void NoOpNotifyFunction(sigval_t) {
372 }
373 
TEST(time,timer_create)374 TEST(time, timer_create) {
375   sigevent_t se;
376   memset(&se, 0, sizeof(se));
377   se.sigev_notify = SIGEV_THREAD;
378   se.sigev_notify_function = NoOpNotifyFunction;
379   timer_t timer_id;
380   ASSERT_EQ(0, timer_create(CLOCK_MONOTONIC, &se, &timer_id));
381 
382   pid_t pid = fork();
383   ASSERT_NE(-1, pid) << strerror(errno);
384 
385   if (pid == 0) {
386     // Timers are not inherited by the child.
387     ASSERT_EQ(-1, timer_delete(timer_id));
388     ASSERT_EQ(EINVAL, errno);
389     _exit(0);
390   }
391 
392   AssertChildExited(pid, 0);
393 
394   ASSERT_EQ(0, timer_delete(timer_id));
395 }
396 
397 static int timer_create_SIGEV_SIGNAL_signal_handler_invocation_count;
timer_create_SIGEV_SIGNAL_signal_handler(int signal_number)398 static void timer_create_SIGEV_SIGNAL_signal_handler(int signal_number) {
399   ++timer_create_SIGEV_SIGNAL_signal_handler_invocation_count;
400   ASSERT_EQ(SIGUSR1, signal_number);
401 }
402 
TEST(time,timer_create_SIGEV_SIGNAL)403 TEST(time, timer_create_SIGEV_SIGNAL) {
404   sigevent_t se;
405   memset(&se, 0, sizeof(se));
406   se.sigev_notify = SIGEV_SIGNAL;
407   se.sigev_signo = SIGUSR1;
408 
409   timer_t timer_id;
410   ASSERT_EQ(0, timer_create(CLOCK_MONOTONIC, &se, &timer_id));
411 
412   timer_create_SIGEV_SIGNAL_signal_handler_invocation_count = 0;
413   ScopedSignalHandler ssh(SIGUSR1, timer_create_SIGEV_SIGNAL_signal_handler);
414 
415   ASSERT_EQ(0, timer_create_SIGEV_SIGNAL_signal_handler_invocation_count);
416 
417   itimerspec ts;
418   ts.it_value.tv_sec =  0;
419   ts.it_value.tv_nsec = 1;
420   ts.it_interval.tv_sec = 0;
421   ts.it_interval.tv_nsec = 0;
422   ASSERT_EQ(0, timer_settime(timer_id, 0, &ts, nullptr));
423 
424   usleep(500000);
425   ASSERT_EQ(1, timer_create_SIGEV_SIGNAL_signal_handler_invocation_count);
426 }
427 
428 struct Counter {
429  private:
430   std::atomic<int> value;
431   timer_t timer_id;
432   sigevent_t se;
433   bool timer_valid;
434 
CreateCounter435   void Create() {
436     ASSERT_FALSE(timer_valid);
437     ASSERT_EQ(0, timer_create(CLOCK_REALTIME, &se, &timer_id));
438     timer_valid = true;
439   }
440 
441  public:
CounterCounter442   explicit Counter(void (*fn)(sigval_t)) : value(0), timer_valid(false) {
443     memset(&se, 0, sizeof(se));
444     se.sigev_notify = SIGEV_THREAD;
445     se.sigev_notify_function = fn;
446     se.sigev_value.sival_ptr = this;
447     Create();
448   }
DeleteTimerCounter449   void DeleteTimer() {
450     ASSERT_TRUE(timer_valid);
451     ASSERT_EQ(0, timer_delete(timer_id));
452     timer_valid = false;
453   }
454 
~CounterCounter455   ~Counter() {
456     if (timer_valid) {
457       DeleteTimer();
458     }
459   }
460 
ValueCounter461   int Value() const {
462     return value;
463   }
464 
SetTimeCounter465   void SetTime(time_t value_s, time_t value_ns, time_t interval_s, time_t interval_ns) {
466     ::SetTime(timer_id, value_s, value_ns, interval_s, interval_ns);
467   }
468 
ValueUpdatedCounter469   bool ValueUpdated() {
470     int current_value = value;
471     time_t start = time(nullptr);
472     while (current_value == value && (time(nullptr) - start) < 5) {
473     }
474     return current_value != value;
475   }
476 
CountNotifyFunctionCounter477   static void CountNotifyFunction(sigval_t value) {
478     Counter* cd = reinterpret_cast<Counter*>(value.sival_ptr);
479     ++cd->value;
480   }
481 
CountAndDisarmNotifyFunctionCounter482   static void CountAndDisarmNotifyFunction(sigval_t value) {
483     Counter* cd = reinterpret_cast<Counter*>(value.sival_ptr);
484     ++cd->value;
485 
486     // Setting the initial expiration time to 0 disarms the timer.
487     cd->SetTime(0, 0, 1, 0);
488   }
489 };
490 
TEST(time,timer_settime_0)491 TEST(time, timer_settime_0) {
492   Counter counter(Counter::CountAndDisarmNotifyFunction);
493   ASSERT_EQ(0, counter.Value());
494 
495   counter.SetTime(0, 500000000, 1, 0);
496   sleep(1);
497 
498   // The count should just be 1 because we disarmed the timer the first time it fired.
499   ASSERT_EQ(1, counter.Value());
500 }
501 
TEST(time,timer_settime_repeats)502 TEST(time, timer_settime_repeats) {
503   Counter counter(Counter::CountNotifyFunction);
504   ASSERT_EQ(0, counter.Value());
505 
506   counter.SetTime(0, 1, 0, 10);
507   ASSERT_TRUE(counter.ValueUpdated());
508   ASSERT_TRUE(counter.ValueUpdated());
509   ASSERT_TRUE(counter.ValueUpdated());
510   counter.DeleteTimer();
511   // Add a sleep as other threads may be calling the callback function when the timer is deleted.
512   usleep(500000);
513 }
514 
515 static int timer_create_NULL_signal_handler_invocation_count;
timer_create_NULL_signal_handler(int signal_number)516 static void timer_create_NULL_signal_handler(int signal_number) {
517   ++timer_create_NULL_signal_handler_invocation_count;
518   ASSERT_EQ(SIGALRM, signal_number);
519 }
520 
TEST(time,timer_create_NULL)521 TEST(time, timer_create_NULL) {
522   // A NULL sigevent* is equivalent to asking for SIGEV_SIGNAL for SIGALRM.
523   timer_t timer_id;
524   ASSERT_EQ(0, timer_create(CLOCK_MONOTONIC, nullptr, &timer_id));
525 
526   timer_create_NULL_signal_handler_invocation_count = 0;
527   ScopedSignalHandler ssh(SIGALRM, timer_create_NULL_signal_handler);
528 
529   ASSERT_EQ(0, timer_create_NULL_signal_handler_invocation_count);
530 
531   SetTime(timer_id, 0, 1, 0, 0);
532   usleep(500000);
533 
534   ASSERT_EQ(1, timer_create_NULL_signal_handler_invocation_count);
535 }
536 
TEST(time,timer_create_EINVAL)537 TEST(time, timer_create_EINVAL) {
538   clockid_t invalid_clock = 16;
539 
540   // A SIGEV_SIGNAL timer is easy; the kernel does all that.
541   timer_t timer_id;
542   ASSERT_EQ(-1, timer_create(invalid_clock, nullptr, &timer_id));
543   ASSERT_EQ(EINVAL, errno);
544 
545   // A SIGEV_THREAD timer is more interesting because we have stuff to clean up.
546   sigevent_t se;
547   memset(&se, 0, sizeof(se));
548   se.sigev_notify = SIGEV_THREAD;
549   se.sigev_notify_function = NoOpNotifyFunction;
550   ASSERT_EQ(-1, timer_create(invalid_clock, &se, &timer_id));
551   ASSERT_EQ(EINVAL, errno);
552 }
553 
TEST(time,timer_create_multiple)554 TEST(time, timer_create_multiple) {
555   Counter counter1(Counter::CountNotifyFunction);
556   Counter counter2(Counter::CountNotifyFunction);
557   Counter counter3(Counter::CountNotifyFunction);
558 
559   ASSERT_EQ(0, counter1.Value());
560   ASSERT_EQ(0, counter2.Value());
561   ASSERT_EQ(0, counter3.Value());
562 
563   counter2.SetTime(0, 500000000, 0, 0);
564   sleep(1);
565 
566   EXPECT_EQ(0, counter1.Value());
567   EXPECT_EQ(1, counter2.Value());
568   EXPECT_EQ(0, counter3.Value());
569 }
570 
571 // Test to verify that disarming a repeatable timer disables the callbacks.
TEST(time,timer_disarm_terminates)572 TEST(time, timer_disarm_terminates) {
573   Counter counter(Counter::CountNotifyFunction);
574   ASSERT_EQ(0, counter.Value());
575 
576   counter.SetTime(0, 1, 0, 1);
577   ASSERT_TRUE(counter.ValueUpdated());
578   ASSERT_TRUE(counter.ValueUpdated());
579   ASSERT_TRUE(counter.ValueUpdated());
580 
581   counter.SetTime(0, 0, 0, 0);
582   // Add a sleep as the kernel may have pending events when the timer is disarmed.
583   usleep(500000);
584   int value = counter.Value();
585   usleep(500000);
586 
587   // Verify the counter has not been incremented.
588   ASSERT_EQ(value, counter.Value());
589 }
590 
591 // Test to verify that deleting a repeatable timer disables the callbacks.
TEST(time,timer_delete_terminates)592 TEST(time, timer_delete_terminates) {
593   Counter counter(Counter::CountNotifyFunction);
594   ASSERT_EQ(0, counter.Value());
595 
596   counter.SetTime(0, 1, 0, 1);
597   ASSERT_TRUE(counter.ValueUpdated());
598   ASSERT_TRUE(counter.ValueUpdated());
599   ASSERT_TRUE(counter.ValueUpdated());
600 
601   counter.DeleteTimer();
602   // Add a sleep as other threads may be calling the callback function when the timer is deleted.
603   usleep(500000);
604   int value = counter.Value();
605   usleep(500000);
606 
607   // Verify the counter has not been incremented.
608   ASSERT_EQ(value, counter.Value());
609 }
610 
611 struct TimerDeleteData {
612   timer_t timer_id;
613   pid_t tid;
614   volatile bool complete;
615 };
616 
TimerDeleteCallback(sigval_t value)617 static void TimerDeleteCallback(sigval_t value) {
618   TimerDeleteData* tdd = reinterpret_cast<TimerDeleteData*>(value.sival_ptr);
619 
620   tdd->tid = gettid();
621   timer_delete(tdd->timer_id);
622   tdd->complete = true;
623 }
624 
TEST(time,timer_delete_from_timer_thread)625 TEST(time, timer_delete_from_timer_thread) {
626   TimerDeleteData tdd;
627   sigevent_t se;
628 
629   memset(&se, 0, sizeof(se));
630   se.sigev_notify = SIGEV_THREAD;
631   se.sigev_notify_function = TimerDeleteCallback;
632   se.sigev_value.sival_ptr = &tdd;
633 
634   tdd.complete = false;
635   ASSERT_EQ(0, timer_create(CLOCK_REALTIME, &se, &tdd.timer_id));
636 
637   itimerspec ts;
638   ts.it_value.tv_sec = 1;
639   ts.it_value.tv_nsec = 0;
640   ts.it_interval.tv_sec = 0;
641   ts.it_interval.tv_nsec = 0;
642   ASSERT_EQ(0, timer_settime(tdd.timer_id, 0, &ts, nullptr));
643 
644   time_t cur_time = time(nullptr);
645   while (!tdd.complete && (time(nullptr) - cur_time) < 5);
646   ASSERT_TRUE(tdd.complete);
647 
648 #if defined(__BIONIC__)
649   // Since bionic timers are implemented by creating a thread to handle the
650   // callback, verify that the thread actually completes.
651   cur_time = time(NULL);
652   while ((kill(tdd.tid, 0) != -1 || errno != ESRCH) && (time(NULL) - cur_time) < 5);
653   ASSERT_EQ(-1, kill(tdd.tid, 0));
654   ASSERT_EQ(ESRCH, errno);
655 #endif
656 }
657 
TEST(time,clock_gettime)658 TEST(time, clock_gettime) {
659   // Try to ensure that our vdso clock_gettime is working.
660   timespec ts1;
661   ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts1));
662   timespec ts2;
663   ASSERT_EQ(0, syscall(__NR_clock_gettime, CLOCK_MONOTONIC, &ts2));
664 
665   // What's the difference between the two?
666   ts2.tv_sec -= ts1.tv_sec;
667   ts2.tv_nsec -= ts1.tv_nsec;
668   if (ts2.tv_nsec < 0) {
669     --ts2.tv_sec;
670     ts2.tv_nsec += NS_PER_S;
671   }
672 
673   // To try to avoid flakiness we'll accept answers within 10,000,000ns (0.01s).
674   ASSERT_EQ(0, ts2.tv_sec);
675   ASSERT_LT(ts2.tv_nsec, 10'000'000);
676 }
677 
TEST(time,clock_gettime_CLOCK_REALTIME)678 TEST(time, clock_gettime_CLOCK_REALTIME) {
679   timespec ts;
680   ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
681 }
682 
TEST(time,clock_gettime_CLOCK_MONOTONIC)683 TEST(time, clock_gettime_CLOCK_MONOTONIC) {
684   timespec ts;
685   ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
686 }
687 
TEST(time,clock_gettime_CLOCK_PROCESS_CPUTIME_ID)688 TEST(time, clock_gettime_CLOCK_PROCESS_CPUTIME_ID) {
689   timespec ts;
690   ASSERT_EQ(0, clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts));
691 }
692 
TEST(time,clock_gettime_CLOCK_THREAD_CPUTIME_ID)693 TEST(time, clock_gettime_CLOCK_THREAD_CPUTIME_ID) {
694   timespec ts;
695   ASSERT_EQ(0, clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts));
696 }
697 
TEST(time,clock_gettime_CLOCK_BOOTTIME)698 TEST(time, clock_gettime_CLOCK_BOOTTIME) {
699   timespec ts;
700   ASSERT_EQ(0, clock_gettime(CLOCK_BOOTTIME, &ts));
701 }
702 
TEST(time,clock_gettime_unknown)703 TEST(time, clock_gettime_unknown) {
704   errno = 0;
705   timespec ts;
706   ASSERT_EQ(-1, clock_gettime(-1, &ts));
707   ASSERT_EQ(EINVAL, errno);
708 }
709 
TEST(time,clock_getres_CLOCK_REALTIME)710 TEST(time, clock_getres_CLOCK_REALTIME) {
711   timespec ts;
712   ASSERT_EQ(0, clock_getres(CLOCK_REALTIME, &ts));
713   ASSERT_EQ(1, ts.tv_nsec);
714   ASSERT_EQ(0, ts.tv_sec);
715 }
716 
TEST(time,clock_getres_CLOCK_MONOTONIC)717 TEST(time, clock_getres_CLOCK_MONOTONIC) {
718   timespec ts;
719   ASSERT_EQ(0, clock_getres(CLOCK_MONOTONIC, &ts));
720   ASSERT_EQ(1, ts.tv_nsec);
721   ASSERT_EQ(0, ts.tv_sec);
722 }
723 
TEST(time,clock_getres_CLOCK_PROCESS_CPUTIME_ID)724 TEST(time, clock_getres_CLOCK_PROCESS_CPUTIME_ID) {
725   timespec ts;
726   ASSERT_EQ(0, clock_getres(CLOCK_PROCESS_CPUTIME_ID, &ts));
727 }
728 
TEST(time,clock_getres_CLOCK_THREAD_CPUTIME_ID)729 TEST(time, clock_getres_CLOCK_THREAD_CPUTIME_ID) {
730   timespec ts;
731   ASSERT_EQ(0, clock_getres(CLOCK_THREAD_CPUTIME_ID, &ts));
732 }
733 
TEST(time,clock_getres_CLOCK_BOOTTIME)734 TEST(time, clock_getres_CLOCK_BOOTTIME) {
735   timespec ts;
736   ASSERT_EQ(0, clock_getres(CLOCK_BOOTTIME, &ts));
737   ASSERT_EQ(1, ts.tv_nsec);
738   ASSERT_EQ(0, ts.tv_sec);
739 }
740 
TEST(time,clock_getres_unknown)741 TEST(time, clock_getres_unknown) {
742   errno = 0;
743   timespec ts = { -1, -1 };
744   ASSERT_EQ(-1, clock_getres(-1, &ts));
745   ASSERT_EQ(EINVAL, errno);
746   ASSERT_EQ(-1, ts.tv_nsec);
747   ASSERT_EQ(-1, ts.tv_sec);
748 }
749 
TEST(time,clock)750 TEST(time, clock) {
751   // clock(3) is hard to test, but a 1s sleep should cost less than 1ms.
752   clock_t t0 = clock();
753   sleep(1);
754   clock_t t1 = clock();
755   ASSERT_LT(t1 - t0, CLOCKS_PER_SEC / 1000);
756 }
757 
GetInvalidPid()758 static pid_t GetInvalidPid() {
759   std::unique_ptr<FILE, decltype(&fclose)> fp{fopen("/proc/sys/kernel/pid_max", "r"), fclose};
760   long pid_max;
761   fscanf(fp.get(), "%ld", &pid_max);
762   return static_cast<pid_t>(pid_max + 1);
763 }
764 
TEST(time,clock_getcpuclockid_current)765 TEST(time, clock_getcpuclockid_current) {
766   clockid_t clockid;
767   ASSERT_EQ(0, clock_getcpuclockid(getpid(), &clockid));
768   timespec ts;
769   ASSERT_EQ(0, clock_gettime(clockid, &ts));
770 }
771 
TEST(time,clock_getcpuclockid_parent)772 TEST(time, clock_getcpuclockid_parent) {
773   clockid_t clockid;
774   ASSERT_EQ(0, clock_getcpuclockid(getppid(), &clockid));
775   timespec ts;
776   ASSERT_EQ(0, clock_gettime(clockid, &ts));
777 }
778 
TEST(time,clock_getcpuclockid_ESRCH)779 TEST(time, clock_getcpuclockid_ESRCH) {
780   // We can't use -1 for invalid pid here, because clock_getcpuclockid() can't detect it.
781   errno = 0;
782   // If this fails, your kernel needs commit e1b6b6ce to be backported.
783   clockid_t clockid;
784   ASSERT_EQ(ESRCH, clock_getcpuclockid(GetInvalidPid(), &clockid)) << "\n"
785     << "Please ensure that the following kernel patches or their replacements have been applied:\n"
786     << "* https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/"
787     << "commit/?id=e1b6b6ce55a0a25c8aa8af019095253b2133a41a\n"
788     << "* https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/"
789     << "commit/?id=c80ed088a519da53f27b798a69748eaabc66aadf\n";
790   ASSERT_EQ(0, errno);
791 }
792 
TEST(time,clock_settime)793 TEST(time, clock_settime) {
794   errno = 0;
795   timespec ts;
796   ASSERT_EQ(-1, clock_settime(-1, &ts));
797   ASSERT_EQ(EINVAL, errno);
798 }
799 
TEST(time,clock_nanosleep)800 TEST(time, clock_nanosleep) {
801   timespec in;
802   timespec out;
803   ASSERT_EQ(EINVAL, clock_nanosleep(-1, 0, &in, &out));
804 }
805 
TEST(time,clock_nanosleep_thread_cputime_id)806 TEST(time, clock_nanosleep_thread_cputime_id) {
807   timespec in;
808   in.tv_sec = 1;
809   in.tv_nsec = 0;
810   ASSERT_EQ(EINVAL, clock_nanosleep(CLOCK_THREAD_CPUTIME_ID, 0, &in, nullptr));
811 }
812 
TEST(time,bug_31938693)813 TEST(time, bug_31938693) {
814   // User-visible symptoms in N:
815   // http://b/31938693
816   // https://code.google.com/p/android/issues/detail?id=225132
817 
818   // Actual underlying bug (the code change, not the tzdata upgrade that first exposed the bug):
819   // http://b/31848040
820 
821   // This isn't a great test, because very few time zones were actually affected, and there's
822   // no real logic to which ones were affected: it was just a coincidence of the data that came
823   // after them in the tzdata file.
824 
825   time_t t = 1475619727;
826   struct tm tm;
827 
828   setenv("TZ", "America/Los_Angeles", 1);
829   tzset();
830   ASSERT_TRUE(localtime_r(&t, &tm) != nullptr);
831   EXPECT_EQ(15, tm.tm_hour);
832 
833   setenv("TZ", "Europe/London", 1);
834   tzset();
835   ASSERT_TRUE(localtime_r(&t, &tm) != nullptr);
836   EXPECT_EQ(23, tm.tm_hour);
837 
838   setenv("TZ", "America/Atka", 1);
839   tzset();
840   ASSERT_TRUE(localtime_r(&t, &tm) != nullptr);
841   EXPECT_EQ(13, tm.tm_hour);
842 
843   setenv("TZ", "Pacific/Apia", 1);
844   tzset();
845   ASSERT_TRUE(localtime_r(&t, &tm) != nullptr);
846   EXPECT_EQ(12, tm.tm_hour);
847 
848   setenv("TZ", "Pacific/Honolulu", 1);
849   tzset();
850   ASSERT_TRUE(localtime_r(&t, &tm) != nullptr);
851   EXPECT_EQ(12, tm.tm_hour);
852 
853   setenv("TZ", "Asia/Magadan", 1);
854   tzset();
855   ASSERT_TRUE(localtime_r(&t, &tm) != nullptr);
856   EXPECT_EQ(9, tm.tm_hour);
857 }
858 
TEST(time,bug_31339449)859 TEST(time, bug_31339449) {
860   // POSIX says localtime acts as if it calls tzset.
861   // tzset does two things:
862   //  1. it sets the time zone ctime/localtime/mktime/strftime will use.
863   //  2. it sets the global `tzname`.
864   // POSIX says localtime_r need not set `tzname` (2).
865   // Q: should localtime_r set the time zone (1)?
866   // Upstream tzcode (and glibc) answer "no", everyone else answers "yes".
867 
868   // Pick a time, any time...
869   time_t t = 1475619727;
870 
871   // Call tzset with a specific timezone.
872   setenv("TZ", "America/Atka", 1);
873   tzset();
874 
875   // If we change the timezone and call localtime, localtime should use the new timezone.
876   setenv("TZ", "America/Los_Angeles", 1);
877   struct tm* tm_p = localtime(&t);
878   EXPECT_EQ(15, tm_p->tm_hour);
879 
880   // Reset the timezone back.
881   setenv("TZ", "America/Atka", 1);
882   tzset();
883 
884 #if defined(__BIONIC__)
885   // If we change the timezone again and call localtime_r, localtime_r should use the new timezone.
886   setenv("TZ", "America/Los_Angeles", 1);
887   struct tm tm = {};
888   localtime_r(&t, &tm);
889   EXPECT_EQ(15, tm.tm_hour);
890 #else
891   // The BSDs agree with us, but glibc gets this wrong.
892 #endif
893 }
894 
TEST(time,asctime)895 TEST(time, asctime) {
896   const struct tm tm = {};
897   ASSERT_STREQ("Sun Jan  0 00:00:00 1900\n", asctime(&tm));
898 }
899 
TEST(time,asctime_r)900 TEST(time, asctime_r) {
901   const struct tm tm = {};
902   char buf[256];
903   ASSERT_EQ(buf, asctime_r(&tm, buf));
904   ASSERT_STREQ("Sun Jan  0 00:00:00 1900\n", buf);
905 }
906 
TEST(time,ctime)907 TEST(time, ctime) {
908   setenv("TZ", "UTC", 1);
909   const time_t t = 0;
910   ASSERT_STREQ("Thu Jan  1 00:00:00 1970\n", ctime(&t));
911 }
912 
TEST(time,ctime_r)913 TEST(time, ctime_r) {
914   setenv("TZ", "UTC", 1);
915   const time_t t = 0;
916   char buf[256];
917   ASSERT_EQ(buf, ctime_r(&t, buf));
918   ASSERT_STREQ("Thu Jan  1 00:00:00 1970\n", buf);
919 }
920 
921 // https://issuetracker.google.com/37128336
TEST(time,strftime_strptime_s)922 TEST(time, strftime_strptime_s) {
923   char buf[32];
924   const struct tm tm0 = { .tm_year = 1982-1900, .tm_mon = 0, .tm_mday = 1 };
925 
926   setenv("TZ", "America/Los_Angeles", 1);
927   strftime(buf, sizeof(buf), "<%s>", &tm0);
928   EXPECT_STREQ("<378720000>", buf);
929 
930   setenv("TZ", "UTC", 1);
931   strftime(buf, sizeof(buf), "<%s>", &tm0);
932   EXPECT_STREQ("<378691200>", buf);
933 
934   struct tm tm;
935 
936   setenv("TZ", "America/Los_Angeles", 1);
937   tzset();
938   memset(&tm, 0xff, sizeof(tm));
939   char* p = strptime("378720000x", "%s", &tm);
940   ASSERT_EQ('x', *p);
941   EXPECT_EQ(0, tm.tm_sec);
942   EXPECT_EQ(0, tm.tm_min);
943   EXPECT_EQ(0, tm.tm_hour);
944   EXPECT_EQ(1, tm.tm_mday);
945   EXPECT_EQ(0, tm.tm_mon);
946   EXPECT_EQ(82, tm.tm_year);
947   EXPECT_EQ(5, tm.tm_wday);
948   EXPECT_EQ(0, tm.tm_yday);
949   EXPECT_EQ(0, tm.tm_isdst);
950 
951   setenv("TZ", "UTC", 1);
952   tzset();
953   memset(&tm, 0xff, sizeof(tm));
954   p = strptime("378691200x", "%s", &tm);
955   ASSERT_EQ('x', *p);
956   EXPECT_EQ(0, tm.tm_sec);
957   EXPECT_EQ(0, tm.tm_min);
958   EXPECT_EQ(0, tm.tm_hour);
959   EXPECT_EQ(1, tm.tm_mday);
960   EXPECT_EQ(0, tm.tm_mon);
961   EXPECT_EQ(82, tm.tm_year);
962   EXPECT_EQ(5, tm.tm_wday);
963   EXPECT_EQ(0, tm.tm_yday);
964   EXPECT_EQ(0, tm.tm_isdst);
965 }
966 
TEST(time,strptime_s_nothing)967 TEST(time, strptime_s_nothing) {
968   struct tm tm;
969   ASSERT_EQ(nullptr, strptime("x", "%s", &tm));
970 }
971 
TEST(time,timespec_get)972 TEST(time, timespec_get) {
973 #if __BIONIC__
974   timespec ts = {};
975   ASSERT_EQ(0, timespec_get(&ts, 123));
976   ASSERT_EQ(TIME_UTC, timespec_get(&ts, TIME_UTC));
977 #else
978   GTEST_SKIP() << "glibc doesn't have timespec_get until 2.21";
979 #endif
980 }
981