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