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