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