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