pthread_test.cpp revision 1d53ae2a01df5c85d23b01e44880103e118712f3
1/*
2 * Copyright (C) 2012 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 <gtest/gtest.h>
18
19#include <errno.h>
20#include <inttypes.h>
21#include <limits.h>
22#include <malloc.h>
23#include <pthread.h>
24#include <signal.h>
25#include <sys/mman.h>
26#include <sys/syscall.h>
27#include <time.h>
28#include <unistd.h>
29
30#include "ScopedSignalHandler.h"
31
32TEST(pthread, pthread_key_create) {
33  pthread_key_t key;
34  ASSERT_EQ(0, pthread_key_create(&key, NULL));
35  ASSERT_EQ(0, pthread_key_delete(key));
36  // Can't delete a key that's already been deleted.
37  ASSERT_EQ(EINVAL, pthread_key_delete(key));
38}
39
40TEST(pthread, pthread_key_create_lots) {
41#if defined(__BIONIC__) // glibc uses keys internally that its sysconf value doesn't account for.
42  // POSIX says PTHREAD_KEYS_MAX should be at least 128.
43  ASSERT_GE(PTHREAD_KEYS_MAX, 128);
44
45  int sysconf_max = sysconf(_SC_THREAD_KEYS_MAX);
46
47  // sysconf shouldn't return a smaller value.
48  ASSERT_GE(sysconf_max, PTHREAD_KEYS_MAX);
49
50  // We can allocate _SC_THREAD_KEYS_MAX keys.
51  sysconf_max -= 2; // (Except that gtest takes two for itself.)
52  std::vector<pthread_key_t> keys;
53  for (int i = 0; i < sysconf_max; ++i) {
54    pthread_key_t key;
55    // If this fails, it's likely that GLOBAL_INIT_THREAD_LOCAL_BUFFER_COUNT is wrong.
56    ASSERT_EQ(0, pthread_key_create(&key, NULL)) << i << " of " << sysconf_max;
57    keys.push_back(key);
58  }
59
60  // ...and that really is the maximum.
61  pthread_key_t key;
62  ASSERT_EQ(EAGAIN, pthread_key_create(&key, NULL));
63
64  // (Don't leak all those keys!)
65  for (size_t i = 0; i < keys.size(); ++i) {
66    ASSERT_EQ(0, pthread_key_delete(keys[i]));
67  }
68#else // __BIONIC__
69  GTEST_LOG_(INFO) << "This test does nothing.\n";
70#endif // __BIONIC__
71}
72
73TEST(pthread, pthread_key_delete) {
74  void* expected = reinterpret_cast<void*>(1234);
75  pthread_key_t key;
76  ASSERT_EQ(0, pthread_key_create(&key, NULL));
77  ASSERT_EQ(0, pthread_setspecific(key, expected));
78  ASSERT_EQ(expected, pthread_getspecific(key));
79  ASSERT_EQ(0, pthread_key_delete(key));
80  // After deletion, pthread_getspecific returns NULL.
81  ASSERT_EQ(NULL, pthread_getspecific(key));
82  // And you can't use pthread_setspecific with the deleted key.
83  ASSERT_EQ(EINVAL, pthread_setspecific(key, expected));
84}
85
86TEST(pthread, pthread_key_fork) {
87  void* expected = reinterpret_cast<void*>(1234);
88  pthread_key_t key;
89  ASSERT_EQ(0, pthread_key_create(&key, NULL));
90  ASSERT_EQ(0, pthread_setspecific(key, expected));
91  ASSERT_EQ(expected, pthread_getspecific(key));
92
93  pid_t pid = fork();
94  ASSERT_NE(-1, pid) << strerror(errno);
95
96  if (pid == 0) {
97    // The surviving thread inherits all the forking thread's TLS values...
98    ASSERT_EQ(expected, pthread_getspecific(key));
99    _exit(99);
100  }
101
102  int status;
103  ASSERT_EQ(pid, waitpid(pid, &status, 0));
104  ASSERT_TRUE(WIFEXITED(status));
105  ASSERT_EQ(99, WEXITSTATUS(status));
106
107  ASSERT_EQ(expected, pthread_getspecific(key));
108  ASSERT_EQ(0, pthread_key_delete(key));
109}
110
111static void* DirtyKeyFn(void* key) {
112  return pthread_getspecific(*reinterpret_cast<pthread_key_t*>(key));
113}
114
115TEST(pthread, pthread_key_dirty) {
116  pthread_key_t key;
117  ASSERT_EQ(0, pthread_key_create(&key, NULL));
118
119  size_t stack_size = 128 * 1024;
120  void* stack = mmap(NULL, stack_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
121  ASSERT_NE(MAP_FAILED, stack);
122  memset(stack, 0xff, stack_size);
123
124  pthread_attr_t attr;
125  ASSERT_EQ(0, pthread_attr_init(&attr));
126  ASSERT_EQ(0, pthread_attr_setstack(&attr, stack, stack_size));
127
128  pthread_t t;
129  ASSERT_EQ(0, pthread_create(&t, &attr, DirtyKeyFn, &key));
130
131  void* result;
132  ASSERT_EQ(0, pthread_join(t, &result));
133  ASSERT_EQ(nullptr, result); // Not ~0!
134
135  ASSERT_EQ(0, munmap(stack, stack_size));
136  ASSERT_EQ(0, pthread_key_delete(key));
137}
138
139static void* IdFn(void* arg) {
140  return arg;
141}
142
143static void* SleepFn(void* arg) {
144  sleep(reinterpret_cast<uintptr_t>(arg));
145  return NULL;
146}
147
148static void* SpinFn(void* arg) {
149  volatile bool* b = reinterpret_cast<volatile bool*>(arg);
150  while (!*b) {
151  }
152  return NULL;
153}
154
155static void* JoinFn(void* arg) {
156  return reinterpret_cast<void*>(pthread_join(reinterpret_cast<pthread_t>(arg), NULL));
157}
158
159static void AssertDetached(pthread_t t, bool is_detached) {
160  pthread_attr_t attr;
161  ASSERT_EQ(0, pthread_getattr_np(t, &attr));
162  int detach_state;
163  ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &detach_state));
164  pthread_attr_destroy(&attr);
165  ASSERT_EQ(is_detached, (detach_state == PTHREAD_CREATE_DETACHED));
166}
167
168static void MakeDeadThread(pthread_t& t) {
169  ASSERT_EQ(0, pthread_create(&t, NULL, IdFn, NULL));
170  void* result;
171  ASSERT_EQ(0, pthread_join(t, &result));
172}
173
174TEST(pthread, pthread_create) {
175  void* expected_result = reinterpret_cast<void*>(123);
176  // Can we create a thread?
177  pthread_t t;
178  ASSERT_EQ(0, pthread_create(&t, NULL, IdFn, expected_result));
179  // If we join, do we get the expected value back?
180  void* result;
181  ASSERT_EQ(0, pthread_join(t, &result));
182  ASSERT_EQ(expected_result, result);
183}
184
185TEST(pthread, pthread_create_EAGAIN) {
186  pthread_attr_t attributes;
187  ASSERT_EQ(0, pthread_attr_init(&attributes));
188  ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, static_cast<size_t>(-1) & ~(getpagesize() - 1)));
189
190  pthread_t t;
191  ASSERT_EQ(EAGAIN, pthread_create(&t, &attributes, IdFn, NULL));
192}
193
194TEST(pthread, pthread_no_join_after_detach) {
195  pthread_t t1;
196  ASSERT_EQ(0, pthread_create(&t1, NULL, SleepFn, reinterpret_cast<void*>(5)));
197
198  // After a pthread_detach...
199  ASSERT_EQ(0, pthread_detach(t1));
200  AssertDetached(t1, true);
201
202  // ...pthread_join should fail.
203  void* result;
204  ASSERT_EQ(EINVAL, pthread_join(t1, &result));
205}
206
207TEST(pthread, pthread_no_op_detach_after_join) {
208  bool done = false;
209
210  pthread_t t1;
211  ASSERT_EQ(0, pthread_create(&t1, NULL, SpinFn, &done));
212
213  // If thread 2 is already waiting to join thread 1...
214  pthread_t t2;
215  ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1)));
216
217  sleep(1); // (Give t2 a chance to call pthread_join.)
218
219  // ...a call to pthread_detach on thread 1 will "succeed" (silently fail)...
220  ASSERT_EQ(0, pthread_detach(t1));
221  AssertDetached(t1, false);
222
223  done = true;
224
225  // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes).
226  void* join_result;
227  ASSERT_EQ(0, pthread_join(t2, &join_result));
228  ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
229}
230
231TEST(pthread, pthread_join_self) {
232  void* result;
233  ASSERT_EQ(EDEADLK, pthread_join(pthread_self(), &result));
234}
235
236struct TestBug37410 {
237  pthread_t main_thread;
238  pthread_mutex_t mutex;
239
240  static void main() {
241    TestBug37410 data;
242    data.main_thread = pthread_self();
243    ASSERT_EQ(0, pthread_mutex_init(&data.mutex, NULL));
244    ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
245
246    pthread_t t;
247    ASSERT_EQ(0, pthread_create(&t, NULL, TestBug37410::thread_fn, reinterpret_cast<void*>(&data)));
248
249    // Wait for the thread to be running...
250    ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
251    ASSERT_EQ(0, pthread_mutex_unlock(&data.mutex));
252
253    // ...and exit.
254    pthread_exit(NULL);
255  }
256
257 private:
258  static void* thread_fn(void* arg) {
259    TestBug37410* data = reinterpret_cast<TestBug37410*>(arg);
260
261    // Let the main thread know we're running.
262    pthread_mutex_unlock(&data->mutex);
263
264    // And wait for the main thread to exit.
265    pthread_join(data->main_thread, NULL);
266
267    return NULL;
268  }
269};
270
271// Even though this isn't really a death test, we have to say "DeathTest" here so gtest knows to
272// run this test (which exits normally) in its own process.
273TEST(pthread_DeathTest, pthread_bug_37410) {
274  // http://code.google.com/p/android/issues/detail?id=37410
275  ::testing::FLAGS_gtest_death_test_style = "threadsafe";
276  ASSERT_EXIT(TestBug37410::main(), ::testing::ExitedWithCode(0), "");
277}
278
279static void* SignalHandlerFn(void* arg) {
280  sigset_t wait_set;
281  sigfillset(&wait_set);
282  return reinterpret_cast<void*>(sigwait(&wait_set, reinterpret_cast<int*>(arg)));
283}
284
285TEST(pthread, pthread_sigmask) {
286  // Check that SIGUSR1 isn't blocked.
287  sigset_t original_set;
288  sigemptyset(&original_set);
289  ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, NULL, &original_set));
290  ASSERT_FALSE(sigismember(&original_set, SIGUSR1));
291
292  // Block SIGUSR1.
293  sigset_t set;
294  sigemptyset(&set);
295  sigaddset(&set, SIGUSR1);
296  ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, &set, NULL));
297
298  // Check that SIGUSR1 is blocked.
299  sigset_t final_set;
300  sigemptyset(&final_set);
301  ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, NULL, &final_set));
302  ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
303  // ...and that sigprocmask agrees with pthread_sigmask.
304  sigemptyset(&final_set);
305  ASSERT_EQ(0, sigprocmask(SIG_BLOCK, NULL, &final_set));
306  ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
307
308  // Spawn a thread that calls sigwait and tells us what it received.
309  pthread_t signal_thread;
310  int received_signal = -1;
311  ASSERT_EQ(0, pthread_create(&signal_thread, NULL, SignalHandlerFn, &received_signal));
312
313  // Send that thread SIGUSR1.
314  pthread_kill(signal_thread, SIGUSR1);
315
316  // See what it got.
317  void* join_result;
318  ASSERT_EQ(0, pthread_join(signal_thread, &join_result));
319  ASSERT_EQ(SIGUSR1, received_signal);
320  ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
321
322  // Restore the original signal mask.
323  ASSERT_EQ(0, pthread_sigmask(SIG_SETMASK, &original_set, NULL));
324}
325
326TEST(pthread, pthread_setname_np__too_long) {
327#if defined(__BIONIC__) // Not all build servers have a new enough glibc? TODO: remove when they're on gprecise.
328  ASSERT_EQ(ERANGE, pthread_setname_np(pthread_self(), "this name is far too long for linux"));
329#else // __BIONIC__
330  GTEST_LOG_(INFO) << "This test does nothing.\n";
331#endif // __BIONIC__
332}
333
334TEST(pthread, pthread_setname_np__self) {
335#if defined(__BIONIC__) // Not all build servers have a new enough glibc? TODO: remove when they're on gprecise.
336  ASSERT_EQ(0, pthread_setname_np(pthread_self(), "short 1"));
337#else // __BIONIC__
338  GTEST_LOG_(INFO) << "This test does nothing.\n";
339#endif // __BIONIC__
340}
341
342TEST(pthread, pthread_setname_np__other) {
343#if defined(__BIONIC__) // Not all build servers have a new enough glibc? TODO: remove when they're on gprecise.
344  // Emulator kernels don't currently support setting the name of other threads.
345  char* filename = NULL;
346  asprintf(&filename, "/proc/self/task/%d/comm", gettid());
347  struct stat sb;
348  bool has_comm = (stat(filename, &sb) != -1);
349  free(filename);
350
351  if (has_comm) {
352    pthread_t t1;
353    ASSERT_EQ(0, pthread_create(&t1, NULL, SleepFn, reinterpret_cast<void*>(5)));
354    ASSERT_EQ(0, pthread_setname_np(t1, "short 2"));
355  } else {
356    fprintf(stderr, "skipping test: this kernel doesn't have /proc/self/task/tid/comm files!\n");
357  }
358#else // __BIONIC__
359  GTEST_LOG_(INFO) << "This test does nothing.\n";
360#endif // __BIONIC__
361}
362
363TEST(pthread, pthread_setname_np__no_such_thread) {
364#if defined(__BIONIC__) // Not all build servers have a new enough glibc? TODO: remove when they're on gprecise.
365  pthread_t dead_thread;
366  MakeDeadThread(dead_thread);
367
368  // Call pthread_setname_np after thread has already exited.
369  ASSERT_EQ(ESRCH, pthread_setname_np(dead_thread, "short 3"));
370#else // __BIONIC__
371  GTEST_LOG_(INFO) << "This test does nothing.\n";
372#endif // __BIONIC__
373}
374
375TEST(pthread, pthread_kill__0) {
376  // Signal 0 just tests that the thread exists, so it's safe to call on ourselves.
377  ASSERT_EQ(0, pthread_kill(pthread_self(), 0));
378}
379
380TEST(pthread, pthread_kill__invalid_signal) {
381  ASSERT_EQ(EINVAL, pthread_kill(pthread_self(), -1));
382}
383
384static void pthread_kill__in_signal_handler_helper(int signal_number) {
385  static int count = 0;
386  ASSERT_EQ(SIGALRM, signal_number);
387  if (++count == 1) {
388    // Can we call pthread_kill from a signal handler?
389    ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
390  }
391}
392
393TEST(pthread, pthread_kill__in_signal_handler) {
394  ScopedSignalHandler ssh(SIGALRM, pthread_kill__in_signal_handler_helper);
395  ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
396}
397
398TEST(pthread, pthread_detach__no_such_thread) {
399  pthread_t dead_thread;
400  MakeDeadThread(dead_thread);
401
402  ASSERT_EQ(ESRCH, pthread_detach(dead_thread));
403}
404
405TEST(pthread, pthread_detach__leak) {
406  size_t initial_bytes = 0;
407  // Run this loop more than once since the first loop causes some memory
408  // to be allocated permenantly. Run an extra loop to help catch any subtle
409  // memory leaks.
410  for (size_t loop = 0; loop < 3; loop++) {
411    // Set the initial bytes on the second loop since the memory in use
412    // should have stabilized.
413    if (loop == 1) {
414      initial_bytes = mallinfo().uordblks;
415    }
416
417    pthread_attr_t attr;
418    ASSERT_EQ(0, pthread_attr_init(&attr));
419    ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
420
421    std::vector<pthread_t> threads;
422    for (size_t i = 0; i < 32; ++i) {
423      pthread_t t;
424      ASSERT_EQ(0, pthread_create(&t, &attr, IdFn, NULL));
425      threads.push_back(t);
426    }
427
428    sleep(1);
429
430    for (size_t i = 0; i < 32; ++i) {
431      ASSERT_EQ(0, pthread_detach(threads[i])) << i;
432    }
433  }
434
435  size_t final_bytes = mallinfo().uordblks;
436  int leaked_bytes = (final_bytes - initial_bytes);
437
438  // User code (like this test) doesn't know how large pthread_internal_t is.
439  // We can be pretty sure it's more than 128 bytes.
440  ASSERT_LT(leaked_bytes, 32 /*threads*/ * 128 /*bytes*/);
441}
442
443TEST(pthread, pthread_getcpuclockid__clock_gettime) {
444  pthread_t t;
445  ASSERT_EQ(0, pthread_create(&t, NULL, SleepFn, reinterpret_cast<void*>(5)));
446
447  clockid_t c;
448  ASSERT_EQ(0, pthread_getcpuclockid(t, &c));
449  timespec ts;
450  ASSERT_EQ(0, clock_gettime(c, &ts));
451}
452
453TEST(pthread, pthread_getcpuclockid__no_such_thread) {
454  pthread_t dead_thread;
455  MakeDeadThread(dead_thread);
456
457  clockid_t c;
458  ASSERT_EQ(ESRCH, pthread_getcpuclockid(dead_thread, &c));
459}
460
461TEST(pthread, pthread_getschedparam__no_such_thread) {
462  pthread_t dead_thread;
463  MakeDeadThread(dead_thread);
464
465  int policy;
466  sched_param param;
467  ASSERT_EQ(ESRCH, pthread_getschedparam(dead_thread, &policy, &param));
468}
469
470TEST(pthread, pthread_setschedparam__no_such_thread) {
471  pthread_t dead_thread;
472  MakeDeadThread(dead_thread);
473
474  int policy = 0;
475  sched_param param;
476  ASSERT_EQ(ESRCH, pthread_setschedparam(dead_thread, policy, &param));
477}
478
479TEST(pthread, pthread_join__no_such_thread) {
480  pthread_t dead_thread;
481  MakeDeadThread(dead_thread);
482
483  void* result;
484  ASSERT_EQ(ESRCH, pthread_join(dead_thread, &result));
485}
486
487TEST(pthread, pthread_kill__no_such_thread) {
488  pthread_t dead_thread;
489  MakeDeadThread(dead_thread);
490
491  ASSERT_EQ(ESRCH, pthread_kill(dead_thread, 0));
492}
493
494TEST(pthread, pthread_join__multijoin) {
495  bool done = false;
496
497  pthread_t t1;
498  ASSERT_EQ(0, pthread_create(&t1, NULL, SpinFn, &done));
499
500  pthread_t t2;
501  ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1)));
502
503  sleep(1); // (Give t2 a chance to call pthread_join.)
504
505  // Multiple joins to the same thread should fail.
506  ASSERT_EQ(EINVAL, pthread_join(t1, NULL));
507
508  done = true;
509
510  // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes).
511  void* join_result;
512  ASSERT_EQ(0, pthread_join(t2, &join_result));
513  ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
514}
515
516TEST(pthread, pthread_join__race) {
517  // http://b/11693195 --- pthread_join could return before the thread had actually exited.
518  // If the joiner unmapped the thread's stack, that could lead to SIGSEGV in the thread.
519  for (size_t i = 0; i < 1024; ++i) {
520    size_t stack_size = 64*1024;
521    void* stack = mmap(NULL, stack_size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
522
523    pthread_attr_t a;
524    pthread_attr_init(&a);
525    pthread_attr_setstack(&a, stack, stack_size);
526
527    pthread_t t;
528    ASSERT_EQ(0, pthread_create(&t, &a, IdFn, NULL));
529    ASSERT_EQ(0, pthread_join(t, NULL));
530    ASSERT_EQ(0, munmap(stack, stack_size));
531  }
532}
533
534static void* GetActualGuardSizeFn(void* arg) {
535  pthread_attr_t attributes;
536  pthread_getattr_np(pthread_self(), &attributes);
537  pthread_attr_getguardsize(&attributes, reinterpret_cast<size_t*>(arg));
538  return NULL;
539}
540
541static size_t GetActualGuardSize(const pthread_attr_t& attributes) {
542  size_t result;
543  pthread_t t;
544  pthread_create(&t, &attributes, GetActualGuardSizeFn, &result);
545  void* join_result;
546  pthread_join(t, &join_result);
547  return result;
548}
549
550static void* GetActualStackSizeFn(void* arg) {
551  pthread_attr_t attributes;
552  pthread_getattr_np(pthread_self(), &attributes);
553  pthread_attr_getstacksize(&attributes, reinterpret_cast<size_t*>(arg));
554  return NULL;
555}
556
557static size_t GetActualStackSize(const pthread_attr_t& attributes) {
558  size_t result;
559  pthread_t t;
560  pthread_create(&t, &attributes, GetActualStackSizeFn, &result);
561  void* join_result;
562  pthread_join(t, &join_result);
563  return result;
564}
565
566TEST(pthread, pthread_attr_setguardsize) {
567  pthread_attr_t attributes;
568  ASSERT_EQ(0, pthread_attr_init(&attributes));
569
570  // Get the default guard size.
571  size_t default_guard_size;
572  ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &default_guard_size));
573
574  // No such thing as too small: will be rounded up to one page by pthread_create.
575  ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 128));
576  size_t guard_size;
577  ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
578  ASSERT_EQ(128U, guard_size);
579  ASSERT_EQ(4096U, GetActualGuardSize(attributes));
580
581  // Large enough and a multiple of the page size.
582  ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024));
583  ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
584  ASSERT_EQ(32*1024U, guard_size);
585
586  // Large enough but not a multiple of the page size; will be rounded up by pthread_create.
587  ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024 + 1));
588  ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
589  ASSERT_EQ(32*1024U + 1, guard_size);
590}
591
592TEST(pthread, pthread_attr_setstacksize) {
593  pthread_attr_t attributes;
594  ASSERT_EQ(0, pthread_attr_init(&attributes));
595
596  // Get the default stack size.
597  size_t default_stack_size;
598  ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &default_stack_size));
599
600  // Too small.
601  ASSERT_EQ(EINVAL, pthread_attr_setstacksize(&attributes, 128));
602  size_t stack_size;
603  ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
604  ASSERT_EQ(default_stack_size, stack_size);
605  ASSERT_GE(GetActualStackSize(attributes), default_stack_size);
606
607  // Large enough and a multiple of the page size.
608  ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024));
609  ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
610  ASSERT_EQ(32*1024U, stack_size);
611  ASSERT_EQ(GetActualStackSize(attributes), 32*1024U);
612
613  // Large enough but not a multiple of the page size; will be rounded up by pthread_create.
614  ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024 + 1));
615  ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
616  ASSERT_EQ(32*1024U + 1, stack_size);
617#if defined(__BIONIC__)
618  // Bionic rounds up, which is what POSIX allows.
619  ASSERT_EQ(GetActualStackSize(attributes), (32 + 4)*1024U);
620#else // __BIONIC__
621  // glibc rounds down, in violation of POSIX. They document this in their BUGS section.
622  ASSERT_EQ(GetActualStackSize(attributes), 32*1024U);
623#endif // __BIONIC__
624}
625
626TEST(pthread, pthread_rwlock_smoke) {
627  pthread_rwlock_t l;
628  ASSERT_EQ(0, pthread_rwlock_init(&l, NULL));
629
630  // Single read lock
631  ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
632  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
633
634  // Multiple read lock
635  ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
636  ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
637  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
638  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
639
640  // Write lock
641  ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
642  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
643
644  // Try writer lock
645  ASSERT_EQ(0, pthread_rwlock_trywrlock(&l));
646  ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
647  ASSERT_EQ(EBUSY, pthread_rwlock_tryrdlock(&l));
648  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
649
650  // Try reader lock
651  ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
652  ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
653  ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
654  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
655  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
656
657  // Try writer lock after unlock
658  ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
659  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
660
661#ifdef __BIONIC__
662  // EDEADLK in "read after write"
663  ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
664  ASSERT_EQ(EDEADLK, pthread_rwlock_rdlock(&l));
665  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
666
667  // EDEADLK in "write after write"
668  ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
669  ASSERT_EQ(EDEADLK, pthread_rwlock_wrlock(&l));
670  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
671#endif
672
673  ASSERT_EQ(0, pthread_rwlock_destroy(&l));
674}
675
676static int g_once_fn_call_count = 0;
677static void OnceFn() {
678  ++g_once_fn_call_count;
679}
680
681TEST(pthread, pthread_once_smoke) {
682  pthread_once_t once_control = PTHREAD_ONCE_INIT;
683  ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
684  ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
685  ASSERT_EQ(1, g_once_fn_call_count);
686}
687
688static std::string pthread_once_1934122_result = "";
689
690static void Routine2() {
691  pthread_once_1934122_result += "2";
692}
693
694static void Routine1() {
695  pthread_once_t once_control_2 = PTHREAD_ONCE_INIT;
696  pthread_once_1934122_result += "1";
697  pthread_once(&once_control_2, &Routine2);
698}
699
700TEST(pthread, pthread_once_1934122) {
701  // Very old versions of Android couldn't call pthread_once from a
702  // pthread_once init routine. http://b/1934122.
703  pthread_once_t once_control_1 = PTHREAD_ONCE_INIT;
704  ASSERT_EQ(0, pthread_once(&once_control_1, &Routine1));
705  ASSERT_EQ("12", pthread_once_1934122_result);
706}
707
708static int g_atfork_prepare_calls = 0;
709static void AtForkPrepare1() { g_atfork_prepare_calls = (g_atfork_prepare_calls << 4) | 1; }
710static void AtForkPrepare2() { g_atfork_prepare_calls = (g_atfork_prepare_calls << 4) | 2; }
711static int g_atfork_parent_calls = 0;
712static void AtForkParent1() { g_atfork_parent_calls = (g_atfork_parent_calls << 4) | 1; }
713static void AtForkParent2() { g_atfork_parent_calls = (g_atfork_parent_calls << 4) | 2; }
714static int g_atfork_child_calls = 0;
715static void AtForkChild1() { g_atfork_child_calls = (g_atfork_child_calls << 4) | 1; }
716static void AtForkChild2() { g_atfork_child_calls = (g_atfork_child_calls << 4) | 2; }
717
718TEST(pthread, pthread_atfork) {
719  ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1));
720  ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2));
721
722  int pid = fork();
723  ASSERT_NE(-1, pid) << strerror(errno);
724
725  // Child and parent calls are made in the order they were registered.
726  if (pid == 0) {
727    ASSERT_EQ(0x12, g_atfork_child_calls);
728    _exit(0);
729  }
730  ASSERT_EQ(0x12, g_atfork_parent_calls);
731
732  // Prepare calls are made in the reverse order.
733  ASSERT_EQ(0x21, g_atfork_prepare_calls);
734}
735
736TEST(pthread, pthread_attr_getscope) {
737  pthread_attr_t attr;
738  ASSERT_EQ(0, pthread_attr_init(&attr));
739
740  int scope;
741  ASSERT_EQ(0, pthread_attr_getscope(&attr, &scope));
742  ASSERT_EQ(PTHREAD_SCOPE_SYSTEM, scope);
743}
744
745TEST(pthread, pthread_condattr_init) {
746  pthread_condattr_t attr;
747  pthread_condattr_init(&attr);
748
749  clockid_t clock;
750  ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
751  ASSERT_EQ(CLOCK_REALTIME, clock);
752
753  int pshared;
754  ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
755  ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
756}
757
758TEST(pthread, pthread_condattr_setclock) {
759  pthread_condattr_t attr;
760  pthread_condattr_init(&attr);
761
762  ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_REALTIME));
763  clockid_t clock;
764  ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
765  ASSERT_EQ(CLOCK_REALTIME, clock);
766
767  ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
768  ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
769  ASSERT_EQ(CLOCK_MONOTONIC, clock);
770
771  ASSERT_EQ(EINVAL, pthread_condattr_setclock(&attr, CLOCK_PROCESS_CPUTIME_ID));
772}
773
774TEST(pthread, pthread_cond_broadcast__preserves_condattr_flags) {
775#if defined(__BIONIC__) // This tests a bionic implementation detail.
776  pthread_condattr_t attr;
777  pthread_condattr_init(&attr);
778
779  ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
780  ASSERT_EQ(0, pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
781
782  pthread_cond_t cond_var;
783  ASSERT_EQ(0, pthread_cond_init(&cond_var, &attr));
784
785  ASSERT_EQ(0, pthread_cond_signal(&cond_var));
786  ASSERT_EQ(0, pthread_cond_broadcast(&cond_var));
787
788  attr = static_cast<pthread_condattr_t>(cond_var.value);
789  clockid_t clock;
790  ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
791  ASSERT_EQ(CLOCK_MONOTONIC, clock);
792  int pshared;
793  ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
794  ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
795#else // __BIONIC__
796  GTEST_LOG_(INFO) << "This test does nothing.\n";
797#endif // __BIONIC__
798}
799
800TEST(pthread, pthread_mutex_timedlock) {
801  pthread_mutex_t m;
802  ASSERT_EQ(0, pthread_mutex_init(&m, NULL));
803
804  // If the mutex is already locked, pthread_mutex_timedlock should time out.
805  ASSERT_EQ(0, pthread_mutex_lock(&m));
806
807  timespec ts;
808  ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
809  ts.tv_nsec += 1;
810  ASSERT_EQ(ETIMEDOUT, pthread_mutex_timedlock(&m, &ts));
811
812  // If the mutex is unlocked, pthread_mutex_timedlock should succeed.
813  ASSERT_EQ(0, pthread_mutex_unlock(&m));
814
815  ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
816  ts.tv_nsec += 1;
817  ASSERT_EQ(0, pthread_mutex_timedlock(&m, &ts));
818
819  ASSERT_EQ(0, pthread_mutex_unlock(&m));
820  ASSERT_EQ(0, pthread_mutex_destroy(&m));
821}
822
823TEST(pthread, pthread_attr_getstack__main_thread) {
824  // This test is only meaningful for the main thread, so make sure we're running on it!
825  ASSERT_EQ(getpid(), syscall(__NR_gettid));
826
827  // Get the main thread's attributes.
828  pthread_attr_t attributes;
829  ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
830
831  // Check that we correctly report that the main thread has no guard page.
832  size_t guard_size;
833  ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
834  ASSERT_EQ(0U, guard_size); // The main thread has no guard page.
835
836  // Get the stack base and the stack size (both ways).
837  void* stack_base;
838  size_t stack_size;
839  ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
840  size_t stack_size2;
841  ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
842
843  // The two methods of asking for the stack size should agree.
844  EXPECT_EQ(stack_size, stack_size2);
845
846  // What does /proc/self/maps' [stack] line say?
847  void* maps_stack_hi = NULL;
848  FILE* fp = fopen("/proc/self/maps", "r");
849  ASSERT_TRUE(fp != NULL);
850  char line[BUFSIZ];
851  while (fgets(line, sizeof(line), fp) != NULL) {
852    uintptr_t lo, hi;
853    char name[10];
854    sscanf(line, "%" PRIxPTR "-%" PRIxPTR " %*4s %*x %*x:%*x %*d %10s", &lo, &hi, name);
855    if (strcmp(name, "[stack]") == 0) {
856      maps_stack_hi = reinterpret_cast<void*>(hi);
857      break;
858    }
859  }
860  fclose(fp);
861
862  // The stack size should correspond to RLIMIT_STACK.
863  rlimit rl;
864  ASSERT_EQ(0, getrlimit(RLIMIT_STACK, &rl));
865  EXPECT_EQ(rl.rlim_cur, stack_size);
866
867  // The high address of the /proc/self/maps [stack] region should equal stack_base + stack_size.
868  // Remember that the stack grows down (and is mapped in on demand), so the low address of the
869  // region isn't very interesting.
870  EXPECT_EQ(maps_stack_hi, reinterpret_cast<uint8_t*>(stack_base) + stack_size);
871
872  //
873  // What if RLIMIT_STACK is smaller than the stack's current extent?
874  //
875  rl.rlim_cur = rl.rlim_max = 1024; // 1KiB. We know the stack must be at least a page already.
876  rl.rlim_max = RLIM_INFINITY;
877  ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
878
879  ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
880  ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
881  ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
882
883  EXPECT_EQ(stack_size, stack_size2);
884  ASSERT_EQ(1024U, stack_size);
885
886  //
887  // What if RLIMIT_STACK isn't a whole number of pages?
888  //
889  rl.rlim_cur = rl.rlim_max = 6666; // Not a whole number of pages.
890  rl.rlim_max = RLIM_INFINITY;
891  ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
892
893  ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
894  ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
895  ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
896
897  EXPECT_EQ(stack_size, stack_size2);
898  ASSERT_EQ(6666U, stack_size);
899}
900