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