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