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