2 * Copyright (C) 2012 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include <gtest/gtest.h>
19 #include "private/ScopeGuard.h"
20 #include "BionicDeathTest.h"
21 #include "ScopedSignalHandler.h"
32 #include <sys/syscall.h>
36 TEST(pthread, pthread_key_create) {
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));
44 TEST(pthread, pthread_keys_max) {
45 // POSIX says PTHREAD_KEYS_MAX should be at least _POSIX_THREAD_KEYS_MAX.
46 ASSERT_GE(PTHREAD_KEYS_MAX, _POSIX_THREAD_KEYS_MAX);
49 TEST(pthread, sysconf_SC_THREAD_KEYS_MAX_eq_PTHREAD_KEYS_MAX) {
50 int sysconf_max = sysconf(_SC_THREAD_KEYS_MAX);
51 ASSERT_EQ(sysconf_max, PTHREAD_KEYS_MAX);
54 TEST(pthread, pthread_key_many_distinct) {
55 // As gtest uses pthread keys, we can't allocate exactly PTHREAD_KEYS_MAX
56 // pthread keys, but We should be able to allocate at least this many keys.
57 int nkeys = PTHREAD_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));
66 for (int i = 0; i < nkeys; ++i) {
68 // If this fails, it's likely that GLOBAL_INIT_THREAD_LOCAL_BUFFER_COUNT is
70 ASSERT_EQ(0, pthread_key_create(&key, NULL)) << i << " of " << nkeys;
72 ASSERT_EQ(0, pthread_setspecific(key, reinterpret_cast<void*>(i)));
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();
79 ASSERT_EQ(0, pthread_key_delete(key));
83 TEST(pthread, pthread_key_not_exceed_PTHREAD_KEYS_MAX) {
84 std::vector<pthread_key_t> keys;
87 // Pthread keys are used by gtest, so PTHREAD_KEYS_MAX should
88 // be more than we are allowed to allocate now.
89 for (int i = 0; i < PTHREAD_KEYS_MAX; i++) {
91 rv = pthread_key_create(&key, NULL);
100 for (auto key : keys) {
101 EXPECT_EQ(0, pthread_key_delete(key));
105 // We should have eventually reached the maximum number of keys and received
107 ASSERT_EQ(EAGAIN, rv);
110 TEST(pthread, pthread_key_delete) {
111 void* expected = reinterpret_cast<void*>(1234);
113 ASSERT_EQ(0, pthread_key_create(&key, NULL));
114 ASSERT_EQ(0, pthread_setspecific(key, expected));
115 ASSERT_EQ(expected, pthread_getspecific(key));
116 ASSERT_EQ(0, pthread_key_delete(key));
117 // After deletion, pthread_getspecific returns NULL.
118 ASSERT_EQ(NULL, pthread_getspecific(key));
119 // And you can't use pthread_setspecific with the deleted key.
120 ASSERT_EQ(EINVAL, pthread_setspecific(key, expected));
123 TEST(pthread, pthread_key_fork) {
124 void* expected = reinterpret_cast<void*>(1234);
126 ASSERT_EQ(0, pthread_key_create(&key, NULL));
127 ASSERT_EQ(0, pthread_setspecific(key, expected));
128 ASSERT_EQ(expected, pthread_getspecific(key));
131 ASSERT_NE(-1, pid) << strerror(errno);
134 // The surviving thread inherits all the forking thread's TLS values...
135 ASSERT_EQ(expected, pthread_getspecific(key));
140 ASSERT_EQ(pid, waitpid(pid, &status, 0));
141 ASSERT_TRUE(WIFEXITED(status));
142 ASSERT_EQ(99, WEXITSTATUS(status));
144 ASSERT_EQ(expected, pthread_getspecific(key));
145 ASSERT_EQ(0, pthread_key_delete(key));
148 static void* DirtyKeyFn(void* key) {
149 return pthread_getspecific(*reinterpret_cast<pthread_key_t*>(key));
152 TEST(pthread, pthread_key_dirty) {
154 ASSERT_EQ(0, pthread_key_create(&key, NULL));
156 size_t stack_size = 128 * 1024;
157 void* stack = mmap(NULL, stack_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
158 ASSERT_NE(MAP_FAILED, stack);
159 memset(stack, 0xff, stack_size);
162 ASSERT_EQ(0, pthread_attr_init(&attr));
163 ASSERT_EQ(0, pthread_attr_setstack(&attr, stack, stack_size));
166 ASSERT_EQ(0, pthread_create(&t, &attr, DirtyKeyFn, &key));
169 ASSERT_EQ(0, pthread_join(t, &result));
170 ASSERT_EQ(nullptr, result); // Not ~0!
172 ASSERT_EQ(0, munmap(stack, stack_size));
173 ASSERT_EQ(0, pthread_key_delete(key));
176 static void* IdFn(void* arg) {
180 class SpinFunctionHelper {
182 SpinFunctionHelper() {
183 SpinFunctionHelper::spin_flag_ = true;
185 ~SpinFunctionHelper() {
188 auto GetFunction() -> void* (*)(void*) {
189 return SpinFunctionHelper::SpinFn;
193 SpinFunctionHelper::spin_flag_ = false;
197 static void* SpinFn(void*) {
198 while (spin_flag_) {}
201 static volatile bool spin_flag_;
204 // It doesn't matter if spin_flag_ is used in several tests,
205 // because it is always set to false after each test. Each thread
206 // loops on spin_flag_ can find it becomes false at some time.
207 volatile bool SpinFunctionHelper::spin_flag_ = false;
209 static void* JoinFn(void* arg) {
210 return reinterpret_cast<void*>(pthread_join(reinterpret_cast<pthread_t>(arg), NULL));
213 static void AssertDetached(pthread_t t, bool is_detached) {
215 ASSERT_EQ(0, pthread_getattr_np(t, &attr));
217 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &detach_state));
218 pthread_attr_destroy(&attr);
219 ASSERT_EQ(is_detached, (detach_state == PTHREAD_CREATE_DETACHED));
222 static void MakeDeadThread(pthread_t& t) {
223 ASSERT_EQ(0, pthread_create(&t, NULL, IdFn, NULL));
224 ASSERT_EQ(0, pthread_join(t, NULL));
227 TEST(pthread, pthread_create) {
228 void* expected_result = reinterpret_cast<void*>(123);
229 // Can we create a thread?
231 ASSERT_EQ(0, pthread_create(&t, NULL, IdFn, expected_result));
232 // If we join, do we get the expected value back?
234 ASSERT_EQ(0, pthread_join(t, &result));
235 ASSERT_EQ(expected_result, result);
238 TEST(pthread, pthread_create_EAGAIN) {
239 pthread_attr_t attributes;
240 ASSERT_EQ(0, pthread_attr_init(&attributes));
241 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, static_cast<size_t>(-1) & ~(getpagesize() - 1)));
244 ASSERT_EQ(EAGAIN, pthread_create(&t, &attributes, IdFn, NULL));
247 TEST(pthread, pthread_no_join_after_detach) {
248 SpinFunctionHelper spinhelper;
251 ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL));
253 // After a pthread_detach...
254 ASSERT_EQ(0, pthread_detach(t1));
255 AssertDetached(t1, true);
257 // ...pthread_join should fail.
258 ASSERT_EQ(EINVAL, pthread_join(t1, NULL));
261 TEST(pthread, pthread_no_op_detach_after_join) {
262 SpinFunctionHelper spinhelper;
265 ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL));
267 // If thread 2 is already waiting to join thread 1...
269 ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1)));
271 sleep(1); // (Give t2 a chance to call pthread_join.)
273 // ...a call to pthread_detach on thread 1 will "succeed" (silently fail)...
274 ASSERT_EQ(0, pthread_detach(t1));
275 AssertDetached(t1, false);
279 // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes).
281 ASSERT_EQ(0, pthread_join(t2, &join_result));
282 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
285 TEST(pthread, pthread_join_self) {
286 ASSERT_EQ(EDEADLK, pthread_join(pthread_self(), NULL));
289 struct TestBug37410 {
290 pthread_t main_thread;
291 pthread_mutex_t mutex;
295 data.main_thread = pthread_self();
296 ASSERT_EQ(0, pthread_mutex_init(&data.mutex, NULL));
297 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
300 ASSERT_EQ(0, pthread_create(&t, NULL, TestBug37410::thread_fn, reinterpret_cast<void*>(&data)));
302 // Wait for the thread to be running...
303 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
304 ASSERT_EQ(0, pthread_mutex_unlock(&data.mutex));
311 static void* thread_fn(void* arg) {
312 TestBug37410* data = reinterpret_cast<TestBug37410*>(arg);
314 // Let the main thread know we're running.
315 pthread_mutex_unlock(&data->mutex);
317 // And wait for the main thread to exit.
318 pthread_join(data->main_thread, NULL);
324 // Even though this isn't really a death test, we have to say "DeathTest" here so gtest knows to
325 // run this test (which exits normally) in its own process.
327 class pthread_DeathTest : public BionicDeathTest {};
329 TEST_F(pthread_DeathTest, pthread_bug_37410) {
330 // http://code.google.com/p/android/issues/detail?id=37410
331 ASSERT_EXIT(TestBug37410::main(), ::testing::ExitedWithCode(0), "");
334 static void* SignalHandlerFn(void* arg) {
336 sigfillset(&wait_set);
337 return reinterpret_cast<void*>(sigwait(&wait_set, reinterpret_cast<int*>(arg)));
340 TEST(pthread, pthread_sigmask) {
341 // Check that SIGUSR1 isn't blocked.
342 sigset_t original_set;
343 sigemptyset(&original_set);
344 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, NULL, &original_set));
345 ASSERT_FALSE(sigismember(&original_set, SIGUSR1));
350 sigaddset(&set, SIGUSR1);
351 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, &set, NULL));
353 // Check that SIGUSR1 is blocked.
355 sigemptyset(&final_set);
356 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, NULL, &final_set));
357 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
358 // ...and that sigprocmask agrees with pthread_sigmask.
359 sigemptyset(&final_set);
360 ASSERT_EQ(0, sigprocmask(SIG_BLOCK, NULL, &final_set));
361 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
363 // Spawn a thread that calls sigwait and tells us what it received.
364 pthread_t signal_thread;
365 int received_signal = -1;
366 ASSERT_EQ(0, pthread_create(&signal_thread, NULL, SignalHandlerFn, &received_signal));
368 // Send that thread SIGUSR1.
369 pthread_kill(signal_thread, SIGUSR1);
373 ASSERT_EQ(0, pthread_join(signal_thread, &join_result));
374 ASSERT_EQ(SIGUSR1, received_signal);
375 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
377 // Restore the original signal mask.
378 ASSERT_EQ(0, pthread_sigmask(SIG_SETMASK, &original_set, NULL));
381 TEST(pthread, pthread_setname_np__too_long) {
382 ASSERT_EQ(ERANGE, pthread_setname_np(pthread_self(), "this name is far too long for linux"));
385 TEST(pthread, pthread_setname_np__self) {
386 ASSERT_EQ(0, pthread_setname_np(pthread_self(), "short 1"));
389 TEST(pthread, pthread_setname_np__other) {
390 SpinFunctionHelper spinhelper;
393 ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL));
394 ASSERT_EQ(0, pthread_setname_np(t1, "short 2"));
397 TEST(pthread, pthread_setname_np__no_such_thread) {
398 pthread_t dead_thread;
399 MakeDeadThread(dead_thread);
401 // Call pthread_setname_np after thread has already exited.
402 ASSERT_EQ(ENOENT, pthread_setname_np(dead_thread, "short 3"));
405 TEST(pthread, pthread_kill__0) {
406 // Signal 0 just tests that the thread exists, so it's safe to call on ourselves.
407 ASSERT_EQ(0, pthread_kill(pthread_self(), 0));
410 TEST(pthread, pthread_kill__invalid_signal) {
411 ASSERT_EQ(EINVAL, pthread_kill(pthread_self(), -1));
414 static void pthread_kill__in_signal_handler_helper(int signal_number) {
415 static int count = 0;
416 ASSERT_EQ(SIGALRM, signal_number);
418 // Can we call pthread_kill from a signal handler?
419 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
423 TEST(pthread, pthread_kill__in_signal_handler) {
424 ScopedSignalHandler ssh(SIGALRM, pthread_kill__in_signal_handler_helper);
425 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
428 TEST(pthread, pthread_detach__no_such_thread) {
429 pthread_t dead_thread;
430 MakeDeadThread(dead_thread);
432 ASSERT_EQ(ESRCH, pthread_detach(dead_thread));
435 TEST(pthread, pthread_detach_no_leak) {
436 size_t initial_bytes = 0;
437 // Run this loop more than once since the first loop causes some memory
438 // to be allocated permenantly. Run an extra loop to help catch any subtle
440 for (size_t loop = 0; loop < 3; loop++) {
441 // Set the initial bytes on the second loop since the memory in use
442 // should have stabilized.
444 initial_bytes = mallinfo().uordblks;
448 ASSERT_EQ(0, pthread_attr_init(&attr));
449 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
451 std::vector<pthread_t> threads;
452 for (size_t i = 0; i < 32; ++i) {
454 ASSERT_EQ(0, pthread_create(&t, &attr, IdFn, NULL));
455 threads.push_back(t);
460 for (size_t i = 0; i < 32; ++i) {
461 ASSERT_EQ(0, pthread_detach(threads[i])) << i;
465 size_t final_bytes = mallinfo().uordblks;
466 int leaked_bytes = (final_bytes - initial_bytes);
468 ASSERT_EQ(0, leaked_bytes);
471 TEST(pthread, pthread_getcpuclockid__clock_gettime) {
472 SpinFunctionHelper spinhelper;
475 ASSERT_EQ(0, pthread_create(&t, NULL, spinhelper.GetFunction(), NULL));
478 ASSERT_EQ(0, pthread_getcpuclockid(t, &c));
480 ASSERT_EQ(0, clock_gettime(c, &ts));
483 TEST(pthread, pthread_getcpuclockid__no_such_thread) {
484 pthread_t dead_thread;
485 MakeDeadThread(dead_thread);
488 ASSERT_EQ(ESRCH, pthread_getcpuclockid(dead_thread, &c));
491 TEST(pthread, pthread_getschedparam__no_such_thread) {
492 pthread_t dead_thread;
493 MakeDeadThread(dead_thread);
497 ASSERT_EQ(ESRCH, pthread_getschedparam(dead_thread, &policy, ¶m));
500 TEST(pthread, pthread_setschedparam__no_such_thread) {
501 pthread_t dead_thread;
502 MakeDeadThread(dead_thread);
506 ASSERT_EQ(ESRCH, pthread_setschedparam(dead_thread, policy, ¶m));
509 TEST(pthread, pthread_join__no_such_thread) {
510 pthread_t dead_thread;
511 MakeDeadThread(dead_thread);
513 ASSERT_EQ(ESRCH, pthread_join(dead_thread, NULL));
516 TEST(pthread, pthread_kill__no_such_thread) {
517 pthread_t dead_thread;
518 MakeDeadThread(dead_thread);
520 ASSERT_EQ(ESRCH, pthread_kill(dead_thread, 0));
523 TEST(pthread, pthread_join__multijoin) {
524 SpinFunctionHelper spinhelper;
527 ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL));
530 ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1)));
532 sleep(1); // (Give t2 a chance to call pthread_join.)
534 // Multiple joins to the same thread should fail.
535 ASSERT_EQ(EINVAL, pthread_join(t1, NULL));
539 // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes).
541 ASSERT_EQ(0, pthread_join(t2, &join_result));
542 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
545 TEST(pthread, pthread_join__race) {
546 // http://b/11693195 --- pthread_join could return before the thread had actually exited.
547 // If the joiner unmapped the thread's stack, that could lead to SIGSEGV in the thread.
548 for (size_t i = 0; i < 1024; ++i) {
549 size_t stack_size = 64*1024;
550 void* stack = mmap(NULL, stack_size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
553 pthread_attr_init(&a);
554 pthread_attr_setstack(&a, stack, stack_size);
557 ASSERT_EQ(0, pthread_create(&t, &a, IdFn, NULL));
558 ASSERT_EQ(0, pthread_join(t, NULL));
559 ASSERT_EQ(0, munmap(stack, stack_size));
563 static void* GetActualGuardSizeFn(void* arg) {
564 pthread_attr_t attributes;
565 pthread_getattr_np(pthread_self(), &attributes);
566 pthread_attr_getguardsize(&attributes, reinterpret_cast<size_t*>(arg));
570 static size_t GetActualGuardSize(const pthread_attr_t& attributes) {
573 pthread_create(&t, &attributes, GetActualGuardSizeFn, &result);
574 pthread_join(t, NULL);
578 static void* GetActualStackSizeFn(void* arg) {
579 pthread_attr_t attributes;
580 pthread_getattr_np(pthread_self(), &attributes);
581 pthread_attr_getstacksize(&attributes, reinterpret_cast<size_t*>(arg));
585 static size_t GetActualStackSize(const pthread_attr_t& attributes) {
588 pthread_create(&t, &attributes, GetActualStackSizeFn, &result);
589 pthread_join(t, NULL);
593 TEST(pthread, pthread_attr_setguardsize) {
594 pthread_attr_t attributes;
595 ASSERT_EQ(0, pthread_attr_init(&attributes));
597 // Get the default guard size.
598 size_t default_guard_size;
599 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &default_guard_size));
601 // No such thing as too small: will be rounded up to one page by pthread_create.
602 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 128));
604 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
605 ASSERT_EQ(128U, guard_size);
606 ASSERT_EQ(4096U, GetActualGuardSize(attributes));
608 // Large enough and a multiple of the page size.
609 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024));
610 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
611 ASSERT_EQ(32*1024U, guard_size);
613 // Large enough but not a multiple of the page size; will be rounded up by pthread_create.
614 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024 + 1));
615 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
616 ASSERT_EQ(32*1024U + 1, guard_size);
619 TEST(pthread, pthread_attr_setstacksize) {
620 pthread_attr_t attributes;
621 ASSERT_EQ(0, pthread_attr_init(&attributes));
623 // Get the default stack size.
624 size_t default_stack_size;
625 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &default_stack_size));
628 ASSERT_EQ(EINVAL, pthread_attr_setstacksize(&attributes, 128));
630 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
631 ASSERT_EQ(default_stack_size, stack_size);
632 ASSERT_GE(GetActualStackSize(attributes), default_stack_size);
634 // Large enough and a multiple of the page size; may be rounded up by pthread_create.
635 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024));
636 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
637 ASSERT_EQ(32*1024U, stack_size);
638 ASSERT_GE(GetActualStackSize(attributes), 32*1024U);
640 // Large enough but not aligned; will be rounded up by pthread_create.
641 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024 + 1));
642 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
643 ASSERT_EQ(32*1024U + 1, stack_size);
644 #if defined(__BIONIC__)
645 ASSERT_GT(GetActualStackSize(attributes), 32*1024U + 1);
647 // glibc rounds down, in violation of POSIX. They document this in their BUGS section.
648 ASSERT_EQ(GetActualStackSize(attributes), 32*1024U);
652 TEST(pthread, pthread_rwlock_smoke) {
654 ASSERT_EQ(0, pthread_rwlock_init(&l, NULL));
657 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
658 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
660 // Multiple read lock
661 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
662 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
663 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
664 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
667 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
668 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
671 ASSERT_EQ(0, pthread_rwlock_trywrlock(&l));
672 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
673 ASSERT_EQ(EBUSY, pthread_rwlock_tryrdlock(&l));
674 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
677 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
678 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
679 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
680 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
681 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
683 // Try writer lock after unlock
684 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
685 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
688 // EDEADLK in "read after write"
689 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
690 ASSERT_EQ(EDEADLK, pthread_rwlock_rdlock(&l));
691 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
693 // EDEADLK in "write after write"
694 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
695 ASSERT_EQ(EDEADLK, pthread_rwlock_wrlock(&l));
696 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
699 ASSERT_EQ(0, pthread_rwlock_destroy(&l));
702 static int g_once_fn_call_count = 0;
703 static void OnceFn() {
704 ++g_once_fn_call_count;
707 TEST(pthread, pthread_once_smoke) {
708 pthread_once_t once_control = PTHREAD_ONCE_INIT;
709 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
710 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
711 ASSERT_EQ(1, g_once_fn_call_count);
714 static std::string pthread_once_1934122_result = "";
716 static void Routine2() {
717 pthread_once_1934122_result += "2";
720 static void Routine1() {
721 pthread_once_t once_control_2 = PTHREAD_ONCE_INIT;
722 pthread_once_1934122_result += "1";
723 pthread_once(&once_control_2, &Routine2);
726 TEST(pthread, pthread_once_1934122) {
727 // Very old versions of Android couldn't call pthread_once from a
728 // pthread_once init routine. http://b/1934122.
729 pthread_once_t once_control_1 = PTHREAD_ONCE_INIT;
730 ASSERT_EQ(0, pthread_once(&once_control_1, &Routine1));
731 ASSERT_EQ("12", pthread_once_1934122_result);
734 static int g_atfork_prepare_calls = 0;
735 static void AtForkPrepare1() { g_atfork_prepare_calls = (g_atfork_prepare_calls << 4) | 1; }
736 static void AtForkPrepare2() { g_atfork_prepare_calls = (g_atfork_prepare_calls << 4) | 2; }
737 static int g_atfork_parent_calls = 0;
738 static void AtForkParent1() { g_atfork_parent_calls = (g_atfork_parent_calls << 4) | 1; }
739 static void AtForkParent2() { g_atfork_parent_calls = (g_atfork_parent_calls << 4) | 2; }
740 static int g_atfork_child_calls = 0;
741 static void AtForkChild1() { g_atfork_child_calls = (g_atfork_child_calls << 4) | 1; }
742 static void AtForkChild2() { g_atfork_child_calls = (g_atfork_child_calls << 4) | 2; }
744 TEST(pthread, pthread_atfork_smoke) {
746 ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1));
747 ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2));
750 ASSERT_NE(-1, pid) << strerror(errno);
752 // Child and parent calls are made in the order they were registered.
754 ASSERT_EQ(0x12, g_atfork_child_calls);
757 ASSERT_EQ(0x12, g_atfork_parent_calls);
759 // Prepare calls are made in the reverse order.
760 ASSERT_EQ(0x21, g_atfork_prepare_calls);
764 TEST(pthread, pthread_attr_getscope) {
766 ASSERT_EQ(0, pthread_attr_init(&attr));
769 ASSERT_EQ(0, pthread_attr_getscope(&attr, &scope));
770 ASSERT_EQ(PTHREAD_SCOPE_SYSTEM, scope);
773 TEST(pthread, pthread_condattr_init) {
774 pthread_condattr_t attr;
775 pthread_condattr_init(&attr);
778 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
779 ASSERT_EQ(CLOCK_REALTIME, clock);
782 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
783 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
786 TEST(pthread, pthread_condattr_setclock) {
787 pthread_condattr_t attr;
788 pthread_condattr_init(&attr);
790 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_REALTIME));
792 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
793 ASSERT_EQ(CLOCK_REALTIME, clock);
795 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
796 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
797 ASSERT_EQ(CLOCK_MONOTONIC, clock);
799 ASSERT_EQ(EINVAL, pthread_condattr_setclock(&attr, CLOCK_PROCESS_CPUTIME_ID));
802 TEST(pthread, pthread_cond_broadcast__preserves_condattr_flags) {
803 #if defined(__BIONIC__) // This tests a bionic implementation detail.
804 pthread_condattr_t attr;
805 pthread_condattr_init(&attr);
807 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
808 ASSERT_EQ(0, pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
810 pthread_cond_t cond_var;
811 ASSERT_EQ(0, pthread_cond_init(&cond_var, &attr));
813 ASSERT_EQ(0, pthread_cond_signal(&cond_var));
814 ASSERT_EQ(0, pthread_cond_broadcast(&cond_var));
816 attr = static_cast<pthread_condattr_t>(cond_var.value);
818 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
819 ASSERT_EQ(CLOCK_MONOTONIC, clock);
821 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
822 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
824 GTEST_LOG_(INFO) << "This test does nothing.\n";
828 TEST(pthread, pthread_mutex_timedlock) {
830 ASSERT_EQ(0, pthread_mutex_init(&m, NULL));
832 // If the mutex is already locked, pthread_mutex_timedlock should time out.
833 ASSERT_EQ(0, pthread_mutex_lock(&m));
836 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
838 ASSERT_EQ(ETIMEDOUT, pthread_mutex_timedlock(&m, &ts));
840 // If the mutex is unlocked, pthread_mutex_timedlock should succeed.
841 ASSERT_EQ(0, pthread_mutex_unlock(&m));
843 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
845 ASSERT_EQ(0, pthread_mutex_timedlock(&m, &ts));
847 ASSERT_EQ(0, pthread_mutex_unlock(&m));
848 ASSERT_EQ(0, pthread_mutex_destroy(&m));
851 TEST(pthread, pthread_attr_getstack__main_thread) {
852 // This test is only meaningful for the main thread, so make sure we're running on it!
853 ASSERT_EQ(getpid(), syscall(__NR_gettid));
855 // Get the main thread's attributes.
856 pthread_attr_t attributes;
857 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
859 // Check that we correctly report that the main thread has no guard page.
861 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
862 ASSERT_EQ(0U, guard_size); // The main thread has no guard page.
864 // Get the stack base and the stack size (both ways).
867 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
869 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
871 // The two methods of asking for the stack size should agree.
872 EXPECT_EQ(stack_size, stack_size2);
874 // What does /proc/self/maps' [stack] line say?
875 void* maps_stack_hi = NULL;
876 FILE* fp = fopen("/proc/self/maps", "r");
877 ASSERT_TRUE(fp != NULL);
879 while (fgets(line, sizeof(line), fp) != NULL) {
882 sscanf(line, "%" PRIxPTR "-%" PRIxPTR " %*4s %*x %*x:%*x %*d %10s", &lo, &hi, name);
883 if (strcmp(name, "[stack]") == 0) {
884 maps_stack_hi = reinterpret_cast<void*>(hi);
890 // The stack size should correspond to RLIMIT_STACK.
892 ASSERT_EQ(0, getrlimit(RLIMIT_STACK, &rl));
893 uint64_t original_rlim_cur = rl.rlim_cur;
894 #if defined(__BIONIC__)
895 if (rl.rlim_cur == RLIM_INFINITY) {
896 rl.rlim_cur = 8 * 1024 * 1024; // Bionic reports unlimited stacks as 8MiB.
899 EXPECT_EQ(rl.rlim_cur, stack_size);
901 auto guard = make_scope_guard([&rl, original_rlim_cur]() {
902 rl.rlim_cur = original_rlim_cur;
903 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
906 // The high address of the /proc/self/maps [stack] region should equal stack_base + stack_size.
907 // Remember that the stack grows down (and is mapped in on demand), so the low address of the
908 // region isn't very interesting.
909 EXPECT_EQ(maps_stack_hi, reinterpret_cast<uint8_t*>(stack_base) + stack_size);
912 // What if RLIMIT_STACK is smaller than the stack's current extent?
914 rl.rlim_cur = rl.rlim_max = 1024; // 1KiB. We know the stack must be at least a page already.
915 rl.rlim_max = RLIM_INFINITY;
916 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
918 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
919 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
920 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
922 EXPECT_EQ(stack_size, stack_size2);
923 ASSERT_EQ(1024U, stack_size);
926 // What if RLIMIT_STACK isn't a whole number of pages?
928 rl.rlim_cur = rl.rlim_max = 6666; // Not a whole number of pages.
929 rl.rlim_max = RLIM_INFINITY;
930 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
932 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
933 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
934 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
936 EXPECT_EQ(stack_size, stack_size2);
937 ASSERT_EQ(6666U, stack_size);
940 static void pthread_attr_getstack_18908062_helper(void*) {
942 pthread_attr_t attributes;
943 pthread_getattr_np(pthread_self(), &attributes);
946 pthread_attr_getstack(&attributes, &stack_base, &stack_size);
948 // Test whether &local_variable is in [stack_base, stack_base + stack_size).
949 ASSERT_LE(reinterpret_cast<char*>(stack_base), &local_variable);
950 ASSERT_LT(&local_variable, reinterpret_cast<char*>(stack_base) + stack_size);
953 // Check whether something on stack is in the range of
954 // [stack_base, stack_base + stack_size). see b/18908062.
955 TEST(pthread, pthread_attr_getstack_18908062) {
957 ASSERT_EQ(0, pthread_create(&t, NULL,
958 reinterpret_cast<void* (*)(void*)>(pthread_attr_getstack_18908062_helper),
960 pthread_join(t, NULL);
963 #if defined(__BIONIC__)
964 static void* pthread_gettid_np_helper(void* arg) {
965 *reinterpret_cast<pid_t*>(arg) = gettid();
970 TEST(pthread, pthread_gettid_np) {
971 #if defined(__BIONIC__)
972 ASSERT_EQ(gettid(), pthread_gettid_np(pthread_self()));
974 pid_t t_gettid_result;
976 pthread_create(&t, NULL, pthread_gettid_np_helper, &t_gettid_result);
978 pid_t t_pthread_gettid_np_result = pthread_gettid_np(t);
980 pthread_join(t, NULL);
982 ASSERT_EQ(t_gettid_result, t_pthread_gettid_np_result);
984 GTEST_LOG_(INFO) << "This test does nothing.\n";
988 static size_t cleanup_counter = 0;
990 static void AbortCleanupRoutine(void*) {
994 static void CountCleanupRoutine(void*) {
998 static void PthreadCleanupTester() {
999 pthread_cleanup_push(CountCleanupRoutine, NULL);
1000 pthread_cleanup_push(CountCleanupRoutine, NULL);
1001 pthread_cleanup_push(AbortCleanupRoutine, NULL);
1003 pthread_cleanup_pop(0); // Pop the abort without executing it.
1004 pthread_cleanup_pop(1); // Pop one count while executing it.
1005 ASSERT_EQ(1U, cleanup_counter);
1006 // Exit while the other count is still on the cleanup stack.
1009 // Calls to pthread_cleanup_pop/pthread_cleanup_push must always be balanced.
1010 pthread_cleanup_pop(0);
1013 static void* PthreadCleanupStartRoutine(void*) {
1014 PthreadCleanupTester();
1018 TEST(pthread, pthread_cleanup_push__pthread_cleanup_pop) {
1020 ASSERT_EQ(0, pthread_create(&t, NULL, PthreadCleanupStartRoutine, NULL));
1021 pthread_join(t, NULL);
1022 ASSERT_EQ(2U, cleanup_counter);
1025 TEST(pthread, PTHREAD_MUTEX_DEFAULT_is_PTHREAD_MUTEX_NORMAL) {
1026 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_DEFAULT);
1029 TEST(pthread, pthread_mutexattr_gettype) {
1030 pthread_mutexattr_t attr;
1031 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1035 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL));
1036 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1037 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, attr_type);
1039 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK));
1040 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1041 ASSERT_EQ(PTHREAD_MUTEX_ERRORCHECK, attr_type);
1043 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE));
1044 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1045 ASSERT_EQ(PTHREAD_MUTEX_RECURSIVE, attr_type);
1048 TEST(pthread, pthread_mutex_lock_NORMAL) {
1049 pthread_mutexattr_t attr;
1050 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1051 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL));
1053 pthread_mutex_t lock;
1054 ASSERT_EQ(0, pthread_mutex_init(&lock, &attr));
1056 ASSERT_EQ(0, pthread_mutex_lock(&lock));
1057 ASSERT_EQ(0, pthread_mutex_unlock(&lock));
1058 ASSERT_EQ(0, pthread_mutex_destroy(&lock));
1061 TEST(pthread, pthread_mutex_lock_ERRORCHECK) {
1062 pthread_mutexattr_t attr;
1063 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1064 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK));
1066 pthread_mutex_t lock;
1067 ASSERT_EQ(0, pthread_mutex_init(&lock, &attr));
1069 ASSERT_EQ(0, pthread_mutex_lock(&lock));
1070 ASSERT_EQ(EDEADLK, pthread_mutex_lock(&lock));
1071 ASSERT_EQ(0, pthread_mutex_unlock(&lock));
1072 ASSERT_EQ(0, pthread_mutex_trylock(&lock));
1073 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&lock));
1074 ASSERT_EQ(0, pthread_mutex_unlock(&lock));
1075 ASSERT_EQ(EPERM, pthread_mutex_unlock(&lock));
1076 ASSERT_EQ(0, pthread_mutex_destroy(&lock));
1079 TEST(pthread, pthread_mutex_lock_RECURSIVE) {
1080 pthread_mutexattr_t attr;
1081 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1082 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE));
1084 pthread_mutex_t lock;
1085 ASSERT_EQ(0, pthread_mutex_init(&lock, &attr));
1087 ASSERT_EQ(0, pthread_mutex_lock(&lock));
1088 ASSERT_EQ(0, pthread_mutex_lock(&lock));
1089 ASSERT_EQ(0, pthread_mutex_unlock(&lock));
1090 ASSERT_EQ(0, pthread_mutex_unlock(&lock));
1091 ASSERT_EQ(0, pthread_mutex_trylock(&lock));
1092 ASSERT_EQ(0, pthread_mutex_unlock(&lock));
1093 ASSERT_EQ(EPERM, pthread_mutex_unlock(&lock));
1094 ASSERT_EQ(0, pthread_mutex_destroy(&lock));
1097 TEST(pthread, pthread_mutex_owner_tid_limit) {
1098 FILE* fp = fopen("/proc/sys/kernel/pid_max", "r");
1099 ASSERT_TRUE(fp != NULL);
1101 ASSERT_EQ(1, fscanf(fp, "%ld", &pid_max));
1103 // Current pthread_mutex uses 16 bits to represent owner tid.
1104 // Change the implementation if we need to support higher value than 65535.
1105 ASSERT_LE(pid_max, 65536);