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/prctl.h> 28 #include <sys/syscall.h> 29 #include <time.h> 30 #include <unistd.h> 31 #include <unwind.h> 32 33 #include <atomic> 34 #include <vector> 35 36 #include <android-base/parseint.h> 37 #include <android-base/scopeguard.h> 38 #include <android-base/strings.h> 39 40 #include "private/bionic_constants.h" 41 #include "private/bionic_macros.h" 42 #include "BionicDeathTest.h" 43 #include "ScopedSignalHandler.h" 44 #include "utils.h" 45 46 TEST(pthread, pthread_key_create) { 47 pthread_key_t key; 48 ASSERT_EQ(0, pthread_key_create(&key, NULL)); 49 ASSERT_EQ(0, pthread_key_delete(key)); 50 // Can't delete a key that's already been deleted. 51 ASSERT_EQ(EINVAL, pthread_key_delete(key)); 52 } 53 54 TEST(pthread, pthread_keys_max) { 55 // POSIX says PTHREAD_KEYS_MAX should be at least _POSIX_THREAD_KEYS_MAX. 56 ASSERT_GE(PTHREAD_KEYS_MAX, _POSIX_THREAD_KEYS_MAX); 57 } 58 59 TEST(pthread, sysconf_SC_THREAD_KEYS_MAX_eq_PTHREAD_KEYS_MAX) { 60 int sysconf_max = sysconf(_SC_THREAD_KEYS_MAX); 61 ASSERT_EQ(sysconf_max, PTHREAD_KEYS_MAX); 62 } 63 64 TEST(pthread, pthread_key_many_distinct) { 65 // As gtest uses pthread keys, we can't allocate exactly PTHREAD_KEYS_MAX 66 // pthread keys, but We should be able to allocate at least this many keys. 67 int nkeys = PTHREAD_KEYS_MAX / 2; 68 std::vector<pthread_key_t> keys; 69 70 auto scope_guard = android::base::make_scope_guard([&keys] { 71 for (const auto& key : keys) { 72 EXPECT_EQ(0, pthread_key_delete(key)); 73 } 74 }); 75 76 for (int i = 0; i < nkeys; ++i) { 77 pthread_key_t key; 78 // If this fails, it's likely that LIBC_PTHREAD_KEY_RESERVED_COUNT is wrong. 79 ASSERT_EQ(0, pthread_key_create(&key, NULL)) << i << " of " << nkeys; 80 keys.push_back(key); 81 ASSERT_EQ(0, pthread_setspecific(key, reinterpret_cast<void*>(i))); 82 } 83 84 for (int i = keys.size() - 1; i >= 0; --i) { 85 ASSERT_EQ(reinterpret_cast<void*>(i), pthread_getspecific(keys.back())); 86 pthread_key_t key = keys.back(); 87 keys.pop_back(); 88 ASSERT_EQ(0, pthread_key_delete(key)); 89 } 90 } 91 92 TEST(pthread, pthread_key_not_exceed_PTHREAD_KEYS_MAX) { 93 std::vector<pthread_key_t> keys; 94 int rv = 0; 95 96 // Pthread keys are used by gtest, so PTHREAD_KEYS_MAX should 97 // be more than we are allowed to allocate now. 98 for (int i = 0; i < PTHREAD_KEYS_MAX; i++) { 99 pthread_key_t key; 100 rv = pthread_key_create(&key, NULL); 101 if (rv == EAGAIN) { 102 break; 103 } 104 EXPECT_EQ(0, rv); 105 keys.push_back(key); 106 } 107 108 // Don't leak keys. 109 for (const auto& key : keys) { 110 EXPECT_EQ(0, pthread_key_delete(key)); 111 } 112 keys.clear(); 113 114 // We should have eventually reached the maximum number of keys and received 115 // EAGAIN. 116 ASSERT_EQ(EAGAIN, rv); 117 } 118 119 TEST(pthread, pthread_key_delete) { 120 void* expected = reinterpret_cast<void*>(1234); 121 pthread_key_t key; 122 ASSERT_EQ(0, pthread_key_create(&key, NULL)); 123 ASSERT_EQ(0, pthread_setspecific(key, expected)); 124 ASSERT_EQ(expected, pthread_getspecific(key)); 125 ASSERT_EQ(0, pthread_key_delete(key)); 126 // After deletion, pthread_getspecific returns NULL. 127 ASSERT_EQ(NULL, pthread_getspecific(key)); 128 // And you can't use pthread_setspecific with the deleted key. 129 ASSERT_EQ(EINVAL, pthread_setspecific(key, expected)); 130 } 131 132 TEST(pthread, pthread_key_fork) { 133 void* expected = reinterpret_cast<void*>(1234); 134 pthread_key_t key; 135 ASSERT_EQ(0, pthread_key_create(&key, NULL)); 136 ASSERT_EQ(0, pthread_setspecific(key, expected)); 137 ASSERT_EQ(expected, pthread_getspecific(key)); 138 139 pid_t pid = fork(); 140 ASSERT_NE(-1, pid) << strerror(errno); 141 142 if (pid == 0) { 143 // The surviving thread inherits all the forking thread's TLS values... 144 ASSERT_EQ(expected, pthread_getspecific(key)); 145 _exit(99); 146 } 147 148 AssertChildExited(pid, 99); 149 150 ASSERT_EQ(expected, pthread_getspecific(key)); 151 ASSERT_EQ(0, pthread_key_delete(key)); 152 } 153 154 static void* DirtyKeyFn(void* key) { 155 return pthread_getspecific(*reinterpret_cast<pthread_key_t*>(key)); 156 } 157 158 TEST(pthread, pthread_key_dirty) { 159 pthread_key_t key; 160 ASSERT_EQ(0, pthread_key_create(&key, NULL)); 161 162 size_t stack_size = 640 * 1024; 163 void* stack = mmap(NULL, stack_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); 164 ASSERT_NE(MAP_FAILED, stack); 165 memset(stack, 0xff, stack_size); 166 167 pthread_attr_t attr; 168 ASSERT_EQ(0, pthread_attr_init(&attr)); 169 ASSERT_EQ(0, pthread_attr_setstack(&attr, stack, stack_size)); 170 171 pthread_t t; 172 ASSERT_EQ(0, pthread_create(&t, &attr, DirtyKeyFn, &key)); 173 174 void* result; 175 ASSERT_EQ(0, pthread_join(t, &result)); 176 ASSERT_EQ(nullptr, result); // Not ~0! 177 178 ASSERT_EQ(0, munmap(stack, stack_size)); 179 ASSERT_EQ(0, pthread_key_delete(key)); 180 } 181 182 TEST(pthread, static_pthread_key_used_before_creation) { 183 #if defined(__BIONIC__) 184 // See http://b/19625804. The bug is about a static/global pthread key being used before creation. 185 // So here tests if the static/global default value 0 can be detected as invalid key. 186 static pthread_key_t key; 187 ASSERT_EQ(nullptr, pthread_getspecific(key)); 188 ASSERT_EQ(EINVAL, pthread_setspecific(key, nullptr)); 189 ASSERT_EQ(EINVAL, pthread_key_delete(key)); 190 #else 191 GTEST_LOG_(INFO) << "This test tests bionic pthread key implementation detail.\n"; 192 #endif 193 } 194 195 static void* IdFn(void* arg) { 196 return arg; 197 } 198 199 class SpinFunctionHelper { 200 public: 201 SpinFunctionHelper() { 202 SpinFunctionHelper::spin_flag_ = true; 203 } 204 205 ~SpinFunctionHelper() { 206 UnSpin(); 207 } 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 std::atomic<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. 228 std::atomic<bool> SpinFunctionHelper::spin_flag_; 229 230 static void* JoinFn(void* arg) { 231 return reinterpret_cast<void*>(pthread_join(reinterpret_cast<pthread_t>(arg), NULL)); 232 } 233 234 static 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 243 static 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 248 TEST(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 259 TEST(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 268 TEST(pthread, pthread_no_join_after_detach) { 269 SpinFunctionHelper spin_helper; 270 271 pthread_t t1; 272 ASSERT_EQ(0, pthread_create(&t1, NULL, spin_helper.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 282 TEST(pthread, pthread_no_op_detach_after_join) { 283 SpinFunctionHelper spin_helper; 284 285 pthread_t t1; 286 ASSERT_EQ(0, pthread_create(&t1, NULL, spin_helper.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 spin_helper.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 309 TEST(pthread, pthread_join_self) { 310 ASSERT_EQ(EDEADLK, pthread_join(pthread_self(), NULL)); 311 } 312 313 struct 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 351 class pthread_DeathTest : public BionicDeathTest {}; 352 353 TEST_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 358 static void* SignalHandlerFn(void* arg) { 359 sigset64_t wait_set; 360 sigfillset64(&wait_set); 361 return reinterpret_cast<void*>(sigwait64(&wait_set, reinterpret_cast<int*>(arg))); 362 } 363 364 TEST(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 405 TEST(pthread, pthread_sigmask64_SIGTRMIN) { 406 // Check that SIGRTMIN isn't blocked. 407 sigset64_t original_set; 408 sigemptyset64(&original_set); 409 ASSERT_EQ(0, pthread_sigmask64(SIG_BLOCK, NULL, &original_set)); 410 ASSERT_FALSE(sigismember64(&original_set, SIGRTMIN)); 411 412 // Block SIGRTMIN. 413 sigset64_t set; 414 sigemptyset64(&set); 415 sigaddset64(&set, SIGRTMIN); 416 ASSERT_EQ(0, pthread_sigmask64(SIG_BLOCK, &set, NULL)); 417 418 // Check that SIGRTMIN is blocked. 419 sigset64_t final_set; 420 sigemptyset64(&final_set); 421 ASSERT_EQ(0, pthread_sigmask64(SIG_BLOCK, NULL, &final_set)); 422 ASSERT_TRUE(sigismember64(&final_set, SIGRTMIN)); 423 // ...and that sigprocmask64 agrees with pthread_sigmask64. 424 sigemptyset64(&final_set); 425 ASSERT_EQ(0, sigprocmask64(SIG_BLOCK, NULL, &final_set)); 426 ASSERT_TRUE(sigismember64(&final_set, SIGRTMIN)); 427 428 // Spawn a thread that calls sigwait64 and tells us what it received. 429 pthread_t signal_thread; 430 int received_signal = -1; 431 ASSERT_EQ(0, pthread_create(&signal_thread, NULL, SignalHandlerFn, &received_signal)); 432 433 // Send that thread SIGRTMIN. 434 pthread_kill(signal_thread, SIGRTMIN); 435 436 // See what it got. 437 void* join_result; 438 ASSERT_EQ(0, pthread_join(signal_thread, &join_result)); 439 ASSERT_EQ(SIGRTMIN, received_signal); 440 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result)); 441 442 // Restore the original signal mask. 443 ASSERT_EQ(0, pthread_sigmask64(SIG_SETMASK, &original_set, NULL)); 444 } 445 446 static void test_pthread_setname_np__pthread_getname_np(pthread_t t) { 447 ASSERT_EQ(0, pthread_setname_np(t, "short")); 448 char name[32]; 449 ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name))); 450 ASSERT_STREQ("short", name); 451 452 // The limit is 15 characters --- the kernel's buffer is 16, but includes a NUL. 453 ASSERT_EQ(0, pthread_setname_np(t, "123456789012345")); 454 ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name))); 455 ASSERT_STREQ("123456789012345", name); 456 457 ASSERT_EQ(ERANGE, pthread_setname_np(t, "1234567890123456")); 458 459 // The passed-in buffer should be at least 16 bytes. 460 ASSERT_EQ(0, pthread_getname_np(t, name, 16)); 461 ASSERT_EQ(ERANGE, pthread_getname_np(t, name, 15)); 462 } 463 464 TEST(pthread, pthread_setname_np__pthread_getname_np__self) { 465 test_pthread_setname_np__pthread_getname_np(pthread_self()); 466 } 467 468 TEST(pthread, pthread_setname_np__pthread_getname_np__other) { 469 SpinFunctionHelper spin_helper; 470 471 pthread_t t; 472 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr)); 473 test_pthread_setname_np__pthread_getname_np(t); 474 spin_helper.UnSpin(); 475 ASSERT_EQ(0, pthread_join(t, nullptr)); 476 } 477 478 // http://b/28051133: a kernel misfeature means that you can't change the 479 // name of another thread if you've set PR_SET_DUMPABLE to 0. 480 TEST(pthread, pthread_setname_np__pthread_getname_np__other_PR_SET_DUMPABLE) { 481 ASSERT_EQ(0, prctl(PR_SET_DUMPABLE, 0)) << strerror(errno); 482 483 SpinFunctionHelper spin_helper; 484 485 pthread_t t; 486 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr)); 487 test_pthread_setname_np__pthread_getname_np(t); 488 spin_helper.UnSpin(); 489 ASSERT_EQ(0, pthread_join(t, nullptr)); 490 } 491 492 TEST_F(pthread_DeathTest, pthread_setname_np__no_such_thread) { 493 pthread_t dead_thread; 494 MakeDeadThread(dead_thread); 495 496 EXPECT_DEATH(pthread_setname_np(dead_thread, "short 3"), "invalid pthread_t"); 497 } 498 499 TEST_F(pthread_DeathTest, pthread_setname_np__null_thread) { 500 pthread_t null_thread = 0; 501 EXPECT_EQ(ENOENT, pthread_setname_np(null_thread, "short 3")); 502 } 503 504 TEST_F(pthread_DeathTest, pthread_getname_np__no_such_thread) { 505 pthread_t dead_thread; 506 MakeDeadThread(dead_thread); 507 508 char name[64]; 509 EXPECT_DEATH(pthread_getname_np(dead_thread, name, sizeof(name)), "invalid pthread_t"); 510 } 511 512 TEST_F(pthread_DeathTest, pthread_getname_np__null_thread) { 513 pthread_t null_thread = 0; 514 515 char name[64]; 516 EXPECT_EQ(ENOENT, pthread_getname_np(null_thread, name, sizeof(name))); 517 } 518 519 TEST(pthread, pthread_kill__0) { 520 // Signal 0 just tests that the thread exists, so it's safe to call on ourselves. 521 ASSERT_EQ(0, pthread_kill(pthread_self(), 0)); 522 } 523 524 TEST(pthread, pthread_kill__invalid_signal) { 525 ASSERT_EQ(EINVAL, pthread_kill(pthread_self(), -1)); 526 } 527 528 static void pthread_kill__in_signal_handler_helper(int signal_number) { 529 static int count = 0; 530 ASSERT_EQ(SIGALRM, signal_number); 531 if (++count == 1) { 532 // Can we call pthread_kill from a signal handler? 533 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM)); 534 } 535 } 536 537 TEST(pthread, pthread_kill__in_signal_handler) { 538 ScopedSignalHandler ssh(SIGALRM, pthread_kill__in_signal_handler_helper); 539 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM)); 540 } 541 542 TEST_F(pthread_DeathTest, pthread_detach__no_such_thread) { 543 pthread_t dead_thread; 544 MakeDeadThread(dead_thread); 545 546 EXPECT_DEATH(pthread_detach(dead_thread), "invalid pthread_t"); 547 } 548 549 TEST_F(pthread_DeathTest, pthread_detach__null_thread) { 550 pthread_t null_thread = 0; 551 EXPECT_EQ(ESRCH, pthread_detach(null_thread)); 552 } 553 554 TEST(pthread, pthread_getcpuclockid__clock_gettime) { 555 SpinFunctionHelper spin_helper; 556 557 pthread_t t; 558 ASSERT_EQ(0, pthread_create(&t, NULL, spin_helper.GetFunction(), NULL)); 559 560 clockid_t c; 561 ASSERT_EQ(0, pthread_getcpuclockid(t, &c)); 562 timespec ts; 563 ASSERT_EQ(0, clock_gettime(c, &ts)); 564 spin_helper.UnSpin(); 565 ASSERT_EQ(0, pthread_join(t, nullptr)); 566 } 567 568 TEST_F(pthread_DeathTest, pthread_getcpuclockid__no_such_thread) { 569 pthread_t dead_thread; 570 MakeDeadThread(dead_thread); 571 572 clockid_t c; 573 EXPECT_DEATH(pthread_getcpuclockid(dead_thread, &c), "invalid pthread_t"); 574 } 575 576 TEST_F(pthread_DeathTest, pthread_getcpuclockid__null_thread) { 577 pthread_t null_thread = 0; 578 clockid_t c; 579 EXPECT_EQ(ESRCH, pthread_getcpuclockid(null_thread, &c)); 580 } 581 582 TEST_F(pthread_DeathTest, pthread_getschedparam__no_such_thread) { 583 pthread_t dead_thread; 584 MakeDeadThread(dead_thread); 585 586 int policy; 587 sched_param param; 588 EXPECT_DEATH(pthread_getschedparam(dead_thread, &policy, ¶m), "invalid pthread_t"); 589 } 590 591 TEST_F(pthread_DeathTest, pthread_getschedparam__null_thread) { 592 pthread_t null_thread = 0; 593 int policy; 594 sched_param param; 595 EXPECT_EQ(ESRCH, pthread_getschedparam(null_thread, &policy, ¶m)); 596 } 597 598 TEST_F(pthread_DeathTest, pthread_setschedparam__no_such_thread) { 599 pthread_t dead_thread; 600 MakeDeadThread(dead_thread); 601 602 int policy = 0; 603 sched_param param; 604 EXPECT_DEATH(pthread_setschedparam(dead_thread, policy, ¶m), "invalid pthread_t"); 605 } 606 607 TEST_F(pthread_DeathTest, pthread_setschedparam__null_thread) { 608 pthread_t null_thread = 0; 609 int policy = 0; 610 sched_param param; 611 EXPECT_EQ(ESRCH, pthread_setschedparam(null_thread, policy, ¶m)); 612 } 613 614 TEST_F(pthread_DeathTest, pthread_setschedprio__no_such_thread) { 615 pthread_t dead_thread; 616 MakeDeadThread(dead_thread); 617 618 EXPECT_DEATH(pthread_setschedprio(dead_thread, 123), "invalid pthread_t"); 619 } 620 621 TEST_F(pthread_DeathTest, pthread_setschedprio__null_thread) { 622 pthread_t null_thread = 0; 623 EXPECT_EQ(ESRCH, pthread_setschedprio(null_thread, 123)); 624 } 625 626 TEST_F(pthread_DeathTest, pthread_join__no_such_thread) { 627 pthread_t dead_thread; 628 MakeDeadThread(dead_thread); 629 630 EXPECT_DEATH(pthread_join(dead_thread, NULL), "invalid pthread_t"); 631 } 632 633 TEST_F(pthread_DeathTest, pthread_join__null_thread) { 634 pthread_t null_thread = 0; 635 EXPECT_EQ(ESRCH, pthread_join(null_thread, NULL)); 636 } 637 638 TEST_F(pthread_DeathTest, pthread_kill__no_such_thread) { 639 pthread_t dead_thread; 640 MakeDeadThread(dead_thread); 641 642 EXPECT_DEATH(pthread_kill(dead_thread, 0), "invalid pthread_t"); 643 } 644 645 TEST_F(pthread_DeathTest, pthread_kill__null_thread) { 646 pthread_t null_thread = 0; 647 EXPECT_EQ(ESRCH, pthread_kill(null_thread, 0)); 648 } 649 650 TEST(pthread, pthread_join__multijoin) { 651 SpinFunctionHelper spin_helper; 652 653 pthread_t t1; 654 ASSERT_EQ(0, pthread_create(&t1, NULL, spin_helper.GetFunction(), NULL)); 655 656 pthread_t t2; 657 ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1))); 658 659 sleep(1); // (Give t2 a chance to call pthread_join.) 660 661 // Multiple joins to the same thread should fail. 662 ASSERT_EQ(EINVAL, pthread_join(t1, NULL)); 663 664 spin_helper.UnSpin(); 665 666 // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes). 667 void* join_result; 668 ASSERT_EQ(0, pthread_join(t2, &join_result)); 669 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result)); 670 } 671 672 TEST(pthread, pthread_join__race) { 673 // http://b/11693195 --- pthread_join could return before the thread had actually exited. 674 // If the joiner unmapped the thread's stack, that could lead to SIGSEGV in the thread. 675 for (size_t i = 0; i < 1024; ++i) { 676 size_t stack_size = 640*1024; 677 void* stack = mmap(NULL, stack_size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0); 678 679 pthread_attr_t a; 680 pthread_attr_init(&a); 681 pthread_attr_setstack(&a, stack, stack_size); 682 683 pthread_t t; 684 ASSERT_EQ(0, pthread_create(&t, &a, IdFn, NULL)); 685 ASSERT_EQ(0, pthread_join(t, NULL)); 686 ASSERT_EQ(0, munmap(stack, stack_size)); 687 } 688 } 689 690 static void* GetActualGuardSizeFn(void* arg) { 691 pthread_attr_t attributes; 692 pthread_getattr_np(pthread_self(), &attributes); 693 pthread_attr_getguardsize(&attributes, reinterpret_cast<size_t*>(arg)); 694 return NULL; 695 } 696 697 static size_t GetActualGuardSize(const pthread_attr_t& attributes) { 698 size_t result; 699 pthread_t t; 700 pthread_create(&t, &attributes, GetActualGuardSizeFn, &result); 701 pthread_join(t, NULL); 702 return result; 703 } 704 705 static void* GetActualStackSizeFn(void* arg) { 706 pthread_attr_t attributes; 707 pthread_getattr_np(pthread_self(), &attributes); 708 pthread_attr_getstacksize(&attributes, reinterpret_cast<size_t*>(arg)); 709 return NULL; 710 } 711 712 static size_t GetActualStackSize(const pthread_attr_t& attributes) { 713 size_t result; 714 pthread_t t; 715 pthread_create(&t, &attributes, GetActualStackSizeFn, &result); 716 pthread_join(t, NULL); 717 return result; 718 } 719 720 TEST(pthread, pthread_attr_setguardsize_tiny) { 721 pthread_attr_t attributes; 722 ASSERT_EQ(0, pthread_attr_init(&attributes)); 723 724 // No such thing as too small: will be rounded up to one page by pthread_create. 725 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 128)); 726 size_t guard_size; 727 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size)); 728 ASSERT_EQ(128U, guard_size); 729 ASSERT_EQ(4096U, GetActualGuardSize(attributes)); 730 } 731 732 TEST(pthread, pthread_attr_setguardsize_reasonable) { 733 pthread_attr_t attributes; 734 ASSERT_EQ(0, pthread_attr_init(&attributes)); 735 736 // Large enough and a multiple of the page size. 737 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024)); 738 size_t guard_size; 739 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size)); 740 ASSERT_EQ(32*1024U, guard_size); 741 ASSERT_EQ(32*1024U, GetActualGuardSize(attributes)); 742 } 743 744 TEST(pthread, pthread_attr_setguardsize_needs_rounding) { 745 pthread_attr_t attributes; 746 ASSERT_EQ(0, pthread_attr_init(&attributes)); 747 748 // Large enough but not a multiple of the page size. 749 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024 + 1)); 750 size_t guard_size; 751 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size)); 752 ASSERT_EQ(32*1024U + 1, guard_size); 753 ASSERT_EQ(36*1024U, GetActualGuardSize(attributes)); 754 } 755 756 TEST(pthread, pthread_attr_setguardsize_enormous) { 757 pthread_attr_t attributes; 758 ASSERT_EQ(0, pthread_attr_init(&attributes)); 759 760 // Larger than the stack itself. (Historically we mistakenly carved 761 // the guard out of the stack itself, rather than adding it after the 762 // end.) 763 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024*1024)); 764 size_t guard_size; 765 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size)); 766 ASSERT_EQ(32*1024*1024U, guard_size); 767 ASSERT_EQ(32*1024*1024U, GetActualGuardSize(attributes)); 768 } 769 770 TEST(pthread, pthread_attr_setstacksize) { 771 pthread_attr_t attributes; 772 ASSERT_EQ(0, pthread_attr_init(&attributes)); 773 774 // Get the default stack size. 775 size_t default_stack_size; 776 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &default_stack_size)); 777 778 // Too small. 779 ASSERT_EQ(EINVAL, pthread_attr_setstacksize(&attributes, 128)); 780 size_t stack_size; 781 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size)); 782 ASSERT_EQ(default_stack_size, stack_size); 783 ASSERT_GE(GetActualStackSize(attributes), default_stack_size); 784 785 // Large enough and a multiple of the page size; may be rounded up by pthread_create. 786 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024)); 787 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size)); 788 ASSERT_EQ(32*1024U, stack_size); 789 ASSERT_GE(GetActualStackSize(attributes), 32*1024U); 790 791 // Large enough but not aligned; will be rounded up by pthread_create. 792 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024 + 1)); 793 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size)); 794 ASSERT_EQ(32*1024U + 1, stack_size); 795 #if defined(__BIONIC__) 796 ASSERT_GT(GetActualStackSize(attributes), 32*1024U + 1); 797 #else // __BIONIC__ 798 // glibc rounds down, in violation of POSIX. They document this in their BUGS section. 799 ASSERT_EQ(GetActualStackSize(attributes), 32*1024U); 800 #endif // __BIONIC__ 801 } 802 803 TEST(pthread, pthread_rwlockattr_smoke) { 804 pthread_rwlockattr_t attr; 805 ASSERT_EQ(0, pthread_rwlockattr_init(&attr)); 806 807 int pshared_value_array[] = {PTHREAD_PROCESS_PRIVATE, PTHREAD_PROCESS_SHARED}; 808 for (size_t i = 0; i < sizeof(pshared_value_array) / sizeof(pshared_value_array[0]); ++i) { 809 ASSERT_EQ(0, pthread_rwlockattr_setpshared(&attr, pshared_value_array[i])); 810 int pshared; 811 ASSERT_EQ(0, pthread_rwlockattr_getpshared(&attr, &pshared)); 812 ASSERT_EQ(pshared_value_array[i], pshared); 813 } 814 815 int kind_array[] = {PTHREAD_RWLOCK_PREFER_READER_NP, 816 PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP}; 817 for (size_t i = 0; i < sizeof(kind_array) / sizeof(kind_array[0]); ++i) { 818 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_array[i])); 819 int kind; 820 ASSERT_EQ(0, pthread_rwlockattr_getkind_np(&attr, &kind)); 821 ASSERT_EQ(kind_array[i], kind); 822 } 823 824 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr)); 825 } 826 827 TEST(pthread, pthread_rwlock_init_same_as_PTHREAD_RWLOCK_INITIALIZER) { 828 pthread_rwlock_t lock1 = PTHREAD_RWLOCK_INITIALIZER; 829 pthread_rwlock_t lock2; 830 ASSERT_EQ(0, pthread_rwlock_init(&lock2, NULL)); 831 ASSERT_EQ(0, memcmp(&lock1, &lock2, sizeof(lock1))); 832 } 833 834 TEST(pthread, pthread_rwlock_smoke) { 835 pthread_rwlock_t l; 836 ASSERT_EQ(0, pthread_rwlock_init(&l, NULL)); 837 838 // Single read lock 839 ASSERT_EQ(0, pthread_rwlock_rdlock(&l)); 840 ASSERT_EQ(0, pthread_rwlock_unlock(&l)); 841 842 // Multiple read lock 843 ASSERT_EQ(0, pthread_rwlock_rdlock(&l)); 844 ASSERT_EQ(0, pthread_rwlock_rdlock(&l)); 845 ASSERT_EQ(0, pthread_rwlock_unlock(&l)); 846 ASSERT_EQ(0, pthread_rwlock_unlock(&l)); 847 848 // Write lock 849 ASSERT_EQ(0, pthread_rwlock_wrlock(&l)); 850 ASSERT_EQ(0, pthread_rwlock_unlock(&l)); 851 852 // Try writer lock 853 ASSERT_EQ(0, pthread_rwlock_trywrlock(&l)); 854 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l)); 855 ASSERT_EQ(EBUSY, pthread_rwlock_tryrdlock(&l)); 856 ASSERT_EQ(0, pthread_rwlock_unlock(&l)); 857 858 // Try reader lock 859 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l)); 860 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l)); 861 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l)); 862 ASSERT_EQ(0, pthread_rwlock_unlock(&l)); 863 ASSERT_EQ(0, pthread_rwlock_unlock(&l)); 864 865 // Try writer lock after unlock 866 ASSERT_EQ(0, pthread_rwlock_wrlock(&l)); 867 ASSERT_EQ(0, pthread_rwlock_unlock(&l)); 868 869 // EDEADLK in "read after write" 870 ASSERT_EQ(0, pthread_rwlock_wrlock(&l)); 871 ASSERT_EQ(EDEADLK, pthread_rwlock_rdlock(&l)); 872 ASSERT_EQ(0, pthread_rwlock_unlock(&l)); 873 874 // EDEADLK in "write after write" 875 ASSERT_EQ(0, pthread_rwlock_wrlock(&l)); 876 ASSERT_EQ(EDEADLK, pthread_rwlock_wrlock(&l)); 877 ASSERT_EQ(0, pthread_rwlock_unlock(&l)); 878 879 ASSERT_EQ(0, pthread_rwlock_destroy(&l)); 880 } 881 882 struct RwlockWakeupHelperArg { 883 pthread_rwlock_t lock; 884 enum Progress { 885 LOCK_INITIALIZED, 886 LOCK_WAITING, 887 LOCK_RELEASED, 888 LOCK_ACCESSED, 889 LOCK_TIMEDOUT, 890 }; 891 std::atomic<Progress> progress; 892 std::atomic<pid_t> tid; 893 std::function<int (pthread_rwlock_t*)> trylock_function; 894 std::function<int (pthread_rwlock_t*)> lock_function; 895 std::function<int (pthread_rwlock_t*, const timespec*)> timed_lock_function; 896 clockid_t clock; 897 }; 898 899 static void pthread_rwlock_wakeup_helper(RwlockWakeupHelperArg* arg) { 900 arg->tid = gettid(); 901 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress); 902 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING; 903 904 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock)); 905 ASSERT_EQ(0, arg->lock_function(&arg->lock)); 906 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_RELEASED, arg->progress); 907 ASSERT_EQ(0, pthread_rwlock_unlock(&arg->lock)); 908 909 arg->progress = RwlockWakeupHelperArg::LOCK_ACCESSED; 910 } 911 912 static void test_pthread_rwlock_reader_wakeup_writer(std::function<int (pthread_rwlock_t*)> lock_function) { 913 RwlockWakeupHelperArg wakeup_arg; 914 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, NULL)); 915 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock)); 916 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED; 917 wakeup_arg.tid = 0; 918 wakeup_arg.trylock_function = &pthread_rwlock_trywrlock; 919 wakeup_arg.lock_function = lock_function; 920 921 pthread_t thread; 922 ASSERT_EQ(0, pthread_create(&thread, NULL, 923 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg)); 924 WaitUntilThreadSleep(wakeup_arg.tid); 925 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress); 926 927 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED; 928 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock)); 929 930 ASSERT_EQ(0, pthread_join(thread, NULL)); 931 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress); 932 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock)); 933 } 934 935 TEST(pthread, pthread_rwlock_reader_wakeup_writer) { 936 test_pthread_rwlock_reader_wakeup_writer(pthread_rwlock_wrlock); 937 } 938 939 TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait) { 940 timespec ts; 941 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts)); 942 ts.tv_sec += 1; 943 test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) { 944 return pthread_rwlock_timedwrlock(lock, &ts); 945 }); 946 } 947 948 TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait_monotonic_np) { 949 #if defined(__BIONIC__) 950 timespec ts; 951 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts)); 952 ts.tv_sec += 1; 953 test_pthread_rwlock_reader_wakeup_writer( 954 [&](pthread_rwlock_t* lock) { return pthread_rwlock_timedwrlock_monotonic_np(lock, &ts); }); 955 #else // __BIONIC__ 956 GTEST_LOG_(INFO) << "This test does nothing since pthread_rwlock_timedwrlock_monotonic_np is " 957 "only supported on bionic"; 958 #endif // __BIONIC__ 959 } 960 961 static void test_pthread_rwlock_writer_wakeup_reader(std::function<int (pthread_rwlock_t*)> lock_function) { 962 RwlockWakeupHelperArg wakeup_arg; 963 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, NULL)); 964 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock)); 965 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED; 966 wakeup_arg.tid = 0; 967 wakeup_arg.trylock_function = &pthread_rwlock_tryrdlock; 968 wakeup_arg.lock_function = lock_function; 969 970 pthread_t thread; 971 ASSERT_EQ(0, pthread_create(&thread, NULL, 972 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg)); 973 WaitUntilThreadSleep(wakeup_arg.tid); 974 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress); 975 976 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED; 977 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock)); 978 979 ASSERT_EQ(0, pthread_join(thread, NULL)); 980 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress); 981 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock)); 982 } 983 984 TEST(pthread, pthread_rwlock_writer_wakeup_reader) { 985 test_pthread_rwlock_writer_wakeup_reader(pthread_rwlock_rdlock); 986 } 987 988 TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait) { 989 timespec ts; 990 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts)); 991 ts.tv_sec += 1; 992 test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) { 993 return pthread_rwlock_timedrdlock(lock, &ts); 994 }); 995 } 996 997 TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait_monotonic_np) { 998 #if defined(__BIONIC__) 999 timespec ts; 1000 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts)); 1001 ts.tv_sec += 1; 1002 test_pthread_rwlock_writer_wakeup_reader( 1003 [&](pthread_rwlock_t* lock) { return pthread_rwlock_timedrdlock_monotonic_np(lock, &ts); }); 1004 #else // __BIONIC__ 1005 GTEST_LOG_(INFO) << "This test does nothing since pthread_rwlock_timedrdlock_monotonic_np is " 1006 "only supported on bionic"; 1007 #endif // __BIONIC__ 1008 } 1009 1010 static void pthread_rwlock_wakeup_timeout_helper(RwlockWakeupHelperArg* arg) { 1011 arg->tid = gettid(); 1012 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress); 1013 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING; 1014 1015 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock)); 1016 1017 timespec ts; 1018 ASSERT_EQ(0, clock_gettime(arg->clock, &ts)); 1019 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts)); 1020 ts.tv_nsec = -1; 1021 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts)); 1022 ts.tv_nsec = NS_PER_S; 1023 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts)); 1024 ts.tv_nsec = NS_PER_S - 1; 1025 ts.tv_sec = -1; 1026 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts)); 1027 ASSERT_EQ(0, clock_gettime(arg->clock, &ts)); 1028 ts.tv_sec += 1; 1029 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts)); 1030 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, arg->progress); 1031 arg->progress = RwlockWakeupHelperArg::LOCK_TIMEDOUT; 1032 } 1033 1034 static void pthread_rwlock_timedrdlock_timeout_helper( 1035 clockid_t clock, int (*lock_function)(pthread_rwlock_t* __rwlock, const timespec* __timeout)) { 1036 RwlockWakeupHelperArg wakeup_arg; 1037 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr)); 1038 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock)); 1039 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED; 1040 wakeup_arg.tid = 0; 1041 wakeup_arg.trylock_function = &pthread_rwlock_tryrdlock; 1042 wakeup_arg.timed_lock_function = lock_function; 1043 wakeup_arg.clock = clock; 1044 1045 pthread_t thread; 1046 ASSERT_EQ(0, pthread_create(&thread, nullptr, 1047 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg)); 1048 WaitUntilThreadSleep(wakeup_arg.tid); 1049 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress); 1050 1051 ASSERT_EQ(0, pthread_join(thread, nullptr)); 1052 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress); 1053 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock)); 1054 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock)); 1055 } 1056 1057 TEST(pthread, pthread_rwlock_timedrdlock_timeout) { 1058 pthread_rwlock_timedrdlock_timeout_helper(CLOCK_REALTIME, pthread_rwlock_timedrdlock); 1059 } 1060 1061 TEST(pthread, pthread_rwlock_timedrdlock_monotonic_np_timeout) { 1062 #if defined(__BIONIC__) 1063 pthread_rwlock_timedrdlock_timeout_helper(CLOCK_MONOTONIC, 1064 pthread_rwlock_timedrdlock_monotonic_np); 1065 #else // __BIONIC__ 1066 GTEST_LOG_(INFO) << "This test does nothing since pthread_rwlock_timedrdlock_monotonic_np is " 1067 "only supported on bionic"; 1068 #endif // __BIONIC__ 1069 } 1070 1071 static void pthread_rwlock_timedwrlock_timeout_helper( 1072 clockid_t clock, int (*lock_function)(pthread_rwlock_t* __rwlock, const timespec* __timeout)) { 1073 RwlockWakeupHelperArg wakeup_arg; 1074 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr)); 1075 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock)); 1076 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED; 1077 wakeup_arg.tid = 0; 1078 wakeup_arg.trylock_function = &pthread_rwlock_trywrlock; 1079 wakeup_arg.timed_lock_function = lock_function; 1080 wakeup_arg.clock = clock; 1081 1082 pthread_t thread; 1083 ASSERT_EQ(0, pthread_create(&thread, nullptr, 1084 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg)); 1085 WaitUntilThreadSleep(wakeup_arg.tid); 1086 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress); 1087 1088 ASSERT_EQ(0, pthread_join(thread, nullptr)); 1089 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress); 1090 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock)); 1091 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock)); 1092 } 1093 1094 TEST(pthread, pthread_rwlock_timedwrlock_timeout) { 1095 pthread_rwlock_timedwrlock_timeout_helper(CLOCK_REALTIME, pthread_rwlock_timedwrlock); 1096 } 1097 1098 TEST(pthread, pthread_rwlock_timedwrlock_monotonic_np_timeout) { 1099 #if defined(__BIONIC__) 1100 pthread_rwlock_timedwrlock_timeout_helper(CLOCK_MONOTONIC, 1101 pthread_rwlock_timedwrlock_monotonic_np); 1102 #else // __BIONIC__ 1103 GTEST_LOG_(INFO) << "This test does nothing since pthread_rwlock_timedwrlock_monotonic_np is " 1104 "only supported on bionic"; 1105 #endif // __BIONIC__ 1106 } 1107 1108 class RwlockKindTestHelper { 1109 private: 1110 struct ThreadArg { 1111 RwlockKindTestHelper* helper; 1112 std::atomic<pid_t>& tid; 1113 1114 ThreadArg(RwlockKindTestHelper* helper, std::atomic<pid_t>& tid) 1115 : helper(helper), tid(tid) { } 1116 }; 1117 1118 public: 1119 pthread_rwlock_t lock; 1120 1121 public: 1122 explicit RwlockKindTestHelper(int kind_type) { 1123 InitRwlock(kind_type); 1124 } 1125 1126 ~RwlockKindTestHelper() { 1127 DestroyRwlock(); 1128 } 1129 1130 void CreateWriterThread(pthread_t& thread, std::atomic<pid_t>& tid) { 1131 tid = 0; 1132 ThreadArg* arg = new ThreadArg(this, tid); 1133 ASSERT_EQ(0, pthread_create(&thread, NULL, 1134 reinterpret_cast<void* (*)(void*)>(WriterThreadFn), arg)); 1135 } 1136 1137 void CreateReaderThread(pthread_t& thread, std::atomic<pid_t>& tid) { 1138 tid = 0; 1139 ThreadArg* arg = new ThreadArg(this, tid); 1140 ASSERT_EQ(0, pthread_create(&thread, NULL, 1141 reinterpret_cast<void* (*)(void*)>(ReaderThreadFn), arg)); 1142 } 1143 1144 private: 1145 void InitRwlock(int kind_type) { 1146 pthread_rwlockattr_t attr; 1147 ASSERT_EQ(0, pthread_rwlockattr_init(&attr)); 1148 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_type)); 1149 ASSERT_EQ(0, pthread_rwlock_init(&lock, &attr)); 1150 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr)); 1151 } 1152 1153 void DestroyRwlock() { 1154 ASSERT_EQ(0, pthread_rwlock_destroy(&lock)); 1155 } 1156 1157 static void WriterThreadFn(ThreadArg* arg) { 1158 arg->tid = gettid(); 1159 1160 RwlockKindTestHelper* helper = arg->helper; 1161 ASSERT_EQ(0, pthread_rwlock_wrlock(&helper->lock)); 1162 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock)); 1163 delete arg; 1164 } 1165 1166 static void ReaderThreadFn(ThreadArg* arg) { 1167 arg->tid = gettid(); 1168 1169 RwlockKindTestHelper* helper = arg->helper; 1170 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper->lock)); 1171 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock)); 1172 delete arg; 1173 } 1174 }; 1175 1176 TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_READER_NP) { 1177 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_READER_NP); 1178 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock)); 1179 1180 pthread_t writer_thread; 1181 std::atomic<pid_t> writer_tid; 1182 helper.CreateWriterThread(writer_thread, writer_tid); 1183 WaitUntilThreadSleep(writer_tid); 1184 1185 pthread_t reader_thread; 1186 std::atomic<pid_t> reader_tid; 1187 helper.CreateReaderThread(reader_thread, reader_tid); 1188 ASSERT_EQ(0, pthread_join(reader_thread, NULL)); 1189 1190 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock)); 1191 ASSERT_EQ(0, pthread_join(writer_thread, NULL)); 1192 } 1193 1194 TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP) { 1195 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP); 1196 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock)); 1197 1198 pthread_t writer_thread; 1199 std::atomic<pid_t> writer_tid; 1200 helper.CreateWriterThread(writer_thread, writer_tid); 1201 WaitUntilThreadSleep(writer_tid); 1202 1203 pthread_t reader_thread; 1204 std::atomic<pid_t> reader_tid; 1205 helper.CreateReaderThread(reader_thread, reader_tid); 1206 WaitUntilThreadSleep(reader_tid); 1207 1208 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock)); 1209 ASSERT_EQ(0, pthread_join(writer_thread, NULL)); 1210 ASSERT_EQ(0, pthread_join(reader_thread, NULL)); 1211 } 1212 1213 static int g_once_fn_call_count = 0; 1214 static void OnceFn() { 1215 ++g_once_fn_call_count; 1216 } 1217 1218 TEST(pthread, pthread_once_smoke) { 1219 pthread_once_t once_control = PTHREAD_ONCE_INIT; 1220 ASSERT_EQ(0, pthread_once(&once_control, OnceFn)); 1221 ASSERT_EQ(0, pthread_once(&once_control, OnceFn)); 1222 ASSERT_EQ(1, g_once_fn_call_count); 1223 } 1224 1225 static std::string pthread_once_1934122_result = ""; 1226 1227 static void Routine2() { 1228 pthread_once_1934122_result += "2"; 1229 } 1230 1231 static void Routine1() { 1232 pthread_once_t once_control_2 = PTHREAD_ONCE_INIT; 1233 pthread_once_1934122_result += "1"; 1234 pthread_once(&once_control_2, &Routine2); 1235 } 1236 1237 TEST(pthread, pthread_once_1934122) { 1238 // Very old versions of Android couldn't call pthread_once from a 1239 // pthread_once init routine. http://b/1934122. 1240 pthread_once_t once_control_1 = PTHREAD_ONCE_INIT; 1241 ASSERT_EQ(0, pthread_once(&once_control_1, &Routine1)); 1242 ASSERT_EQ("12", pthread_once_1934122_result); 1243 } 1244 1245 static int g_atfork_prepare_calls = 0; 1246 static void AtForkPrepare1() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 1; } 1247 static void AtForkPrepare2() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 2; } 1248 static int g_atfork_parent_calls = 0; 1249 static void AtForkParent1() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 1; } 1250 static void AtForkParent2() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 2; } 1251 static int g_atfork_child_calls = 0; 1252 static void AtForkChild1() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 1; } 1253 static void AtForkChild2() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 2; } 1254 1255 TEST(pthread, pthread_atfork_smoke) { 1256 ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1)); 1257 ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2)); 1258 1259 pid_t pid = fork(); 1260 ASSERT_NE(-1, pid) << strerror(errno); 1261 1262 // Child and parent calls are made in the order they were registered. 1263 if (pid == 0) { 1264 ASSERT_EQ(12, g_atfork_child_calls); 1265 _exit(0); 1266 } 1267 ASSERT_EQ(12, g_atfork_parent_calls); 1268 1269 // Prepare calls are made in the reverse order. 1270 ASSERT_EQ(21, g_atfork_prepare_calls); 1271 AssertChildExited(pid, 0); 1272 } 1273 1274 TEST(pthread, pthread_attr_getscope) { 1275 pthread_attr_t attr; 1276 ASSERT_EQ(0, pthread_attr_init(&attr)); 1277 1278 int scope; 1279 ASSERT_EQ(0, pthread_attr_getscope(&attr, &scope)); 1280 ASSERT_EQ(PTHREAD_SCOPE_SYSTEM, scope); 1281 } 1282 1283 TEST(pthread, pthread_condattr_init) { 1284 pthread_condattr_t attr; 1285 pthread_condattr_init(&attr); 1286 1287 clockid_t clock; 1288 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock)); 1289 ASSERT_EQ(CLOCK_REALTIME, clock); 1290 1291 int pshared; 1292 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared)); 1293 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared); 1294 } 1295 1296 TEST(pthread, pthread_condattr_setclock) { 1297 pthread_condattr_t attr; 1298 pthread_condattr_init(&attr); 1299 1300 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_REALTIME)); 1301 clockid_t clock; 1302 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock)); 1303 ASSERT_EQ(CLOCK_REALTIME, clock); 1304 1305 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC)); 1306 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock)); 1307 ASSERT_EQ(CLOCK_MONOTONIC, clock); 1308 1309 ASSERT_EQ(EINVAL, pthread_condattr_setclock(&attr, CLOCK_PROCESS_CPUTIME_ID)); 1310 } 1311 1312 TEST(pthread, pthread_cond_broadcast__preserves_condattr_flags) { 1313 #if defined(__BIONIC__) 1314 pthread_condattr_t attr; 1315 pthread_condattr_init(&attr); 1316 1317 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC)); 1318 ASSERT_EQ(0, pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED)); 1319 1320 pthread_cond_t cond_var; 1321 ASSERT_EQ(0, pthread_cond_init(&cond_var, &attr)); 1322 1323 ASSERT_EQ(0, pthread_cond_signal(&cond_var)); 1324 ASSERT_EQ(0, pthread_cond_broadcast(&cond_var)); 1325 1326 attr = static_cast<pthread_condattr_t>(*reinterpret_cast<uint32_t*>(cond_var.__private)); 1327 clockid_t clock; 1328 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock)); 1329 ASSERT_EQ(CLOCK_MONOTONIC, clock); 1330 int pshared; 1331 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared)); 1332 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared); 1333 #else // !defined(__BIONIC__) 1334 GTEST_LOG_(INFO) << "This tests a bionic implementation detail.\n"; 1335 #endif // !defined(__BIONIC__) 1336 } 1337 1338 class pthread_CondWakeupTest : public ::testing::Test { 1339 protected: 1340 pthread_mutex_t mutex; 1341 pthread_cond_t cond; 1342 1343 enum Progress { 1344 INITIALIZED, 1345 WAITING, 1346 SIGNALED, 1347 FINISHED, 1348 }; 1349 std::atomic<Progress> progress; 1350 pthread_t thread; 1351 std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function; 1352 1353 protected: 1354 void SetUp() override { 1355 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr)); 1356 } 1357 1358 void InitCond(clockid_t clock=CLOCK_REALTIME) { 1359 pthread_condattr_t attr; 1360 ASSERT_EQ(0, pthread_condattr_init(&attr)); 1361 ASSERT_EQ(0, pthread_condattr_setclock(&attr, clock)); 1362 ASSERT_EQ(0, pthread_cond_init(&cond, &attr)); 1363 ASSERT_EQ(0, pthread_condattr_destroy(&attr)); 1364 } 1365 1366 void StartWaitingThread(std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function) { 1367 progress = INITIALIZED; 1368 this->wait_function = wait_function; 1369 ASSERT_EQ(0, pthread_create(&thread, NULL, reinterpret_cast<void* (*)(void*)>(WaitThreadFn), this)); 1370 while (progress != WAITING) { 1371 usleep(5000); 1372 } 1373 usleep(5000); 1374 } 1375 1376 void TearDown() override { 1377 ASSERT_EQ(0, pthread_join(thread, nullptr)); 1378 ASSERT_EQ(FINISHED, progress); 1379 ASSERT_EQ(0, pthread_cond_destroy(&cond)); 1380 ASSERT_EQ(0, pthread_mutex_destroy(&mutex)); 1381 } 1382 1383 private: 1384 static void WaitThreadFn(pthread_CondWakeupTest* test) { 1385 ASSERT_EQ(0, pthread_mutex_lock(&test->mutex)); 1386 test->progress = WAITING; 1387 while (test->progress == WAITING) { 1388 ASSERT_EQ(0, test->wait_function(&test->cond, &test->mutex)); 1389 } 1390 ASSERT_EQ(SIGNALED, test->progress); 1391 test->progress = FINISHED; 1392 ASSERT_EQ(0, pthread_mutex_unlock(&test->mutex)); 1393 } 1394 }; 1395 1396 TEST_F(pthread_CondWakeupTest, signal_wait) { 1397 InitCond(); 1398 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) { 1399 return pthread_cond_wait(cond, mutex); 1400 }); 1401 progress = SIGNALED; 1402 ASSERT_EQ(0, pthread_cond_signal(&cond)); 1403 } 1404 1405 TEST_F(pthread_CondWakeupTest, broadcast_wait) { 1406 InitCond(); 1407 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) { 1408 return pthread_cond_wait(cond, mutex); 1409 }); 1410 progress = SIGNALED; 1411 ASSERT_EQ(0, pthread_cond_broadcast(&cond)); 1412 } 1413 1414 TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_REALTIME) { 1415 InitCond(CLOCK_REALTIME); 1416 timespec ts; 1417 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts)); 1418 ts.tv_sec += 1; 1419 StartWaitingThread([&](pthread_cond_t* cond, pthread_mutex_t* mutex) { 1420 return pthread_cond_timedwait(cond, mutex, &ts); 1421 }); 1422 progress = SIGNALED; 1423 ASSERT_EQ(0, pthread_cond_signal(&cond)); 1424 } 1425 1426 TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC) { 1427 InitCond(CLOCK_MONOTONIC); 1428 timespec ts; 1429 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts)); 1430 ts.tv_sec += 1; 1431 StartWaitingThread([&](pthread_cond_t* cond, pthread_mutex_t* mutex) { 1432 return pthread_cond_timedwait(cond, mutex, &ts); 1433 }); 1434 progress = SIGNALED; 1435 ASSERT_EQ(0, pthread_cond_signal(&cond)); 1436 } 1437 1438 TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC_np) { 1439 #if defined(__BIONIC__) 1440 InitCond(CLOCK_REALTIME); 1441 timespec ts; 1442 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts)); 1443 ts.tv_sec += 1; 1444 StartWaitingThread([&](pthread_cond_t* cond, pthread_mutex_t* mutex) { 1445 return pthread_cond_timedwait_monotonic_np(cond, mutex, &ts); 1446 }); 1447 progress = SIGNALED; 1448 ASSERT_EQ(0, pthread_cond_signal(&cond)); 1449 #else // __BIONIC__ 1450 GTEST_LOG_(INFO) << "This test does nothing since pthread_cond_timedwait_monotonic_np is only " 1451 "supported on bionic"; 1452 #endif // __BIONIC__ 1453 } 1454 1455 static void pthread_cond_timedwait_timeout_helper(clockid_t clock, 1456 int (*wait_function)(pthread_cond_t* __cond, 1457 pthread_mutex_t* __mutex, 1458 const timespec* __timeout)) { 1459 pthread_mutex_t mutex; 1460 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr)); 1461 pthread_cond_t cond; 1462 ASSERT_EQ(0, pthread_cond_init(&cond, nullptr)); 1463 ASSERT_EQ(0, pthread_mutex_lock(&mutex)); 1464 1465 timespec ts; 1466 ASSERT_EQ(0, clock_gettime(clock, &ts)); 1467 ASSERT_EQ(ETIMEDOUT, wait_function(&cond, &mutex, &ts)); 1468 ts.tv_nsec = -1; 1469 ASSERT_EQ(EINVAL, wait_function(&cond, &mutex, &ts)); 1470 ts.tv_nsec = NS_PER_S; 1471 ASSERT_EQ(EINVAL, wait_function(&cond, &mutex, &ts)); 1472 ts.tv_nsec = NS_PER_S - 1; 1473 ts.tv_sec = -1; 1474 ASSERT_EQ(ETIMEDOUT, wait_function(&cond, &mutex, &ts)); 1475 ASSERT_EQ(0, pthread_mutex_unlock(&mutex)); 1476 } 1477 1478 TEST(pthread, pthread_cond_timedwait_timeout) { 1479 pthread_cond_timedwait_timeout_helper(CLOCK_REALTIME, pthread_cond_timedwait); 1480 } 1481 1482 TEST(pthread, pthread_cond_timedwait_monotonic_np_timeout) { 1483 #if defined(__BIONIC__) 1484 pthread_cond_timedwait_timeout_helper(CLOCK_MONOTONIC, pthread_cond_timedwait_monotonic_np); 1485 #else // __BIONIC__ 1486 GTEST_LOG_(INFO) << "This test does nothing since pthread_cond_timedwait_monotonic_np is only " 1487 "supported on bionic"; 1488 #endif // __BIONIC__ 1489 } 1490 1491 TEST(pthread, pthread_attr_getstack__main_thread) { 1492 // This test is only meaningful for the main thread, so make sure we're running on it! 1493 ASSERT_EQ(getpid(), syscall(__NR_gettid)); 1494 1495 // Get the main thread's attributes. 1496 pthread_attr_t attributes; 1497 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes)); 1498 1499 // Check that we correctly report that the main thread has no guard page. 1500 size_t guard_size; 1501 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size)); 1502 ASSERT_EQ(0U, guard_size); // The main thread has no guard page. 1503 1504 // Get the stack base and the stack size (both ways). 1505 void* stack_base; 1506 size_t stack_size; 1507 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size)); 1508 size_t stack_size2; 1509 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2)); 1510 1511 // The two methods of asking for the stack size should agree. 1512 EXPECT_EQ(stack_size, stack_size2); 1513 1514 #if defined(__BIONIC__) 1515 // Find stack in /proc/self/maps using a pointer to the stack. 1516 // 1517 // We do not use "[stack]" label because in native-bridge environment it is not 1518 // guaranteed to point to the right stack. A native bridge implementation may 1519 // keep separate stack for the guest code. 1520 void* maps_stack_hi = NULL; 1521 std::vector<map_record> maps; 1522 ASSERT_TRUE(Maps::parse_maps(&maps)); 1523 uintptr_t stack_address = reinterpret_cast<uintptr_t>(&maps_stack_hi); 1524 for (const auto& map : maps) { 1525 if (map.addr_start <= stack_address && map.addr_end > stack_address){ 1526 maps_stack_hi = reinterpret_cast<void*>(map.addr_end); 1527 break; 1528 } 1529 } 1530 1531 // The high address of the /proc/self/maps stack region should equal stack_base + stack_size. 1532 // Remember that the stack grows down (and is mapped in on demand), so the low address of the 1533 // region isn't very interesting. 1534 EXPECT_EQ(maps_stack_hi, reinterpret_cast<uint8_t*>(stack_base) + stack_size); 1535 1536 // The stack size should correspond to RLIMIT_STACK. 1537 rlimit rl; 1538 ASSERT_EQ(0, getrlimit(RLIMIT_STACK, &rl)); 1539 uint64_t original_rlim_cur = rl.rlim_cur; 1540 if (rl.rlim_cur == RLIM_INFINITY) { 1541 rl.rlim_cur = 8 * 1024 * 1024; // Bionic reports unlimited stacks as 8MiB. 1542 } 1543 EXPECT_EQ(rl.rlim_cur, stack_size); 1544 1545 auto guard = android::base::make_scope_guard([&rl, original_rlim_cur]() { 1546 rl.rlim_cur = original_rlim_cur; 1547 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl)); 1548 }); 1549 1550 // 1551 // What if RLIMIT_STACK is smaller than the stack's current extent? 1552 // 1553 rl.rlim_cur = rl.rlim_max = 1024; // 1KiB. We know the stack must be at least a page already. 1554 rl.rlim_max = RLIM_INFINITY; 1555 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl)); 1556 1557 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes)); 1558 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size)); 1559 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2)); 1560 1561 EXPECT_EQ(stack_size, stack_size2); 1562 ASSERT_EQ(1024U, stack_size); 1563 1564 // 1565 // What if RLIMIT_STACK isn't a whole number of pages? 1566 // 1567 rl.rlim_cur = rl.rlim_max = 6666; // Not a whole number of pages. 1568 rl.rlim_max = RLIM_INFINITY; 1569 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl)); 1570 1571 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes)); 1572 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size)); 1573 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2)); 1574 1575 EXPECT_EQ(stack_size, stack_size2); 1576 ASSERT_EQ(6666U, stack_size); 1577 #endif 1578 } 1579 1580 struct GetStackSignalHandlerArg { 1581 volatile bool done; 1582 void* signal_stack_base; 1583 size_t signal_stack_size; 1584 void* main_stack_base; 1585 size_t main_stack_size; 1586 }; 1587 1588 static GetStackSignalHandlerArg getstack_signal_handler_arg; 1589 1590 static void getstack_signal_handler(int sig) { 1591 ASSERT_EQ(SIGUSR1, sig); 1592 // Use sleep() to make current thread be switched out by the kernel to provoke the error. 1593 sleep(1); 1594 pthread_attr_t attr; 1595 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr)); 1596 void* stack_base; 1597 size_t stack_size; 1598 ASSERT_EQ(0, pthread_attr_getstack(&attr, &stack_base, &stack_size)); 1599 1600 // Verify if the stack used by the signal handler is the alternate stack just registered. 1601 ASSERT_LE(getstack_signal_handler_arg.signal_stack_base, &attr); 1602 ASSERT_LT(static_cast<void*>(&attr), 1603 static_cast<char*>(getstack_signal_handler_arg.signal_stack_base) + 1604 getstack_signal_handler_arg.signal_stack_size); 1605 1606 // Verify if the main thread's stack got in the signal handler is correct. 1607 ASSERT_EQ(getstack_signal_handler_arg.main_stack_base, stack_base); 1608 ASSERT_LE(getstack_signal_handler_arg.main_stack_size, stack_size); 1609 1610 getstack_signal_handler_arg.done = true; 1611 } 1612 1613 // The previous code obtained the main thread's stack by reading the entry in 1614 // /proc/self/task/<pid>/maps that was labeled [stack]. Unfortunately, on x86/x86_64, the kernel 1615 // relies on sp0 in task state segment(tss) to label the stack map with [stack]. If the kernel 1616 // switches a process while the main thread is in an alternate stack, then the kernel will label 1617 // the wrong map with [stack]. This test verifies that when the above situation happens, the main 1618 // thread's stack is found correctly. 1619 TEST(pthread, pthread_attr_getstack_in_signal_handler) { 1620 // This test is only meaningful for the main thread, so make sure we're running on it! 1621 ASSERT_EQ(getpid(), syscall(__NR_gettid)); 1622 1623 const size_t sig_stack_size = 16 * 1024; 1624 void* sig_stack = mmap(NULL, sig_stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 1625 -1, 0); 1626 ASSERT_NE(MAP_FAILED, sig_stack); 1627 stack_t ss; 1628 ss.ss_sp = sig_stack; 1629 ss.ss_size = sig_stack_size; 1630 ss.ss_flags = 0; 1631 stack_t oss; 1632 ASSERT_EQ(0, sigaltstack(&ss, &oss)); 1633 1634 pthread_attr_t attr; 1635 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr)); 1636 void* main_stack_base; 1637 size_t main_stack_size; 1638 ASSERT_EQ(0, pthread_attr_getstack(&attr, &main_stack_base, &main_stack_size)); 1639 1640 ScopedSignalHandler handler(SIGUSR1, getstack_signal_handler, SA_ONSTACK); 1641 getstack_signal_handler_arg.done = false; 1642 getstack_signal_handler_arg.signal_stack_base = sig_stack; 1643 getstack_signal_handler_arg.signal_stack_size = sig_stack_size; 1644 getstack_signal_handler_arg.main_stack_base = main_stack_base; 1645 getstack_signal_handler_arg.main_stack_size = main_stack_size; 1646 kill(getpid(), SIGUSR1); 1647 ASSERT_EQ(true, getstack_signal_handler_arg.done); 1648 1649 ASSERT_EQ(0, sigaltstack(&oss, nullptr)); 1650 ASSERT_EQ(0, munmap(sig_stack, sig_stack_size)); 1651 } 1652 1653 static void pthread_attr_getstack_18908062_helper(void*) { 1654 char local_variable; 1655 pthread_attr_t attributes; 1656 pthread_getattr_np(pthread_self(), &attributes); 1657 void* stack_base; 1658 size_t stack_size; 1659 pthread_attr_getstack(&attributes, &stack_base, &stack_size); 1660 1661 // Test whether &local_variable is in [stack_base, stack_base + stack_size). 1662 ASSERT_LE(reinterpret_cast<char*>(stack_base), &local_variable); 1663 ASSERT_LT(&local_variable, reinterpret_cast<char*>(stack_base) + stack_size); 1664 } 1665 1666 // Check whether something on stack is in the range of 1667 // [stack_base, stack_base + stack_size). see b/18908062. 1668 TEST(pthread, pthread_attr_getstack_18908062) { 1669 pthread_t t; 1670 ASSERT_EQ(0, pthread_create(&t, NULL, 1671 reinterpret_cast<void* (*)(void*)>(pthread_attr_getstack_18908062_helper), 1672 NULL)); 1673 ASSERT_EQ(0, pthread_join(t, NULL)); 1674 } 1675 1676 #if defined(__BIONIC__) 1677 static pthread_mutex_t pthread_gettid_np_mutex = PTHREAD_MUTEX_INITIALIZER; 1678 1679 static void* pthread_gettid_np_helper(void* arg) { 1680 *reinterpret_cast<pid_t*>(arg) = gettid(); 1681 1682 // Wait for our parent to call pthread_gettid_np on us before exiting. 1683 pthread_mutex_lock(&pthread_gettid_np_mutex); 1684 pthread_mutex_unlock(&pthread_gettid_np_mutex); 1685 return NULL; 1686 } 1687 #endif 1688 1689 TEST(pthread, pthread_gettid_np) { 1690 #if defined(__BIONIC__) 1691 ASSERT_EQ(gettid(), pthread_gettid_np(pthread_self())); 1692 1693 // Ensure the other thread doesn't exit until after we've called 1694 // pthread_gettid_np on it. 1695 pthread_mutex_lock(&pthread_gettid_np_mutex); 1696 1697 pid_t t_gettid_result; 1698 pthread_t t; 1699 pthread_create(&t, NULL, pthread_gettid_np_helper, &t_gettid_result); 1700 1701 pid_t t_pthread_gettid_np_result = pthread_gettid_np(t); 1702 1703 // Release the other thread and wait for it to exit. 1704 pthread_mutex_unlock(&pthread_gettid_np_mutex); 1705 ASSERT_EQ(0, pthread_join(t, NULL)); 1706 1707 ASSERT_EQ(t_gettid_result, t_pthread_gettid_np_result); 1708 #else 1709 GTEST_LOG_(INFO) << "This test does nothing.\n"; 1710 #endif 1711 } 1712 1713 static size_t cleanup_counter = 0; 1714 1715 static void AbortCleanupRoutine(void*) { 1716 abort(); 1717 } 1718 1719 static void CountCleanupRoutine(void*) { 1720 ++cleanup_counter; 1721 } 1722 1723 static void PthreadCleanupTester() { 1724 pthread_cleanup_push(CountCleanupRoutine, NULL); 1725 pthread_cleanup_push(CountCleanupRoutine, NULL); 1726 pthread_cleanup_push(AbortCleanupRoutine, NULL); 1727 1728 pthread_cleanup_pop(0); // Pop the abort without executing it. 1729 pthread_cleanup_pop(1); // Pop one count while executing it. 1730 ASSERT_EQ(1U, cleanup_counter); 1731 // Exit while the other count is still on the cleanup stack. 1732 pthread_exit(NULL); 1733 1734 // Calls to pthread_cleanup_pop/pthread_cleanup_push must always be balanced. 1735 pthread_cleanup_pop(0); 1736 } 1737 1738 static void* PthreadCleanupStartRoutine(void*) { 1739 PthreadCleanupTester(); 1740 return NULL; 1741 } 1742 1743 TEST(pthread, pthread_cleanup_push__pthread_cleanup_pop) { 1744 pthread_t t; 1745 ASSERT_EQ(0, pthread_create(&t, NULL, PthreadCleanupStartRoutine, NULL)); 1746 ASSERT_EQ(0, pthread_join(t, NULL)); 1747 ASSERT_EQ(2U, cleanup_counter); 1748 } 1749 1750 TEST(pthread, PTHREAD_MUTEX_DEFAULT_is_PTHREAD_MUTEX_NORMAL) { 1751 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_DEFAULT); 1752 } 1753 1754 TEST(pthread, pthread_mutexattr_gettype) { 1755 pthread_mutexattr_t attr; 1756 ASSERT_EQ(0, pthread_mutexattr_init(&attr)); 1757 1758 int attr_type; 1759 1760 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL)); 1761 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type)); 1762 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, attr_type); 1763 1764 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK)); 1765 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type)); 1766 ASSERT_EQ(PTHREAD_MUTEX_ERRORCHECK, attr_type); 1767 1768 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)); 1769 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type)); 1770 ASSERT_EQ(PTHREAD_MUTEX_RECURSIVE, attr_type); 1771 1772 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr)); 1773 } 1774 1775 TEST(pthread, pthread_mutexattr_protocol) { 1776 pthread_mutexattr_t attr; 1777 ASSERT_EQ(0, pthread_mutexattr_init(&attr)); 1778 1779 int protocol; 1780 ASSERT_EQ(0, pthread_mutexattr_getprotocol(&attr, &protocol)); 1781 ASSERT_EQ(PTHREAD_PRIO_NONE, protocol); 1782 for (size_t repeat = 0; repeat < 2; ++repeat) { 1783 for (int set_protocol : {PTHREAD_PRIO_NONE, PTHREAD_PRIO_INHERIT}) { 1784 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, set_protocol)); 1785 ASSERT_EQ(0, pthread_mutexattr_getprotocol(&attr, &protocol)); 1786 ASSERT_EQ(protocol, set_protocol); 1787 } 1788 } 1789 } 1790 1791 struct PthreadMutex { 1792 pthread_mutex_t lock; 1793 1794 explicit PthreadMutex(int mutex_type, int protocol = PTHREAD_PRIO_NONE) { 1795 init(mutex_type, protocol); 1796 } 1797 1798 ~PthreadMutex() { 1799 destroy(); 1800 } 1801 1802 private: 1803 void init(int mutex_type, int protocol) { 1804 pthread_mutexattr_t attr; 1805 ASSERT_EQ(0, pthread_mutexattr_init(&attr)); 1806 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, mutex_type)); 1807 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, protocol)); 1808 ASSERT_EQ(0, pthread_mutex_init(&lock, &attr)); 1809 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr)); 1810 } 1811 1812 void destroy() { 1813 ASSERT_EQ(0, pthread_mutex_destroy(&lock)); 1814 } 1815 1816 DISALLOW_COPY_AND_ASSIGN(PthreadMutex); 1817 }; 1818 1819 static void TestPthreadMutexLockNormal(int protocol) { 1820 PthreadMutex m(PTHREAD_MUTEX_NORMAL, protocol); 1821 1822 ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); 1823 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); 1824 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock)); 1825 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock)); 1826 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); 1827 } 1828 1829 static void TestPthreadMutexLockErrorCheck(int protocol) { 1830 PthreadMutex m(PTHREAD_MUTEX_ERRORCHECK, protocol); 1831 1832 ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); 1833 ASSERT_EQ(EDEADLK, pthread_mutex_lock(&m.lock)); 1834 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); 1835 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock)); 1836 if (protocol == PTHREAD_PRIO_NONE) { 1837 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock)); 1838 } else { 1839 ASSERT_EQ(EDEADLK, pthread_mutex_trylock(&m.lock)); 1840 } 1841 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); 1842 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock)); 1843 } 1844 1845 static void TestPthreadMutexLockRecursive(int protocol) { 1846 PthreadMutex m(PTHREAD_MUTEX_RECURSIVE, protocol); 1847 1848 ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); 1849 ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); 1850 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); 1851 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); 1852 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock)); 1853 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock)); 1854 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); 1855 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); 1856 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock)); 1857 } 1858 1859 TEST(pthread, pthread_mutex_lock_NORMAL) { 1860 TestPthreadMutexLockNormal(PTHREAD_PRIO_NONE); 1861 } 1862 1863 TEST(pthread, pthread_mutex_lock_ERRORCHECK) { 1864 TestPthreadMutexLockErrorCheck(PTHREAD_PRIO_NONE); 1865 } 1866 1867 TEST(pthread, pthread_mutex_lock_RECURSIVE) { 1868 TestPthreadMutexLockRecursive(PTHREAD_PRIO_NONE); 1869 } 1870 1871 TEST(pthread, pthread_mutex_lock_pi) { 1872 TestPthreadMutexLockNormal(PTHREAD_PRIO_INHERIT); 1873 TestPthreadMutexLockErrorCheck(PTHREAD_PRIO_INHERIT); 1874 TestPthreadMutexLockRecursive(PTHREAD_PRIO_INHERIT); 1875 } 1876 1877 TEST(pthread, pthread_mutex_pi_count_limit) { 1878 #if defined(__BIONIC__) && !defined(__LP64__) 1879 // Bionic only supports 65536 pi mutexes in 32-bit programs. 1880 pthread_mutexattr_t attr; 1881 ASSERT_EQ(0, pthread_mutexattr_init(&attr)); 1882 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT)); 1883 std::vector<pthread_mutex_t> mutexes(65536); 1884 // Test if we can use 65536 pi mutexes at the same time. 1885 // Run 2 times to check if freed pi mutexes can be recycled. 1886 for (int repeat = 0; repeat < 2; ++repeat) { 1887 for (auto& m : mutexes) { 1888 ASSERT_EQ(0, pthread_mutex_init(&m, &attr)); 1889 } 1890 pthread_mutex_t m; 1891 ASSERT_EQ(ENOMEM, pthread_mutex_init(&m, &attr)); 1892 for (auto& m : mutexes) { 1893 ASSERT_EQ(0, pthread_mutex_lock(&m)); 1894 } 1895 for (auto& m : mutexes) { 1896 ASSERT_EQ(0, pthread_mutex_unlock(&m)); 1897 } 1898 for (auto& m : mutexes) { 1899 ASSERT_EQ(0, pthread_mutex_destroy(&m)); 1900 } 1901 } 1902 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr)); 1903 #else 1904 GTEST_LOG_(INFO) << "This test does nothing as pi mutex count isn't limited.\n"; 1905 #endif 1906 } 1907 1908 TEST(pthread, pthread_mutex_init_same_as_static_initializers) { 1909 pthread_mutex_t lock_normal = PTHREAD_MUTEX_INITIALIZER; 1910 PthreadMutex m1(PTHREAD_MUTEX_NORMAL); 1911 ASSERT_EQ(0, memcmp(&lock_normal, &m1.lock, sizeof(pthread_mutex_t))); 1912 pthread_mutex_destroy(&lock_normal); 1913 1914 pthread_mutex_t lock_errorcheck = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP; 1915 PthreadMutex m2(PTHREAD_MUTEX_ERRORCHECK); 1916 ASSERT_EQ(0, memcmp(&lock_errorcheck, &m2.lock, sizeof(pthread_mutex_t))); 1917 pthread_mutex_destroy(&lock_errorcheck); 1918 1919 pthread_mutex_t lock_recursive = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; 1920 PthreadMutex m3(PTHREAD_MUTEX_RECURSIVE); 1921 ASSERT_EQ(0, memcmp(&lock_recursive, &m3.lock, sizeof(pthread_mutex_t))); 1922 ASSERT_EQ(0, pthread_mutex_destroy(&lock_recursive)); 1923 } 1924 1925 class MutexWakeupHelper { 1926 private: 1927 PthreadMutex m; 1928 enum Progress { 1929 LOCK_INITIALIZED, 1930 LOCK_WAITING, 1931 LOCK_RELEASED, 1932 LOCK_ACCESSED 1933 }; 1934 std::atomic<Progress> progress; 1935 std::atomic<pid_t> tid; 1936 1937 static void thread_fn(MutexWakeupHelper* helper) { 1938 helper->tid = gettid(); 1939 ASSERT_EQ(LOCK_INITIALIZED, helper->progress); 1940 helper->progress = LOCK_WAITING; 1941 1942 ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock)); 1943 ASSERT_EQ(LOCK_RELEASED, helper->progress); 1944 ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock)); 1945 1946 helper->progress = LOCK_ACCESSED; 1947 } 1948 1949 public: 1950 explicit MutexWakeupHelper(int mutex_type) : m(mutex_type) { 1951 } 1952 1953 void test() { 1954 ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); 1955 progress = LOCK_INITIALIZED; 1956 tid = 0; 1957 1958 pthread_t thread; 1959 ASSERT_EQ(0, pthread_create(&thread, NULL, 1960 reinterpret_cast<void* (*)(void*)>(MutexWakeupHelper::thread_fn), this)); 1961 1962 WaitUntilThreadSleep(tid); 1963 ASSERT_EQ(LOCK_WAITING, progress); 1964 1965 progress = LOCK_RELEASED; 1966 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); 1967 1968 ASSERT_EQ(0, pthread_join(thread, NULL)); 1969 ASSERT_EQ(LOCK_ACCESSED, progress); 1970 } 1971 }; 1972 1973 TEST(pthread, pthread_mutex_NORMAL_wakeup) { 1974 MutexWakeupHelper helper(PTHREAD_MUTEX_NORMAL); 1975 helper.test(); 1976 } 1977 1978 TEST(pthread, pthread_mutex_ERRORCHECK_wakeup) { 1979 MutexWakeupHelper helper(PTHREAD_MUTEX_ERRORCHECK); 1980 helper.test(); 1981 } 1982 1983 TEST(pthread, pthread_mutex_RECURSIVE_wakeup) { 1984 MutexWakeupHelper helper(PTHREAD_MUTEX_RECURSIVE); 1985 helper.test(); 1986 } 1987 1988 static int GetThreadPriority(pid_t tid) { 1989 // sched_getparam() returns the static priority of a thread, which can't reflect a thread's 1990 // priority after priority inheritance. So read /proc/<pid>/stat to get the dynamic priority. 1991 std::string filename = android::base::StringPrintf("/proc/%d/stat", tid); 1992 std::string content; 1993 int result = INT_MAX; 1994 if (!android::base::ReadFileToString(filename, &content)) { 1995 return result; 1996 } 1997 std::vector<std::string> strs = android::base::Split(content, " "); 1998 if (strs.size() < 18) { 1999 return result; 2000 } 2001 if (!android::base::ParseInt(strs[17], &result)) { 2002 return INT_MAX; 2003 } 2004 return result; 2005 } 2006 2007 class PIMutexWakeupHelper { 2008 private: 2009 PthreadMutex m; 2010 int protocol; 2011 enum Progress { 2012 LOCK_INITIALIZED, 2013 LOCK_CHILD_READY, 2014 LOCK_WAITING, 2015 LOCK_RELEASED, 2016 }; 2017 std::atomic<Progress> progress; 2018 std::atomic<pid_t> main_tid; 2019 std::atomic<pid_t> child_tid; 2020 PthreadMutex start_thread_m; 2021 2022 static void thread_fn(PIMutexWakeupHelper* helper) { 2023 helper->child_tid = gettid(); 2024 ASSERT_EQ(LOCK_INITIALIZED, helper->progress); 2025 ASSERT_EQ(0, setpriority(PRIO_PROCESS, gettid(), 1)); 2026 ASSERT_EQ(21, GetThreadPriority(gettid())); 2027 ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock)); 2028 helper->progress = LOCK_CHILD_READY; 2029 ASSERT_EQ(0, pthread_mutex_lock(&helper->start_thread_m.lock)); 2030 2031 ASSERT_EQ(0, pthread_mutex_unlock(&helper->start_thread_m.lock)); 2032 WaitUntilThreadSleep(helper->main_tid); 2033 ASSERT_EQ(LOCK_WAITING, helper->progress); 2034 2035 if (helper->protocol == PTHREAD_PRIO_INHERIT) { 2036 ASSERT_EQ(20, GetThreadPriority(gettid())); 2037 } else { 2038 ASSERT_EQ(21, GetThreadPriority(gettid())); 2039 } 2040 helper->progress = LOCK_RELEASED; 2041 ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock)); 2042 } 2043 2044 public: 2045 explicit PIMutexWakeupHelper(int mutex_type, int protocol) 2046 : m(mutex_type, protocol), protocol(protocol), start_thread_m(PTHREAD_MUTEX_NORMAL) { 2047 } 2048 2049 void test() { 2050 ASSERT_EQ(0, pthread_mutex_lock(&start_thread_m.lock)); 2051 main_tid = gettid(); 2052 ASSERT_EQ(20, GetThreadPriority(main_tid)); 2053 progress = LOCK_INITIALIZED; 2054 child_tid = 0; 2055 2056 pthread_t thread; 2057 ASSERT_EQ(0, pthread_create(&thread, NULL, 2058 reinterpret_cast<void* (*)(void*)>(PIMutexWakeupHelper::thread_fn), this)); 2059 2060 WaitUntilThreadSleep(child_tid); 2061 ASSERT_EQ(LOCK_CHILD_READY, progress); 2062 ASSERT_EQ(0, pthread_mutex_unlock(&start_thread_m.lock)); 2063 progress = LOCK_WAITING; 2064 ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); 2065 2066 ASSERT_EQ(LOCK_RELEASED, progress); 2067 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); 2068 ASSERT_EQ(0, pthread_join(thread, nullptr)); 2069 } 2070 }; 2071 2072 TEST(pthread, pthread_mutex_pi_wakeup) { 2073 for (int type : {PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_RECURSIVE, PTHREAD_MUTEX_ERRORCHECK}) { 2074 for (int protocol : {PTHREAD_PRIO_INHERIT}) { 2075 PIMutexWakeupHelper helper(type, protocol); 2076 helper.test(); 2077 } 2078 } 2079 } 2080 2081 TEST(pthread, pthread_mutex_owner_tid_limit) { 2082 #if defined(__BIONIC__) && !defined(__LP64__) 2083 FILE* fp = fopen("/proc/sys/kernel/pid_max", "r"); 2084 ASSERT_TRUE(fp != NULL); 2085 long pid_max; 2086 ASSERT_EQ(1, fscanf(fp, "%ld", &pid_max)); 2087 fclose(fp); 2088 // Bionic's pthread_mutex implementation on 32-bit devices uses 16 bits to represent owner tid. 2089 ASSERT_LE(pid_max, 65536); 2090 #else 2091 GTEST_LOG_(INFO) << "This test does nothing as 32-bit tid is supported by pthread_mutex.\n"; 2092 #endif 2093 } 2094 2095 static void pthread_mutex_timedlock_helper(clockid_t clock, 2096 int (*lock_function)(pthread_mutex_t* __mutex, 2097 const timespec* __timeout)) { 2098 pthread_mutex_t m; 2099 ASSERT_EQ(0, pthread_mutex_init(&m, nullptr)); 2100 2101 // If the mutex is already locked, pthread_mutex_timedlock should time out. 2102 ASSERT_EQ(0, pthread_mutex_lock(&m)); 2103 2104 timespec ts; 2105 ASSERT_EQ(0, clock_gettime(clock, &ts)); 2106 ASSERT_EQ(ETIMEDOUT, lock_function(&m, &ts)); 2107 ts.tv_nsec = -1; 2108 ASSERT_EQ(EINVAL, lock_function(&m, &ts)); 2109 ts.tv_nsec = NS_PER_S; 2110 ASSERT_EQ(EINVAL, lock_function(&m, &ts)); 2111 ts.tv_nsec = NS_PER_S - 1; 2112 ts.tv_sec = -1; 2113 ASSERT_EQ(ETIMEDOUT, lock_function(&m, &ts)); 2114 2115 // If the mutex is unlocked, pthread_mutex_timedlock should succeed. 2116 ASSERT_EQ(0, pthread_mutex_unlock(&m)); 2117 2118 ASSERT_EQ(0, clock_gettime(clock, &ts)); 2119 ts.tv_sec += 1; 2120 ASSERT_EQ(0, lock_function(&m, &ts)); 2121 2122 ASSERT_EQ(0, pthread_mutex_unlock(&m)); 2123 ASSERT_EQ(0, pthread_mutex_destroy(&m)); 2124 } 2125 2126 TEST(pthread, pthread_mutex_timedlock) { 2127 pthread_mutex_timedlock_helper(CLOCK_REALTIME, pthread_mutex_timedlock); 2128 } 2129 2130 TEST(pthread, pthread_mutex_timedlock_monotonic_np) { 2131 #if defined(__BIONIC__) 2132 pthread_mutex_timedlock_helper(CLOCK_MONOTONIC, pthread_mutex_timedlock_monotonic_np); 2133 #else // __BIONIC__ 2134 GTEST_LOG_(INFO) << "This test does nothing since pthread_mutex_timedlock_monotonic_np is only " 2135 "supported on bionic"; 2136 #endif // __BIONIC__ 2137 } 2138 2139 static void pthread_mutex_timedlock_pi_helper(clockid_t clock, 2140 int (*lock_function)(pthread_mutex_t* __mutex, 2141 const timespec* __timeout)) { 2142 PthreadMutex m(PTHREAD_MUTEX_NORMAL, PTHREAD_PRIO_INHERIT); 2143 2144 timespec ts; 2145 clock_gettime(clock, &ts); 2146 ts.tv_sec += 1; 2147 ASSERT_EQ(0, lock_function(&m.lock, &ts)); 2148 2149 struct ThreadArgs { 2150 clockid_t clock; 2151 int (*lock_function)(pthread_mutex_t* __mutex, const timespec* __timeout); 2152 PthreadMutex& m; 2153 }; 2154 2155 ThreadArgs thread_args = { 2156 .clock = clock, 2157 .lock_function = lock_function, 2158 .m = m, 2159 }; 2160 2161 auto ThreadFn = [](void* arg) -> void* { 2162 auto args = static_cast<ThreadArgs*>(arg); 2163 timespec ts; 2164 clock_gettime(args->clock, &ts); 2165 ts.tv_sec += 1; 2166 intptr_t result = args->lock_function(&args->m.lock, &ts); 2167 return reinterpret_cast<void*>(result); 2168 }; 2169 2170 pthread_t thread; 2171 ASSERT_EQ(0, pthread_create(&thread, NULL, ThreadFn, &thread_args)); 2172 void* result; 2173 ASSERT_EQ(0, pthread_join(thread, &result)); 2174 ASSERT_EQ(ETIMEDOUT, reinterpret_cast<intptr_t>(result)); 2175 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); 2176 } 2177 2178 TEST(pthread, pthread_mutex_timedlock_pi) { 2179 pthread_mutex_timedlock_pi_helper(CLOCK_REALTIME, pthread_mutex_timedlock); 2180 } 2181 2182 TEST(pthread, pthread_mutex_timedlock_monotonic_np_pi) { 2183 #if defined(__BIONIC__) 2184 pthread_mutex_timedlock_pi_helper(CLOCK_MONOTONIC, pthread_mutex_timedlock_monotonic_np); 2185 #else // __BIONIC__ 2186 GTEST_LOG_(INFO) << "This test does nothing since pthread_mutex_timedlock_monotonic_np is only " 2187 "supported on bionic"; 2188 #endif // __BIONIC__ 2189 } 2190 2191 TEST(pthread, pthread_mutex_using_destroyed_mutex) { 2192 #if defined(__BIONIC__) 2193 pthread_mutex_t m; 2194 ASSERT_EQ(0, pthread_mutex_init(&m, nullptr)); 2195 ASSERT_EQ(0, pthread_mutex_destroy(&m)); 2196 ASSERT_EXIT(pthread_mutex_lock(&m), ::testing::KilledBySignal(SIGABRT), 2197 "pthread_mutex_lock called on a destroyed mutex"); 2198 ASSERT_EXIT(pthread_mutex_unlock(&m), ::testing::KilledBySignal(SIGABRT), 2199 "pthread_mutex_unlock called on a destroyed mutex"); 2200 ASSERT_EXIT(pthread_mutex_trylock(&m), ::testing::KilledBySignal(SIGABRT), 2201 "pthread_mutex_trylock called on a destroyed mutex"); 2202 timespec ts; 2203 ASSERT_EXIT(pthread_mutex_timedlock(&m, &ts), ::testing::KilledBySignal(SIGABRT), 2204 "pthread_mutex_timedlock called on a destroyed mutex"); 2205 ASSERT_EXIT(pthread_mutex_timedlock_monotonic_np(&m, &ts), ::testing::KilledBySignal(SIGABRT), 2206 "pthread_mutex_timedlock_monotonic_np called on a destroyed mutex"); 2207 ASSERT_EXIT(pthread_mutex_destroy(&m), ::testing::KilledBySignal(SIGABRT), 2208 "pthread_mutex_destroy called on a destroyed mutex"); 2209 #else 2210 GTEST_LOG_(INFO) << "This test tests bionic pthread mutex implementation details."; 2211 #endif 2212 } 2213 2214 class StrictAlignmentAllocator { 2215 public: 2216 void* allocate(size_t size, size_t alignment) { 2217 char* p = new char[size + alignment * 2]; 2218 allocated_array.push_back(p); 2219 while (!is_strict_aligned(p, alignment)) { 2220 ++p; 2221 } 2222 return p; 2223 } 2224 2225 ~StrictAlignmentAllocator() { 2226 for (const auto& p : allocated_array) { 2227 delete[] p; 2228 } 2229 } 2230 2231 private: 2232 bool is_strict_aligned(char* p, size_t alignment) { 2233 return (reinterpret_cast<uintptr_t>(p) % (alignment * 2)) == alignment; 2234 } 2235 2236 std::vector<char*> allocated_array; 2237 }; 2238 2239 TEST(pthread, pthread_types_allow_four_bytes_alignment) { 2240 #if defined(__BIONIC__) 2241 // For binary compatibility with old version, we need to allow 4-byte aligned data for pthread types. 2242 StrictAlignmentAllocator allocator; 2243 pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>( 2244 allocator.allocate(sizeof(pthread_mutex_t), 4)); 2245 ASSERT_EQ(0, pthread_mutex_init(mutex, NULL)); 2246 ASSERT_EQ(0, pthread_mutex_lock(mutex)); 2247 ASSERT_EQ(0, pthread_mutex_unlock(mutex)); 2248 ASSERT_EQ(0, pthread_mutex_destroy(mutex)); 2249 2250 pthread_cond_t* cond = reinterpret_cast<pthread_cond_t*>( 2251 allocator.allocate(sizeof(pthread_cond_t), 4)); 2252 ASSERT_EQ(0, pthread_cond_init(cond, NULL)); 2253 ASSERT_EQ(0, pthread_cond_signal(cond)); 2254 ASSERT_EQ(0, pthread_cond_broadcast(cond)); 2255 ASSERT_EQ(0, pthread_cond_destroy(cond)); 2256 2257 pthread_rwlock_t* rwlock = reinterpret_cast<pthread_rwlock_t*>( 2258 allocator.allocate(sizeof(pthread_rwlock_t), 4)); 2259 ASSERT_EQ(0, pthread_rwlock_init(rwlock, NULL)); 2260 ASSERT_EQ(0, pthread_rwlock_rdlock(rwlock)); 2261 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock)); 2262 ASSERT_EQ(0, pthread_rwlock_wrlock(rwlock)); 2263 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock)); 2264 ASSERT_EQ(0, pthread_rwlock_destroy(rwlock)); 2265 2266 #else 2267 GTEST_LOG_(INFO) << "This test tests bionic implementation details."; 2268 #endif 2269 } 2270 2271 TEST(pthread, pthread_mutex_lock_null_32) { 2272 #if defined(__BIONIC__) && !defined(__LP64__) 2273 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return 2274 // EINVAL in that case: http://b/19995172. 2275 // 2276 // We decorate the public defintion with _Nonnull so that people recompiling 2277 // their code with get a warning and might fix their bug, but need to pass 2278 // NULL here to test that we remain compatible. 2279 pthread_mutex_t* null_value = nullptr; 2280 ASSERT_EQ(EINVAL, pthread_mutex_lock(null_value)); 2281 #else 2282 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 32 bit devices."; 2283 #endif 2284 } 2285 2286 TEST(pthread, pthread_mutex_unlock_null_32) { 2287 #if defined(__BIONIC__) && !defined(__LP64__) 2288 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return 2289 // EINVAL in that case: http://b/19995172. 2290 // 2291 // We decorate the public defintion with _Nonnull so that people recompiling 2292 // their code with get a warning and might fix their bug, but need to pass 2293 // NULL here to test that we remain compatible. 2294 pthread_mutex_t* null_value = nullptr; 2295 ASSERT_EQ(EINVAL, pthread_mutex_unlock(null_value)); 2296 #else 2297 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 32 bit devices."; 2298 #endif 2299 } 2300 2301 TEST_F(pthread_DeathTest, pthread_mutex_lock_null_64) { 2302 #if defined(__BIONIC__) && defined(__LP64__) 2303 pthread_mutex_t* null_value = nullptr; 2304 ASSERT_EXIT(pthread_mutex_lock(null_value), testing::KilledBySignal(SIGSEGV), ""); 2305 #else 2306 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 64 bit devices."; 2307 #endif 2308 } 2309 2310 TEST_F(pthread_DeathTest, pthread_mutex_unlock_null_64) { 2311 #if defined(__BIONIC__) && defined(__LP64__) 2312 pthread_mutex_t* null_value = nullptr; 2313 ASSERT_EXIT(pthread_mutex_unlock(null_value), testing::KilledBySignal(SIGSEGV), ""); 2314 #else 2315 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 64 bit devices."; 2316 #endif 2317 } 2318 2319 extern _Unwind_Reason_Code FrameCounter(_Unwind_Context* ctx, void* arg); 2320 2321 static volatile bool signal_handler_on_altstack_done; 2322 2323 __attribute__((__noinline__)) 2324 static void signal_handler_backtrace() { 2325 // Check if we have enough stack space for unwinding. 2326 int count = 0; 2327 _Unwind_Backtrace(FrameCounter, &count); 2328 ASSERT_GT(count, 0); 2329 } 2330 2331 __attribute__((__noinline__)) 2332 static void signal_handler_logging() { 2333 // Check if we have enough stack space for logging. 2334 std::string s(2048, '*'); 2335 GTEST_LOG_(INFO) << s; 2336 signal_handler_on_altstack_done = true; 2337 } 2338 2339 __attribute__((__noinline__)) 2340 static void signal_handler_snprintf() { 2341 // Check if we have enough stack space for snprintf to a PATH_MAX buffer, plus some extra. 2342 char buf[PATH_MAX + 2048]; 2343 ASSERT_GT(snprintf(buf, sizeof(buf), "/proc/%d/status", getpid()), 0); 2344 } 2345 2346 static void SignalHandlerOnAltStack(int signo, siginfo_t*, void*) { 2347 ASSERT_EQ(SIGUSR1, signo); 2348 signal_handler_backtrace(); 2349 signal_handler_logging(); 2350 signal_handler_snprintf(); 2351 } 2352 2353 TEST(pthread, big_enough_signal_stack) { 2354 signal_handler_on_altstack_done = false; 2355 ScopedSignalHandler handler(SIGUSR1, SignalHandlerOnAltStack, SA_SIGINFO | SA_ONSTACK); 2356 kill(getpid(), SIGUSR1); 2357 ASSERT_TRUE(signal_handler_on_altstack_done); 2358 } 2359 2360 TEST(pthread, pthread_barrierattr_smoke) { 2361 pthread_barrierattr_t attr; 2362 ASSERT_EQ(0, pthread_barrierattr_init(&attr)); 2363 int pshared; 2364 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared)); 2365 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared); 2366 ASSERT_EQ(0, pthread_barrierattr_setpshared(&attr, PTHREAD_PROCESS_SHARED)); 2367 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared)); 2368 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared); 2369 ASSERT_EQ(0, pthread_barrierattr_destroy(&attr)); 2370 } 2371 2372 struct BarrierTestHelperData { 2373 size_t thread_count; 2374 pthread_barrier_t barrier; 2375 std::atomic<int> finished_mask; 2376 std::atomic<int> serial_thread_count; 2377 size_t iteration_count; 2378 std::atomic<size_t> finished_iteration_count; 2379 2380 BarrierTestHelperData(size_t thread_count, size_t iteration_count) 2381 : thread_count(thread_count), finished_mask(0), serial_thread_count(0), 2382 iteration_count(iteration_count), finished_iteration_count(0) { 2383 } 2384 }; 2385 2386 struct BarrierTestHelperArg { 2387 int id; 2388 BarrierTestHelperData* data; 2389 }; 2390 2391 static void BarrierTestHelper(BarrierTestHelperArg* arg) { 2392 for (size_t i = 0; i < arg->data->iteration_count; ++i) { 2393 int result = pthread_barrier_wait(&arg->data->barrier); 2394 if (result == PTHREAD_BARRIER_SERIAL_THREAD) { 2395 arg->data->serial_thread_count++; 2396 } else { 2397 ASSERT_EQ(0, result); 2398 } 2399 int mask = arg->data->finished_mask.fetch_or(1 << arg->id); 2400 mask |= 1 << arg->id; 2401 if (mask == ((1 << arg->data->thread_count) - 1)) { 2402 ASSERT_EQ(1, arg->data->serial_thread_count); 2403 arg->data->finished_iteration_count++; 2404 arg->data->finished_mask = 0; 2405 arg->data->serial_thread_count = 0; 2406 } 2407 } 2408 } 2409 2410 TEST(pthread, pthread_barrier_smoke) { 2411 const size_t BARRIER_ITERATION_COUNT = 10; 2412 const size_t BARRIER_THREAD_COUNT = 10; 2413 BarrierTestHelperData data(BARRIER_THREAD_COUNT, BARRIER_ITERATION_COUNT); 2414 ASSERT_EQ(0, pthread_barrier_init(&data.barrier, nullptr, data.thread_count)); 2415 std::vector<pthread_t> threads(data.thread_count); 2416 std::vector<BarrierTestHelperArg> args(threads.size()); 2417 for (size_t i = 0; i < threads.size(); ++i) { 2418 args[i].id = i; 2419 args[i].data = &data; 2420 ASSERT_EQ(0, pthread_create(&threads[i], nullptr, 2421 reinterpret_cast<void* (*)(void*)>(BarrierTestHelper), &args[i])); 2422 } 2423 for (size_t i = 0; i < threads.size(); ++i) { 2424 ASSERT_EQ(0, pthread_join(threads[i], nullptr)); 2425 } 2426 ASSERT_EQ(data.iteration_count, data.finished_iteration_count); 2427 ASSERT_EQ(0, pthread_barrier_destroy(&data.barrier)); 2428 } 2429 2430 struct BarrierDestroyTestArg { 2431 std::atomic<int> tid; 2432 pthread_barrier_t* barrier; 2433 }; 2434 2435 static void BarrierDestroyTestHelper(BarrierDestroyTestArg* arg) { 2436 arg->tid = gettid(); 2437 ASSERT_EQ(0, pthread_barrier_wait(arg->barrier)); 2438 } 2439 2440 TEST(pthread, pthread_barrier_destroy) { 2441 pthread_barrier_t barrier; 2442 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, 2)); 2443 pthread_t thread; 2444 BarrierDestroyTestArg arg; 2445 arg.tid = 0; 2446 arg.barrier = &barrier; 2447 ASSERT_EQ(0, pthread_create(&thread, nullptr, 2448 reinterpret_cast<void* (*)(void*)>(BarrierDestroyTestHelper), &arg)); 2449 WaitUntilThreadSleep(arg.tid); 2450 ASSERT_EQ(EBUSY, pthread_barrier_destroy(&barrier)); 2451 ASSERT_EQ(PTHREAD_BARRIER_SERIAL_THREAD, pthread_barrier_wait(&barrier)); 2452 // Verify if the barrier can be destroyed directly after pthread_barrier_wait(). 2453 ASSERT_EQ(0, pthread_barrier_destroy(&barrier)); 2454 ASSERT_EQ(0, pthread_join(thread, nullptr)); 2455 #if defined(__BIONIC__) 2456 ASSERT_EQ(EINVAL, pthread_barrier_destroy(&barrier)); 2457 #endif 2458 } 2459 2460 struct BarrierOrderingTestHelperArg { 2461 pthread_barrier_t* barrier; 2462 size_t* array; 2463 size_t array_length; 2464 size_t id; 2465 }; 2466 2467 void BarrierOrderingTestHelper(BarrierOrderingTestHelperArg* arg) { 2468 const size_t ITERATION_COUNT = 10000; 2469 for (size_t i = 1; i <= ITERATION_COUNT; ++i) { 2470 arg->array[arg->id] = i; 2471 int result = pthread_barrier_wait(arg->barrier); 2472 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD); 2473 for (size_t j = 0; j < arg->array_length; ++j) { 2474 ASSERT_EQ(i, arg->array[j]); 2475 } 2476 result = pthread_barrier_wait(arg->barrier); 2477 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD); 2478 } 2479 } 2480 2481 TEST(pthread, pthread_barrier_check_ordering) { 2482 const size_t THREAD_COUNT = 4; 2483 pthread_barrier_t barrier; 2484 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, THREAD_COUNT)); 2485 size_t array[THREAD_COUNT]; 2486 std::vector<pthread_t> threads(THREAD_COUNT); 2487 std::vector<BarrierOrderingTestHelperArg> args(THREAD_COUNT); 2488 for (size_t i = 0; i < THREAD_COUNT; ++i) { 2489 args[i].barrier = &barrier; 2490 args[i].array = array; 2491 args[i].array_length = THREAD_COUNT; 2492 args[i].id = i; 2493 ASSERT_EQ(0, pthread_create(&threads[i], nullptr, 2494 reinterpret_cast<void* (*)(void*)>(BarrierOrderingTestHelper), 2495 &args[i])); 2496 } 2497 for (size_t i = 0; i < THREAD_COUNT; ++i) { 2498 ASSERT_EQ(0, pthread_join(threads[i], nullptr)); 2499 } 2500 } 2501 2502 TEST(pthread, pthread_spinlock_smoke) { 2503 pthread_spinlock_t lock; 2504 ASSERT_EQ(0, pthread_spin_init(&lock, 0)); 2505 ASSERT_EQ(0, pthread_spin_trylock(&lock)); 2506 ASSERT_EQ(0, pthread_spin_unlock(&lock)); 2507 ASSERT_EQ(0, pthread_spin_lock(&lock)); 2508 ASSERT_EQ(EBUSY, pthread_spin_trylock(&lock)); 2509 ASSERT_EQ(0, pthread_spin_unlock(&lock)); 2510 ASSERT_EQ(0, pthread_spin_destroy(&lock)); 2511 } 2512 2513 TEST(pthread, pthread_attr_getdetachstate__pthread_attr_setdetachstate) { 2514 pthread_attr_t attr; 2515 ASSERT_EQ(0, pthread_attr_init(&attr)); 2516 2517 int state; 2518 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)); 2519 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state)); 2520 ASSERT_EQ(PTHREAD_CREATE_DETACHED, state); 2521 2522 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE)); 2523 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state)); 2524 ASSERT_EQ(PTHREAD_CREATE_JOINABLE, state); 2525 2526 ASSERT_EQ(EINVAL, pthread_attr_setdetachstate(&attr, 123)); 2527 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state)); 2528 ASSERT_EQ(PTHREAD_CREATE_JOINABLE, state); 2529 } 2530 2531 TEST(pthread, pthread_create__mmap_failures) { 2532 pthread_attr_t attr; 2533 ASSERT_EQ(0, pthread_attr_init(&attr)); 2534 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)); 2535 2536 const auto kPageSize = sysconf(_SC_PAGE_SIZE); 2537 2538 // Use up all the VMAs. By default this is 64Ki (though some will already be in use). 2539 std::vector<void*> pages; 2540 pages.reserve(64 * 1024); 2541 int prot = PROT_NONE; 2542 while (true) { 2543 void* page = mmap(nullptr, kPageSize, prot, MAP_ANON|MAP_PRIVATE, -1, 0); 2544 if (page == MAP_FAILED) break; 2545 pages.push_back(page); 2546 prot = (prot == PROT_NONE) ? PROT_READ : PROT_NONE; 2547 } 2548 2549 // Try creating threads, freeing up a page each time we fail. 2550 size_t EAGAIN_count = 0; 2551 size_t i = 0; 2552 for (; i < pages.size(); ++i) { 2553 pthread_t t; 2554 int status = pthread_create(&t, &attr, IdFn, nullptr); 2555 if (status != EAGAIN) break; 2556 ++EAGAIN_count; 2557 ASSERT_EQ(0, munmap(pages[i], kPageSize)); 2558 } 2559 2560 // Creating a thread uses at least six VMAs: the stack, the TLS, and a guard each side of both. 2561 // So we should have seen at least six failures. 2562 ASSERT_GE(EAGAIN_count, 6U); 2563 2564 for (; i < pages.size(); ++i) { 2565 ASSERT_EQ(0, munmap(pages[i], kPageSize)); 2566 } 2567 } 2568 2569 TEST(pthread, pthread_setschedparam) { 2570 sched_param p = { .sched_priority = INT_MIN }; 2571 ASSERT_EQ(EINVAL, pthread_setschedparam(pthread_self(), INT_MIN, &p)); 2572 } 2573 2574 TEST(pthread, pthread_setschedprio) { 2575 ASSERT_EQ(EINVAL, pthread_setschedprio(pthread_self(), INT_MIN)); 2576 } 2577 2578 TEST(pthread, pthread_attr_getinheritsched__pthread_attr_setinheritsched) { 2579 pthread_attr_t attr; 2580 ASSERT_EQ(0, pthread_attr_init(&attr)); 2581 2582 int state; 2583 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED)); 2584 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state)); 2585 ASSERT_EQ(PTHREAD_INHERIT_SCHED, state); 2586 2587 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED)); 2588 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state)); 2589 ASSERT_EQ(PTHREAD_EXPLICIT_SCHED, state); 2590 2591 ASSERT_EQ(EINVAL, pthread_attr_setinheritsched(&attr, 123)); 2592 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state)); 2593 ASSERT_EQ(PTHREAD_EXPLICIT_SCHED, state); 2594 } 2595 2596 TEST(pthread, pthread_attr_setinheritsched__PTHREAD_INHERIT_SCHED__PTHREAD_EXPLICIT_SCHED) { 2597 pthread_attr_t attr; 2598 ASSERT_EQ(0, pthread_attr_init(&attr)); 2599 2600 // If we set invalid scheduling attributes but choose to inherit, everything's fine... 2601 sched_param param = { .sched_priority = sched_get_priority_max(SCHED_FIFO) + 1 }; 2602 ASSERT_EQ(0, pthread_attr_setschedparam(&attr, ¶m)); 2603 ASSERT_EQ(0, pthread_attr_setschedpolicy(&attr, SCHED_FIFO)); 2604 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED)); 2605 2606 pthread_t t; 2607 ASSERT_EQ(0, pthread_create(&t, &attr, IdFn, nullptr)); 2608 ASSERT_EQ(0, pthread_join(t, nullptr)); 2609 2610 #if defined(__LP64__) 2611 // If we ask to use them, though, we'll see a failure... 2612 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED)); 2613 ASSERT_EQ(EINVAL, pthread_create(&t, &attr, IdFn, nullptr)); 2614 #else 2615 // For backwards compatibility with broken apps, we just ignore failures 2616 // to set scheduler attributes on LP32. 2617 #endif 2618 } 2619 2620 TEST(pthread, pthread_attr_setinheritsched_PTHREAD_INHERIT_SCHED_takes_effect) { 2621 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) }; 2622 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO, ¶m); 2623 if (rc == EPERM) { 2624 GTEST_LOG_(INFO) << "pthread_setschedparam failed with EPERM, skipping test\n"; 2625 return; 2626 } 2627 ASSERT_EQ(0, rc); 2628 2629 pthread_attr_t attr; 2630 ASSERT_EQ(0, pthread_attr_init(&attr)); 2631 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED)); 2632 2633 SpinFunctionHelper spin_helper; 2634 pthread_t t; 2635 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr)); 2636 int actual_policy; 2637 sched_param actual_param; 2638 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param)); 2639 ASSERT_EQ(SCHED_FIFO, actual_policy); 2640 spin_helper.UnSpin(); 2641 ASSERT_EQ(0, pthread_join(t, nullptr)); 2642 } 2643 2644 TEST(pthread, pthread_attr_setinheritsched_PTHREAD_EXPLICIT_SCHED_takes_effect) { 2645 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) }; 2646 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO, ¶m); 2647 if (rc == EPERM) { 2648 GTEST_LOG_(INFO) << "pthread_setschedparam failed with EPERM, skipping test\n"; 2649 return; 2650 } 2651 ASSERT_EQ(0, rc); 2652 2653 pthread_attr_t attr; 2654 ASSERT_EQ(0, pthread_attr_init(&attr)); 2655 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED)); 2656 ASSERT_EQ(0, pthread_attr_setschedpolicy(&attr, SCHED_OTHER)); 2657 2658 SpinFunctionHelper spin_helper; 2659 pthread_t t; 2660 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr)); 2661 int actual_policy; 2662 sched_param actual_param; 2663 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param)); 2664 ASSERT_EQ(SCHED_OTHER, actual_policy); 2665 spin_helper.UnSpin(); 2666 ASSERT_EQ(0, pthread_join(t, nullptr)); 2667 } 2668 2669 TEST(pthread, pthread_attr_setinheritsched__takes_effect_despite_SCHED_RESET_ON_FORK) { 2670 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) }; 2671 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO | SCHED_RESET_ON_FORK, ¶m); 2672 if (rc == EPERM) { 2673 GTEST_LOG_(INFO) << "pthread_setschedparam failed with EPERM, skipping test\n"; 2674 return; 2675 } 2676 ASSERT_EQ(0, rc); 2677 2678 pthread_attr_t attr; 2679 ASSERT_EQ(0, pthread_attr_init(&attr)); 2680 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED)); 2681 2682 SpinFunctionHelper spin_helper; 2683 pthread_t t; 2684 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr)); 2685 int actual_policy; 2686 sched_param actual_param; 2687 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param)); 2688 ASSERT_EQ(SCHED_FIFO | SCHED_RESET_ON_FORK, actual_policy); 2689 spin_helper.UnSpin(); 2690 ASSERT_EQ(0, pthread_join(t, nullptr)); 2691 } 2692