pthread_test.cpp revision e69c24543db577d8b219ab74b0ba7566e0f13b38
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
31#include <atomic>
32#include <vector>
33
34#include "private/bionic_macros.h"
35#include "private/ScopeGuard.h"
36#include "BionicDeathTest.h"
37#include "ScopedSignalHandler.h"
38
39TEST(pthread, pthread_key_create) {
40  pthread_key_t key;
41  ASSERT_EQ(0, pthread_key_create(&key, NULL));
42  ASSERT_EQ(0, pthread_key_delete(key));
43  // Can't delete a key that's already been deleted.
44  ASSERT_EQ(EINVAL, pthread_key_delete(key));
45}
46
47TEST(pthread, pthread_keys_max) {
48  // POSIX says PTHREAD_KEYS_MAX should be at least _POSIX_THREAD_KEYS_MAX.
49  ASSERT_GE(PTHREAD_KEYS_MAX, _POSIX_THREAD_KEYS_MAX);
50}
51
52TEST(pthread, sysconf_SC_THREAD_KEYS_MAX_eq_PTHREAD_KEYS_MAX) {
53  int sysconf_max = sysconf(_SC_THREAD_KEYS_MAX);
54  ASSERT_EQ(sysconf_max, PTHREAD_KEYS_MAX);
55}
56
57TEST(pthread, pthread_key_many_distinct) {
58  // As gtest uses pthread keys, we can't allocate exactly PTHREAD_KEYS_MAX
59  // pthread keys, but We should be able to allocate at least this many keys.
60  int nkeys = PTHREAD_KEYS_MAX / 2;
61  std::vector<pthread_key_t> keys;
62
63  auto scope_guard = make_scope_guard([&keys]{
64    for (auto key : keys) {
65      EXPECT_EQ(0, pthread_key_delete(key));
66    }
67  });
68
69  for (int i = 0; i < nkeys; ++i) {
70    pthread_key_t key;
71    // If this fails, it's likely that GLOBAL_INIT_THREAD_LOCAL_BUFFER_COUNT is
72    // wrong.
73    ASSERT_EQ(0, pthread_key_create(&key, NULL)) << i << " of " << nkeys;
74    keys.push_back(key);
75    ASSERT_EQ(0, pthread_setspecific(key, reinterpret_cast<void*>(i)));
76  }
77
78  for (int i = keys.size() - 1; i >= 0; --i) {
79    ASSERT_EQ(reinterpret_cast<void*>(i), pthread_getspecific(keys.back()));
80    pthread_key_t key = keys.back();
81    keys.pop_back();
82    ASSERT_EQ(0, pthread_key_delete(key));
83  }
84}
85
86TEST(pthread, pthread_key_not_exceed_PTHREAD_KEYS_MAX) {
87  std::vector<pthread_key_t> keys;
88  int rv = 0;
89
90  // Pthread keys are used by gtest, so PTHREAD_KEYS_MAX should
91  // be more than we are allowed to allocate now.
92  for (int i = 0; i < PTHREAD_KEYS_MAX; i++) {
93    pthread_key_t key;
94    rv = pthread_key_create(&key, NULL);
95    if (rv == EAGAIN) {
96      break;
97    }
98    EXPECT_EQ(0, rv);
99    keys.push_back(key);
100  }
101
102  // Don't leak keys.
103  for (auto key : keys) {
104    EXPECT_EQ(0, pthread_key_delete(key));
105  }
106  keys.clear();
107
108  // We should have eventually reached the maximum number of keys and received
109  // EAGAIN.
110  ASSERT_EQ(EAGAIN, rv);
111}
112
113TEST(pthread, pthread_key_delete) {
114  void* expected = reinterpret_cast<void*>(1234);
115  pthread_key_t key;
116  ASSERT_EQ(0, pthread_key_create(&key, NULL));
117  ASSERT_EQ(0, pthread_setspecific(key, expected));
118  ASSERT_EQ(expected, pthread_getspecific(key));
119  ASSERT_EQ(0, pthread_key_delete(key));
120  // After deletion, pthread_getspecific returns NULL.
121  ASSERT_EQ(NULL, pthread_getspecific(key));
122  // And you can't use pthread_setspecific with the deleted key.
123  ASSERT_EQ(EINVAL, pthread_setspecific(key, expected));
124}
125
126TEST(pthread, pthread_key_fork) {
127  void* expected = reinterpret_cast<void*>(1234);
128  pthread_key_t key;
129  ASSERT_EQ(0, pthread_key_create(&key, NULL));
130  ASSERT_EQ(0, pthread_setspecific(key, expected));
131  ASSERT_EQ(expected, pthread_getspecific(key));
132
133  pid_t pid = fork();
134  ASSERT_NE(-1, pid) << strerror(errno);
135
136  if (pid == 0) {
137    // The surviving thread inherits all the forking thread's TLS values...
138    ASSERT_EQ(expected, pthread_getspecific(key));
139    _exit(99);
140  }
141
142  int status;
143  ASSERT_EQ(pid, waitpid(pid, &status, 0));
144  ASSERT_TRUE(WIFEXITED(status));
145  ASSERT_EQ(99, WEXITSTATUS(status));
146
147  ASSERT_EQ(expected, pthread_getspecific(key));
148  ASSERT_EQ(0, pthread_key_delete(key));
149}
150
151static void* DirtyKeyFn(void* key) {
152  return pthread_getspecific(*reinterpret_cast<pthread_key_t*>(key));
153}
154
155TEST(pthread, pthread_key_dirty) {
156  pthread_key_t key;
157  ASSERT_EQ(0, pthread_key_create(&key, NULL));
158
159  size_t stack_size = 128 * 1024;
160  void* stack = mmap(NULL, stack_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
161  ASSERT_NE(MAP_FAILED, stack);
162  memset(stack, 0xff, stack_size);
163
164  pthread_attr_t attr;
165  ASSERT_EQ(0, pthread_attr_init(&attr));
166  ASSERT_EQ(0, pthread_attr_setstack(&attr, stack, stack_size));
167
168  pthread_t t;
169  ASSERT_EQ(0, pthread_create(&t, &attr, DirtyKeyFn, &key));
170
171  void* result;
172  ASSERT_EQ(0, pthread_join(t, &result));
173  ASSERT_EQ(nullptr, result); // Not ~0!
174
175  ASSERT_EQ(0, munmap(stack, stack_size));
176  ASSERT_EQ(0, pthread_key_delete(key));
177}
178
179static void* IdFn(void* arg) {
180  return arg;
181}
182
183class SpinFunctionHelper {
184 public:
185  SpinFunctionHelper() {
186    SpinFunctionHelper::spin_flag_ = true;
187  }
188  ~SpinFunctionHelper() {
189    UnSpin();
190  }
191  auto GetFunction() -> void* (*)(void*) {
192    return SpinFunctionHelper::SpinFn;
193  }
194
195  void UnSpin() {
196    SpinFunctionHelper::spin_flag_ = false;
197  }
198
199 private:
200  static void* SpinFn(void*) {
201    while (spin_flag_) {}
202    return NULL;
203  }
204  static volatile bool spin_flag_;
205};
206
207// It doesn't matter if spin_flag_ is used in several tests,
208// because it is always set to false after each test. Each thread
209// loops on spin_flag_ can find it becomes false at some time.
210volatile bool SpinFunctionHelper::spin_flag_ = false;
211
212static void* JoinFn(void* arg) {
213  return reinterpret_cast<void*>(pthread_join(reinterpret_cast<pthread_t>(arg), NULL));
214}
215
216static void AssertDetached(pthread_t t, bool is_detached) {
217  pthread_attr_t attr;
218  ASSERT_EQ(0, pthread_getattr_np(t, &attr));
219  int detach_state;
220  ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &detach_state));
221  pthread_attr_destroy(&attr);
222  ASSERT_EQ(is_detached, (detach_state == PTHREAD_CREATE_DETACHED));
223}
224
225static void MakeDeadThread(pthread_t& t) {
226  ASSERT_EQ(0, pthread_create(&t, NULL, IdFn, NULL));
227  ASSERT_EQ(0, pthread_join(t, NULL));
228}
229
230TEST(pthread, pthread_create) {
231  void* expected_result = reinterpret_cast<void*>(123);
232  // Can we create a thread?
233  pthread_t t;
234  ASSERT_EQ(0, pthread_create(&t, NULL, IdFn, expected_result));
235  // If we join, do we get the expected value back?
236  void* result;
237  ASSERT_EQ(0, pthread_join(t, &result));
238  ASSERT_EQ(expected_result, result);
239}
240
241TEST(pthread, pthread_create_EAGAIN) {
242  pthread_attr_t attributes;
243  ASSERT_EQ(0, pthread_attr_init(&attributes));
244  ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, static_cast<size_t>(-1) & ~(getpagesize() - 1)));
245
246  pthread_t t;
247  ASSERT_EQ(EAGAIN, pthread_create(&t, &attributes, IdFn, NULL));
248}
249
250TEST(pthread, pthread_no_join_after_detach) {
251  SpinFunctionHelper spinhelper;
252
253  pthread_t t1;
254  ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL));
255
256  // After a pthread_detach...
257  ASSERT_EQ(0, pthread_detach(t1));
258  AssertDetached(t1, true);
259
260  // ...pthread_join should fail.
261  ASSERT_EQ(EINVAL, pthread_join(t1, NULL));
262}
263
264TEST(pthread, pthread_no_op_detach_after_join) {
265  SpinFunctionHelper spinhelper;
266
267  pthread_t t1;
268  ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL));
269
270  // If thread 2 is already waiting to join thread 1...
271  pthread_t t2;
272  ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1)));
273
274  sleep(1); // (Give t2 a chance to call pthread_join.)
275
276#if defined(__BIONIC__)
277  ASSERT_EQ(EINVAL, pthread_detach(t1));
278#else
279  ASSERT_EQ(0, pthread_detach(t1));
280#endif
281  AssertDetached(t1, false);
282
283  spinhelper.UnSpin();
284
285  // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes).
286  void* join_result;
287  ASSERT_EQ(0, pthread_join(t2, &join_result));
288  ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
289}
290
291TEST(pthread, pthread_join_self) {
292  ASSERT_EQ(EDEADLK, pthread_join(pthread_self(), NULL));
293}
294
295struct TestBug37410 {
296  pthread_t main_thread;
297  pthread_mutex_t mutex;
298
299  static void main() {
300    TestBug37410 data;
301    data.main_thread = pthread_self();
302    ASSERT_EQ(0, pthread_mutex_init(&data.mutex, NULL));
303    ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
304
305    pthread_t t;
306    ASSERT_EQ(0, pthread_create(&t, NULL, TestBug37410::thread_fn, reinterpret_cast<void*>(&data)));
307
308    // Wait for the thread to be running...
309    ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
310    ASSERT_EQ(0, pthread_mutex_unlock(&data.mutex));
311
312    // ...and exit.
313    pthread_exit(NULL);
314  }
315
316 private:
317  static void* thread_fn(void* arg) {
318    TestBug37410* data = reinterpret_cast<TestBug37410*>(arg);
319
320    // Let the main thread know we're running.
321    pthread_mutex_unlock(&data->mutex);
322
323    // And wait for the main thread to exit.
324    pthread_join(data->main_thread, NULL);
325
326    return NULL;
327  }
328};
329
330// Even though this isn't really a death test, we have to say "DeathTest" here so gtest knows to
331// run this test (which exits normally) in its own process.
332
333class pthread_DeathTest : public BionicDeathTest {};
334
335TEST_F(pthread_DeathTest, pthread_bug_37410) {
336  // http://code.google.com/p/android/issues/detail?id=37410
337  ASSERT_EXIT(TestBug37410::main(), ::testing::ExitedWithCode(0), "");
338}
339
340static void* SignalHandlerFn(void* arg) {
341  sigset_t wait_set;
342  sigfillset(&wait_set);
343  return reinterpret_cast<void*>(sigwait(&wait_set, reinterpret_cast<int*>(arg)));
344}
345
346TEST(pthread, pthread_sigmask) {
347  // Check that SIGUSR1 isn't blocked.
348  sigset_t original_set;
349  sigemptyset(&original_set);
350  ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, NULL, &original_set));
351  ASSERT_FALSE(sigismember(&original_set, SIGUSR1));
352
353  // Block SIGUSR1.
354  sigset_t set;
355  sigemptyset(&set);
356  sigaddset(&set, SIGUSR1);
357  ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, &set, NULL));
358
359  // Check that SIGUSR1 is blocked.
360  sigset_t final_set;
361  sigemptyset(&final_set);
362  ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, NULL, &final_set));
363  ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
364  // ...and that sigprocmask agrees with pthread_sigmask.
365  sigemptyset(&final_set);
366  ASSERT_EQ(0, sigprocmask(SIG_BLOCK, NULL, &final_set));
367  ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
368
369  // Spawn a thread that calls sigwait and tells us what it received.
370  pthread_t signal_thread;
371  int received_signal = -1;
372  ASSERT_EQ(0, pthread_create(&signal_thread, NULL, SignalHandlerFn, &received_signal));
373
374  // Send that thread SIGUSR1.
375  pthread_kill(signal_thread, SIGUSR1);
376
377  // See what it got.
378  void* join_result;
379  ASSERT_EQ(0, pthread_join(signal_thread, &join_result));
380  ASSERT_EQ(SIGUSR1, received_signal);
381  ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
382
383  // Restore the original signal mask.
384  ASSERT_EQ(0, pthread_sigmask(SIG_SETMASK, &original_set, NULL));
385}
386
387TEST(pthread, pthread_setname_np__too_long) {
388  ASSERT_EQ(ERANGE, pthread_setname_np(pthread_self(), "this name is far too long for linux"));
389}
390
391TEST(pthread, pthread_setname_np__self) {
392  ASSERT_EQ(0, pthread_setname_np(pthread_self(), "short 1"));
393}
394
395TEST(pthread, pthread_setname_np__other) {
396  SpinFunctionHelper spinhelper;
397
398  pthread_t t1;
399  ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL));
400  ASSERT_EQ(0, pthread_setname_np(t1, "short 2"));
401}
402
403TEST(pthread, pthread_setname_np__no_such_thread) {
404  pthread_t dead_thread;
405  MakeDeadThread(dead_thread);
406
407  // Call pthread_setname_np after thread has already exited.
408  ASSERT_EQ(ENOENT, pthread_setname_np(dead_thread, "short 3"));
409}
410
411TEST(pthread, pthread_kill__0) {
412  // Signal 0 just tests that the thread exists, so it's safe to call on ourselves.
413  ASSERT_EQ(0, pthread_kill(pthread_self(), 0));
414}
415
416TEST(pthread, pthread_kill__invalid_signal) {
417  ASSERT_EQ(EINVAL, pthread_kill(pthread_self(), -1));
418}
419
420static void pthread_kill__in_signal_handler_helper(int signal_number) {
421  static int count = 0;
422  ASSERT_EQ(SIGALRM, signal_number);
423  if (++count == 1) {
424    // Can we call pthread_kill from a signal handler?
425    ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
426  }
427}
428
429TEST(pthread, pthread_kill__in_signal_handler) {
430  ScopedSignalHandler ssh(SIGALRM, pthread_kill__in_signal_handler_helper);
431  ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
432}
433
434TEST(pthread, pthread_detach__no_such_thread) {
435  pthread_t dead_thread;
436  MakeDeadThread(dead_thread);
437
438  ASSERT_EQ(ESRCH, pthread_detach(dead_thread));
439}
440
441TEST(pthread, pthread_detach_no_leak) {
442  size_t initial_bytes = 0;
443  // Run this loop more than once since the first loop causes some memory
444  // to be allocated permenantly. Run an extra loop to help catch any subtle
445  // memory leaks.
446  for (size_t loop = 0; loop < 3; loop++) {
447    // Set the initial bytes on the second loop since the memory in use
448    // should have stabilized.
449    if (loop == 1) {
450      initial_bytes = mallinfo().uordblks;
451    }
452
453    pthread_attr_t attr;
454    ASSERT_EQ(0, pthread_attr_init(&attr));
455    ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
456
457    std::vector<pthread_t> threads;
458    for (size_t i = 0; i < 32; ++i) {
459      pthread_t t;
460      ASSERT_EQ(0, pthread_create(&t, &attr, IdFn, NULL));
461      threads.push_back(t);
462    }
463
464    sleep(1);
465
466    for (size_t i = 0; i < 32; ++i) {
467      ASSERT_EQ(0, pthread_detach(threads[i])) << i;
468    }
469  }
470
471  size_t final_bytes = mallinfo().uordblks;
472  int leaked_bytes = (final_bytes - initial_bytes);
473
474  ASSERT_EQ(0, leaked_bytes);
475}
476
477TEST(pthread, pthread_getcpuclockid__clock_gettime) {
478  SpinFunctionHelper spinhelper;
479
480  pthread_t t;
481  ASSERT_EQ(0, pthread_create(&t, NULL, spinhelper.GetFunction(), NULL));
482
483  clockid_t c;
484  ASSERT_EQ(0, pthread_getcpuclockid(t, &c));
485  timespec ts;
486  ASSERT_EQ(0, clock_gettime(c, &ts));
487}
488
489TEST(pthread, pthread_getcpuclockid__no_such_thread) {
490  pthread_t dead_thread;
491  MakeDeadThread(dead_thread);
492
493  clockid_t c;
494  ASSERT_EQ(ESRCH, pthread_getcpuclockid(dead_thread, &c));
495}
496
497TEST(pthread, pthread_getschedparam__no_such_thread) {
498  pthread_t dead_thread;
499  MakeDeadThread(dead_thread);
500
501  int policy;
502  sched_param param;
503  ASSERT_EQ(ESRCH, pthread_getschedparam(dead_thread, &policy, &param));
504}
505
506TEST(pthread, pthread_setschedparam__no_such_thread) {
507  pthread_t dead_thread;
508  MakeDeadThread(dead_thread);
509
510  int policy = 0;
511  sched_param param;
512  ASSERT_EQ(ESRCH, pthread_setschedparam(dead_thread, policy, &param));
513}
514
515TEST(pthread, pthread_join__no_such_thread) {
516  pthread_t dead_thread;
517  MakeDeadThread(dead_thread);
518
519  ASSERT_EQ(ESRCH, pthread_join(dead_thread, NULL));
520}
521
522TEST(pthread, pthread_kill__no_such_thread) {
523  pthread_t dead_thread;
524  MakeDeadThread(dead_thread);
525
526  ASSERT_EQ(ESRCH, pthread_kill(dead_thread, 0));
527}
528
529TEST(pthread, pthread_join__multijoin) {
530  SpinFunctionHelper spinhelper;
531
532  pthread_t t1;
533  ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL));
534
535  pthread_t t2;
536  ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1)));
537
538  sleep(1); // (Give t2 a chance to call pthread_join.)
539
540  // Multiple joins to the same thread should fail.
541  ASSERT_EQ(EINVAL, pthread_join(t1, NULL));
542
543  spinhelper.UnSpin();
544
545  // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes).
546  void* join_result;
547  ASSERT_EQ(0, pthread_join(t2, &join_result));
548  ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
549}
550
551TEST(pthread, pthread_join__race) {
552  // http://b/11693195 --- pthread_join could return before the thread had actually exited.
553  // If the joiner unmapped the thread's stack, that could lead to SIGSEGV in the thread.
554  for (size_t i = 0; i < 1024; ++i) {
555    size_t stack_size = 64*1024;
556    void* stack = mmap(NULL, stack_size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
557
558    pthread_attr_t a;
559    pthread_attr_init(&a);
560    pthread_attr_setstack(&a, stack, stack_size);
561
562    pthread_t t;
563    ASSERT_EQ(0, pthread_create(&t, &a, IdFn, NULL));
564    ASSERT_EQ(0, pthread_join(t, NULL));
565    ASSERT_EQ(0, munmap(stack, stack_size));
566  }
567}
568
569static void* GetActualGuardSizeFn(void* arg) {
570  pthread_attr_t attributes;
571  pthread_getattr_np(pthread_self(), &attributes);
572  pthread_attr_getguardsize(&attributes, reinterpret_cast<size_t*>(arg));
573  return NULL;
574}
575
576static size_t GetActualGuardSize(const pthread_attr_t& attributes) {
577  size_t result;
578  pthread_t t;
579  pthread_create(&t, &attributes, GetActualGuardSizeFn, &result);
580  pthread_join(t, NULL);
581  return result;
582}
583
584static void* GetActualStackSizeFn(void* arg) {
585  pthread_attr_t attributes;
586  pthread_getattr_np(pthread_self(), &attributes);
587  pthread_attr_getstacksize(&attributes, reinterpret_cast<size_t*>(arg));
588  return NULL;
589}
590
591static size_t GetActualStackSize(const pthread_attr_t& attributes) {
592  size_t result;
593  pthread_t t;
594  pthread_create(&t, &attributes, GetActualStackSizeFn, &result);
595  pthread_join(t, NULL);
596  return result;
597}
598
599TEST(pthread, pthread_attr_setguardsize) {
600  pthread_attr_t attributes;
601  ASSERT_EQ(0, pthread_attr_init(&attributes));
602
603  // Get the default guard size.
604  size_t default_guard_size;
605  ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &default_guard_size));
606
607  // No such thing as too small: will be rounded up to one page by pthread_create.
608  ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 128));
609  size_t guard_size;
610  ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
611  ASSERT_EQ(128U, guard_size);
612  ASSERT_EQ(4096U, GetActualGuardSize(attributes));
613
614  // Large enough and a multiple of the page size.
615  ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024));
616  ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
617  ASSERT_EQ(32*1024U, guard_size);
618
619  // Large enough but not a multiple of the page size; will be rounded up by pthread_create.
620  ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024 + 1));
621  ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
622  ASSERT_EQ(32*1024U + 1, guard_size);
623}
624
625TEST(pthread, pthread_attr_setstacksize) {
626  pthread_attr_t attributes;
627  ASSERT_EQ(0, pthread_attr_init(&attributes));
628
629  // Get the default stack size.
630  size_t default_stack_size;
631  ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &default_stack_size));
632
633  // Too small.
634  ASSERT_EQ(EINVAL, pthread_attr_setstacksize(&attributes, 128));
635  size_t stack_size;
636  ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
637  ASSERT_EQ(default_stack_size, stack_size);
638  ASSERT_GE(GetActualStackSize(attributes), default_stack_size);
639
640  // Large enough and a multiple of the page size; may be rounded up by pthread_create.
641  ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024));
642  ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
643  ASSERT_EQ(32*1024U, stack_size);
644  ASSERT_GE(GetActualStackSize(attributes), 32*1024U);
645
646  // Large enough but not aligned; will be rounded up by pthread_create.
647  ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024 + 1));
648  ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
649  ASSERT_EQ(32*1024U + 1, stack_size);
650#if defined(__BIONIC__)
651  ASSERT_GT(GetActualStackSize(attributes), 32*1024U + 1);
652#else // __BIONIC__
653  // glibc rounds down, in violation of POSIX. They document this in their BUGS section.
654  ASSERT_EQ(GetActualStackSize(attributes), 32*1024U);
655#endif // __BIONIC__
656}
657
658TEST(pthread, pthread_rwlock_smoke) {
659  pthread_rwlock_t l;
660  ASSERT_EQ(0, pthread_rwlock_init(&l, NULL));
661
662  // Single read lock
663  ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
664  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
665
666  // Multiple read lock
667  ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
668  ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
669  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
670  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
671
672  // Write lock
673  ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
674  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
675
676  // Try writer lock
677  ASSERT_EQ(0, pthread_rwlock_trywrlock(&l));
678  ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
679  ASSERT_EQ(EBUSY, pthread_rwlock_tryrdlock(&l));
680  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
681
682  // Try reader lock
683  ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
684  ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
685  ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
686  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
687  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
688
689  // Try writer lock after unlock
690  ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
691  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
692
693#ifdef __BIONIC__
694  // EDEADLK in "read after write"
695  ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
696  ASSERT_EQ(EDEADLK, pthread_rwlock_rdlock(&l));
697  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
698
699  // EDEADLK in "write after write"
700  ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
701  ASSERT_EQ(EDEADLK, pthread_rwlock_wrlock(&l));
702  ASSERT_EQ(0, pthread_rwlock_unlock(&l));
703#endif
704
705  ASSERT_EQ(0, pthread_rwlock_destroy(&l));
706}
707
708struct RwlockWakeupHelperArg {
709  pthread_rwlock_t lock;
710  enum Progress {
711    LOCK_INITIALIZED,
712    LOCK_WAITING,
713    LOCK_RELEASED,
714    LOCK_ACCESSED
715  };
716  std::atomic<Progress> progress;
717};
718
719static void pthread_rwlock_reader_wakeup_writer_helper(RwlockWakeupHelperArg* arg) {
720  ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
721  arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
722
723  ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&arg->lock));
724  ASSERT_EQ(0, pthread_rwlock_wrlock(&arg->lock));
725  ASSERT_EQ(RwlockWakeupHelperArg::LOCK_RELEASED, arg->progress);
726  ASSERT_EQ(0, pthread_rwlock_unlock(&arg->lock));
727
728  arg->progress = RwlockWakeupHelperArg::LOCK_ACCESSED;
729}
730
731TEST(pthread, pthread_rwlock_reader_wakeup_writer) {
732  RwlockWakeupHelperArg wakeup_arg;
733  ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, NULL));
734  ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
735  wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
736
737  pthread_t thread;
738  ASSERT_EQ(0, pthread_create(&thread, NULL,
739    reinterpret_cast<void* (*)(void*)>(pthread_rwlock_reader_wakeup_writer_helper), &wakeup_arg));
740  while (wakeup_arg.progress != RwlockWakeupHelperArg::LOCK_WAITING) {
741    usleep(5000);
742  }
743  usleep(5000);
744  wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
745  ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
746
747  ASSERT_EQ(0, pthread_join(thread, NULL));
748  ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
749  ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
750}
751
752static void pthread_rwlock_writer_wakeup_reader_helper(RwlockWakeupHelperArg* arg) {
753  ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
754  arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
755
756  ASSERT_EQ(EBUSY, pthread_rwlock_tryrdlock(&arg->lock));
757  ASSERT_EQ(0, pthread_rwlock_rdlock(&arg->lock));
758  ASSERT_EQ(RwlockWakeupHelperArg::LOCK_RELEASED, arg->progress);
759  ASSERT_EQ(0, pthread_rwlock_unlock(&arg->lock));
760
761  arg->progress = RwlockWakeupHelperArg::LOCK_ACCESSED;
762}
763
764TEST(pthread, pthread_rwlock_writer_wakeup_reader) {
765  RwlockWakeupHelperArg wakeup_arg;
766  ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, NULL));
767  ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
768  wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
769
770  pthread_t thread;
771  ASSERT_EQ(0, pthread_create(&thread, NULL,
772    reinterpret_cast<void* (*)(void*)>(pthread_rwlock_writer_wakeup_reader_helper), &wakeup_arg));
773  while (wakeup_arg.progress != RwlockWakeupHelperArg::LOCK_WAITING) {
774    usleep(5000);
775  }
776  usleep(5000);
777  wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
778  ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
779
780  ASSERT_EQ(0, pthread_join(thread, NULL));
781  ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
782  ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
783}
784
785static int g_once_fn_call_count = 0;
786static void OnceFn() {
787  ++g_once_fn_call_count;
788}
789
790TEST(pthread, pthread_once_smoke) {
791  pthread_once_t once_control = PTHREAD_ONCE_INIT;
792  ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
793  ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
794  ASSERT_EQ(1, g_once_fn_call_count);
795}
796
797static std::string pthread_once_1934122_result = "";
798
799static void Routine2() {
800  pthread_once_1934122_result += "2";
801}
802
803static void Routine1() {
804  pthread_once_t once_control_2 = PTHREAD_ONCE_INIT;
805  pthread_once_1934122_result += "1";
806  pthread_once(&once_control_2, &Routine2);
807}
808
809TEST(pthread, pthread_once_1934122) {
810  // Very old versions of Android couldn't call pthread_once from a
811  // pthread_once init routine. http://b/1934122.
812  pthread_once_t once_control_1 = PTHREAD_ONCE_INIT;
813  ASSERT_EQ(0, pthread_once(&once_control_1, &Routine1));
814  ASSERT_EQ("12", pthread_once_1934122_result);
815}
816
817static int g_atfork_prepare_calls = 0;
818static void AtForkPrepare1() { g_atfork_prepare_calls = (g_atfork_prepare_calls << 4) | 1; }
819static void AtForkPrepare2() { g_atfork_prepare_calls = (g_atfork_prepare_calls << 4) | 2; }
820static int g_atfork_parent_calls = 0;
821static void AtForkParent1() { g_atfork_parent_calls = (g_atfork_parent_calls << 4) | 1; }
822static void AtForkParent2() { g_atfork_parent_calls = (g_atfork_parent_calls << 4) | 2; }
823static int g_atfork_child_calls = 0;
824static void AtForkChild1() { g_atfork_child_calls = (g_atfork_child_calls << 4) | 1; }
825static void AtForkChild2() { g_atfork_child_calls = (g_atfork_child_calls << 4) | 2; }
826
827TEST(pthread, pthread_atfork_smoke) {
828  ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1));
829  ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2));
830
831  int pid = fork();
832  ASSERT_NE(-1, pid) << strerror(errno);
833
834  // Child and parent calls are made in the order they were registered.
835  if (pid == 0) {
836    ASSERT_EQ(0x12, g_atfork_child_calls);
837    _exit(0);
838  }
839  ASSERT_EQ(0x12, g_atfork_parent_calls);
840
841  // Prepare calls are made in the reverse order.
842  ASSERT_EQ(0x21, g_atfork_prepare_calls);
843}
844
845TEST(pthread, pthread_attr_getscope) {
846  pthread_attr_t attr;
847  ASSERT_EQ(0, pthread_attr_init(&attr));
848
849  int scope;
850  ASSERT_EQ(0, pthread_attr_getscope(&attr, &scope));
851  ASSERT_EQ(PTHREAD_SCOPE_SYSTEM, scope);
852}
853
854TEST(pthread, pthread_condattr_init) {
855  pthread_condattr_t attr;
856  pthread_condattr_init(&attr);
857
858  clockid_t clock;
859  ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
860  ASSERT_EQ(CLOCK_REALTIME, clock);
861
862  int pshared;
863  ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
864  ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
865}
866
867TEST(pthread, pthread_condattr_setclock) {
868  pthread_condattr_t attr;
869  pthread_condattr_init(&attr);
870
871  ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_REALTIME));
872  clockid_t clock;
873  ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
874  ASSERT_EQ(CLOCK_REALTIME, clock);
875
876  ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
877  ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
878  ASSERT_EQ(CLOCK_MONOTONIC, clock);
879
880  ASSERT_EQ(EINVAL, pthread_condattr_setclock(&attr, CLOCK_PROCESS_CPUTIME_ID));
881}
882
883TEST(pthread, pthread_cond_broadcast__preserves_condattr_flags) {
884#if defined(__BIONIC__)
885  pthread_condattr_t attr;
886  pthread_condattr_init(&attr);
887
888  ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
889  ASSERT_EQ(0, pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
890
891  pthread_cond_t cond_var;
892  ASSERT_EQ(0, pthread_cond_init(&cond_var, &attr));
893
894  ASSERT_EQ(0, pthread_cond_signal(&cond_var));
895  ASSERT_EQ(0, pthread_cond_broadcast(&cond_var));
896
897  attr = static_cast<pthread_condattr_t>(*reinterpret_cast<uint32_t*>(cond_var.__private));
898  clockid_t clock;
899  ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
900  ASSERT_EQ(CLOCK_MONOTONIC, clock);
901  int pshared;
902  ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
903  ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
904#else  // !defined(__BIONIC__)
905  GTEST_LOG_(INFO) << "This tests a bionic implementation detail.\n";
906#endif  // !defined(__BIONIC__)
907}
908
909class pthread_CondWakeupTest : public ::testing::Test {
910 protected:
911  pthread_mutex_t mutex;
912  pthread_cond_t cond;
913
914  enum Progress {
915    INITIALIZED,
916    WAITING,
917    SIGNALED,
918    FINISHED,
919  };
920  std::atomic<Progress> progress;
921  pthread_t thread;
922
923 protected:
924  virtual void SetUp() {
925    ASSERT_EQ(0, pthread_mutex_init(&mutex, NULL));
926    ASSERT_EQ(0, pthread_cond_init(&cond, NULL));
927    progress = INITIALIZED;
928    ASSERT_EQ(0,
929      pthread_create(&thread, NULL, reinterpret_cast<void* (*)(void*)>(WaitThreadFn), this));
930  }
931
932  virtual void TearDown() {
933    ASSERT_EQ(0, pthread_join(thread, NULL));
934    ASSERT_EQ(FINISHED, progress);
935    ASSERT_EQ(0, pthread_cond_destroy(&cond));
936    ASSERT_EQ(0, pthread_mutex_destroy(&mutex));
937  }
938
939  void SleepUntilProgress(Progress expected_progress) {
940    while (progress != expected_progress) {
941      usleep(5000);
942    }
943    usleep(5000);
944  }
945
946 private:
947  static void WaitThreadFn(pthread_CondWakeupTest* test) {
948    ASSERT_EQ(0, pthread_mutex_lock(&test->mutex));
949    test->progress = WAITING;
950    while (test->progress == WAITING) {
951      ASSERT_EQ(0, pthread_cond_wait(&test->cond, &test->mutex));
952    }
953    ASSERT_EQ(SIGNALED, test->progress);
954    test->progress = FINISHED;
955    ASSERT_EQ(0, pthread_mutex_unlock(&test->mutex));
956  }
957};
958
959TEST_F(pthread_CondWakeupTest, signal) {
960  SleepUntilProgress(WAITING);
961  progress = SIGNALED;
962  pthread_cond_signal(&cond);
963}
964
965TEST_F(pthread_CondWakeupTest, broadcast) {
966  SleepUntilProgress(WAITING);
967  progress = SIGNALED;
968  pthread_cond_broadcast(&cond);
969}
970
971TEST(pthread, pthread_mutex_timedlock) {
972  pthread_mutex_t m;
973  ASSERT_EQ(0, pthread_mutex_init(&m, NULL));
974
975  // If the mutex is already locked, pthread_mutex_timedlock should time out.
976  ASSERT_EQ(0, pthread_mutex_lock(&m));
977
978  timespec ts;
979  ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
980  ts.tv_nsec += 1;
981  ASSERT_EQ(ETIMEDOUT, pthread_mutex_timedlock(&m, &ts));
982
983  // If the mutex is unlocked, pthread_mutex_timedlock should succeed.
984  ASSERT_EQ(0, pthread_mutex_unlock(&m));
985
986  ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
987  ts.tv_nsec += 1;
988  ASSERT_EQ(0, pthread_mutex_timedlock(&m, &ts));
989
990  ASSERT_EQ(0, pthread_mutex_unlock(&m));
991  ASSERT_EQ(0, pthread_mutex_destroy(&m));
992}
993
994TEST(pthread, pthread_attr_getstack__main_thread) {
995  // This test is only meaningful for the main thread, so make sure we're running on it!
996  ASSERT_EQ(getpid(), syscall(__NR_gettid));
997
998  // Get the main thread's attributes.
999  pthread_attr_t attributes;
1000  ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1001
1002  // Check that we correctly report that the main thread has no guard page.
1003  size_t guard_size;
1004  ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
1005  ASSERT_EQ(0U, guard_size); // The main thread has no guard page.
1006
1007  // Get the stack base and the stack size (both ways).
1008  void* stack_base;
1009  size_t stack_size;
1010  ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1011  size_t stack_size2;
1012  ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1013
1014  // The two methods of asking for the stack size should agree.
1015  EXPECT_EQ(stack_size, stack_size2);
1016
1017  // What does /proc/self/maps' [stack] line say?
1018  void* maps_stack_hi = NULL;
1019  FILE* fp = fopen("/proc/self/maps", "r");
1020  ASSERT_TRUE(fp != NULL);
1021  char line[BUFSIZ];
1022  while (fgets(line, sizeof(line), fp) != NULL) {
1023    uintptr_t lo, hi;
1024    char name[10];
1025    sscanf(line, "%" PRIxPTR "-%" PRIxPTR " %*4s %*x %*x:%*x %*d %10s", &lo, &hi, name);
1026    if (strcmp(name, "[stack]") == 0) {
1027      maps_stack_hi = reinterpret_cast<void*>(hi);
1028      break;
1029    }
1030  }
1031  fclose(fp);
1032
1033  // The stack size should correspond to RLIMIT_STACK.
1034  rlimit rl;
1035  ASSERT_EQ(0, getrlimit(RLIMIT_STACK, &rl));
1036  uint64_t original_rlim_cur = rl.rlim_cur;
1037#if defined(__BIONIC__)
1038  if (rl.rlim_cur == RLIM_INFINITY) {
1039    rl.rlim_cur = 8 * 1024 * 1024; // Bionic reports unlimited stacks as 8MiB.
1040  }
1041#endif
1042  EXPECT_EQ(rl.rlim_cur, stack_size);
1043
1044  auto guard = make_scope_guard([&rl, original_rlim_cur]() {
1045    rl.rlim_cur = original_rlim_cur;
1046    ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1047  });
1048
1049  // The high address of the /proc/self/maps [stack] region should equal stack_base + stack_size.
1050  // Remember that the stack grows down (and is mapped in on demand), so the low address of the
1051  // region isn't very interesting.
1052  EXPECT_EQ(maps_stack_hi, reinterpret_cast<uint8_t*>(stack_base) + stack_size);
1053
1054  //
1055  // What if RLIMIT_STACK is smaller than the stack's current extent?
1056  //
1057  rl.rlim_cur = rl.rlim_max = 1024; // 1KiB. We know the stack must be at least a page already.
1058  rl.rlim_max = RLIM_INFINITY;
1059  ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1060
1061  ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1062  ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1063  ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1064
1065  EXPECT_EQ(stack_size, stack_size2);
1066  ASSERT_EQ(1024U, stack_size);
1067
1068  //
1069  // What if RLIMIT_STACK isn't a whole number of pages?
1070  //
1071  rl.rlim_cur = rl.rlim_max = 6666; // Not a whole number of pages.
1072  rl.rlim_max = RLIM_INFINITY;
1073  ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1074
1075  ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1076  ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1077  ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1078
1079  EXPECT_EQ(stack_size, stack_size2);
1080  ASSERT_EQ(6666U, stack_size);
1081}
1082
1083static void pthread_attr_getstack_18908062_helper(void*) {
1084  char local_variable;
1085  pthread_attr_t attributes;
1086  pthread_getattr_np(pthread_self(), &attributes);
1087  void* stack_base;
1088  size_t stack_size;
1089  pthread_attr_getstack(&attributes, &stack_base, &stack_size);
1090
1091  // Test whether &local_variable is in [stack_base, stack_base + stack_size).
1092  ASSERT_LE(reinterpret_cast<char*>(stack_base), &local_variable);
1093  ASSERT_LT(&local_variable, reinterpret_cast<char*>(stack_base) + stack_size);
1094}
1095
1096// Check whether something on stack is in the range of
1097// [stack_base, stack_base + stack_size). see b/18908062.
1098TEST(pthread, pthread_attr_getstack_18908062) {
1099  pthread_t t;
1100  ASSERT_EQ(0, pthread_create(&t, NULL,
1101            reinterpret_cast<void* (*)(void*)>(pthread_attr_getstack_18908062_helper),
1102            NULL));
1103  pthread_join(t, NULL);
1104}
1105
1106#if defined(__BIONIC__)
1107static void* pthread_gettid_np_helper(void* arg) {
1108  *reinterpret_cast<pid_t*>(arg) = gettid();
1109  return NULL;
1110}
1111#endif
1112
1113TEST(pthread, pthread_gettid_np) {
1114#if defined(__BIONIC__)
1115  ASSERT_EQ(gettid(), pthread_gettid_np(pthread_self()));
1116
1117  pid_t t_gettid_result;
1118  pthread_t t;
1119  pthread_create(&t, NULL, pthread_gettid_np_helper, &t_gettid_result);
1120
1121  pid_t t_pthread_gettid_np_result = pthread_gettid_np(t);
1122
1123  pthread_join(t, NULL);
1124
1125  ASSERT_EQ(t_gettid_result, t_pthread_gettid_np_result);
1126#else
1127  GTEST_LOG_(INFO) << "This test does nothing.\n";
1128#endif
1129}
1130
1131static size_t cleanup_counter = 0;
1132
1133static void AbortCleanupRoutine(void*) {
1134  abort();
1135}
1136
1137static void CountCleanupRoutine(void*) {
1138  ++cleanup_counter;
1139}
1140
1141static void PthreadCleanupTester() {
1142  pthread_cleanup_push(CountCleanupRoutine, NULL);
1143  pthread_cleanup_push(CountCleanupRoutine, NULL);
1144  pthread_cleanup_push(AbortCleanupRoutine, NULL);
1145
1146  pthread_cleanup_pop(0); // Pop the abort without executing it.
1147  pthread_cleanup_pop(1); // Pop one count while executing it.
1148  ASSERT_EQ(1U, cleanup_counter);
1149  // Exit while the other count is still on the cleanup stack.
1150  pthread_exit(NULL);
1151
1152  // Calls to pthread_cleanup_pop/pthread_cleanup_push must always be balanced.
1153  pthread_cleanup_pop(0);
1154}
1155
1156static void* PthreadCleanupStartRoutine(void*) {
1157  PthreadCleanupTester();
1158  return NULL;
1159}
1160
1161TEST(pthread, pthread_cleanup_push__pthread_cleanup_pop) {
1162  pthread_t t;
1163  ASSERT_EQ(0, pthread_create(&t, NULL, PthreadCleanupStartRoutine, NULL));
1164  pthread_join(t, NULL);
1165  ASSERT_EQ(2U, cleanup_counter);
1166}
1167
1168TEST(pthread, PTHREAD_MUTEX_DEFAULT_is_PTHREAD_MUTEX_NORMAL) {
1169  ASSERT_EQ(PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_DEFAULT);
1170}
1171
1172TEST(pthread, pthread_mutexattr_gettype) {
1173  pthread_mutexattr_t attr;
1174  ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1175
1176  int attr_type;
1177
1178  ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL));
1179  ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1180  ASSERT_EQ(PTHREAD_MUTEX_NORMAL, attr_type);
1181
1182  ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK));
1183  ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1184  ASSERT_EQ(PTHREAD_MUTEX_ERRORCHECK, attr_type);
1185
1186  ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE));
1187  ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1188  ASSERT_EQ(PTHREAD_MUTEX_RECURSIVE, attr_type);
1189
1190  ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
1191}
1192
1193struct PthreadMutex {
1194  pthread_mutex_t lock;
1195
1196  PthreadMutex(int mutex_type) {
1197    init(mutex_type);
1198  }
1199
1200  ~PthreadMutex() {
1201    destroy();
1202  }
1203
1204 private:
1205  void init(int mutex_type) {
1206    pthread_mutexattr_t attr;
1207    ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1208    ASSERT_EQ(0, pthread_mutexattr_settype(&attr, mutex_type));
1209    ASSERT_EQ(0, pthread_mutex_init(&lock, &attr));
1210    ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
1211  }
1212
1213  void destroy() {
1214    ASSERT_EQ(0, pthread_mutex_destroy(&lock));
1215  }
1216
1217  DISALLOW_COPY_AND_ASSIGN(PthreadMutex);
1218};
1219
1220TEST(pthread, pthread_mutex_lock_NORMAL) {
1221  PthreadMutex m(PTHREAD_MUTEX_NORMAL);
1222
1223  ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1224  ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1225}
1226
1227TEST(pthread, pthread_mutex_lock_ERRORCHECK) {
1228  PthreadMutex m(PTHREAD_MUTEX_ERRORCHECK);
1229
1230  ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1231  ASSERT_EQ(EDEADLK, pthread_mutex_lock(&m.lock));
1232  ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1233  ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
1234  ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
1235  ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1236  ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
1237}
1238
1239TEST(pthread, pthread_mutex_lock_RECURSIVE) {
1240  PthreadMutex m(PTHREAD_MUTEX_RECURSIVE);
1241
1242  ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1243  ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1244  ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1245  ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1246  ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
1247  ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1248  ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
1249}
1250
1251TEST(pthread, pthread_mutex_init_same_as_static_initializers) {
1252  pthread_mutex_t lock_normal = PTHREAD_MUTEX_INITIALIZER;
1253  PthreadMutex m1(PTHREAD_MUTEX_NORMAL);
1254  ASSERT_EQ(0, memcmp(&lock_normal, &m1.lock, sizeof(pthread_mutex_t)));
1255  pthread_mutex_destroy(&lock_normal);
1256
1257  pthread_mutex_t lock_errorcheck = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
1258  PthreadMutex m2(PTHREAD_MUTEX_ERRORCHECK);
1259  ASSERT_EQ(0, memcmp(&lock_errorcheck, &m2.lock, sizeof(pthread_mutex_t)));
1260  pthread_mutex_destroy(&lock_errorcheck);
1261
1262  pthread_mutex_t lock_recursive = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
1263  PthreadMutex m3(PTHREAD_MUTEX_RECURSIVE);
1264  ASSERT_EQ(0, memcmp(&lock_recursive, &m3.lock, sizeof(pthread_mutex_t)));
1265  ASSERT_EQ(0, pthread_mutex_destroy(&lock_recursive));
1266}
1267
1268class MutexWakeupHelper {
1269 private:
1270  PthreadMutex m;
1271  enum Progress {
1272    LOCK_INITIALIZED,
1273    LOCK_WAITING,
1274    LOCK_RELEASED,
1275    LOCK_ACCESSED
1276  };
1277  std::atomic<Progress> progress;
1278
1279  static void thread_fn(MutexWakeupHelper* helper) {
1280    ASSERT_EQ(LOCK_INITIALIZED, helper->progress);
1281    helper->progress = LOCK_WAITING;
1282
1283    ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock));
1284    ASSERT_EQ(LOCK_RELEASED, helper->progress);
1285    ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock));
1286
1287    helper->progress = LOCK_ACCESSED;
1288  }
1289
1290 public:
1291  MutexWakeupHelper(int mutex_type) : m(mutex_type) {
1292  }
1293
1294  void test() {
1295    ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1296    progress = LOCK_INITIALIZED;
1297
1298    pthread_t thread;
1299    ASSERT_EQ(0, pthread_create(&thread, NULL,
1300      reinterpret_cast<void* (*)(void*)>(MutexWakeupHelper::thread_fn), this));
1301
1302    while (progress != LOCK_WAITING) {
1303      usleep(5000);
1304    }
1305    usleep(5000);
1306    progress = LOCK_RELEASED;
1307    ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1308
1309    ASSERT_EQ(0, pthread_join(thread, NULL));
1310    ASSERT_EQ(LOCK_ACCESSED, progress);
1311  }
1312};
1313
1314TEST(pthread, pthread_mutex_NORMAL_wakeup) {
1315  MutexWakeupHelper helper(PTHREAD_MUTEX_NORMAL);
1316  helper.test();
1317}
1318
1319TEST(pthread, pthread_mutex_ERRORCHECK_wakeup) {
1320  MutexWakeupHelper helper(PTHREAD_MUTEX_ERRORCHECK);
1321  helper.test();
1322}
1323
1324TEST(pthread, pthread_mutex_RECURSIVE_wakeup) {
1325  MutexWakeupHelper helper(PTHREAD_MUTEX_RECURSIVE);
1326  helper.test();
1327}
1328
1329TEST(pthread, pthread_mutex_owner_tid_limit) {
1330#if defined(__BIONIC__) && !defined(__LP64__)
1331  FILE* fp = fopen("/proc/sys/kernel/pid_max", "r");
1332  ASSERT_TRUE(fp != NULL);
1333  long pid_max;
1334  ASSERT_EQ(1, fscanf(fp, "%ld", &pid_max));
1335  fclose(fp);
1336  // Bionic's pthread_mutex implementation on 32-bit devices uses 16 bits to represent owner tid.
1337  ASSERT_LE(pid_max, 65536);
1338#else
1339  GTEST_LOG_(INFO) << "This test does nothing as 32-bit tid is supported by pthread_mutex.\n";
1340#endif
1341}
1342
1343class StrictAlignmentAllocator {
1344 public:
1345  void* allocate(size_t size, size_t alignment) {
1346    char* p = new char[size + alignment * 2];
1347    allocated_array.push_back(p);
1348    while (!is_strict_aligned(p, alignment)) {
1349      ++p;
1350    }
1351    return p;
1352  }
1353
1354  ~StrictAlignmentAllocator() {
1355    for (auto& p : allocated_array) {
1356      delete [] p;
1357    }
1358  }
1359
1360 private:
1361  bool is_strict_aligned(char* p, size_t alignment) {
1362    return (reinterpret_cast<uintptr_t>(p) % (alignment * 2)) == alignment;
1363  }
1364
1365  std::vector<char*> allocated_array;
1366};
1367
1368TEST(pthread, pthread_types_allow_four_bytes_alignment) {
1369#if defined(__BIONIC__)
1370  // For binary compatibility with old version, we need to allow 4-byte aligned data for pthread types.
1371  StrictAlignmentAllocator allocator;
1372  pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(
1373                             allocator.allocate(sizeof(pthread_mutex_t), 4));
1374  ASSERT_EQ(0, pthread_mutex_init(mutex, NULL));
1375  ASSERT_EQ(0, pthread_mutex_lock(mutex));
1376  ASSERT_EQ(0, pthread_mutex_unlock(mutex));
1377  ASSERT_EQ(0, pthread_mutex_destroy(mutex));
1378
1379  pthread_cond_t* cond = reinterpret_cast<pthread_cond_t*>(
1380                           allocator.allocate(sizeof(pthread_cond_t), 4));
1381  ASSERT_EQ(0, pthread_cond_init(cond, NULL));
1382  ASSERT_EQ(0, pthread_cond_signal(cond));
1383  ASSERT_EQ(0, pthread_cond_broadcast(cond));
1384  ASSERT_EQ(0, pthread_cond_destroy(cond));
1385
1386  pthread_rwlock_t* rwlock = reinterpret_cast<pthread_rwlock_t*>(
1387                               allocator.allocate(sizeof(pthread_rwlock_t), 4));
1388  ASSERT_EQ(0, pthread_rwlock_init(rwlock, NULL));
1389  ASSERT_EQ(0, pthread_rwlock_rdlock(rwlock));
1390  ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
1391  ASSERT_EQ(0, pthread_rwlock_wrlock(rwlock));
1392  ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
1393  ASSERT_EQ(0, pthread_rwlock_destroy(rwlock));
1394
1395#else
1396  GTEST_LOG_(INFO) << "This test tests bionic implementation details.";
1397#endif
1398}
1399