pthread_test.cpp revision d1aea30b2ade504550f7bb7996c808b9af1c415d
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 <stdio.h> 26#include <sys/mman.h> 27#include <sys/syscall.h> 28#include <time.h> 29#include <unistd.h> 30 31#include <atomic> 32#include <regex> 33#include <vector> 34 35#include <base/file.h> 36#include <base/stringprintf.h> 37 38#include "private/bionic_macros.h" 39#include "private/ScopeGuard.h" 40#include "BionicDeathTest.h" 41#include "ScopedSignalHandler.h" 42 43extern "C" pid_t gettid(); 44 45TEST(pthread, pthread_key_create) { 46 pthread_key_t key; 47 ASSERT_EQ(0, pthread_key_create(&key, NULL)); 48 ASSERT_EQ(0, pthread_key_delete(key)); 49 // Can't delete a key that's already been deleted. 50 ASSERT_EQ(EINVAL, pthread_key_delete(key)); 51} 52 53TEST(pthread, pthread_keys_max) { 54 // POSIX says PTHREAD_KEYS_MAX should be at least _POSIX_THREAD_KEYS_MAX. 55 ASSERT_GE(PTHREAD_KEYS_MAX, _POSIX_THREAD_KEYS_MAX); 56} 57 58TEST(pthread, sysconf_SC_THREAD_KEYS_MAX_eq_PTHREAD_KEYS_MAX) { 59 int sysconf_max = sysconf(_SC_THREAD_KEYS_MAX); 60 ASSERT_EQ(sysconf_max, PTHREAD_KEYS_MAX); 61} 62 63TEST(pthread, pthread_key_many_distinct) { 64 // As gtest uses pthread keys, we can't allocate exactly PTHREAD_KEYS_MAX 65 // pthread keys, but We should be able to allocate at least this many keys. 66 int nkeys = PTHREAD_KEYS_MAX / 2; 67 std::vector<pthread_key_t> keys; 68 69 auto scope_guard = make_scope_guard([&keys]{ 70 for (auto key : keys) { 71 EXPECT_EQ(0, pthread_key_delete(key)); 72 } 73 }); 74 75 for (int i = 0; i < nkeys; ++i) { 76 pthread_key_t key; 77 // If this fails, it's likely that LIBC_PTHREAD_KEY_RESERVED_COUNT is wrong. 78 ASSERT_EQ(0, pthread_key_create(&key, NULL)) << i << " of " << nkeys; 79 keys.push_back(key); 80 ASSERT_EQ(0, pthread_setspecific(key, reinterpret_cast<void*>(i))); 81 } 82 83 for (int i = keys.size() - 1; i >= 0; --i) { 84 ASSERT_EQ(reinterpret_cast<void*>(i), pthread_getspecific(keys.back())); 85 pthread_key_t key = keys.back(); 86 keys.pop_back(); 87 ASSERT_EQ(0, pthread_key_delete(key)); 88 } 89} 90 91TEST(pthread, pthread_key_not_exceed_PTHREAD_KEYS_MAX) { 92 std::vector<pthread_key_t> keys; 93 int rv = 0; 94 95 // Pthread keys are used by gtest, so PTHREAD_KEYS_MAX should 96 // be more than we are allowed to allocate now. 97 for (int i = 0; i < PTHREAD_KEYS_MAX; i++) { 98 pthread_key_t key; 99 rv = pthread_key_create(&key, NULL); 100 if (rv == EAGAIN) { 101 break; 102 } 103 EXPECT_EQ(0, rv); 104 keys.push_back(key); 105 } 106 107 // Don't leak keys. 108 for (auto key : keys) { 109 EXPECT_EQ(0, pthread_key_delete(key)); 110 } 111 keys.clear(); 112 113 // We should have eventually reached the maximum number of keys and received 114 // EAGAIN. 115 ASSERT_EQ(EAGAIN, rv); 116} 117 118TEST(pthread, pthread_key_delete) { 119 void* expected = reinterpret_cast<void*>(1234); 120 pthread_key_t key; 121 ASSERT_EQ(0, pthread_key_create(&key, NULL)); 122 ASSERT_EQ(0, pthread_setspecific(key, expected)); 123 ASSERT_EQ(expected, pthread_getspecific(key)); 124 ASSERT_EQ(0, pthread_key_delete(key)); 125 // After deletion, pthread_getspecific returns NULL. 126 ASSERT_EQ(NULL, pthread_getspecific(key)); 127 // And you can't use pthread_setspecific with the deleted key. 128 ASSERT_EQ(EINVAL, pthread_setspecific(key, expected)); 129} 130 131TEST(pthread, pthread_key_fork) { 132 void* expected = reinterpret_cast<void*>(1234); 133 pthread_key_t key; 134 ASSERT_EQ(0, pthread_key_create(&key, NULL)); 135 ASSERT_EQ(0, pthread_setspecific(key, expected)); 136 ASSERT_EQ(expected, pthread_getspecific(key)); 137 138 pid_t pid = fork(); 139 ASSERT_NE(-1, pid) << strerror(errno); 140 141 if (pid == 0) { 142 // The surviving thread inherits all the forking thread's TLS values... 143 ASSERT_EQ(expected, pthread_getspecific(key)); 144 _exit(99); 145 } 146 147 int status; 148 ASSERT_EQ(pid, waitpid(pid, &status, 0)); 149 ASSERT_TRUE(WIFEXITED(status)); 150 ASSERT_EQ(99, WEXITSTATUS(status)); 151 152 ASSERT_EQ(expected, pthread_getspecific(key)); 153 ASSERT_EQ(0, pthread_key_delete(key)); 154} 155 156static void* DirtyKeyFn(void* key) { 157 return pthread_getspecific(*reinterpret_cast<pthread_key_t*>(key)); 158} 159 160TEST(pthread, pthread_key_dirty) { 161 pthread_key_t key; 162 ASSERT_EQ(0, pthread_key_create(&key, NULL)); 163 164 size_t stack_size = 128 * 1024; 165 void* stack = mmap(NULL, stack_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); 166 ASSERT_NE(MAP_FAILED, stack); 167 memset(stack, 0xff, stack_size); 168 169 pthread_attr_t attr; 170 ASSERT_EQ(0, pthread_attr_init(&attr)); 171 ASSERT_EQ(0, pthread_attr_setstack(&attr, stack, stack_size)); 172 173 pthread_t t; 174 ASSERT_EQ(0, pthread_create(&t, &attr, DirtyKeyFn, &key)); 175 176 void* result; 177 ASSERT_EQ(0, pthread_join(t, &result)); 178 ASSERT_EQ(nullptr, result); // Not ~0! 179 180 ASSERT_EQ(0, munmap(stack, stack_size)); 181 ASSERT_EQ(0, pthread_key_delete(key)); 182} 183 184TEST(pthread, static_pthread_key_used_before_creation) { 185#if defined(__BIONIC__) 186 // See http://b/19625804. The bug is about a static/global pthread key being used before creation. 187 // So here tests if the static/global default value 0 can be detected as invalid key. 188 static pthread_key_t key; 189 ASSERT_EQ(nullptr, pthread_getspecific(key)); 190 ASSERT_EQ(EINVAL, pthread_setspecific(key, nullptr)); 191 ASSERT_EQ(EINVAL, pthread_key_delete(key)); 192#else 193 GTEST_LOG_(INFO) << "This test tests bionic pthread key implementation detail.\n"; 194#endif 195} 196 197static void* IdFn(void* arg) { 198 return arg; 199} 200 201class SpinFunctionHelper { 202 public: 203 SpinFunctionHelper() { 204 SpinFunctionHelper::spin_flag_ = true; 205 } 206 ~SpinFunctionHelper() { 207 UnSpin(); 208 } 209 auto GetFunction() -> void* (*)(void*) { 210 return SpinFunctionHelper::SpinFn; 211 } 212 213 void UnSpin() { 214 SpinFunctionHelper::spin_flag_ = false; 215 } 216 217 private: 218 static void* SpinFn(void*) { 219 while (spin_flag_) {} 220 return NULL; 221 } 222 static volatile bool spin_flag_; 223}; 224 225// It doesn't matter if spin_flag_ is used in several tests, 226// because it is always set to false after each test. Each thread 227// loops on spin_flag_ can find it becomes false at some time. 228volatile bool SpinFunctionHelper::spin_flag_ = false; 229 230static void* JoinFn(void* arg) { 231 return reinterpret_cast<void*>(pthread_join(reinterpret_cast<pthread_t>(arg), NULL)); 232} 233 234static void AssertDetached(pthread_t t, bool is_detached) { 235 pthread_attr_t attr; 236 ASSERT_EQ(0, pthread_getattr_np(t, &attr)); 237 int detach_state; 238 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &detach_state)); 239 pthread_attr_destroy(&attr); 240 ASSERT_EQ(is_detached, (detach_state == PTHREAD_CREATE_DETACHED)); 241} 242 243static void MakeDeadThread(pthread_t& t) { 244 ASSERT_EQ(0, pthread_create(&t, NULL, IdFn, NULL)); 245 ASSERT_EQ(0, pthread_join(t, NULL)); 246} 247 248TEST(pthread, pthread_create) { 249 void* expected_result = reinterpret_cast<void*>(123); 250 // Can we create a thread? 251 pthread_t t; 252 ASSERT_EQ(0, pthread_create(&t, NULL, IdFn, expected_result)); 253 // If we join, do we get the expected value back? 254 void* result; 255 ASSERT_EQ(0, pthread_join(t, &result)); 256 ASSERT_EQ(expected_result, result); 257} 258 259TEST(pthread, pthread_create_EAGAIN) { 260 pthread_attr_t attributes; 261 ASSERT_EQ(0, pthread_attr_init(&attributes)); 262 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, static_cast<size_t>(-1) & ~(getpagesize() - 1))); 263 264 pthread_t t; 265 ASSERT_EQ(EAGAIN, pthread_create(&t, &attributes, IdFn, NULL)); 266} 267 268TEST(pthread, pthread_no_join_after_detach) { 269 SpinFunctionHelper spinhelper; 270 271 pthread_t t1; 272 ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL)); 273 274 // After a pthread_detach... 275 ASSERT_EQ(0, pthread_detach(t1)); 276 AssertDetached(t1, true); 277 278 // ...pthread_join should fail. 279 ASSERT_EQ(EINVAL, pthread_join(t1, NULL)); 280} 281 282TEST(pthread, pthread_no_op_detach_after_join) { 283 SpinFunctionHelper spinhelper; 284 285 pthread_t t1; 286 ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL)); 287 288 // If thread 2 is already waiting to join thread 1... 289 pthread_t t2; 290 ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1))); 291 292 sleep(1); // (Give t2 a chance to call pthread_join.) 293 294#if defined(__BIONIC__) 295 ASSERT_EQ(EINVAL, pthread_detach(t1)); 296#else 297 ASSERT_EQ(0, pthread_detach(t1)); 298#endif 299 AssertDetached(t1, false); 300 301 spinhelper.UnSpin(); 302 303 // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes). 304 void* join_result; 305 ASSERT_EQ(0, pthread_join(t2, &join_result)); 306 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result)); 307} 308 309TEST(pthread, pthread_join_self) { 310 ASSERT_EQ(EDEADLK, pthread_join(pthread_self(), NULL)); 311} 312 313struct TestBug37410 { 314 pthread_t main_thread; 315 pthread_mutex_t mutex; 316 317 static void main() { 318 TestBug37410 data; 319 data.main_thread = pthread_self(); 320 ASSERT_EQ(0, pthread_mutex_init(&data.mutex, NULL)); 321 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex)); 322 323 pthread_t t; 324 ASSERT_EQ(0, pthread_create(&t, NULL, TestBug37410::thread_fn, reinterpret_cast<void*>(&data))); 325 326 // Wait for the thread to be running... 327 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex)); 328 ASSERT_EQ(0, pthread_mutex_unlock(&data.mutex)); 329 330 // ...and exit. 331 pthread_exit(NULL); 332 } 333 334 private: 335 static void* thread_fn(void* arg) { 336 TestBug37410* data = reinterpret_cast<TestBug37410*>(arg); 337 338 // Let the main thread know we're running. 339 pthread_mutex_unlock(&data->mutex); 340 341 // And wait for the main thread to exit. 342 pthread_join(data->main_thread, NULL); 343 344 return NULL; 345 } 346}; 347 348// Even though this isn't really a death test, we have to say "DeathTest" here so gtest knows to 349// run this test (which exits normally) in its own process. 350 351class pthread_DeathTest : public BionicDeathTest {}; 352 353TEST_F(pthread_DeathTest, pthread_bug_37410) { 354 // http://code.google.com/p/android/issues/detail?id=37410 355 ASSERT_EXIT(TestBug37410::main(), ::testing::ExitedWithCode(0), ""); 356} 357 358static void* SignalHandlerFn(void* arg) { 359 sigset_t wait_set; 360 sigfillset(&wait_set); 361 return reinterpret_cast<void*>(sigwait(&wait_set, reinterpret_cast<int*>(arg))); 362} 363 364TEST(pthread, pthread_sigmask) { 365 // Check that SIGUSR1 isn't blocked. 366 sigset_t original_set; 367 sigemptyset(&original_set); 368 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, NULL, &original_set)); 369 ASSERT_FALSE(sigismember(&original_set, SIGUSR1)); 370 371 // Block SIGUSR1. 372 sigset_t set; 373 sigemptyset(&set); 374 sigaddset(&set, SIGUSR1); 375 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, &set, NULL)); 376 377 // Check that SIGUSR1 is blocked. 378 sigset_t final_set; 379 sigemptyset(&final_set); 380 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, NULL, &final_set)); 381 ASSERT_TRUE(sigismember(&final_set, SIGUSR1)); 382 // ...and that sigprocmask agrees with pthread_sigmask. 383 sigemptyset(&final_set); 384 ASSERT_EQ(0, sigprocmask(SIG_BLOCK, NULL, &final_set)); 385 ASSERT_TRUE(sigismember(&final_set, SIGUSR1)); 386 387 // Spawn a thread that calls sigwait and tells us what it received. 388 pthread_t signal_thread; 389 int received_signal = -1; 390 ASSERT_EQ(0, pthread_create(&signal_thread, NULL, SignalHandlerFn, &received_signal)); 391 392 // Send that thread SIGUSR1. 393 pthread_kill(signal_thread, SIGUSR1); 394 395 // See what it got. 396 void* join_result; 397 ASSERT_EQ(0, pthread_join(signal_thread, &join_result)); 398 ASSERT_EQ(SIGUSR1, received_signal); 399 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result)); 400 401 // Restore the original signal mask. 402 ASSERT_EQ(0, pthread_sigmask(SIG_SETMASK, &original_set, NULL)); 403} 404 405TEST(pthread, pthread_setname_np__too_long) { 406 // The limit is 15 characters --- the kernel's buffer is 16, but includes a NUL. 407 ASSERT_EQ(0, pthread_setname_np(pthread_self(), "123456789012345")); 408 ASSERT_EQ(ERANGE, pthread_setname_np(pthread_self(), "1234567890123456")); 409} 410 411TEST(pthread, pthread_setname_np__self) { 412 ASSERT_EQ(0, pthread_setname_np(pthread_self(), "short 1")); 413} 414 415TEST(pthread, pthread_setname_np__other) { 416 SpinFunctionHelper spinhelper; 417 418 pthread_t t1; 419 ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL)); 420 ASSERT_EQ(0, pthread_setname_np(t1, "short 2")); 421} 422 423TEST(pthread, pthread_setname_np__no_such_thread) { 424 pthread_t dead_thread; 425 MakeDeadThread(dead_thread); 426 427 // Call pthread_setname_np after thread has already exited. 428 ASSERT_EQ(ENOENT, pthread_setname_np(dead_thread, "short 3")); 429} 430 431TEST(pthread, pthread_kill__0) { 432 // Signal 0 just tests that the thread exists, so it's safe to call on ourselves. 433 ASSERT_EQ(0, pthread_kill(pthread_self(), 0)); 434} 435 436TEST(pthread, pthread_kill__invalid_signal) { 437 ASSERT_EQ(EINVAL, pthread_kill(pthread_self(), -1)); 438} 439 440static void pthread_kill__in_signal_handler_helper(int signal_number) { 441 static int count = 0; 442 ASSERT_EQ(SIGALRM, signal_number); 443 if (++count == 1) { 444 // Can we call pthread_kill from a signal handler? 445 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM)); 446 } 447} 448 449TEST(pthread, pthread_kill__in_signal_handler) { 450 ScopedSignalHandler ssh(SIGALRM, pthread_kill__in_signal_handler_helper); 451 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM)); 452} 453 454TEST(pthread, pthread_detach__no_such_thread) { 455 pthread_t dead_thread; 456 MakeDeadThread(dead_thread); 457 458 ASSERT_EQ(ESRCH, pthread_detach(dead_thread)); 459} 460 461TEST(pthread, pthread_detach_no_leak) { 462 size_t initial_bytes = 0; 463 // Run this loop more than once since the first loop causes some memory 464 // to be allocated permenantly. Run an extra loop to help catch any subtle 465 // memory leaks. 466 for (size_t loop = 0; loop < 3; loop++) { 467 // Set the initial bytes on the second loop since the memory in use 468 // should have stabilized. 469 if (loop == 1) { 470 initial_bytes = mallinfo().uordblks; 471 } 472 473 pthread_attr_t attr; 474 ASSERT_EQ(0, pthread_attr_init(&attr)); 475 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE)); 476 477 std::vector<pthread_t> threads; 478 for (size_t i = 0; i < 32; ++i) { 479 pthread_t t; 480 ASSERT_EQ(0, pthread_create(&t, &attr, IdFn, NULL)); 481 threads.push_back(t); 482 } 483 484 sleep(1); 485 486 for (size_t i = 0; i < 32; ++i) { 487 ASSERT_EQ(0, pthread_detach(threads[i])) << i; 488 } 489 } 490 491 size_t final_bytes = mallinfo().uordblks; 492 int leaked_bytes = (final_bytes - initial_bytes); 493 494 ASSERT_EQ(0, leaked_bytes); 495} 496 497TEST(pthread, pthread_getcpuclockid__clock_gettime) { 498 SpinFunctionHelper spinhelper; 499 500 pthread_t t; 501 ASSERT_EQ(0, pthread_create(&t, NULL, spinhelper.GetFunction(), NULL)); 502 503 clockid_t c; 504 ASSERT_EQ(0, pthread_getcpuclockid(t, &c)); 505 timespec ts; 506 ASSERT_EQ(0, clock_gettime(c, &ts)); 507} 508 509TEST(pthread, pthread_getcpuclockid__no_such_thread) { 510 pthread_t dead_thread; 511 MakeDeadThread(dead_thread); 512 513 clockid_t c; 514 ASSERT_EQ(ESRCH, pthread_getcpuclockid(dead_thread, &c)); 515} 516 517TEST(pthread, pthread_getschedparam__no_such_thread) { 518 pthread_t dead_thread; 519 MakeDeadThread(dead_thread); 520 521 int policy; 522 sched_param param; 523 ASSERT_EQ(ESRCH, pthread_getschedparam(dead_thread, &policy, ¶m)); 524} 525 526TEST(pthread, pthread_setschedparam__no_such_thread) { 527 pthread_t dead_thread; 528 MakeDeadThread(dead_thread); 529 530 int policy = 0; 531 sched_param param; 532 ASSERT_EQ(ESRCH, pthread_setschedparam(dead_thread, policy, ¶m)); 533} 534 535TEST(pthread, pthread_join__no_such_thread) { 536 pthread_t dead_thread; 537 MakeDeadThread(dead_thread); 538 539 ASSERT_EQ(ESRCH, pthread_join(dead_thread, NULL)); 540} 541 542TEST(pthread, pthread_kill__no_such_thread) { 543 pthread_t dead_thread; 544 MakeDeadThread(dead_thread); 545 546 ASSERT_EQ(ESRCH, pthread_kill(dead_thread, 0)); 547} 548 549TEST(pthread, pthread_join__multijoin) { 550 SpinFunctionHelper spinhelper; 551 552 pthread_t t1; 553 ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL)); 554 555 pthread_t t2; 556 ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1))); 557 558 sleep(1); // (Give t2 a chance to call pthread_join.) 559 560 // Multiple joins to the same thread should fail. 561 ASSERT_EQ(EINVAL, pthread_join(t1, NULL)); 562 563 spinhelper.UnSpin(); 564 565 // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes). 566 void* join_result; 567 ASSERT_EQ(0, pthread_join(t2, &join_result)); 568 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result)); 569} 570 571TEST(pthread, pthread_join__race) { 572 // http://b/11693195 --- pthread_join could return before the thread had actually exited. 573 // If the joiner unmapped the thread's stack, that could lead to SIGSEGV in the thread. 574 for (size_t i = 0; i < 1024; ++i) { 575 size_t stack_size = 64*1024; 576 void* stack = mmap(NULL, stack_size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0); 577 578 pthread_attr_t a; 579 pthread_attr_init(&a); 580 pthread_attr_setstack(&a, stack, stack_size); 581 582 pthread_t t; 583 ASSERT_EQ(0, pthread_create(&t, &a, IdFn, NULL)); 584 ASSERT_EQ(0, pthread_join(t, NULL)); 585 ASSERT_EQ(0, munmap(stack, stack_size)); 586 } 587} 588 589static void* GetActualGuardSizeFn(void* arg) { 590 pthread_attr_t attributes; 591 pthread_getattr_np(pthread_self(), &attributes); 592 pthread_attr_getguardsize(&attributes, reinterpret_cast<size_t*>(arg)); 593 return NULL; 594} 595 596static size_t GetActualGuardSize(const pthread_attr_t& attributes) { 597 size_t result; 598 pthread_t t; 599 pthread_create(&t, &attributes, GetActualGuardSizeFn, &result); 600 pthread_join(t, NULL); 601 return result; 602} 603 604static void* GetActualStackSizeFn(void* arg) { 605 pthread_attr_t attributes; 606 pthread_getattr_np(pthread_self(), &attributes); 607 pthread_attr_getstacksize(&attributes, reinterpret_cast<size_t*>(arg)); 608 return NULL; 609} 610 611static size_t GetActualStackSize(const pthread_attr_t& attributes) { 612 size_t result; 613 pthread_t t; 614 pthread_create(&t, &attributes, GetActualStackSizeFn, &result); 615 pthread_join(t, NULL); 616 return result; 617} 618 619TEST(pthread, pthread_attr_setguardsize) { 620 pthread_attr_t attributes; 621 ASSERT_EQ(0, pthread_attr_init(&attributes)); 622 623 // Get the default guard size. 624 size_t default_guard_size; 625 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &default_guard_size)); 626 627 // No such thing as too small: will be rounded up to one page by pthread_create. 628 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 128)); 629 size_t guard_size; 630 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size)); 631 ASSERT_EQ(128U, guard_size); 632 ASSERT_EQ(4096U, GetActualGuardSize(attributes)); 633 634 // Large enough and a multiple of the page size. 635 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024)); 636 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size)); 637 ASSERT_EQ(32*1024U, guard_size); 638 639 // Large enough but not a multiple of the page size; will be rounded up by pthread_create. 640 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024 + 1)); 641 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size)); 642 ASSERT_EQ(32*1024U + 1, guard_size); 643} 644 645TEST(pthread, pthread_attr_setstacksize) { 646 pthread_attr_t attributes; 647 ASSERT_EQ(0, pthread_attr_init(&attributes)); 648 649 // Get the default stack size. 650 size_t default_stack_size; 651 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &default_stack_size)); 652 653 // Too small. 654 ASSERT_EQ(EINVAL, pthread_attr_setstacksize(&attributes, 128)); 655 size_t stack_size; 656 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size)); 657 ASSERT_EQ(default_stack_size, stack_size); 658 ASSERT_GE(GetActualStackSize(attributes), default_stack_size); 659 660 // Large enough and a multiple of the page size; may be rounded up by pthread_create. 661 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024)); 662 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size)); 663 ASSERT_EQ(32*1024U, stack_size); 664 ASSERT_GE(GetActualStackSize(attributes), 32*1024U); 665 666 // Large enough but not aligned; will be rounded up by pthread_create. 667 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024 + 1)); 668 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size)); 669 ASSERT_EQ(32*1024U + 1, stack_size); 670#if defined(__BIONIC__) 671 ASSERT_GT(GetActualStackSize(attributes), 32*1024U + 1); 672#else // __BIONIC__ 673 // glibc rounds down, in violation of POSIX. They document this in their BUGS section. 674 ASSERT_EQ(GetActualStackSize(attributes), 32*1024U); 675#endif // __BIONIC__ 676} 677 678TEST(pthread, pthread_rwlockattr_smoke) { 679 pthread_rwlockattr_t attr; 680 ASSERT_EQ(0, pthread_rwlockattr_init(&attr)); 681 682 int pshared_value_array[] = {PTHREAD_PROCESS_PRIVATE, PTHREAD_PROCESS_SHARED}; 683 for (size_t i = 0; i < sizeof(pshared_value_array) / sizeof(pshared_value_array[0]); ++i) { 684 ASSERT_EQ(0, pthread_rwlockattr_setpshared(&attr, pshared_value_array[i])); 685 int pshared; 686 ASSERT_EQ(0, pthread_rwlockattr_getpshared(&attr, &pshared)); 687 ASSERT_EQ(pshared_value_array[i], pshared); 688 } 689 690 int kind_array[] = {PTHREAD_RWLOCK_PREFER_READER_NP, 691 PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP}; 692 for (size_t i = 0; i < sizeof(kind_array) / sizeof(kind_array[0]); ++i) { 693 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_array[i])); 694 int kind; 695 ASSERT_EQ(0, pthread_rwlockattr_getkind_np(&attr, &kind)); 696 ASSERT_EQ(kind_array[i], kind); 697 } 698 699 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr)); 700} 701 702TEST(pthread, pthread_rwlock_init_same_as_PTHREAD_RWLOCK_INITIALIZER) { 703 pthread_rwlock_t lock1 = PTHREAD_RWLOCK_INITIALIZER; 704 pthread_rwlock_t lock2; 705 ASSERT_EQ(0, pthread_rwlock_init(&lock2, NULL)); 706 ASSERT_EQ(0, memcmp(&lock1, &lock2, sizeof(lock1))); 707} 708 709TEST(pthread, pthread_rwlock_smoke) { 710 pthread_rwlock_t l; 711 ASSERT_EQ(0, pthread_rwlock_init(&l, NULL)); 712 713 // Single read lock 714 ASSERT_EQ(0, pthread_rwlock_rdlock(&l)); 715 ASSERT_EQ(0, pthread_rwlock_unlock(&l)); 716 717 // Multiple read lock 718 ASSERT_EQ(0, pthread_rwlock_rdlock(&l)); 719 ASSERT_EQ(0, pthread_rwlock_rdlock(&l)); 720 ASSERT_EQ(0, pthread_rwlock_unlock(&l)); 721 ASSERT_EQ(0, pthread_rwlock_unlock(&l)); 722 723 // Write lock 724 ASSERT_EQ(0, pthread_rwlock_wrlock(&l)); 725 ASSERT_EQ(0, pthread_rwlock_unlock(&l)); 726 727 // Try writer lock 728 ASSERT_EQ(0, pthread_rwlock_trywrlock(&l)); 729 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l)); 730 ASSERT_EQ(EBUSY, pthread_rwlock_tryrdlock(&l)); 731 ASSERT_EQ(0, pthread_rwlock_unlock(&l)); 732 733 // Try reader lock 734 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l)); 735 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l)); 736 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l)); 737 ASSERT_EQ(0, pthread_rwlock_unlock(&l)); 738 ASSERT_EQ(0, pthread_rwlock_unlock(&l)); 739 740 // Try writer lock after unlock 741 ASSERT_EQ(0, pthread_rwlock_wrlock(&l)); 742 ASSERT_EQ(0, pthread_rwlock_unlock(&l)); 743 744 // EDEADLK in "read after write" 745 ASSERT_EQ(0, pthread_rwlock_wrlock(&l)); 746 ASSERT_EQ(EDEADLK, pthread_rwlock_rdlock(&l)); 747 ASSERT_EQ(0, pthread_rwlock_unlock(&l)); 748 749 // EDEADLK in "write after write" 750 ASSERT_EQ(0, pthread_rwlock_wrlock(&l)); 751 ASSERT_EQ(EDEADLK, pthread_rwlock_wrlock(&l)); 752 ASSERT_EQ(0, pthread_rwlock_unlock(&l)); 753 754 ASSERT_EQ(0, pthread_rwlock_destroy(&l)); 755} 756 757static void WaitUntilThreadSleep(std::atomic<pid_t>& pid) { 758 while (pid == 0) { 759 usleep(1000); 760 } 761 std::string filename = android::base::StringPrintf("/proc/%d/stat", pid.load()); 762 std::regex regex {R"(\s+S\s+)"}; 763 764 while (true) { 765 std::string content; 766 ASSERT_TRUE(android::base::ReadFileToString(filename, &content)); 767 if (std::regex_search(content, regex)) { 768 break; 769 } 770 usleep(1000); 771 } 772} 773 774struct RwlockWakeupHelperArg { 775 pthread_rwlock_t lock; 776 enum Progress { 777 LOCK_INITIALIZED, 778 LOCK_WAITING, 779 LOCK_RELEASED, 780 LOCK_ACCESSED 781 }; 782 std::atomic<Progress> progress; 783 std::atomic<pid_t> tid; 784}; 785 786static void pthread_rwlock_reader_wakeup_writer_helper(RwlockWakeupHelperArg* arg) { 787 arg->tid = gettid(); 788 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress); 789 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING; 790 791 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&arg->lock)); 792 ASSERT_EQ(0, pthread_rwlock_wrlock(&arg->lock)); 793 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_RELEASED, arg->progress); 794 ASSERT_EQ(0, pthread_rwlock_unlock(&arg->lock)); 795 796 arg->progress = RwlockWakeupHelperArg::LOCK_ACCESSED; 797} 798 799TEST(pthread, pthread_rwlock_reader_wakeup_writer) { 800 RwlockWakeupHelperArg wakeup_arg; 801 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, NULL)); 802 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock)); 803 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED; 804 wakeup_arg.tid = 0; 805 806 pthread_t thread; 807 ASSERT_EQ(0, pthread_create(&thread, NULL, 808 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_reader_wakeup_writer_helper), &wakeup_arg)); 809 WaitUntilThreadSleep(wakeup_arg.tid); 810 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress); 811 812 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED; 813 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock)); 814 815 ASSERT_EQ(0, pthread_join(thread, NULL)); 816 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress); 817 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock)); 818} 819 820static void pthread_rwlock_writer_wakeup_reader_helper(RwlockWakeupHelperArg* arg) { 821 arg->tid = gettid(); 822 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress); 823 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING; 824 825 ASSERT_EQ(EBUSY, pthread_rwlock_tryrdlock(&arg->lock)); 826 ASSERT_EQ(0, pthread_rwlock_rdlock(&arg->lock)); 827 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_RELEASED, arg->progress); 828 ASSERT_EQ(0, pthread_rwlock_unlock(&arg->lock)); 829 830 arg->progress = RwlockWakeupHelperArg::LOCK_ACCESSED; 831} 832 833TEST(pthread, pthread_rwlock_writer_wakeup_reader) { 834 RwlockWakeupHelperArg wakeup_arg; 835 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, NULL)); 836 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock)); 837 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED; 838 wakeup_arg.tid = 0; 839 840 pthread_t thread; 841 ASSERT_EQ(0, pthread_create(&thread, NULL, 842 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_writer_wakeup_reader_helper), &wakeup_arg)); 843 WaitUntilThreadSleep(wakeup_arg.tid); 844 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress); 845 846 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED; 847 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock)); 848 849 ASSERT_EQ(0, pthread_join(thread, NULL)); 850 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress); 851 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock)); 852} 853 854class RwlockKindTestHelper { 855 private: 856 struct ThreadArg { 857 RwlockKindTestHelper* helper; 858 std::atomic<pid_t>& tid; 859 860 ThreadArg(RwlockKindTestHelper* helper, std::atomic<pid_t>& tid) 861 : helper(helper), tid(tid) { } 862 }; 863 864 public: 865 pthread_rwlock_t lock; 866 867 public: 868 RwlockKindTestHelper(int kind_type) { 869 InitRwlock(kind_type); 870 } 871 872 ~RwlockKindTestHelper() { 873 DestroyRwlock(); 874 } 875 876 void CreateWriterThread(pthread_t& thread, std::atomic<pid_t>& tid) { 877 tid = 0; 878 ThreadArg* arg = new ThreadArg(this, tid); 879 ASSERT_EQ(0, pthread_create(&thread, NULL, 880 reinterpret_cast<void* (*)(void*)>(WriterThreadFn), arg)); 881 } 882 883 void CreateReaderThread(pthread_t& thread, std::atomic<pid_t>& tid) { 884 tid = 0; 885 ThreadArg* arg = new ThreadArg(this, tid); 886 ASSERT_EQ(0, pthread_create(&thread, NULL, 887 reinterpret_cast<void* (*)(void*)>(ReaderThreadFn), arg)); 888 } 889 890 private: 891 void InitRwlock(int kind_type) { 892 pthread_rwlockattr_t attr; 893 ASSERT_EQ(0, pthread_rwlockattr_init(&attr)); 894 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_type)); 895 ASSERT_EQ(0, pthread_rwlock_init(&lock, &attr)); 896 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr)); 897 } 898 899 void DestroyRwlock() { 900 ASSERT_EQ(0, pthread_rwlock_destroy(&lock)); 901 } 902 903 static void WriterThreadFn(ThreadArg* arg) { 904 arg->tid = gettid(); 905 906 RwlockKindTestHelper* helper = arg->helper; 907 ASSERT_EQ(0, pthread_rwlock_wrlock(&helper->lock)); 908 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock)); 909 delete arg; 910 } 911 912 static void ReaderThreadFn(ThreadArg* arg) { 913 arg->tid = gettid(); 914 915 RwlockKindTestHelper* helper = arg->helper; 916 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper->lock)); 917 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock)); 918 delete arg; 919 } 920}; 921 922TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_READER_NP) { 923 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_READER_NP); 924 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock)); 925 926 pthread_t writer_thread; 927 std::atomic<pid_t> writer_tid; 928 helper.CreateWriterThread(writer_thread, writer_tid); 929 WaitUntilThreadSleep(writer_tid); 930 931 pthread_t reader_thread; 932 std::atomic<pid_t> reader_tid; 933 helper.CreateReaderThread(reader_thread, reader_tid); 934 ASSERT_EQ(0, pthread_join(reader_thread, NULL)); 935 936 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock)); 937 ASSERT_EQ(0, pthread_join(writer_thread, NULL)); 938} 939 940TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP) { 941 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP); 942 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock)); 943 944 pthread_t writer_thread; 945 std::atomic<pid_t> writer_tid; 946 helper.CreateWriterThread(writer_thread, writer_tid); 947 WaitUntilThreadSleep(writer_tid); 948 949 pthread_t reader_thread; 950 std::atomic<pid_t> reader_tid; 951 helper.CreateReaderThread(reader_thread, reader_tid); 952 WaitUntilThreadSleep(reader_tid); 953 954 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock)); 955 ASSERT_EQ(0, pthread_join(writer_thread, NULL)); 956 ASSERT_EQ(0, pthread_join(reader_thread, NULL)); 957} 958 959static int g_once_fn_call_count = 0; 960static void OnceFn() { 961 ++g_once_fn_call_count; 962} 963 964TEST(pthread, pthread_once_smoke) { 965 pthread_once_t once_control = PTHREAD_ONCE_INIT; 966 ASSERT_EQ(0, pthread_once(&once_control, OnceFn)); 967 ASSERT_EQ(0, pthread_once(&once_control, OnceFn)); 968 ASSERT_EQ(1, g_once_fn_call_count); 969} 970 971static std::string pthread_once_1934122_result = ""; 972 973static void Routine2() { 974 pthread_once_1934122_result += "2"; 975} 976 977static void Routine1() { 978 pthread_once_t once_control_2 = PTHREAD_ONCE_INIT; 979 pthread_once_1934122_result += "1"; 980 pthread_once(&once_control_2, &Routine2); 981} 982 983TEST(pthread, pthread_once_1934122) { 984 // Very old versions of Android couldn't call pthread_once from a 985 // pthread_once init routine. http://b/1934122. 986 pthread_once_t once_control_1 = PTHREAD_ONCE_INIT; 987 ASSERT_EQ(0, pthread_once(&once_control_1, &Routine1)); 988 ASSERT_EQ("12", pthread_once_1934122_result); 989} 990 991static int g_atfork_prepare_calls = 0; 992static void AtForkPrepare1() { g_atfork_prepare_calls = (g_atfork_prepare_calls << 4) | 1; } 993static void AtForkPrepare2() { g_atfork_prepare_calls = (g_atfork_prepare_calls << 4) | 2; } 994static int g_atfork_parent_calls = 0; 995static void AtForkParent1() { g_atfork_parent_calls = (g_atfork_parent_calls << 4) | 1; } 996static void AtForkParent2() { g_atfork_parent_calls = (g_atfork_parent_calls << 4) | 2; } 997static int g_atfork_child_calls = 0; 998static void AtForkChild1() { g_atfork_child_calls = (g_atfork_child_calls << 4) | 1; } 999static void AtForkChild2() { g_atfork_child_calls = (g_atfork_child_calls << 4) | 2; } 1000 1001TEST(pthread, pthread_atfork_smoke) { 1002 ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1)); 1003 ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2)); 1004 1005 int pid = fork(); 1006 ASSERT_NE(-1, pid) << strerror(errno); 1007 1008 // Child and parent calls are made in the order they were registered. 1009 if (pid == 0) { 1010 ASSERT_EQ(0x12, g_atfork_child_calls); 1011 _exit(0); 1012 } 1013 ASSERT_EQ(0x12, g_atfork_parent_calls); 1014 1015 // Prepare calls are made in the reverse order. 1016 ASSERT_EQ(0x21, g_atfork_prepare_calls); 1017} 1018 1019TEST(pthread, pthread_attr_getscope) { 1020 pthread_attr_t attr; 1021 ASSERT_EQ(0, pthread_attr_init(&attr)); 1022 1023 int scope; 1024 ASSERT_EQ(0, pthread_attr_getscope(&attr, &scope)); 1025 ASSERT_EQ(PTHREAD_SCOPE_SYSTEM, scope); 1026} 1027 1028TEST(pthread, pthread_condattr_init) { 1029 pthread_condattr_t attr; 1030 pthread_condattr_init(&attr); 1031 1032 clockid_t clock; 1033 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock)); 1034 ASSERT_EQ(CLOCK_REALTIME, clock); 1035 1036 int pshared; 1037 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared)); 1038 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared); 1039} 1040 1041TEST(pthread, pthread_condattr_setclock) { 1042 pthread_condattr_t attr; 1043 pthread_condattr_init(&attr); 1044 1045 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_REALTIME)); 1046 clockid_t clock; 1047 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock)); 1048 ASSERT_EQ(CLOCK_REALTIME, clock); 1049 1050 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC)); 1051 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock)); 1052 ASSERT_EQ(CLOCK_MONOTONIC, clock); 1053 1054 ASSERT_EQ(EINVAL, pthread_condattr_setclock(&attr, CLOCK_PROCESS_CPUTIME_ID)); 1055} 1056 1057TEST(pthread, pthread_cond_broadcast__preserves_condattr_flags) { 1058#if defined(__BIONIC__) 1059 pthread_condattr_t attr; 1060 pthread_condattr_init(&attr); 1061 1062 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC)); 1063 ASSERT_EQ(0, pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED)); 1064 1065 pthread_cond_t cond_var; 1066 ASSERT_EQ(0, pthread_cond_init(&cond_var, &attr)); 1067 1068 ASSERT_EQ(0, pthread_cond_signal(&cond_var)); 1069 ASSERT_EQ(0, pthread_cond_broadcast(&cond_var)); 1070 1071 attr = static_cast<pthread_condattr_t>(*reinterpret_cast<uint32_t*>(cond_var.__private)); 1072 clockid_t clock; 1073 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock)); 1074 ASSERT_EQ(CLOCK_MONOTONIC, clock); 1075 int pshared; 1076 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared)); 1077 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared); 1078#else // !defined(__BIONIC__) 1079 GTEST_LOG_(INFO) << "This tests a bionic implementation detail.\n"; 1080#endif // !defined(__BIONIC__) 1081} 1082 1083class pthread_CondWakeupTest : public ::testing::Test { 1084 protected: 1085 pthread_mutex_t mutex; 1086 pthread_cond_t cond; 1087 1088 enum Progress { 1089 INITIALIZED, 1090 WAITING, 1091 SIGNALED, 1092 FINISHED, 1093 }; 1094 std::atomic<Progress> progress; 1095 pthread_t thread; 1096 1097 protected: 1098 virtual void SetUp() { 1099 ASSERT_EQ(0, pthread_mutex_init(&mutex, NULL)); 1100 ASSERT_EQ(0, pthread_cond_init(&cond, NULL)); 1101 progress = INITIALIZED; 1102 ASSERT_EQ(0, 1103 pthread_create(&thread, NULL, reinterpret_cast<void* (*)(void*)>(WaitThreadFn), this)); 1104 } 1105 1106 virtual void TearDown() { 1107 ASSERT_EQ(0, pthread_join(thread, NULL)); 1108 ASSERT_EQ(FINISHED, progress); 1109 ASSERT_EQ(0, pthread_cond_destroy(&cond)); 1110 ASSERT_EQ(0, pthread_mutex_destroy(&mutex)); 1111 } 1112 1113 void SleepUntilProgress(Progress expected_progress) { 1114 while (progress != expected_progress) { 1115 usleep(5000); 1116 } 1117 usleep(5000); 1118 } 1119 1120 private: 1121 static void WaitThreadFn(pthread_CondWakeupTest* test) { 1122 ASSERT_EQ(0, pthread_mutex_lock(&test->mutex)); 1123 test->progress = WAITING; 1124 while (test->progress == WAITING) { 1125 ASSERT_EQ(0, pthread_cond_wait(&test->cond, &test->mutex)); 1126 } 1127 ASSERT_EQ(SIGNALED, test->progress); 1128 test->progress = FINISHED; 1129 ASSERT_EQ(0, pthread_mutex_unlock(&test->mutex)); 1130 } 1131}; 1132 1133TEST_F(pthread_CondWakeupTest, signal) { 1134 SleepUntilProgress(WAITING); 1135 progress = SIGNALED; 1136 pthread_cond_signal(&cond); 1137} 1138 1139TEST_F(pthread_CondWakeupTest, broadcast) { 1140 SleepUntilProgress(WAITING); 1141 progress = SIGNALED; 1142 pthread_cond_broadcast(&cond); 1143} 1144 1145TEST(pthread, pthread_mutex_timedlock) { 1146 pthread_mutex_t m; 1147 ASSERT_EQ(0, pthread_mutex_init(&m, NULL)); 1148 1149 // If the mutex is already locked, pthread_mutex_timedlock should time out. 1150 ASSERT_EQ(0, pthread_mutex_lock(&m)); 1151 1152 timespec ts; 1153 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts)); 1154 ts.tv_nsec += 1; 1155 ASSERT_EQ(ETIMEDOUT, pthread_mutex_timedlock(&m, &ts)); 1156 1157 // If the mutex is unlocked, pthread_mutex_timedlock should succeed. 1158 ASSERT_EQ(0, pthread_mutex_unlock(&m)); 1159 1160 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts)); 1161 ts.tv_nsec += 1; 1162 ASSERT_EQ(0, pthread_mutex_timedlock(&m, &ts)); 1163 1164 ASSERT_EQ(0, pthread_mutex_unlock(&m)); 1165 ASSERT_EQ(0, pthread_mutex_destroy(&m)); 1166} 1167 1168TEST(pthread, pthread_attr_getstack__main_thread) { 1169 // This test is only meaningful for the main thread, so make sure we're running on it! 1170 ASSERT_EQ(getpid(), syscall(__NR_gettid)); 1171 1172 // Get the main thread's attributes. 1173 pthread_attr_t attributes; 1174 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes)); 1175 1176 // Check that we correctly report that the main thread has no guard page. 1177 size_t guard_size; 1178 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size)); 1179 ASSERT_EQ(0U, guard_size); // The main thread has no guard page. 1180 1181 // Get the stack base and the stack size (both ways). 1182 void* stack_base; 1183 size_t stack_size; 1184 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size)); 1185 size_t stack_size2; 1186 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2)); 1187 1188 // The two methods of asking for the stack size should agree. 1189 EXPECT_EQ(stack_size, stack_size2); 1190 1191 // What does /proc/self/maps' [stack] line say? 1192 void* maps_stack_hi = NULL; 1193 FILE* fp = fopen("/proc/self/maps", "r"); 1194 ASSERT_TRUE(fp != NULL); 1195 char line[BUFSIZ]; 1196 while (fgets(line, sizeof(line), fp) != NULL) { 1197 uintptr_t lo, hi; 1198 char name[10]; 1199 sscanf(line, "%" PRIxPTR "-%" PRIxPTR " %*4s %*x %*x:%*x %*d %10s", &lo, &hi, name); 1200 if (strcmp(name, "[stack]") == 0) { 1201 maps_stack_hi = reinterpret_cast<void*>(hi); 1202 break; 1203 } 1204 } 1205 fclose(fp); 1206 1207 // The stack size should correspond to RLIMIT_STACK. 1208 rlimit rl; 1209 ASSERT_EQ(0, getrlimit(RLIMIT_STACK, &rl)); 1210 uint64_t original_rlim_cur = rl.rlim_cur; 1211#if defined(__BIONIC__) 1212 if (rl.rlim_cur == RLIM_INFINITY) { 1213 rl.rlim_cur = 8 * 1024 * 1024; // Bionic reports unlimited stacks as 8MiB. 1214 } 1215#endif 1216 EXPECT_EQ(rl.rlim_cur, stack_size); 1217 1218 auto guard = make_scope_guard([&rl, original_rlim_cur]() { 1219 rl.rlim_cur = original_rlim_cur; 1220 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl)); 1221 }); 1222 1223 // The high address of the /proc/self/maps [stack] region should equal stack_base + stack_size. 1224 // Remember that the stack grows down (and is mapped in on demand), so the low address of the 1225 // region isn't very interesting. 1226 EXPECT_EQ(maps_stack_hi, reinterpret_cast<uint8_t*>(stack_base) + stack_size); 1227 1228 // 1229 // What if RLIMIT_STACK is smaller than the stack's current extent? 1230 // 1231 rl.rlim_cur = rl.rlim_max = 1024; // 1KiB. We know the stack must be at least a page already. 1232 rl.rlim_max = RLIM_INFINITY; 1233 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl)); 1234 1235 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes)); 1236 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size)); 1237 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2)); 1238 1239 EXPECT_EQ(stack_size, stack_size2); 1240 ASSERT_EQ(1024U, stack_size); 1241 1242 // 1243 // What if RLIMIT_STACK isn't a whole number of pages? 1244 // 1245 rl.rlim_cur = rl.rlim_max = 6666; // Not a whole number of pages. 1246 rl.rlim_max = RLIM_INFINITY; 1247 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl)); 1248 1249 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes)); 1250 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size)); 1251 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2)); 1252 1253 EXPECT_EQ(stack_size, stack_size2); 1254 ASSERT_EQ(6666U, stack_size); 1255} 1256 1257static void pthread_attr_getstack_18908062_helper(void*) { 1258 char local_variable; 1259 pthread_attr_t attributes; 1260 pthread_getattr_np(pthread_self(), &attributes); 1261 void* stack_base; 1262 size_t stack_size; 1263 pthread_attr_getstack(&attributes, &stack_base, &stack_size); 1264 1265 // Test whether &local_variable is in [stack_base, stack_base + stack_size). 1266 ASSERT_LE(reinterpret_cast<char*>(stack_base), &local_variable); 1267 ASSERT_LT(&local_variable, reinterpret_cast<char*>(stack_base) + stack_size); 1268} 1269 1270// Check whether something on stack is in the range of 1271// [stack_base, stack_base + stack_size). see b/18908062. 1272TEST(pthread, pthread_attr_getstack_18908062) { 1273 pthread_t t; 1274 ASSERT_EQ(0, pthread_create(&t, NULL, 1275 reinterpret_cast<void* (*)(void*)>(pthread_attr_getstack_18908062_helper), 1276 NULL)); 1277 pthread_join(t, NULL); 1278} 1279 1280#if defined(__BIONIC__) 1281static void* pthread_gettid_np_helper(void* arg) { 1282 *reinterpret_cast<pid_t*>(arg) = gettid(); 1283 return NULL; 1284} 1285#endif 1286 1287TEST(pthread, pthread_gettid_np) { 1288#if defined(__BIONIC__) 1289 ASSERT_EQ(gettid(), pthread_gettid_np(pthread_self())); 1290 1291 pid_t t_gettid_result; 1292 pthread_t t; 1293 pthread_create(&t, NULL, pthread_gettid_np_helper, &t_gettid_result); 1294 1295 pid_t t_pthread_gettid_np_result = pthread_gettid_np(t); 1296 1297 pthread_join(t, NULL); 1298 1299 ASSERT_EQ(t_gettid_result, t_pthread_gettid_np_result); 1300#else 1301 GTEST_LOG_(INFO) << "This test does nothing.\n"; 1302#endif 1303} 1304 1305static size_t cleanup_counter = 0; 1306 1307static void AbortCleanupRoutine(void*) { 1308 abort(); 1309} 1310 1311static void CountCleanupRoutine(void*) { 1312 ++cleanup_counter; 1313} 1314 1315static void PthreadCleanupTester() { 1316 pthread_cleanup_push(CountCleanupRoutine, NULL); 1317 pthread_cleanup_push(CountCleanupRoutine, NULL); 1318 pthread_cleanup_push(AbortCleanupRoutine, NULL); 1319 1320 pthread_cleanup_pop(0); // Pop the abort without executing it. 1321 pthread_cleanup_pop(1); // Pop one count while executing it. 1322 ASSERT_EQ(1U, cleanup_counter); 1323 // Exit while the other count is still on the cleanup stack. 1324 pthread_exit(NULL); 1325 1326 // Calls to pthread_cleanup_pop/pthread_cleanup_push must always be balanced. 1327 pthread_cleanup_pop(0); 1328} 1329 1330static void* PthreadCleanupStartRoutine(void*) { 1331 PthreadCleanupTester(); 1332 return NULL; 1333} 1334 1335TEST(pthread, pthread_cleanup_push__pthread_cleanup_pop) { 1336 pthread_t t; 1337 ASSERT_EQ(0, pthread_create(&t, NULL, PthreadCleanupStartRoutine, NULL)); 1338 pthread_join(t, NULL); 1339 ASSERT_EQ(2U, cleanup_counter); 1340} 1341 1342TEST(pthread, PTHREAD_MUTEX_DEFAULT_is_PTHREAD_MUTEX_NORMAL) { 1343 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_DEFAULT); 1344} 1345 1346TEST(pthread, pthread_mutexattr_gettype) { 1347 pthread_mutexattr_t attr; 1348 ASSERT_EQ(0, pthread_mutexattr_init(&attr)); 1349 1350 int attr_type; 1351 1352 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL)); 1353 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type)); 1354 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, attr_type); 1355 1356 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK)); 1357 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type)); 1358 ASSERT_EQ(PTHREAD_MUTEX_ERRORCHECK, attr_type); 1359 1360 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)); 1361 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type)); 1362 ASSERT_EQ(PTHREAD_MUTEX_RECURSIVE, attr_type); 1363 1364 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr)); 1365} 1366 1367struct PthreadMutex { 1368 pthread_mutex_t lock; 1369 1370 PthreadMutex(int mutex_type) { 1371 init(mutex_type); 1372 } 1373 1374 ~PthreadMutex() { 1375 destroy(); 1376 } 1377 1378 private: 1379 void init(int mutex_type) { 1380 pthread_mutexattr_t attr; 1381 ASSERT_EQ(0, pthread_mutexattr_init(&attr)); 1382 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, mutex_type)); 1383 ASSERT_EQ(0, pthread_mutex_init(&lock, &attr)); 1384 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr)); 1385 } 1386 1387 void destroy() { 1388 ASSERT_EQ(0, pthread_mutex_destroy(&lock)); 1389 } 1390 1391 DISALLOW_COPY_AND_ASSIGN(PthreadMutex); 1392}; 1393 1394TEST(pthread, pthread_mutex_lock_NORMAL) { 1395 PthreadMutex m(PTHREAD_MUTEX_NORMAL); 1396 1397 ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); 1398 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); 1399} 1400 1401TEST(pthread, pthread_mutex_lock_ERRORCHECK) { 1402 PthreadMutex m(PTHREAD_MUTEX_ERRORCHECK); 1403 1404 ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); 1405 ASSERT_EQ(EDEADLK, pthread_mutex_lock(&m.lock)); 1406 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); 1407 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock)); 1408 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock)); 1409 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); 1410 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock)); 1411} 1412 1413TEST(pthread, pthread_mutex_lock_RECURSIVE) { 1414 PthreadMutex m(PTHREAD_MUTEX_RECURSIVE); 1415 1416 ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); 1417 ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); 1418 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); 1419 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); 1420 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock)); 1421 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); 1422 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock)); 1423} 1424 1425TEST(pthread, pthread_mutex_init_same_as_static_initializers) { 1426 pthread_mutex_t lock_normal = PTHREAD_MUTEX_INITIALIZER; 1427 PthreadMutex m1(PTHREAD_MUTEX_NORMAL); 1428 ASSERT_EQ(0, memcmp(&lock_normal, &m1.lock, sizeof(pthread_mutex_t))); 1429 pthread_mutex_destroy(&lock_normal); 1430 1431 pthread_mutex_t lock_errorcheck = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP; 1432 PthreadMutex m2(PTHREAD_MUTEX_ERRORCHECK); 1433 ASSERT_EQ(0, memcmp(&lock_errorcheck, &m2.lock, sizeof(pthread_mutex_t))); 1434 pthread_mutex_destroy(&lock_errorcheck); 1435 1436 pthread_mutex_t lock_recursive = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; 1437 PthreadMutex m3(PTHREAD_MUTEX_RECURSIVE); 1438 ASSERT_EQ(0, memcmp(&lock_recursive, &m3.lock, sizeof(pthread_mutex_t))); 1439 ASSERT_EQ(0, pthread_mutex_destroy(&lock_recursive)); 1440} 1441class MutexWakeupHelper { 1442 private: 1443 PthreadMutex m; 1444 enum Progress { 1445 LOCK_INITIALIZED, 1446 LOCK_WAITING, 1447 LOCK_RELEASED, 1448 LOCK_ACCESSED 1449 }; 1450 std::atomic<Progress> progress; 1451 std::atomic<pid_t> tid; 1452 1453 static void thread_fn(MutexWakeupHelper* helper) { 1454 helper->tid = gettid(); 1455 ASSERT_EQ(LOCK_INITIALIZED, helper->progress); 1456 helper->progress = LOCK_WAITING; 1457 1458 ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock)); 1459 ASSERT_EQ(LOCK_RELEASED, helper->progress); 1460 ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock)); 1461 1462 helper->progress = LOCK_ACCESSED; 1463 } 1464 1465 public: 1466 MutexWakeupHelper(int mutex_type) : m(mutex_type) { 1467 } 1468 1469 void test() { 1470 ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); 1471 progress = LOCK_INITIALIZED; 1472 tid = 0; 1473 1474 pthread_t thread; 1475 ASSERT_EQ(0, pthread_create(&thread, NULL, 1476 reinterpret_cast<void* (*)(void*)>(MutexWakeupHelper::thread_fn), this)); 1477 1478 WaitUntilThreadSleep(tid); 1479 ASSERT_EQ(LOCK_WAITING, progress); 1480 1481 progress = LOCK_RELEASED; 1482 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); 1483 1484 ASSERT_EQ(0, pthread_join(thread, NULL)); 1485 ASSERT_EQ(LOCK_ACCESSED, progress); 1486 } 1487}; 1488 1489TEST(pthread, pthread_mutex_NORMAL_wakeup) { 1490 MutexWakeupHelper helper(PTHREAD_MUTEX_NORMAL); 1491 helper.test(); 1492} 1493 1494TEST(pthread, pthread_mutex_ERRORCHECK_wakeup) { 1495 MutexWakeupHelper helper(PTHREAD_MUTEX_ERRORCHECK); 1496 helper.test(); 1497} 1498 1499TEST(pthread, pthread_mutex_RECURSIVE_wakeup) { 1500 MutexWakeupHelper helper(PTHREAD_MUTEX_RECURSIVE); 1501 helper.test(); 1502} 1503 1504TEST(pthread, pthread_mutex_owner_tid_limit) { 1505#if defined(__BIONIC__) && !defined(__LP64__) 1506 FILE* fp = fopen("/proc/sys/kernel/pid_max", "r"); 1507 ASSERT_TRUE(fp != NULL); 1508 long pid_max; 1509 ASSERT_EQ(1, fscanf(fp, "%ld", &pid_max)); 1510 fclose(fp); 1511 // Bionic's pthread_mutex implementation on 32-bit devices uses 16 bits to represent owner tid. 1512 ASSERT_LE(pid_max, 65536); 1513#else 1514 GTEST_LOG_(INFO) << "This test does nothing as 32-bit tid is supported by pthread_mutex.\n"; 1515#endif 1516} 1517 1518class StrictAlignmentAllocator { 1519 public: 1520 void* allocate(size_t size, size_t alignment) { 1521 char* p = new char[size + alignment * 2]; 1522 allocated_array.push_back(p); 1523 while (!is_strict_aligned(p, alignment)) { 1524 ++p; 1525 } 1526 return p; 1527 } 1528 1529 ~StrictAlignmentAllocator() { 1530 for (auto& p : allocated_array) { 1531 delete [] p; 1532 } 1533 } 1534 1535 private: 1536 bool is_strict_aligned(char* p, size_t alignment) { 1537 return (reinterpret_cast<uintptr_t>(p) % (alignment * 2)) == alignment; 1538 } 1539 1540 std::vector<char*> allocated_array; 1541}; 1542 1543TEST(pthread, pthread_types_allow_four_bytes_alignment) { 1544#if defined(__BIONIC__) 1545 // For binary compatibility with old version, we need to allow 4-byte aligned data for pthread types. 1546 StrictAlignmentAllocator allocator; 1547 pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>( 1548 allocator.allocate(sizeof(pthread_mutex_t), 4)); 1549 ASSERT_EQ(0, pthread_mutex_init(mutex, NULL)); 1550 ASSERT_EQ(0, pthread_mutex_lock(mutex)); 1551 ASSERT_EQ(0, pthread_mutex_unlock(mutex)); 1552 ASSERT_EQ(0, pthread_mutex_destroy(mutex)); 1553 1554 pthread_cond_t* cond = reinterpret_cast<pthread_cond_t*>( 1555 allocator.allocate(sizeof(pthread_cond_t), 4)); 1556 ASSERT_EQ(0, pthread_cond_init(cond, NULL)); 1557 ASSERT_EQ(0, pthread_cond_signal(cond)); 1558 ASSERT_EQ(0, pthread_cond_broadcast(cond)); 1559 ASSERT_EQ(0, pthread_cond_destroy(cond)); 1560 1561 pthread_rwlock_t* rwlock = reinterpret_cast<pthread_rwlock_t*>( 1562 allocator.allocate(sizeof(pthread_rwlock_t), 4)); 1563 ASSERT_EQ(0, pthread_rwlock_init(rwlock, NULL)); 1564 ASSERT_EQ(0, pthread_rwlock_rdlock(rwlock)); 1565 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock)); 1566 ASSERT_EQ(0, pthread_rwlock_wrlock(rwlock)); 1567 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock)); 1568 ASSERT_EQ(0, pthread_rwlock_destroy(rwlock)); 1569 1570#else 1571 GTEST_LOG_(INFO) << "This test tests bionic implementation details."; 1572#endif 1573} 1574