pthread_test.cpp revision c9a659c57b256001fd63f9825bde69e660c2655b
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 <stdio.h>
26#include <sys/mman.h>
27#include <sys/syscall.h>
28#include <time.h>
29#include <unistd.h>
30#include <unwind.h>
31
32#include <atomic>
33#include <regex>
34#include <vector>
35
36#include <base/file.h>
37#include <base/stringprintf.h>
38
39#include "private/bionic_constants.h"
40#include "private/bionic_macros.h"
41#include "private/ScopeGuard.h"
42#include "BionicDeathTest.h"
43#include "ScopedSignalHandler.h"
44
45#include "utils.h"
46
47extern "C" pid_t gettid();
48
49TEST(pthread, pthread_key_create) {
50  pthread_key_t key;
51  ASSERT_EQ(0, pthread_key_create(&key, NULL));
52  ASSERT_EQ(0, pthread_key_delete(key));
53  // Can't delete a key that's already been deleted.
54  ASSERT_EQ(EINVAL, pthread_key_delete(key));
55}
56
57TEST(pthread, pthread_keys_max) {
58  // POSIX says PTHREAD_KEYS_MAX should be at least _POSIX_THREAD_KEYS_MAX.
59  ASSERT_GE(PTHREAD_KEYS_MAX, _POSIX_THREAD_KEYS_MAX);
60}
61
62TEST(pthread, sysconf_SC_THREAD_KEYS_MAX_eq_PTHREAD_KEYS_MAX) {
63  int sysconf_max = sysconf(_SC_THREAD_KEYS_MAX);
64  ASSERT_EQ(sysconf_max, PTHREAD_KEYS_MAX);
65}
66
67TEST(pthread, pthread_key_many_distinct) {
68  // As gtest uses pthread keys, we can't allocate exactly PTHREAD_KEYS_MAX
69  // pthread keys, but We should be able to allocate at least this many keys.
70  int nkeys = PTHREAD_KEYS_MAX / 2;
71  std::vector<pthread_key_t> keys;
72
73  auto scope_guard = make_scope_guard([&keys]{
74    for (const auto& key : keys) {
75      EXPECT_EQ(0, pthread_key_delete(key));
76    }
77  });
78
79  for (int i = 0; i < nkeys; ++i) {
80    pthread_key_t key;
81    // If this fails, it's likely that LIBC_PTHREAD_KEY_RESERVED_COUNT is wrong.
82    ASSERT_EQ(0, pthread_key_create(&key, NULL)) << i << " of " << nkeys;
83    keys.push_back(key);
84    ASSERT_EQ(0, pthread_setspecific(key, reinterpret_cast<void*>(i)));
85  }
86
87  for (int i = keys.size() - 1; i >= 0; --i) {
88    ASSERT_EQ(reinterpret_cast<void*>(i), pthread_getspecific(keys.back()));
89    pthread_key_t key = keys.back();
90    keys.pop_back();
91    ASSERT_EQ(0, pthread_key_delete(key));
92  }
93}
94
95TEST(pthread, pthread_key_not_exceed_PTHREAD_KEYS_MAX) {
96  std::vector<pthread_key_t> keys;
97  int rv = 0;
98
99  // Pthread keys are used by gtest, so PTHREAD_KEYS_MAX should
100  // be more than we are allowed to allocate now.
101  for (int i = 0; i < PTHREAD_KEYS_MAX; i++) {
102    pthread_key_t key;
103    rv = pthread_key_create(&key, NULL);
104    if (rv == EAGAIN) {
105      break;
106    }
107    EXPECT_EQ(0, rv);
108    keys.push_back(key);
109  }
110
111  // Don't leak keys.
112  for (const auto& key : keys) {
113    EXPECT_EQ(0, pthread_key_delete(key));
114  }
115  keys.clear();
116
117  // We should have eventually reached the maximum number of keys and received
118  // EAGAIN.
119  ASSERT_EQ(EAGAIN, rv);
120}
121
122TEST(pthread, pthread_key_delete) {
123  void* expected = reinterpret_cast<void*>(1234);
124  pthread_key_t key;
125  ASSERT_EQ(0, pthread_key_create(&key, NULL));
126  ASSERT_EQ(0, pthread_setspecific(key, expected));
127  ASSERT_EQ(expected, pthread_getspecific(key));
128  ASSERT_EQ(0, pthread_key_delete(key));
129  // After deletion, pthread_getspecific returns NULL.
130  ASSERT_EQ(NULL, pthread_getspecific(key));
131  // And you can't use pthread_setspecific with the deleted key.
132  ASSERT_EQ(EINVAL, pthread_setspecific(key, expected));
133}
134
135TEST(pthread, pthread_key_fork) {
136  void* expected = reinterpret_cast<void*>(1234);
137  pthread_key_t key;
138  ASSERT_EQ(0, pthread_key_create(&key, NULL));
139  ASSERT_EQ(0, pthread_setspecific(key, expected));
140  ASSERT_EQ(expected, pthread_getspecific(key));
141
142  pid_t pid = fork();
143  ASSERT_NE(-1, pid) << strerror(errno);
144
145  if (pid == 0) {
146    // The surviving thread inherits all the forking thread's TLS values...
147    ASSERT_EQ(expected, pthread_getspecific(key));
148    _exit(99);
149  }
150
151  int status;
152  ASSERT_EQ(pid, waitpid(pid, &status, 0));
153  ASSERT_TRUE(WIFEXITED(status));
154  ASSERT_EQ(99, WEXITSTATUS(status));
155
156  ASSERT_EQ(expected, pthread_getspecific(key));
157  ASSERT_EQ(0, pthread_key_delete(key));
158}
159
160static void* DirtyKeyFn(void* key) {
161  return pthread_getspecific(*reinterpret_cast<pthread_key_t*>(key));
162}
163
164TEST(pthread, pthread_key_dirty) {
165  pthread_key_t key;
166  ASSERT_EQ(0, pthread_key_create(&key, NULL));
167
168  size_t stack_size = 128 * 1024;
169  void* stack = mmap(NULL, stack_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
170  ASSERT_NE(MAP_FAILED, stack);
171  memset(stack, 0xff, stack_size);
172
173  pthread_attr_t attr;
174  ASSERT_EQ(0, pthread_attr_init(&attr));
175  ASSERT_EQ(0, pthread_attr_setstack(&attr, stack, stack_size));
176
177  pthread_t t;
178  ASSERT_EQ(0, pthread_create(&t, &attr, DirtyKeyFn, &key));
179
180  void* result;
181  ASSERT_EQ(0, pthread_join(t, &result));
182  ASSERT_EQ(nullptr, result); // Not ~0!
183
184  ASSERT_EQ(0, munmap(stack, stack_size));
185  ASSERT_EQ(0, pthread_key_delete(key));
186}
187
188TEST(pthread, static_pthread_key_used_before_creation) {
189#if defined(__BIONIC__)
190  // See http://b/19625804. The bug is about a static/global pthread key being used before creation.
191  // So here tests if the static/global default value 0 can be detected as invalid key.
192  static pthread_key_t key;
193  ASSERT_EQ(nullptr, pthread_getspecific(key));
194  ASSERT_EQ(EINVAL, pthread_setspecific(key, nullptr));
195  ASSERT_EQ(EINVAL, pthread_key_delete(key));
196#else
197  GTEST_LOG_(INFO) << "This test tests bionic pthread key implementation detail.\n";
198#endif
199}
200
201static void* IdFn(void* arg) {
202  return arg;
203}
204
205class SpinFunctionHelper {
206 public:
207  SpinFunctionHelper() {
208    SpinFunctionHelper::spin_flag_ = true;
209  }
210  ~SpinFunctionHelper() {
211    UnSpin();
212  }
213  auto GetFunction() -> void* (*)(void*) {
214    return SpinFunctionHelper::SpinFn;
215  }
216
217  void UnSpin() {
218    SpinFunctionHelper::spin_flag_ = false;
219  }
220
221 private:
222  static void* SpinFn(void*) {
223    while (spin_flag_) {}
224    return NULL;
225  }
226  static volatile bool spin_flag_;
227};
228
229// It doesn't matter if spin_flag_ is used in several tests,
230// because it is always set to false after each test. Each thread
231// loops on spin_flag_ can find it becomes false at some time.
232volatile bool SpinFunctionHelper::spin_flag_ = false;
233
234static void* JoinFn(void* arg) {
235  return reinterpret_cast<void*>(pthread_join(reinterpret_cast<pthread_t>(arg), NULL));
236}
237
238static void AssertDetached(pthread_t t, bool is_detached) {
239  pthread_attr_t attr;
240  ASSERT_EQ(0, pthread_getattr_np(t, &attr));
241  int detach_state;
242  ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &detach_state));
243  pthread_attr_destroy(&attr);
244  ASSERT_EQ(is_detached, (detach_state == PTHREAD_CREATE_DETACHED));
245}
246
247static void MakeDeadThread(pthread_t& t) {
248  ASSERT_EQ(0, pthread_create(&t, NULL, IdFn, NULL));
249  ASSERT_EQ(0, pthread_join(t, NULL));
250}
251
252TEST(pthread, pthread_create) {
253  void* expected_result = reinterpret_cast<void*>(123);
254  // Can we create a thread?
255  pthread_t t;
256  ASSERT_EQ(0, pthread_create(&t, NULL, IdFn, expected_result));
257  // If we join, do we get the expected value back?
258  void* result;
259  ASSERT_EQ(0, pthread_join(t, &result));
260  ASSERT_EQ(expected_result, result);
261}
262
263TEST(pthread, pthread_create_EAGAIN) {
264  pthread_attr_t attributes;
265  ASSERT_EQ(0, pthread_attr_init(&attributes));
266  ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, static_cast<size_t>(-1) & ~(getpagesize() - 1)));
267
268  pthread_t t;
269  ASSERT_EQ(EAGAIN, pthread_create(&t, &attributes, IdFn, NULL));
270}
271
272TEST(pthread, pthread_no_join_after_detach) {
273  SpinFunctionHelper spinhelper;
274
275  pthread_t t1;
276  ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL));
277
278  // After a pthread_detach...
279  ASSERT_EQ(0, pthread_detach(t1));
280  AssertDetached(t1, true);
281
282  // ...pthread_join should fail.
283  ASSERT_EQ(EINVAL, pthread_join(t1, NULL));
284}
285
286TEST(pthread, pthread_no_op_detach_after_join) {
287  SpinFunctionHelper spinhelper;
288
289  pthread_t t1;
290  ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL));
291
292  // If thread 2 is already waiting to join thread 1...
293  pthread_t t2;
294  ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1)));
295
296  sleep(1); // (Give t2 a chance to call pthread_join.)
297
298#if defined(__BIONIC__)
299  ASSERT_EQ(EINVAL, pthread_detach(t1));
300#else
301  ASSERT_EQ(0, pthread_detach(t1));
302#endif
303  AssertDetached(t1, false);
304
305  spinhelper.UnSpin();
306
307  // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes).
308  void* join_result;
309  ASSERT_EQ(0, pthread_join(t2, &join_result));
310  ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
311}
312
313TEST(pthread, pthread_join_self) {
314  ASSERT_EQ(EDEADLK, pthread_join(pthread_self(), NULL));
315}
316
317struct TestBug37410 {
318  pthread_t main_thread;
319  pthread_mutex_t mutex;
320
321  static void main() {
322    TestBug37410 data;
323    data.main_thread = pthread_self();
324    ASSERT_EQ(0, pthread_mutex_init(&data.mutex, NULL));
325    ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
326
327    pthread_t t;
328    ASSERT_EQ(0, pthread_create(&t, NULL, TestBug37410::thread_fn, reinterpret_cast<void*>(&data)));
329
330    // Wait for the thread to be running...
331    ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
332    ASSERT_EQ(0, pthread_mutex_unlock(&data.mutex));
333
334    // ...and exit.
335    pthread_exit(NULL);
336  }
337
338 private:
339  static void* thread_fn(void* arg) {
340    TestBug37410* data = reinterpret_cast<TestBug37410*>(arg);
341
342    // Let the main thread know we're running.
343    pthread_mutex_unlock(&data->mutex);
344
345    // And wait for the main thread to exit.
346    pthread_join(data->main_thread, NULL);
347
348    return NULL;
349  }
350};
351
352// Even though this isn't really a death test, we have to say "DeathTest" here so gtest knows to
353// run this test (which exits normally) in its own process.
354
355class pthread_DeathTest : public BionicDeathTest {};
356
357TEST_F(pthread_DeathTest, pthread_bug_37410) {
358  // http://code.google.com/p/android/issues/detail?id=37410
359  ASSERT_EXIT(TestBug37410::main(), ::testing::ExitedWithCode(0), "");
360}
361
362static void* SignalHandlerFn(void* arg) {
363  sigset_t wait_set;
364  sigfillset(&wait_set);
365  return reinterpret_cast<void*>(sigwait(&wait_set, reinterpret_cast<int*>(arg)));
366}
367
368TEST(pthread, pthread_sigmask) {
369  // Check that SIGUSR1 isn't blocked.
370  sigset_t original_set;
371  sigemptyset(&original_set);
372  ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, NULL, &original_set));
373  ASSERT_FALSE(sigismember(&original_set, SIGUSR1));
374
375  // Block SIGUSR1.
376  sigset_t set;
377  sigemptyset(&set);
378  sigaddset(&set, SIGUSR1);
379  ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, &set, NULL));
380
381  // Check that SIGUSR1 is blocked.
382  sigset_t final_set;
383  sigemptyset(&final_set);
384  ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, NULL, &final_set));
385  ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
386  // ...and that sigprocmask agrees with pthread_sigmask.
387  sigemptyset(&final_set);
388  ASSERT_EQ(0, sigprocmask(SIG_BLOCK, NULL, &final_set));
389  ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
390
391  // Spawn a thread that calls sigwait and tells us what it received.
392  pthread_t signal_thread;
393  int received_signal = -1;
394  ASSERT_EQ(0, pthread_create(&signal_thread, NULL, SignalHandlerFn, &received_signal));
395
396  // Send that thread SIGUSR1.
397  pthread_kill(signal_thread, SIGUSR1);
398
399  // See what it got.
400  void* join_result;
401  ASSERT_EQ(0, pthread_join(signal_thread, &join_result));
402  ASSERT_EQ(SIGUSR1, received_signal);
403  ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
404
405  // Restore the original signal mask.
406  ASSERT_EQ(0, pthread_sigmask(SIG_SETMASK, &original_set, NULL));
407}
408
409TEST(pthread, pthread_setname_np__too_long) {
410  // The limit is 15 characters --- the kernel's buffer is 16, but includes a NUL.
411  ASSERT_EQ(0, pthread_setname_np(pthread_self(), "123456789012345"));
412  ASSERT_EQ(ERANGE, pthread_setname_np(pthread_self(), "1234567890123456"));
413}
414
415TEST(pthread, pthread_setname_np__self) {
416  ASSERT_EQ(0, pthread_setname_np(pthread_self(), "short 1"));
417}
418
419TEST(pthread, pthread_setname_np__other) {
420  SpinFunctionHelper spinhelper;
421
422  pthread_t t1;
423  ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL));
424  ASSERT_EQ(0, pthread_setname_np(t1, "short 2"));
425}
426
427TEST(pthread, pthread_setname_np__no_such_thread) {
428  pthread_t dead_thread;
429  MakeDeadThread(dead_thread);
430
431  // Call pthread_setname_np after thread has already exited.
432  ASSERT_EQ(ENOENT, pthread_setname_np(dead_thread, "short 3"));
433}
434
435TEST(pthread, pthread_kill__0) {
436  // Signal 0 just tests that the thread exists, so it's safe to call on ourselves.
437  ASSERT_EQ(0, pthread_kill(pthread_self(), 0));
438}
439
440TEST(pthread, pthread_kill__invalid_signal) {
441  ASSERT_EQ(EINVAL, pthread_kill(pthread_self(), -1));
442}
443
444static void pthread_kill__in_signal_handler_helper(int signal_number) {
445  static int count = 0;
446  ASSERT_EQ(SIGALRM, signal_number);
447  if (++count == 1) {
448    // Can we call pthread_kill from a signal handler?
449    ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
450  }
451}
452
453TEST(pthread, pthread_kill__in_signal_handler) {
454  ScopedSignalHandler ssh(SIGALRM, pthread_kill__in_signal_handler_helper);
455  ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
456}
457
458TEST(pthread, pthread_detach__no_such_thread) {
459  pthread_t dead_thread;
460  MakeDeadThread(dead_thread);
461
462  ASSERT_EQ(ESRCH, pthread_detach(dead_thread));
463}
464
465TEST(pthread, pthread_getcpuclockid__clock_gettime) {
466  SpinFunctionHelper spinhelper;
467
468  pthread_t t;
469  ASSERT_EQ(0, pthread_create(&t, NULL, spinhelper.GetFunction(), NULL));
470
471  clockid_t c;
472  ASSERT_EQ(0, pthread_getcpuclockid(t, &c));
473  timespec ts;
474  ASSERT_EQ(0, clock_gettime(c, &ts));
475}
476
477TEST(pthread, pthread_getcpuclockid__no_such_thread) {
478  pthread_t dead_thread;
479  MakeDeadThread(dead_thread);
480
481  clockid_t c;
482  ASSERT_EQ(ESRCH, pthread_getcpuclockid(dead_thread, &c));
483}
484
485TEST(pthread, pthread_getschedparam__no_such_thread) {
486  pthread_t dead_thread;
487  MakeDeadThread(dead_thread);
488
489  int policy;
490  sched_param param;
491  ASSERT_EQ(ESRCH, pthread_getschedparam(dead_thread, &policy, &param));
492}
493
494TEST(pthread, pthread_setschedparam__no_such_thread) {
495  pthread_t dead_thread;
496  MakeDeadThread(dead_thread);
497
498  int policy = 0;
499  sched_param param;
500  ASSERT_EQ(ESRCH, pthread_setschedparam(dead_thread, policy, &param));
501}
502
503TEST(pthread, pthread_join__no_such_thread) {
504  pthread_t dead_thread;
505  MakeDeadThread(dead_thread);
506
507  ASSERT_EQ(ESRCH, pthread_join(dead_thread, NULL));
508}
509
510TEST(pthread, pthread_kill__no_such_thread) {
511  pthread_t dead_thread;
512  MakeDeadThread(dead_thread);
513
514  ASSERT_EQ(ESRCH, pthread_kill(dead_thread, 0));
515}
516
517TEST(pthread, pthread_join__multijoin) {
518  SpinFunctionHelper spinhelper;
519
520  pthread_t t1;
521  ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL));
522
523  pthread_t t2;
524  ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1)));
525
526  sleep(1); // (Give t2 a chance to call pthread_join.)
527
528  // Multiple joins to the same thread should fail.
529  ASSERT_EQ(EINVAL, pthread_join(t1, NULL));
530
531  spinhelper.UnSpin();
532
533  // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes).
534  void* join_result;
535  ASSERT_EQ(0, pthread_join(t2, &join_result));
536  ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
537}
538
539TEST(pthread, pthread_join__race) {
540  // http://b/11693195 --- pthread_join could return before the thread had actually exited.
541  // If the joiner unmapped the thread's stack, that could lead to SIGSEGV in the thread.
542  for (size_t i = 0; i < 1024; ++i) {
543    size_t stack_size = 64*1024;
544    void* stack = mmap(NULL, stack_size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
545
546    pthread_attr_t a;
547    pthread_attr_init(&a);
548    pthread_attr_setstack(&a, stack, stack_size);
549
550    pthread_t t;
551    ASSERT_EQ(0, pthread_create(&t, &a, IdFn, NULL));
552    ASSERT_EQ(0, pthread_join(t, NULL));
553    ASSERT_EQ(0, munmap(stack, stack_size));
554  }
555}
556
557static void* GetActualGuardSizeFn(void* arg) {
558  pthread_attr_t attributes;
559  pthread_getattr_np(pthread_self(), &attributes);
560  pthread_attr_getguardsize(&attributes, reinterpret_cast<size_t*>(arg));
561  return NULL;
562}
563
564static size_t GetActualGuardSize(const pthread_attr_t& attributes) {
565  size_t result;
566  pthread_t t;
567  pthread_create(&t, &attributes, GetActualGuardSizeFn, &result);
568  pthread_join(t, NULL);
569  return result;
570}
571
572static void* GetActualStackSizeFn(void* arg) {
573  pthread_attr_t attributes;
574  pthread_getattr_np(pthread_self(), &attributes);
575  pthread_attr_getstacksize(&attributes, reinterpret_cast<size_t*>(arg));
576  return NULL;
577}
578
579static size_t GetActualStackSize(const pthread_attr_t& attributes) {
580  size_t result;
581  pthread_t t;
582  pthread_create(&t, &attributes, GetActualStackSizeFn, &result);
583  pthread_join(t, NULL);
584  return result;
585}
586
587TEST(pthread, pthread_attr_setguardsize) {
588  pthread_attr_t attributes;
589  ASSERT_EQ(0, pthread_attr_init(&attributes));
590
591  // Get the default guard size.
592  size_t default_guard_size;
593  ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &default_guard_size));
594
595  // No such thing as too small: will be rounded up to one page by pthread_create.
596  ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 128));
597  size_t guard_size;
598  ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
599  ASSERT_EQ(128U, guard_size);
600  ASSERT_EQ(4096U, GetActualGuardSize(attributes));
601
602  // Large enough and a multiple of the page size.
603  ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024));
604  ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
605  ASSERT_EQ(32*1024U, guard_size);
606
607  // Large enough but not a multiple of the page size; will be rounded up by pthread_create.
608  ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024 + 1));
609  ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
610  ASSERT_EQ(32*1024U + 1, guard_size);
611}
612
613TEST(pthread, pthread_attr_setstacksize) {
614  pthread_attr_t attributes;
615  ASSERT_EQ(0, pthread_attr_init(&attributes));
616
617  // Get the default stack size.
618  size_t default_stack_size;
619  ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &default_stack_size));
620
621  // Too small.
622  ASSERT_EQ(EINVAL, pthread_attr_setstacksize(&attributes, 128));
623  size_t stack_size;
624  ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
625  ASSERT_EQ(default_stack_size, stack_size);
626  ASSERT_GE(GetActualStackSize(attributes), default_stack_size);
627
628  // Large enough and a multiple of the page size; may be rounded up by pthread_create.
629  ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024));
630  ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
631  ASSERT_EQ(32*1024U, stack_size);
632  ASSERT_GE(GetActualStackSize(attributes), 32*1024U);
633
634  // Large enough but not aligned; will be rounded up by pthread_create.
635  ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024 + 1));
636  ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
637  ASSERT_EQ(32*1024U + 1, stack_size);
638#if defined(__BIONIC__)
639  ASSERT_GT(GetActualStackSize(attributes), 32*1024U + 1);
640#else // __BIONIC__
641  // glibc rounds down, in violation of POSIX. They document this in their BUGS section.
642  ASSERT_EQ(GetActualStackSize(attributes), 32*1024U);
643#endif // __BIONIC__
644}
645
646TEST(pthread, pthread_rwlockattr_smoke) {
647  pthread_rwlockattr_t attr;
648  ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
649
650  int pshared_value_array[] = {PTHREAD_PROCESS_PRIVATE, PTHREAD_PROCESS_SHARED};
651  for (size_t i = 0; i < sizeof(pshared_value_array) / sizeof(pshared_value_array[0]); ++i) {
652    ASSERT_EQ(0, pthread_rwlockattr_setpshared(&attr, pshared_value_array[i]));
653    int pshared;
654    ASSERT_EQ(0, pthread_rwlockattr_getpshared(&attr, &pshared));
655    ASSERT_EQ(pshared_value_array[i], pshared);
656  }
657
658  int kind_array[] = {PTHREAD_RWLOCK_PREFER_READER_NP,
659                      PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP};
660  for (size_t i = 0; i < sizeof(kind_array) / sizeof(kind_array[0]); ++i) {
661    ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_array[i]));
662    int kind;
663    ASSERT_EQ(0, pthread_rwlockattr_getkind_np(&attr, &kind));
664    ASSERT_EQ(kind_array[i], kind);
665  }
666
667  ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
668}
669
670TEST(pthread, pthread_rwlock_init_same_as_PTHREAD_RWLOCK_INITIALIZER) {
671  pthread_rwlock_t lock1 = PTHREAD_RWLOCK_INITIALIZER;
672  pthread_rwlock_t lock2;
673  ASSERT_EQ(0, pthread_rwlock_init(&lock2, NULL));
674  ASSERT_EQ(0, memcmp(&lock1, &lock2, sizeof(lock1)));
675}
676
677TEST(pthread, pthread_rwlock_smoke) {
678  pthread_rwlock_t l;
679  ASSERT_EQ(0, pthread_rwlock_init(&l, NULL));
680
681  // Single read lock
682  ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
683  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
684
685  // Multiple read lock
686  ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
687  ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
688  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
689  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
690
691  // Write lock
692  ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
693  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
694
695  // Try writer lock
696  ASSERT_EQ(0, pthread_rwlock_trywrlock(&l));
697  ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
698  ASSERT_EQ(EBUSY, pthread_rwlock_tryrdlock(&l));
699  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
700
701  // Try reader lock
702  ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
703  ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
704  ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
705  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
706  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
707
708  // Try writer lock after unlock
709  ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
710  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
711
712  // EDEADLK in "read after write"
713  ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
714  ASSERT_EQ(EDEADLK, pthread_rwlock_rdlock(&l));
715  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
716
717  // EDEADLK in "write after write"
718  ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
719  ASSERT_EQ(EDEADLK, pthread_rwlock_wrlock(&l));
720  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
721
722  ASSERT_EQ(0, pthread_rwlock_destroy(&l));
723}
724
725static void WaitUntilThreadSleep(std::atomic<pid_t>& tid) {
726  while (tid == 0) {
727    usleep(1000);
728  }
729  std::string filename = android::base::StringPrintf("/proc/%d/stat", tid.load());
730  std::regex regex {R"(\s+S\s+)"};
731
732  while (true) {
733    std::string content;
734    ASSERT_TRUE(android::base::ReadFileToString(filename, &content));
735    if (std::regex_search(content, regex)) {
736      break;
737    }
738    usleep(1000);
739  }
740}
741
742struct RwlockWakeupHelperArg {
743  pthread_rwlock_t lock;
744  enum Progress {
745    LOCK_INITIALIZED,
746    LOCK_WAITING,
747    LOCK_RELEASED,
748    LOCK_ACCESSED,
749    LOCK_TIMEDOUT,
750  };
751  std::atomic<Progress> progress;
752  std::atomic<pid_t> tid;
753  std::function<int (pthread_rwlock_t*)> trylock_function;
754  std::function<int (pthread_rwlock_t*)> lock_function;
755  std::function<int (pthread_rwlock_t*, const timespec*)> timed_lock_function;
756};
757
758static void pthread_rwlock_wakeup_helper(RwlockWakeupHelperArg* arg) {
759  arg->tid = gettid();
760  ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
761  arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
762
763  ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
764  ASSERT_EQ(0, arg->lock_function(&arg->lock));
765  ASSERT_EQ(RwlockWakeupHelperArg::LOCK_RELEASED, arg->progress);
766  ASSERT_EQ(0, pthread_rwlock_unlock(&arg->lock));
767
768  arg->progress = RwlockWakeupHelperArg::LOCK_ACCESSED;
769}
770
771static void test_pthread_rwlock_reader_wakeup_writer(std::function<int (pthread_rwlock_t*)> lock_function) {
772  RwlockWakeupHelperArg wakeup_arg;
773  ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, NULL));
774  ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
775  wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
776  wakeup_arg.tid = 0;
777  wakeup_arg.trylock_function = pthread_rwlock_trywrlock;
778  wakeup_arg.lock_function = lock_function;
779
780  pthread_t thread;
781  ASSERT_EQ(0, pthread_create(&thread, NULL,
782    reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
783  WaitUntilThreadSleep(wakeup_arg.tid);
784  ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
785
786  wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
787  ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
788
789  ASSERT_EQ(0, pthread_join(thread, NULL));
790  ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
791  ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
792}
793
794TEST(pthread, pthread_rwlock_reader_wakeup_writer) {
795  test_pthread_rwlock_reader_wakeup_writer(pthread_rwlock_wrlock);
796}
797
798TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait) {
799  timespec ts;
800  ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
801  ts.tv_sec += 1;
802  test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) {
803    return pthread_rwlock_timedwrlock(lock, &ts);
804  });
805}
806
807static void test_pthread_rwlock_writer_wakeup_reader(std::function<int (pthread_rwlock_t*)> lock_function) {
808  RwlockWakeupHelperArg wakeup_arg;
809  ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, NULL));
810  ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
811  wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
812  wakeup_arg.tid = 0;
813  wakeup_arg.trylock_function = pthread_rwlock_tryrdlock;
814  wakeup_arg.lock_function = lock_function;
815
816  pthread_t thread;
817  ASSERT_EQ(0, pthread_create(&thread, NULL,
818    reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
819  WaitUntilThreadSleep(wakeup_arg.tid);
820  ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
821
822  wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
823  ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
824
825  ASSERT_EQ(0, pthread_join(thread, NULL));
826  ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
827  ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
828}
829
830TEST(pthread, pthread_rwlock_writer_wakeup_reader) {
831  test_pthread_rwlock_writer_wakeup_reader(pthread_rwlock_rdlock);
832}
833
834TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait) {
835  timespec ts;
836  ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
837  ts.tv_sec += 1;
838  test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) {
839    return pthread_rwlock_timedrdlock(lock, &ts);
840  });
841}
842
843static void pthread_rwlock_wakeup_timeout_helper(RwlockWakeupHelperArg* arg) {
844  arg->tid = gettid();
845  ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
846  arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
847
848  ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
849
850  timespec ts;
851  ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
852  ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
853  ts.tv_nsec = -1;
854  ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
855  ts.tv_nsec = NS_PER_S;
856  ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
857  ts.tv_nsec = NS_PER_S - 1;
858  ts.tv_sec = -1;
859  ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
860  ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
861  ts.tv_sec += 1;
862  ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
863  ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, arg->progress);
864  arg->progress = RwlockWakeupHelperArg::LOCK_TIMEDOUT;
865}
866
867TEST(pthread, pthread_rwlock_timedrdlock_timeout) {
868  RwlockWakeupHelperArg wakeup_arg;
869  ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
870  ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
871  wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
872  wakeup_arg.tid = 0;
873  wakeup_arg.trylock_function = pthread_rwlock_tryrdlock;
874  wakeup_arg.timed_lock_function = pthread_rwlock_timedrdlock;
875
876  pthread_t thread;
877  ASSERT_EQ(0, pthread_create(&thread, nullptr,
878      reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
879  WaitUntilThreadSleep(wakeup_arg.tid);
880  ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
881
882  ASSERT_EQ(0, pthread_join(thread, nullptr));
883  ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
884  ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
885  ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
886}
887
888TEST(pthread, pthread_rwlock_timedwrlock_timeout) {
889  RwlockWakeupHelperArg wakeup_arg;
890  ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
891  ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
892  wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
893  wakeup_arg.tid = 0;
894  wakeup_arg.trylock_function = pthread_rwlock_trywrlock;
895  wakeup_arg.timed_lock_function = pthread_rwlock_timedwrlock;
896
897  pthread_t thread;
898  ASSERT_EQ(0, pthread_create(&thread, nullptr,
899      reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
900  WaitUntilThreadSleep(wakeup_arg.tid);
901  ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
902
903  ASSERT_EQ(0, pthread_join(thread, nullptr));
904  ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
905  ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
906  ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
907}
908
909class RwlockKindTestHelper {
910 private:
911  struct ThreadArg {
912    RwlockKindTestHelper* helper;
913    std::atomic<pid_t>& tid;
914
915    ThreadArg(RwlockKindTestHelper* helper, std::atomic<pid_t>& tid)
916      : helper(helper), tid(tid) { }
917  };
918
919 public:
920  pthread_rwlock_t lock;
921
922 public:
923  RwlockKindTestHelper(int kind_type) {
924    InitRwlock(kind_type);
925  }
926
927  ~RwlockKindTestHelper() {
928    DestroyRwlock();
929  }
930
931  void CreateWriterThread(pthread_t& thread, std::atomic<pid_t>& tid) {
932    tid = 0;
933    ThreadArg* arg = new ThreadArg(this, tid);
934    ASSERT_EQ(0, pthread_create(&thread, NULL,
935                                reinterpret_cast<void* (*)(void*)>(WriterThreadFn), arg));
936  }
937
938  void CreateReaderThread(pthread_t& thread, std::atomic<pid_t>& tid) {
939    tid = 0;
940    ThreadArg* arg = new ThreadArg(this, tid);
941    ASSERT_EQ(0, pthread_create(&thread, NULL,
942                                reinterpret_cast<void* (*)(void*)>(ReaderThreadFn), arg));
943  }
944
945 private:
946  void InitRwlock(int kind_type) {
947    pthread_rwlockattr_t attr;
948    ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
949    ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_type));
950    ASSERT_EQ(0, pthread_rwlock_init(&lock, &attr));
951    ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
952  }
953
954  void DestroyRwlock() {
955    ASSERT_EQ(0, pthread_rwlock_destroy(&lock));
956  }
957
958  static void WriterThreadFn(ThreadArg* arg) {
959    arg->tid = gettid();
960
961    RwlockKindTestHelper* helper = arg->helper;
962    ASSERT_EQ(0, pthread_rwlock_wrlock(&helper->lock));
963    ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
964    delete arg;
965  }
966
967  static void ReaderThreadFn(ThreadArg* arg) {
968    arg->tid = gettid();
969
970    RwlockKindTestHelper* helper = arg->helper;
971    ASSERT_EQ(0, pthread_rwlock_rdlock(&helper->lock));
972    ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
973    delete arg;
974  }
975};
976
977TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_READER_NP) {
978  RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_READER_NP);
979  ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
980
981  pthread_t writer_thread;
982  std::atomic<pid_t> writer_tid;
983  helper.CreateWriterThread(writer_thread, writer_tid);
984  WaitUntilThreadSleep(writer_tid);
985
986  pthread_t reader_thread;
987  std::atomic<pid_t> reader_tid;
988  helper.CreateReaderThread(reader_thread, reader_tid);
989  ASSERT_EQ(0, pthread_join(reader_thread, NULL));
990
991  ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
992  ASSERT_EQ(0, pthread_join(writer_thread, NULL));
993}
994
995TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP) {
996  RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
997  ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
998
999  pthread_t writer_thread;
1000  std::atomic<pid_t> writer_tid;
1001  helper.CreateWriterThread(writer_thread, writer_tid);
1002  WaitUntilThreadSleep(writer_tid);
1003
1004  pthread_t reader_thread;
1005  std::atomic<pid_t> reader_tid;
1006  helper.CreateReaderThread(reader_thread, reader_tid);
1007  WaitUntilThreadSleep(reader_tid);
1008
1009  ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
1010  ASSERT_EQ(0, pthread_join(writer_thread, NULL));
1011  ASSERT_EQ(0, pthread_join(reader_thread, NULL));
1012}
1013
1014static int g_once_fn_call_count = 0;
1015static void OnceFn() {
1016  ++g_once_fn_call_count;
1017}
1018
1019TEST(pthread, pthread_once_smoke) {
1020  pthread_once_t once_control = PTHREAD_ONCE_INIT;
1021  ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
1022  ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
1023  ASSERT_EQ(1, g_once_fn_call_count);
1024}
1025
1026static std::string pthread_once_1934122_result = "";
1027
1028static void Routine2() {
1029  pthread_once_1934122_result += "2";
1030}
1031
1032static void Routine1() {
1033  pthread_once_t once_control_2 = PTHREAD_ONCE_INIT;
1034  pthread_once_1934122_result += "1";
1035  pthread_once(&once_control_2, &Routine2);
1036}
1037
1038TEST(pthread, pthread_once_1934122) {
1039  // Very old versions of Android couldn't call pthread_once from a
1040  // pthread_once init routine. http://b/1934122.
1041  pthread_once_t once_control_1 = PTHREAD_ONCE_INIT;
1042  ASSERT_EQ(0, pthread_once(&once_control_1, &Routine1));
1043  ASSERT_EQ("12", pthread_once_1934122_result);
1044}
1045
1046static int g_atfork_prepare_calls = 0;
1047static void AtForkPrepare1() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 1; }
1048static void AtForkPrepare2() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 2; }
1049static int g_atfork_parent_calls = 0;
1050static void AtForkParent1() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 1; }
1051static void AtForkParent2() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 2; }
1052static int g_atfork_child_calls = 0;
1053static void AtForkChild1() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 1; }
1054static void AtForkChild2() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 2; }
1055
1056TEST(pthread, pthread_atfork_smoke) {
1057  ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1));
1058  ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2));
1059
1060  int pid = fork();
1061  ASSERT_NE(-1, pid) << strerror(errno);
1062
1063  // Child and parent calls are made in the order they were registered.
1064  if (pid == 0) {
1065    ASSERT_EQ(12, g_atfork_child_calls);
1066    _exit(0);
1067  }
1068  ASSERT_EQ(12, g_atfork_parent_calls);
1069
1070  // Prepare calls are made in the reverse order.
1071  ASSERT_EQ(21, g_atfork_prepare_calls);
1072  int status;
1073  ASSERT_EQ(pid, waitpid(pid, &status, 0));
1074}
1075
1076TEST(pthread, pthread_attr_getscope) {
1077  pthread_attr_t attr;
1078  ASSERT_EQ(0, pthread_attr_init(&attr));
1079
1080  int scope;
1081  ASSERT_EQ(0, pthread_attr_getscope(&attr, &scope));
1082  ASSERT_EQ(PTHREAD_SCOPE_SYSTEM, scope);
1083}
1084
1085TEST(pthread, pthread_condattr_init) {
1086  pthread_condattr_t attr;
1087  pthread_condattr_init(&attr);
1088
1089  clockid_t clock;
1090  ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1091  ASSERT_EQ(CLOCK_REALTIME, clock);
1092
1093  int pshared;
1094  ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1095  ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
1096}
1097
1098TEST(pthread, pthread_condattr_setclock) {
1099  pthread_condattr_t attr;
1100  pthread_condattr_init(&attr);
1101
1102  ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_REALTIME));
1103  clockid_t clock;
1104  ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1105  ASSERT_EQ(CLOCK_REALTIME, clock);
1106
1107  ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1108  ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1109  ASSERT_EQ(CLOCK_MONOTONIC, clock);
1110
1111  ASSERT_EQ(EINVAL, pthread_condattr_setclock(&attr, CLOCK_PROCESS_CPUTIME_ID));
1112}
1113
1114TEST(pthread, pthread_cond_broadcast__preserves_condattr_flags) {
1115#if defined(__BIONIC__)
1116  pthread_condattr_t attr;
1117  pthread_condattr_init(&attr);
1118
1119  ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1120  ASSERT_EQ(0, pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
1121
1122  pthread_cond_t cond_var;
1123  ASSERT_EQ(0, pthread_cond_init(&cond_var, &attr));
1124
1125  ASSERT_EQ(0, pthread_cond_signal(&cond_var));
1126  ASSERT_EQ(0, pthread_cond_broadcast(&cond_var));
1127
1128  attr = static_cast<pthread_condattr_t>(*reinterpret_cast<uint32_t*>(cond_var.__private));
1129  clockid_t clock;
1130  ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1131  ASSERT_EQ(CLOCK_MONOTONIC, clock);
1132  int pshared;
1133  ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1134  ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
1135#else  // !defined(__BIONIC__)
1136  GTEST_LOG_(INFO) << "This tests a bionic implementation detail.\n";
1137#endif  // !defined(__BIONIC__)
1138}
1139
1140class pthread_CondWakeupTest : public ::testing::Test {
1141 protected:
1142  pthread_mutex_t mutex;
1143  pthread_cond_t cond;
1144
1145  enum Progress {
1146    INITIALIZED,
1147    WAITING,
1148    SIGNALED,
1149    FINISHED,
1150  };
1151  std::atomic<Progress> progress;
1152  pthread_t thread;
1153  std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function;
1154
1155 protected:
1156  void SetUp() override {
1157    ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1158  }
1159
1160  void InitCond(clockid_t clock=CLOCK_REALTIME) {
1161    pthread_condattr_t attr;
1162    ASSERT_EQ(0, pthread_condattr_init(&attr));
1163    ASSERT_EQ(0, pthread_condattr_setclock(&attr, clock));
1164    ASSERT_EQ(0, pthread_cond_init(&cond, &attr));
1165    ASSERT_EQ(0, pthread_condattr_destroy(&attr));
1166  }
1167
1168  void StartWaitingThread(std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function) {
1169    progress = INITIALIZED;
1170    this->wait_function = wait_function;
1171    ASSERT_EQ(0, pthread_create(&thread, NULL, reinterpret_cast<void* (*)(void*)>(WaitThreadFn), this));
1172    while (progress != WAITING) {
1173      usleep(5000);
1174    }
1175    usleep(5000);
1176  }
1177
1178  void TearDown() override {
1179    ASSERT_EQ(0, pthread_join(thread, nullptr));
1180    ASSERT_EQ(FINISHED, progress);
1181    ASSERT_EQ(0, pthread_cond_destroy(&cond));
1182    ASSERT_EQ(0, pthread_mutex_destroy(&mutex));
1183  }
1184
1185 private:
1186  static void WaitThreadFn(pthread_CondWakeupTest* test) {
1187    ASSERT_EQ(0, pthread_mutex_lock(&test->mutex));
1188    test->progress = WAITING;
1189    while (test->progress == WAITING) {
1190      ASSERT_EQ(0, test->wait_function(&test->cond, &test->mutex));
1191    }
1192    ASSERT_EQ(SIGNALED, test->progress);
1193    test->progress = FINISHED;
1194    ASSERT_EQ(0, pthread_mutex_unlock(&test->mutex));
1195  }
1196};
1197
1198TEST_F(pthread_CondWakeupTest, signal_wait) {
1199  InitCond();
1200  StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1201    return pthread_cond_wait(cond, mutex);
1202  });
1203  progress = SIGNALED;
1204  ASSERT_EQ(0, pthread_cond_signal(&cond));
1205}
1206
1207TEST_F(pthread_CondWakeupTest, broadcast_wait) {
1208  InitCond();
1209  StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1210    return pthread_cond_wait(cond, mutex);
1211  });
1212  progress = SIGNALED;
1213  ASSERT_EQ(0, pthread_cond_broadcast(&cond));
1214}
1215
1216TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_REALTIME) {
1217  InitCond(CLOCK_REALTIME);
1218  timespec ts;
1219  ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1220  ts.tv_sec += 1;
1221  StartWaitingThread([&](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1222    return pthread_cond_timedwait(cond, mutex, &ts);
1223  });
1224  progress = SIGNALED;
1225  ASSERT_EQ(0, pthread_cond_signal(&cond));
1226}
1227
1228TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC) {
1229  InitCond(CLOCK_MONOTONIC);
1230  timespec ts;
1231  ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1232  ts.tv_sec += 1;
1233  StartWaitingThread([&](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1234    return pthread_cond_timedwait(cond, mutex, &ts);
1235  });
1236  progress = SIGNALED;
1237  ASSERT_EQ(0, pthread_cond_signal(&cond));
1238}
1239
1240TEST(pthread, pthread_cond_timedwait_timeout) {
1241  pthread_mutex_t mutex;
1242  ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1243  pthread_cond_t cond;
1244  ASSERT_EQ(0, pthread_cond_init(&cond, nullptr));
1245  ASSERT_EQ(0, pthread_mutex_lock(&mutex));
1246  timespec ts;
1247  ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1248  ASSERT_EQ(ETIMEDOUT, pthread_cond_timedwait(&cond, &mutex, &ts));
1249  ts.tv_nsec = -1;
1250  ASSERT_EQ(EINVAL, pthread_cond_timedwait(&cond, &mutex, &ts));
1251  ts.tv_nsec = NS_PER_S;
1252  ASSERT_EQ(EINVAL, pthread_cond_timedwait(&cond, &mutex, &ts));
1253  ts.tv_nsec = NS_PER_S - 1;
1254  ts.tv_sec = -1;
1255  ASSERT_EQ(ETIMEDOUT, pthread_cond_timedwait(&cond, &mutex, &ts));
1256  ASSERT_EQ(0, pthread_mutex_unlock(&mutex));
1257}
1258
1259TEST(pthread, pthread_attr_getstack__main_thread) {
1260  // This test is only meaningful for the main thread, so make sure we're running on it!
1261  ASSERT_EQ(getpid(), syscall(__NR_gettid));
1262
1263  // Get the main thread's attributes.
1264  pthread_attr_t attributes;
1265  ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1266
1267  // Check that we correctly report that the main thread has no guard page.
1268  size_t guard_size;
1269  ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
1270  ASSERT_EQ(0U, guard_size); // The main thread has no guard page.
1271
1272  // Get the stack base and the stack size (both ways).
1273  void* stack_base;
1274  size_t stack_size;
1275  ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1276  size_t stack_size2;
1277  ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1278
1279  // The two methods of asking for the stack size should agree.
1280  EXPECT_EQ(stack_size, stack_size2);
1281
1282#if defined(__BIONIC__)
1283  // What does /proc/self/maps' [stack] line say?
1284  void* maps_stack_hi = NULL;
1285  std::vector<map_record> maps;
1286  ASSERT_TRUE(Maps::parse_maps(&maps));
1287  for (const auto& map : maps) {
1288    if (map.pathname == "[stack]") {
1289      maps_stack_hi = reinterpret_cast<void*>(map.addr_end);
1290      break;
1291    }
1292  }
1293
1294  // The high address of the /proc/self/maps [stack] region should equal stack_base + stack_size.
1295  // Remember that the stack grows down (and is mapped in on demand), so the low address of the
1296  // region isn't very interesting.
1297  EXPECT_EQ(maps_stack_hi, reinterpret_cast<uint8_t*>(stack_base) + stack_size);
1298
1299  // The stack size should correspond to RLIMIT_STACK.
1300  rlimit rl;
1301  ASSERT_EQ(0, getrlimit(RLIMIT_STACK, &rl));
1302  uint64_t original_rlim_cur = rl.rlim_cur;
1303  if (rl.rlim_cur == RLIM_INFINITY) {
1304    rl.rlim_cur = 8 * 1024 * 1024; // Bionic reports unlimited stacks as 8MiB.
1305  }
1306  EXPECT_EQ(rl.rlim_cur, stack_size);
1307
1308  auto guard = make_scope_guard([&rl, original_rlim_cur]() {
1309    rl.rlim_cur = original_rlim_cur;
1310    ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1311  });
1312
1313  //
1314  // What if RLIMIT_STACK is smaller than the stack's current extent?
1315  //
1316  rl.rlim_cur = rl.rlim_max = 1024; // 1KiB. We know the stack must be at least a page already.
1317  rl.rlim_max = RLIM_INFINITY;
1318  ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1319
1320  ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1321  ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1322  ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1323
1324  EXPECT_EQ(stack_size, stack_size2);
1325  ASSERT_EQ(1024U, stack_size);
1326
1327  //
1328  // What if RLIMIT_STACK isn't a whole number of pages?
1329  //
1330  rl.rlim_cur = rl.rlim_max = 6666; // Not a whole number of pages.
1331  rl.rlim_max = RLIM_INFINITY;
1332  ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1333
1334  ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1335  ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1336  ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1337
1338  EXPECT_EQ(stack_size, stack_size2);
1339  ASSERT_EQ(6666U, stack_size);
1340#endif
1341}
1342
1343struct GetStackSignalHandlerArg {
1344  volatile bool done;
1345  void* signal_handler_sp;
1346  void* main_stack_base;
1347  size_t main_stack_size;
1348};
1349
1350static GetStackSignalHandlerArg getstack_signal_handler_arg;
1351
1352static void getstack_signal_handler(int sig) {
1353  ASSERT_EQ(SIGUSR1, sig);
1354  // Use sleep() to make current thread be switched out by the kernel to provoke the error.
1355  sleep(1);
1356  pthread_attr_t attr;
1357  ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1358  void* stack_base;
1359  size_t stack_size;
1360  ASSERT_EQ(0, pthread_attr_getstack(&attr, &stack_base, &stack_size));
1361  getstack_signal_handler_arg.signal_handler_sp = &attr;
1362  getstack_signal_handler_arg.main_stack_base = stack_base;
1363  getstack_signal_handler_arg.main_stack_size = stack_size;
1364  getstack_signal_handler_arg.done = true;
1365}
1366
1367// The previous code obtained the main thread's stack by reading the entry in
1368// /proc/self/task/<pid>/maps that was labeled [stack]. Unfortunately, on x86/x86_64, the kernel
1369// relies on sp0 in task state segment(tss) to label the stack map with [stack]. If the kernel
1370// switches a process while the main thread is in an alternate stack, then the kernel will label
1371// the wrong map with [stack]. This test verifies that when the above situation happens, the main
1372// thread's stack is found correctly.
1373TEST(pthread, pthread_attr_getstack_in_signal_handler) {
1374  const size_t sig_stack_size = 16 * 1024;
1375  void* sig_stack = mmap(NULL, sig_stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS,
1376                         -1, 0);
1377  ASSERT_NE(MAP_FAILED, sig_stack);
1378  stack_t ss;
1379  ss.ss_sp = sig_stack;
1380  ss.ss_size = sig_stack_size;
1381  ss.ss_flags = 0;
1382  stack_t oss;
1383  ASSERT_EQ(0, sigaltstack(&ss, &oss));
1384
1385  ScopedSignalHandler handler(SIGUSR1, getstack_signal_handler, SA_ONSTACK);
1386  getstack_signal_handler_arg.done = false;
1387  kill(getpid(), SIGUSR1);
1388  ASSERT_EQ(true, getstack_signal_handler_arg.done);
1389
1390  // Verify if the stack used by the signal handler is the alternate stack just registered.
1391  ASSERT_LE(sig_stack, getstack_signal_handler_arg.signal_handler_sp);
1392  ASSERT_GE(reinterpret_cast<char*>(sig_stack) + sig_stack_size,
1393            getstack_signal_handler_arg.signal_handler_sp);
1394
1395  // Verify if the main thread's stack got in the signal handler is correct.
1396  ASSERT_LE(getstack_signal_handler_arg.main_stack_base, &ss);
1397  ASSERT_GE(reinterpret_cast<char*>(getstack_signal_handler_arg.main_stack_base) +
1398            getstack_signal_handler_arg.main_stack_size, reinterpret_cast<void*>(&ss));
1399
1400  ASSERT_EQ(0, sigaltstack(&oss, nullptr));
1401  ASSERT_EQ(0, munmap(sig_stack, sig_stack_size));
1402}
1403
1404static void pthread_attr_getstack_18908062_helper(void*) {
1405  char local_variable;
1406  pthread_attr_t attributes;
1407  pthread_getattr_np(pthread_self(), &attributes);
1408  void* stack_base;
1409  size_t stack_size;
1410  pthread_attr_getstack(&attributes, &stack_base, &stack_size);
1411
1412  // Test whether &local_variable is in [stack_base, stack_base + stack_size).
1413  ASSERT_LE(reinterpret_cast<char*>(stack_base), &local_variable);
1414  ASSERT_LT(&local_variable, reinterpret_cast<char*>(stack_base) + stack_size);
1415}
1416
1417// Check whether something on stack is in the range of
1418// [stack_base, stack_base + stack_size). see b/18908062.
1419TEST(pthread, pthread_attr_getstack_18908062) {
1420  pthread_t t;
1421  ASSERT_EQ(0, pthread_create(&t, NULL,
1422            reinterpret_cast<void* (*)(void*)>(pthread_attr_getstack_18908062_helper),
1423            NULL));
1424  pthread_join(t, NULL);
1425}
1426
1427#if defined(__BIONIC__)
1428static pthread_mutex_t pthread_gettid_np_mutex = PTHREAD_MUTEX_INITIALIZER;
1429
1430static void* pthread_gettid_np_helper(void* arg) {
1431  *reinterpret_cast<pid_t*>(arg) = gettid();
1432
1433  // Wait for our parent to call pthread_gettid_np on us before exiting.
1434  pthread_mutex_lock(&pthread_gettid_np_mutex);
1435  pthread_mutex_unlock(&pthread_gettid_np_mutex);
1436  return NULL;
1437}
1438#endif
1439
1440TEST(pthread, pthread_gettid_np) {
1441#if defined(__BIONIC__)
1442  ASSERT_EQ(gettid(), pthread_gettid_np(pthread_self()));
1443
1444  // Ensure the other thread doesn't exit until after we've called
1445  // pthread_gettid_np on it.
1446  pthread_mutex_lock(&pthread_gettid_np_mutex);
1447
1448  pid_t t_gettid_result;
1449  pthread_t t;
1450  pthread_create(&t, NULL, pthread_gettid_np_helper, &t_gettid_result);
1451
1452  pid_t t_pthread_gettid_np_result = pthread_gettid_np(t);
1453
1454  // Release the other thread and wait for it to exit.
1455  pthread_mutex_unlock(&pthread_gettid_np_mutex);
1456  pthread_join(t, NULL);
1457
1458  ASSERT_EQ(t_gettid_result, t_pthread_gettid_np_result);
1459#else
1460  GTEST_LOG_(INFO) << "This test does nothing.\n";
1461#endif
1462}
1463
1464static size_t cleanup_counter = 0;
1465
1466static void AbortCleanupRoutine(void*) {
1467  abort();
1468}
1469
1470static void CountCleanupRoutine(void*) {
1471  ++cleanup_counter;
1472}
1473
1474static void PthreadCleanupTester() {
1475  pthread_cleanup_push(CountCleanupRoutine, NULL);
1476  pthread_cleanup_push(CountCleanupRoutine, NULL);
1477  pthread_cleanup_push(AbortCleanupRoutine, NULL);
1478
1479  pthread_cleanup_pop(0); // Pop the abort without executing it.
1480  pthread_cleanup_pop(1); // Pop one count while executing it.
1481  ASSERT_EQ(1U, cleanup_counter);
1482  // Exit while the other count is still on the cleanup stack.
1483  pthread_exit(NULL);
1484
1485  // Calls to pthread_cleanup_pop/pthread_cleanup_push must always be balanced.
1486  pthread_cleanup_pop(0);
1487}
1488
1489static void* PthreadCleanupStartRoutine(void*) {
1490  PthreadCleanupTester();
1491  return NULL;
1492}
1493
1494TEST(pthread, pthread_cleanup_push__pthread_cleanup_pop) {
1495  pthread_t t;
1496  ASSERT_EQ(0, pthread_create(&t, NULL, PthreadCleanupStartRoutine, NULL));
1497  pthread_join(t, NULL);
1498  ASSERT_EQ(2U, cleanup_counter);
1499}
1500
1501TEST(pthread, PTHREAD_MUTEX_DEFAULT_is_PTHREAD_MUTEX_NORMAL) {
1502  ASSERT_EQ(PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_DEFAULT);
1503}
1504
1505TEST(pthread, pthread_mutexattr_gettype) {
1506  pthread_mutexattr_t attr;
1507  ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1508
1509  int attr_type;
1510
1511  ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL));
1512  ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1513  ASSERT_EQ(PTHREAD_MUTEX_NORMAL, attr_type);
1514
1515  ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK));
1516  ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1517  ASSERT_EQ(PTHREAD_MUTEX_ERRORCHECK, attr_type);
1518
1519  ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE));
1520  ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1521  ASSERT_EQ(PTHREAD_MUTEX_RECURSIVE, attr_type);
1522
1523  ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
1524}
1525
1526struct PthreadMutex {
1527  pthread_mutex_t lock;
1528
1529  PthreadMutex(int mutex_type) {
1530    init(mutex_type);
1531  }
1532
1533  ~PthreadMutex() {
1534    destroy();
1535  }
1536
1537 private:
1538  void init(int mutex_type) {
1539    pthread_mutexattr_t attr;
1540    ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1541    ASSERT_EQ(0, pthread_mutexattr_settype(&attr, mutex_type));
1542    ASSERT_EQ(0, pthread_mutex_init(&lock, &attr));
1543    ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
1544  }
1545
1546  void destroy() {
1547    ASSERT_EQ(0, pthread_mutex_destroy(&lock));
1548  }
1549
1550  DISALLOW_COPY_AND_ASSIGN(PthreadMutex);
1551};
1552
1553TEST(pthread, pthread_mutex_lock_NORMAL) {
1554  PthreadMutex m(PTHREAD_MUTEX_NORMAL);
1555
1556  ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1557  ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1558}
1559
1560TEST(pthread, pthread_mutex_lock_ERRORCHECK) {
1561  PthreadMutex m(PTHREAD_MUTEX_ERRORCHECK);
1562
1563  ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1564  ASSERT_EQ(EDEADLK, pthread_mutex_lock(&m.lock));
1565  ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1566  ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
1567  ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
1568  ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1569  ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
1570}
1571
1572TEST(pthread, pthread_mutex_lock_RECURSIVE) {
1573  PthreadMutex m(PTHREAD_MUTEX_RECURSIVE);
1574
1575  ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1576  ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1577  ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1578  ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1579  ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
1580  ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1581  ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
1582}
1583
1584TEST(pthread, pthread_mutex_init_same_as_static_initializers) {
1585  pthread_mutex_t lock_normal = PTHREAD_MUTEX_INITIALIZER;
1586  PthreadMutex m1(PTHREAD_MUTEX_NORMAL);
1587  ASSERT_EQ(0, memcmp(&lock_normal, &m1.lock, sizeof(pthread_mutex_t)));
1588  pthread_mutex_destroy(&lock_normal);
1589
1590  pthread_mutex_t lock_errorcheck = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
1591  PthreadMutex m2(PTHREAD_MUTEX_ERRORCHECK);
1592  ASSERT_EQ(0, memcmp(&lock_errorcheck, &m2.lock, sizeof(pthread_mutex_t)));
1593  pthread_mutex_destroy(&lock_errorcheck);
1594
1595  pthread_mutex_t lock_recursive = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
1596  PthreadMutex m3(PTHREAD_MUTEX_RECURSIVE);
1597  ASSERT_EQ(0, memcmp(&lock_recursive, &m3.lock, sizeof(pthread_mutex_t)));
1598  ASSERT_EQ(0, pthread_mutex_destroy(&lock_recursive));
1599}
1600class MutexWakeupHelper {
1601 private:
1602  PthreadMutex m;
1603  enum Progress {
1604    LOCK_INITIALIZED,
1605    LOCK_WAITING,
1606    LOCK_RELEASED,
1607    LOCK_ACCESSED
1608  };
1609  std::atomic<Progress> progress;
1610  std::atomic<pid_t> tid;
1611
1612  static void thread_fn(MutexWakeupHelper* helper) {
1613    helper->tid = gettid();
1614    ASSERT_EQ(LOCK_INITIALIZED, helper->progress);
1615    helper->progress = LOCK_WAITING;
1616
1617    ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock));
1618    ASSERT_EQ(LOCK_RELEASED, helper->progress);
1619    ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock));
1620
1621    helper->progress = LOCK_ACCESSED;
1622  }
1623
1624 public:
1625  MutexWakeupHelper(int mutex_type) : m(mutex_type) {
1626  }
1627
1628  void test() {
1629    ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1630    progress = LOCK_INITIALIZED;
1631    tid = 0;
1632
1633    pthread_t thread;
1634    ASSERT_EQ(0, pthread_create(&thread, NULL,
1635      reinterpret_cast<void* (*)(void*)>(MutexWakeupHelper::thread_fn), this));
1636
1637    WaitUntilThreadSleep(tid);
1638    ASSERT_EQ(LOCK_WAITING, progress);
1639
1640    progress = LOCK_RELEASED;
1641    ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1642
1643    ASSERT_EQ(0, pthread_join(thread, NULL));
1644    ASSERT_EQ(LOCK_ACCESSED, progress);
1645  }
1646};
1647
1648TEST(pthread, pthread_mutex_NORMAL_wakeup) {
1649  MutexWakeupHelper helper(PTHREAD_MUTEX_NORMAL);
1650  helper.test();
1651}
1652
1653TEST(pthread, pthread_mutex_ERRORCHECK_wakeup) {
1654  MutexWakeupHelper helper(PTHREAD_MUTEX_ERRORCHECK);
1655  helper.test();
1656}
1657
1658TEST(pthread, pthread_mutex_RECURSIVE_wakeup) {
1659  MutexWakeupHelper helper(PTHREAD_MUTEX_RECURSIVE);
1660  helper.test();
1661}
1662
1663TEST(pthread, pthread_mutex_owner_tid_limit) {
1664#if defined(__BIONIC__) && !defined(__LP64__)
1665  FILE* fp = fopen("/proc/sys/kernel/pid_max", "r");
1666  ASSERT_TRUE(fp != NULL);
1667  long pid_max;
1668  ASSERT_EQ(1, fscanf(fp, "%ld", &pid_max));
1669  fclose(fp);
1670  // Bionic's pthread_mutex implementation on 32-bit devices uses 16 bits to represent owner tid.
1671  ASSERT_LE(pid_max, 65536);
1672#else
1673  GTEST_LOG_(INFO) << "This test does nothing as 32-bit tid is supported by pthread_mutex.\n";
1674#endif
1675}
1676
1677TEST(pthread, pthread_mutex_timedlock) {
1678  pthread_mutex_t m;
1679  ASSERT_EQ(0, pthread_mutex_init(&m, nullptr));
1680
1681  // If the mutex is already locked, pthread_mutex_timedlock should time out.
1682  ASSERT_EQ(0, pthread_mutex_lock(&m));
1683
1684  timespec ts;
1685  ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1686  ASSERT_EQ(ETIMEDOUT, pthread_mutex_timedlock(&m, &ts));
1687  ts.tv_nsec = -1;
1688  ASSERT_EQ(EINVAL, pthread_mutex_timedlock(&m, &ts));
1689  ts.tv_nsec = NS_PER_S;
1690  ASSERT_EQ(EINVAL, pthread_mutex_timedlock(&m, &ts));
1691  ts.tv_nsec = NS_PER_S - 1;
1692  ts.tv_sec = -1;
1693  ASSERT_EQ(ETIMEDOUT, pthread_mutex_timedlock(&m, &ts));
1694
1695  // If the mutex is unlocked, pthread_mutex_timedlock should succeed.
1696  ASSERT_EQ(0, pthread_mutex_unlock(&m));
1697
1698  ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1699  ts.tv_sec += 1;
1700  ASSERT_EQ(0, pthread_mutex_timedlock(&m, &ts));
1701
1702  ASSERT_EQ(0, pthread_mutex_unlock(&m));
1703  ASSERT_EQ(0, pthread_mutex_destroy(&m));
1704}
1705
1706class StrictAlignmentAllocator {
1707 public:
1708  void* allocate(size_t size, size_t alignment) {
1709    char* p = new char[size + alignment * 2];
1710    allocated_array.push_back(p);
1711    while (!is_strict_aligned(p, alignment)) {
1712      ++p;
1713    }
1714    return p;
1715  }
1716
1717  ~StrictAlignmentAllocator() {
1718    for (const auto& p : allocated_array) {
1719      delete[] p;
1720    }
1721  }
1722
1723 private:
1724  bool is_strict_aligned(char* p, size_t alignment) {
1725    return (reinterpret_cast<uintptr_t>(p) % (alignment * 2)) == alignment;
1726  }
1727
1728  std::vector<char*> allocated_array;
1729};
1730
1731TEST(pthread, pthread_types_allow_four_bytes_alignment) {
1732#if defined(__BIONIC__)
1733  // For binary compatibility with old version, we need to allow 4-byte aligned data for pthread types.
1734  StrictAlignmentAllocator allocator;
1735  pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(
1736                             allocator.allocate(sizeof(pthread_mutex_t), 4));
1737  ASSERT_EQ(0, pthread_mutex_init(mutex, NULL));
1738  ASSERT_EQ(0, pthread_mutex_lock(mutex));
1739  ASSERT_EQ(0, pthread_mutex_unlock(mutex));
1740  ASSERT_EQ(0, pthread_mutex_destroy(mutex));
1741
1742  pthread_cond_t* cond = reinterpret_cast<pthread_cond_t*>(
1743                           allocator.allocate(sizeof(pthread_cond_t), 4));
1744  ASSERT_EQ(0, pthread_cond_init(cond, NULL));
1745  ASSERT_EQ(0, pthread_cond_signal(cond));
1746  ASSERT_EQ(0, pthread_cond_broadcast(cond));
1747  ASSERT_EQ(0, pthread_cond_destroy(cond));
1748
1749  pthread_rwlock_t* rwlock = reinterpret_cast<pthread_rwlock_t*>(
1750                               allocator.allocate(sizeof(pthread_rwlock_t), 4));
1751  ASSERT_EQ(0, pthread_rwlock_init(rwlock, NULL));
1752  ASSERT_EQ(0, pthread_rwlock_rdlock(rwlock));
1753  ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
1754  ASSERT_EQ(0, pthread_rwlock_wrlock(rwlock));
1755  ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
1756  ASSERT_EQ(0, pthread_rwlock_destroy(rwlock));
1757
1758#else
1759  GTEST_LOG_(INFO) << "This test tests bionic implementation details.";
1760#endif
1761}
1762
1763TEST(pthread, pthread_mutex_lock_null_32) {
1764#if defined(__BIONIC__) && !defined(__LP64__)
1765  ASSERT_EQ(EINVAL, pthread_mutex_lock(NULL));
1766#else
1767  GTEST_LOG_(INFO) << "This test tests bionic implementation details on 32 bit devices.";
1768#endif
1769}
1770
1771TEST(pthread, pthread_mutex_unlock_null_32) {
1772#if defined(__BIONIC__) && !defined(__LP64__)
1773  ASSERT_EQ(EINVAL, pthread_mutex_unlock(NULL));
1774#else
1775  GTEST_LOG_(INFO) << "This test tests bionic implementation details on 32 bit devices.";
1776#endif
1777}
1778
1779TEST_F(pthread_DeathTest, pthread_mutex_lock_null_64) {
1780#if defined(__BIONIC__) && defined(__LP64__)
1781  pthread_mutex_t* null_value = nullptr;
1782  ASSERT_EXIT(pthread_mutex_lock(null_value), testing::KilledBySignal(SIGSEGV), "");
1783#else
1784  GTEST_LOG_(INFO) << "This test tests bionic implementation details on 64 bit devices.";
1785#endif
1786}
1787
1788TEST_F(pthread_DeathTest, pthread_mutex_unlock_null_64) {
1789#if defined(__BIONIC__) && defined(__LP64__)
1790  pthread_mutex_t* null_value = nullptr;
1791  ASSERT_EXIT(pthread_mutex_unlock(null_value), testing::KilledBySignal(SIGSEGV), "");
1792#else
1793  GTEST_LOG_(INFO) << "This test tests bionic implementation details on 64 bit devices.";
1794#endif
1795}
1796
1797extern _Unwind_Reason_Code FrameCounter(_Unwind_Context* ctx, void* arg);
1798
1799static volatile bool signal_handler_on_altstack_done;
1800
1801static void SignalHandlerOnAltStack(int signo, siginfo_t*, void*) {
1802  ASSERT_EQ(SIGUSR1, signo);
1803  // Check if we have enough stack space for unwinding.
1804  int count = 0;
1805  _Unwind_Backtrace(FrameCounter, &count);
1806  ASSERT_GT(count, 0);
1807  // Check if we have enough stack space for logging.
1808  std::string s(2048, '*');
1809  GTEST_LOG_(INFO) << s;
1810  signal_handler_on_altstack_done = true;
1811}
1812
1813TEST(pthread, big_enough_signal_stack_for_64bit_arch) {
1814  signal_handler_on_altstack_done = false;
1815  ScopedSignalHandler handler(SIGUSR1, SignalHandlerOnAltStack, SA_SIGINFO | SA_ONSTACK);
1816  kill(getpid(), SIGUSR1);
1817  ASSERT_TRUE(signal_handler_on_altstack_done);
1818}
1819
1820TEST(pthread, pthread_barrierattr_smoke) {
1821  pthread_barrierattr_t attr;
1822  ASSERT_EQ(0, pthread_barrierattr_init(&attr));
1823  int pshared;
1824  ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
1825  ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
1826  ASSERT_EQ(0, pthread_barrierattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
1827  ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
1828  ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
1829  ASSERT_EQ(0, pthread_barrierattr_destroy(&attr));
1830}
1831
1832struct BarrierTestHelperArg {
1833  std::atomic<pid_t> tid;
1834  pthread_barrier_t* barrier;
1835  size_t iteration_count;
1836};
1837
1838static void BarrierTestHelper(BarrierTestHelperArg* arg) {
1839  arg->tid = gettid();
1840  for (size_t i = 0; i < arg->iteration_count; ++i) {
1841    ASSERT_EQ(0, pthread_barrier_wait(arg->barrier));
1842  }
1843}
1844
1845TEST(pthread, pthread_barrier_smoke) {
1846  const size_t BARRIER_ITERATION_COUNT = 10;
1847  const size_t BARRIER_THREAD_COUNT = 10;
1848  pthread_barrier_t barrier;
1849  ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, BARRIER_THREAD_COUNT + 1));
1850  std::vector<pthread_t> threads(BARRIER_THREAD_COUNT);
1851  std::vector<BarrierTestHelperArg> args(threads.size());
1852  for (size_t i = 0; i < threads.size(); ++i) {
1853    args[i].tid = 0;
1854    args[i].barrier = &barrier;
1855    args[i].iteration_count = BARRIER_ITERATION_COUNT;
1856    ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
1857                                reinterpret_cast<void* (*)(void*)>(BarrierTestHelper), &args[i]));
1858  }
1859  for (size_t iteration = 0; iteration < BARRIER_ITERATION_COUNT; ++iteration) {
1860    for (size_t i = 0; i < threads.size(); ++i) {
1861      WaitUntilThreadSleep(args[i].tid);
1862    }
1863    ASSERT_EQ(PTHREAD_BARRIER_SERIAL_THREAD, pthread_barrier_wait(&barrier));
1864  }
1865  for (size_t i = 0; i < threads.size(); ++i) {
1866    ASSERT_EQ(0, pthread_join(threads[i], nullptr));
1867  }
1868  ASSERT_EQ(0, pthread_barrier_destroy(&barrier));
1869}
1870
1871TEST(pthread, pthread_barrier_destroy) {
1872  pthread_barrier_t barrier;
1873  ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, 2));
1874  pthread_t thread;
1875  BarrierTestHelperArg arg;
1876  arg.tid = 0;
1877  arg.barrier = &barrier;
1878  arg.iteration_count = 1;
1879  ASSERT_EQ(0, pthread_create(&thread, nullptr,
1880                              reinterpret_cast<void* (*)(void*)>(BarrierTestHelper), &arg));
1881  WaitUntilThreadSleep(arg.tid);
1882  ASSERT_EQ(EBUSY, pthread_barrier_destroy(&barrier));
1883  ASSERT_EQ(PTHREAD_BARRIER_SERIAL_THREAD, pthread_barrier_wait(&barrier));
1884  // Verify if the barrier can be destroyed directly after pthread_barrier_wait().
1885  ASSERT_EQ(0, pthread_barrier_destroy(&barrier));
1886  ASSERT_EQ(0, pthread_join(thread, nullptr));
1887#if defined(__BIONIC__)
1888  ASSERT_EQ(EINVAL, pthread_barrier_destroy(&barrier));
1889#endif
1890}
1891
1892struct BarrierOrderingTestHelperArg {
1893  pthread_barrier_t* barrier;
1894  size_t* array;
1895  size_t array_length;
1896  size_t id;
1897};
1898
1899void BarrierOrderingTestHelper(BarrierOrderingTestHelperArg* arg) {
1900  const size_t ITERATION_COUNT = 10000;
1901  for (size_t i = 1; i <= ITERATION_COUNT; ++i) {
1902    arg->array[arg->id] = i;
1903    int result = pthread_barrier_wait(arg->barrier);
1904    ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
1905    for (size_t j = 0; j < arg->array_length; ++j) {
1906      ASSERT_EQ(i, arg->array[j]);
1907    }
1908    result = pthread_barrier_wait(arg->barrier);
1909    ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
1910  }
1911}
1912
1913TEST(pthread, pthread_barrier_check_ordering) {
1914  const size_t THREAD_COUNT = 4;
1915  pthread_barrier_t barrier;
1916  ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, THREAD_COUNT));
1917  size_t array[THREAD_COUNT];
1918  std::vector<pthread_t> threads(THREAD_COUNT);
1919  std::vector<BarrierOrderingTestHelperArg> args(THREAD_COUNT);
1920  for (size_t i = 0; i < THREAD_COUNT; ++i) {
1921    args[i].barrier = &barrier;
1922    args[i].array = array;
1923    args[i].array_length = THREAD_COUNT;
1924    args[i].id = i;
1925    ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
1926                                reinterpret_cast<void* (*)(void*)>(BarrierOrderingTestHelper),
1927                                &args[i]));
1928  }
1929  for (size_t i = 0; i < THREAD_COUNT; ++i) {
1930    ASSERT_EQ(0, pthread_join(threads[i], nullptr));
1931  }
1932}
1933