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