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