blob: 1a882beb5babe061492adef73e7e5e865b7f1280 [file] [log] [blame]
Elliott Hughesbfeab1b2012-09-05 17:47:37 -07001/*
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>
Elliott Hughes5b9310e2013-10-02 16:59:05 -070020#include <inttypes.h>
Elliott Hughesb95cf0d2013-07-15 14:51:07 -070021#include <limits.h>
Elliott Hughes04620a32014-03-07 17:59:05 -080022#include <malloc.h>
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070023#include <pthread.h>
Christopher Ferrisf04935c2013-12-20 18:43:21 -080024#include <signal.h>
Yabin Cui140f3672015-02-03 10:32:00 -080025#include <stdio.h>
Colin Cross4c5595c2021-08-16 15:51:59 -070026#include <sys/cdefs.h>
Elliott Hughes70b24b12013-11-15 11:51:07 -080027#include <sys/mman.h>
Juan Yescas65af9a82023-12-07 11:35:21 -080028#include <sys/param.h>
Elliott Hughes4d098ca2016-04-11 12:43:05 -070029#include <sys/prctl.h>
George Burgess IV08fd0722019-01-15 19:00:11 -080030#include <sys/resource.h>
Elliott Hughes57b7a612014-08-25 17:26:50 -070031#include <sys/syscall.h>
Narayan Kamath51e6cb32014-03-03 15:38:51 +000032#include <time.h>
Elliott Hughes4d014e12012-09-07 16:47:54 -070033#include <unistd.h>
Yabin Cui33ac04a2015-09-22 11:16:15 -070034#include <unwind.h>
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070035
Yabin Cui08ee8d22015-02-11 17:04:36 -080036#include <atomic>
Josh Gaoddf757e2018-10-17 15:23:03 -070037#include <future>
Yabin Cuib5845722015-03-16 22:46:42 -070038#include <vector>
Yabin Cui08ee8d22015-02-11 17:04:36 -080039
Elliott Hughes5e62b342018-10-25 11:00:00 -070040#include <android-base/macros.h>
Yabin Cui6b9c85b2018-01-23 12:56:18 -080041#include <android-base/parseint.h>
Tom Cherryb8ab6182017-04-05 16:20:29 -070042#include <android-base/scopeguard.h>
Elliott Hughes141b9172021-04-09 17:13:09 -070043#include <android-base/silent_death_test.h>
Yabin Cui6b9c85b2018-01-23 12:56:18 -080044#include <android-base/strings.h>
Florian Mayerf9666202023-02-28 14:26:06 -080045#include <android-base/test_utils.h>
Tom Cherryb8ab6182017-04-05 16:20:29 -070046
Yabin Cuic9a659c2015-11-05 15:36:08 -080047#include "private/bionic_constants.h"
Elliott Hughes71ba5892018-02-07 12:44:45 -080048#include "SignalUtils.h"
Elliott Hughes15dfd632015-09-22 16:40:14 -070049#include "utils.h"
50
Elliott Hughes141b9172021-04-09 17:13:09 -070051using pthread_DeathTest = SilentDeathTest;
Elliott Hughese657eb42021-02-18 17:11:56 -080052
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070053TEST(pthread, pthread_key_create) {
54 pthread_key_t key;
Yi Kong32bc0fc2018-08-02 17:31:13 -070055 ASSERT_EQ(0, pthread_key_create(&key, nullptr));
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070056 ASSERT_EQ(0, pthread_key_delete(key));
57 // Can't delete a key that's already been deleted.
58 ASSERT_EQ(EINVAL, pthread_key_delete(key));
59}
Elliott Hughes4d014e12012-09-07 16:47:54 -070060
Dan Albertc4bcc752014-09-30 11:48:24 -070061TEST(pthread, pthread_keys_max) {
Yabin Cui6c238f22014-12-11 20:50:41 -080062 // POSIX says PTHREAD_KEYS_MAX should be at least _POSIX_THREAD_KEYS_MAX.
63 ASSERT_GE(PTHREAD_KEYS_MAX, _POSIX_THREAD_KEYS_MAX);
Dan Albertc4bcc752014-09-30 11:48:24 -070064}
Elliott Hughes718a5b52014-01-28 17:02:03 -080065
Yabin Cui6c238f22014-12-11 20:50:41 -080066TEST(pthread, sysconf_SC_THREAD_KEYS_MAX_eq_PTHREAD_KEYS_MAX) {
Dan Albertc4bcc752014-09-30 11:48:24 -070067 int sysconf_max = sysconf(_SC_THREAD_KEYS_MAX);
Yabin Cui6c238f22014-12-11 20:50:41 -080068 ASSERT_EQ(sysconf_max, PTHREAD_KEYS_MAX);
Dan Albertc4bcc752014-09-30 11:48:24 -070069}
70
71TEST(pthread, pthread_key_many_distinct) {
Yabin Cui6c238f22014-12-11 20:50:41 -080072 // As gtest uses pthread keys, we can't allocate exactly PTHREAD_KEYS_MAX
73 // pthread keys, but We should be able to allocate at least this many keys.
74 int nkeys = PTHREAD_KEYS_MAX / 2;
Dan Albertc4bcc752014-09-30 11:48:24 -070075 std::vector<pthread_key_t> keys;
76
Tom Cherryb8ab6182017-04-05 16:20:29 -070077 auto scope_guard = android::base::make_scope_guard([&keys] {
Elliott Hughes0b2acdf2015-10-02 18:25:19 -070078 for (const auto& key : keys) {
Dan Albertc4bcc752014-09-30 11:48:24 -070079 EXPECT_EQ(0, pthread_key_delete(key));
80 }
81 });
82
83 for (int i = 0; i < nkeys; ++i) {
84 pthread_key_t key;
Elliott Hughes61706932015-03-31 10:56:58 -070085 // If this fails, it's likely that LIBC_PTHREAD_KEY_RESERVED_COUNT is wrong.
Yi Kong32bc0fc2018-08-02 17:31:13 -070086 ASSERT_EQ(0, pthread_key_create(&key, nullptr)) << i << " of " << nkeys;
Dan Albertc4bcc752014-09-30 11:48:24 -070087 keys.push_back(key);
88 ASSERT_EQ(0, pthread_setspecific(key, reinterpret_cast<void*>(i)));
89 }
90
91 for (int i = keys.size() - 1; i >= 0; --i) {
92 ASSERT_EQ(reinterpret_cast<void*>(i), pthread_getspecific(keys.back()));
93 pthread_key_t key = keys.back();
94 keys.pop_back();
95 ASSERT_EQ(0, pthread_key_delete(key));
96 }
97}
98
Yabin Cui6c238f22014-12-11 20:50:41 -080099TEST(pthread, pthread_key_not_exceed_PTHREAD_KEYS_MAX) {
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000100 std::vector<pthread_key_t> keys;
Dan Albertc4bcc752014-09-30 11:48:24 -0700101 int rv = 0;
Yabin Cui6c238f22014-12-11 20:50:41 -0800102
103 // Pthread keys are used by gtest, so PTHREAD_KEYS_MAX should
104 // be more than we are allowed to allocate now.
105 for (int i = 0; i < PTHREAD_KEYS_MAX; i++) {
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000106 pthread_key_t key;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700107 rv = pthread_key_create(&key, nullptr);
Dan Albertc4bcc752014-09-30 11:48:24 -0700108 if (rv == EAGAIN) {
109 break;
110 }
111 EXPECT_EQ(0, rv);
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000112 keys.push_back(key);
113 }
114
Dan Albertc4bcc752014-09-30 11:48:24 -0700115 // Don't leak keys.
Elliott Hughes0b2acdf2015-10-02 18:25:19 -0700116 for (const auto& key : keys) {
Dan Albertc4bcc752014-09-30 11:48:24 -0700117 EXPECT_EQ(0, pthread_key_delete(key));
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000118 }
Dan Albertc4bcc752014-09-30 11:48:24 -0700119 keys.clear();
120
121 // We should have eventually reached the maximum number of keys and received
122 // EAGAIN.
123 ASSERT_EQ(EAGAIN, rv);
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000124}
125
Elliott Hughesebb770f2014-06-25 13:46:46 -0700126TEST(pthread, pthread_key_delete) {
127 void* expected = reinterpret_cast<void*>(1234);
128 pthread_key_t key;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700129 ASSERT_EQ(0, pthread_key_create(&key, nullptr));
Elliott Hughesebb770f2014-06-25 13:46:46 -0700130 ASSERT_EQ(0, pthread_setspecific(key, expected));
131 ASSERT_EQ(expected, pthread_getspecific(key));
132 ASSERT_EQ(0, pthread_key_delete(key));
Yi Kong32bc0fc2018-08-02 17:31:13 -0700133 // After deletion, pthread_getspecific returns nullptr.
134 ASSERT_EQ(nullptr, pthread_getspecific(key));
Elliott Hughesebb770f2014-06-25 13:46:46 -0700135 // And you can't use pthread_setspecific with the deleted key.
136 ASSERT_EQ(EINVAL, pthread_setspecific(key, expected));
137}
138
Elliott Hughes40a52172014-07-30 14:48:10 -0700139TEST(pthread, pthread_key_fork) {
140 void* expected = reinterpret_cast<void*>(1234);
141 pthread_key_t key;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700142 ASSERT_EQ(0, pthread_key_create(&key, nullptr));
Elliott Hughes40a52172014-07-30 14:48:10 -0700143 ASSERT_EQ(0, pthread_setspecific(key, expected));
144 ASSERT_EQ(expected, pthread_getspecific(key));
145
146 pid_t pid = fork();
147 ASSERT_NE(-1, pid) << strerror(errno);
148
149 if (pid == 0) {
150 // The surviving thread inherits all the forking thread's TLS values...
151 ASSERT_EQ(expected, pthread_getspecific(key));
152 _exit(99);
153 }
154
Elliott Hughes33697a02016-01-26 13:04:57 -0800155 AssertChildExited(pid, 99);
Elliott Hughes40a52172014-07-30 14:48:10 -0700156
157 ASSERT_EQ(expected, pthread_getspecific(key));
Dan Albert1d53ae22014-09-02 15:24:26 -0700158 ASSERT_EQ(0, pthread_key_delete(key));
Elliott Hughes40a52172014-07-30 14:48:10 -0700159}
160
161static void* DirtyKeyFn(void* key) {
162 return pthread_getspecific(*reinterpret_cast<pthread_key_t*>(key));
163}
164
165TEST(pthread, pthread_key_dirty) {
166 pthread_key_t key;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700167 ASSERT_EQ(0, pthread_key_create(&key, nullptr));
Elliott Hughes40a52172014-07-30 14:48:10 -0700168
Yabin Cuia36158a2015-11-16 21:06:16 -0800169 size_t stack_size = 640 * 1024;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700170 void* stack = mmap(nullptr, stack_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
Elliott Hughes40a52172014-07-30 14:48:10 -0700171 ASSERT_NE(MAP_FAILED, stack);
172 memset(stack, 0xff, stack_size);
173
174 pthread_attr_t attr;
175 ASSERT_EQ(0, pthread_attr_init(&attr));
176 ASSERT_EQ(0, pthread_attr_setstack(&attr, stack, stack_size));
177
178 pthread_t t;
179 ASSERT_EQ(0, pthread_create(&t, &attr, DirtyKeyFn, &key));
180
181 void* result;
182 ASSERT_EQ(0, pthread_join(t, &result));
183 ASSERT_EQ(nullptr, result); // Not ~0!
184
185 ASSERT_EQ(0, munmap(stack, stack_size));
Dan Albert1d53ae22014-09-02 15:24:26 -0700186 ASSERT_EQ(0, pthread_key_delete(key));
Elliott Hughes40a52172014-07-30 14:48:10 -0700187}
188
Florian Mayerf9666202023-02-28 14:26:06 -0800189static void* FnWithStackFrame(void*) {
190 int x;
191 *const_cast<volatile int*>(&x) = 1;
192 return nullptr;
193}
194
195TEST(pthread, pthread_heap_allocated_stack) {
196 SKIP_WITH_HWASAN; // TODO(b/148982147): Re-enable when fixed.
197
198 size_t stack_size = 640 * 1024;
Elliott Hughes18e335b2023-04-21 11:18:40 -0700199 std::unique_ptr<char[]> stack(new (std::align_val_t(getpagesize())) char[stack_size]);
200 memset(stack.get(), '\xff', stack_size);
Florian Mayerf9666202023-02-28 14:26:06 -0800201
202 pthread_attr_t attr;
203 ASSERT_EQ(0, pthread_attr_init(&attr));
Elliott Hughes18e335b2023-04-21 11:18:40 -0700204 ASSERT_EQ(0, pthread_attr_setstack(&attr, stack.get(), stack_size));
Florian Mayerf9666202023-02-28 14:26:06 -0800205
206 pthread_t t;
207 ASSERT_EQ(0, pthread_create(&t, &attr, FnWithStackFrame, nullptr));
208
209 void* result;
210 ASSERT_EQ(0, pthread_join(t, &result));
211}
212
Yabin Cui5ddbb3f2015-03-05 20:35:32 -0800213TEST(pthread, static_pthread_key_used_before_creation) {
214#if defined(__BIONIC__)
215 // See http://b/19625804. The bug is about a static/global pthread key being used before creation.
216 // So here tests if the static/global default value 0 can be detected as invalid key.
217 static pthread_key_t key;
218 ASSERT_EQ(nullptr, pthread_getspecific(key));
219 ASSERT_EQ(EINVAL, pthread_setspecific(key, nullptr));
220 ASSERT_EQ(EINVAL, pthread_key_delete(key));
221#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -0800222 GTEST_SKIP() << "bionic-only test";
Yabin Cui5ddbb3f2015-03-05 20:35:32 -0800223#endif
224}
225
Elliott Hughes4d014e12012-09-07 16:47:54 -0700226static void* IdFn(void* arg) {
227 return arg;
228}
229
Yabin Cui63481602014-12-01 17:41:04 -0800230class SpinFunctionHelper {
231 public:
232 SpinFunctionHelper() {
233 SpinFunctionHelper::spin_flag_ = true;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400234 }
Elliott Hughes0bd9d132017-11-02 13:11:13 -0700235
Yabin Cui63481602014-12-01 17:41:04 -0800236 ~SpinFunctionHelper() {
237 UnSpin();
238 }
Elliott Hughes0bd9d132017-11-02 13:11:13 -0700239
Yabin Cui63481602014-12-01 17:41:04 -0800240 auto GetFunction() -> void* (*)(void*) {
241 return SpinFunctionHelper::SpinFn;
242 }
243
244 void UnSpin() {
245 SpinFunctionHelper::spin_flag_ = false;
246 }
247
248 private:
249 static void* SpinFn(void*) {
250 while (spin_flag_) {}
Yi Kong32bc0fc2018-08-02 17:31:13 -0700251 return nullptr;
Yabin Cui63481602014-12-01 17:41:04 -0800252 }
Yabin Cuia36158a2015-11-16 21:06:16 -0800253 static std::atomic<bool> spin_flag_;
Yabin Cui63481602014-12-01 17:41:04 -0800254};
255
256// It doesn't matter if spin_flag_ is used in several tests,
257// because it is always set to false after each test. Each thread
258// loops on spin_flag_ can find it becomes false at some time.
Yabin Cuia36158a2015-11-16 21:06:16 -0800259std::atomic<bool> SpinFunctionHelper::spin_flag_;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400260
Elliott Hughes4d014e12012-09-07 16:47:54 -0700261static void* JoinFn(void* arg) {
Yi Kong32bc0fc2018-08-02 17:31:13 -0700262 return reinterpret_cast<void*>(pthread_join(reinterpret_cast<pthread_t>(arg), nullptr));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700263}
264
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400265static void AssertDetached(pthread_t t, bool is_detached) {
266 pthread_attr_t attr;
267 ASSERT_EQ(0, pthread_getattr_np(t, &attr));
268 int detach_state;
269 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &detach_state));
270 pthread_attr_destroy(&attr);
271 ASSERT_EQ(is_detached, (detach_state == PTHREAD_CREATE_DETACHED));
272}
273
Elliott Hughes7484c212017-02-02 02:41:38 +0000274static void MakeDeadThread(pthread_t& t) {
Yi Kong32bc0fc2018-08-02 17:31:13 -0700275 ASSERT_EQ(0, pthread_create(&t, nullptr, IdFn, nullptr));
276 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes7484c212017-02-02 02:41:38 +0000277}
278
Elliott Hughes4d014e12012-09-07 16:47:54 -0700279TEST(pthread, pthread_create) {
280 void* expected_result = reinterpret_cast<void*>(123);
281 // Can we create a thread?
282 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700283 ASSERT_EQ(0, pthread_create(&t, nullptr, IdFn, expected_result));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700284 // If we join, do we get the expected value back?
285 void* result;
286 ASSERT_EQ(0, pthread_join(t, &result));
287 ASSERT_EQ(expected_result, result);
288}
289
Elliott Hughes3e898472013-02-12 16:40:24 +0000290TEST(pthread, pthread_create_EAGAIN) {
291 pthread_attr_t attributes;
292 ASSERT_EQ(0, pthread_attr_init(&attributes));
293 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, static_cast<size_t>(-1) & ~(getpagesize() - 1)));
294
295 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700296 ASSERT_EQ(EAGAIN, pthread_create(&t, &attributes, IdFn, nullptr));
Elliott Hughes3e898472013-02-12 16:40:24 +0000297}
298
Elliott Hughes4d014e12012-09-07 16:47:54 -0700299TEST(pthread, pthread_no_join_after_detach) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700300 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800301
Elliott Hughes4d014e12012-09-07 16:47:54 -0700302 pthread_t t1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700303 ASSERT_EQ(0, pthread_create(&t1, nullptr, spin_helper.GetFunction(), nullptr));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700304
305 // After a pthread_detach...
306 ASSERT_EQ(0, pthread_detach(t1));
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400307 AssertDetached(t1, true);
Elliott Hughes4d014e12012-09-07 16:47:54 -0700308
309 // ...pthread_join should fail.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700310 ASSERT_EQ(EINVAL, pthread_join(t1, nullptr));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700311}
312
313TEST(pthread, pthread_no_op_detach_after_join) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700314 SpinFunctionHelper spin_helper;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400315
Elliott Hughes4d014e12012-09-07 16:47:54 -0700316 pthread_t t1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700317 ASSERT_EQ(0, pthread_create(&t1, nullptr, spin_helper.GetFunction(), nullptr));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700318
319 // If thread 2 is already waiting to join thread 1...
320 pthread_t t2;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700321 ASSERT_EQ(0, pthread_create(&t2, nullptr, JoinFn, reinterpret_cast<void*>(t1)));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700322
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400323 sleep(1); // (Give t2 a chance to call pthread_join.)
Elliott Hughes4d014e12012-09-07 16:47:54 -0700324
Yabin Cuibbb04322015-03-19 15:19:25 -0700325#if defined(__BIONIC__)
326 ASSERT_EQ(EINVAL, pthread_detach(t1));
327#else
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400328 ASSERT_EQ(0, pthread_detach(t1));
Yabin Cuibbb04322015-03-19 15:19:25 -0700329#endif
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400330 AssertDetached(t1, false);
331
Elliott Hughes725b2a92016-03-23 11:20:47 -0700332 spin_helper.UnSpin();
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400333
334 // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes).
Elliott Hughes4d014e12012-09-07 16:47:54 -0700335 void* join_result;
336 ASSERT_EQ(0, pthread_join(t2, &join_result));
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700337 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700338}
Elliott Hughes14f19592012-10-29 10:19:44 -0700339
340TEST(pthread, pthread_join_self) {
Yi Kong32bc0fc2018-08-02 17:31:13 -0700341 ASSERT_EQ(EDEADLK, pthread_join(pthread_self(), nullptr));
Elliott Hughes14f19592012-10-29 10:19:44 -0700342}
Elliott Hughes4f251be2012-11-01 16:33:29 -0700343
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800344struct TestBug37410 {
345 pthread_t main_thread;
346 pthread_mutex_t mutex;
Elliott Hughes4f251be2012-11-01 16:33:29 -0700347
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800348 static void main() {
349 TestBug37410 data;
350 data.main_thread = pthread_self();
Yi Kong32bc0fc2018-08-02 17:31:13 -0700351 ASSERT_EQ(0, pthread_mutex_init(&data.mutex, nullptr));
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800352 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
353
354 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700355 ASSERT_EQ(0, pthread_create(&t, nullptr, TestBug37410::thread_fn, reinterpret_cast<void*>(&data)));
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800356
357 // Wait for the thread to be running...
358 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
359 ASSERT_EQ(0, pthread_mutex_unlock(&data.mutex));
360
361 // ...and exit.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700362 pthread_exit(nullptr);
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800363 }
364
365 private:
366 static void* thread_fn(void* arg) {
367 TestBug37410* data = reinterpret_cast<TestBug37410*>(arg);
368
Evgenii Stepanov352853a2019-02-05 17:37:37 -0800369 // Unlocking data->mutex will cause the main thread to exit, invalidating *data. Save the handle.
370 pthread_t main_thread = data->main_thread;
371
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800372 // Let the main thread know we're running.
373 pthread_mutex_unlock(&data->mutex);
374
375 // And wait for the main thread to exit.
Evgenii Stepanov352853a2019-02-05 17:37:37 -0800376 pthread_join(main_thread, nullptr);
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800377
Yi Kong32bc0fc2018-08-02 17:31:13 -0700378 return nullptr;
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800379 }
380};
Elliott Hughes4f251be2012-11-01 16:33:29 -0700381
Elliott Hughes7fd803c2013-02-14 16:33:52 -0800382// Even though this isn't really a death test, we have to say "DeathTest" here so gtest knows to
383// run this test (which exits normally) in its own process.
Yabin Cui9df70402014-11-05 18:01:01 -0800384TEST_F(pthread_DeathTest, pthread_bug_37410) {
Elliott Hughes4f251be2012-11-01 16:33:29 -0700385 // http://code.google.com/p/android/issues/detail?id=37410
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800386 ASSERT_EXIT(TestBug37410::main(), ::testing::ExitedWithCode(0), "");
Elliott Hughes4f251be2012-11-01 16:33:29 -0700387}
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800388
389static void* SignalHandlerFn(void* arg) {
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800390 sigset64_t wait_set;
391 sigfillset64(&wait_set);
392 return reinterpret_cast<void*>(sigwait64(&wait_set, reinterpret_cast<int*>(arg)));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800393}
394
395TEST(pthread, pthread_sigmask) {
Elliott Hughes19e62322013-10-15 11:23:57 -0700396 // Check that SIGUSR1 isn't blocked.
397 sigset_t original_set;
398 sigemptyset(&original_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700399 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, nullptr, &original_set));
Elliott Hughes19e62322013-10-15 11:23:57 -0700400 ASSERT_FALSE(sigismember(&original_set, SIGUSR1));
401
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800402 // Block SIGUSR1.
403 sigset_t set;
404 sigemptyset(&set);
405 sigaddset(&set, SIGUSR1);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700406 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, &set, nullptr));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800407
Elliott Hughes19e62322013-10-15 11:23:57 -0700408 // Check that SIGUSR1 is blocked.
409 sigset_t final_set;
410 sigemptyset(&final_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700411 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, nullptr, &final_set));
Elliott Hughes19e62322013-10-15 11:23:57 -0700412 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
413 // ...and that sigprocmask agrees with pthread_sigmask.
414 sigemptyset(&final_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700415 ASSERT_EQ(0, sigprocmask(SIG_BLOCK, nullptr, &final_set));
Elliott Hughes19e62322013-10-15 11:23:57 -0700416 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
417
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800418 // Spawn a thread that calls sigwait and tells us what it received.
419 pthread_t signal_thread;
420 int received_signal = -1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700421 ASSERT_EQ(0, pthread_create(&signal_thread, nullptr, SignalHandlerFn, &received_signal));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800422
423 // Send that thread SIGUSR1.
424 pthread_kill(signal_thread, SIGUSR1);
425
426 // See what it got.
427 void* join_result;
428 ASSERT_EQ(0, pthread_join(signal_thread, &join_result));
429 ASSERT_EQ(SIGUSR1, received_signal);
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700430 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
Elliott Hughes19e62322013-10-15 11:23:57 -0700431
432 // Restore the original signal mask.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700433 ASSERT_EQ(0, pthread_sigmask(SIG_SETMASK, &original_set, nullptr));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800434}
Elliott Hughes5e3fc432013-02-11 16:36:48 -0800435
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800436TEST(pthread, pthread_sigmask64_SIGTRMIN) {
437 // Check that SIGRTMIN isn't blocked.
438 sigset64_t original_set;
439 sigemptyset64(&original_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700440 ASSERT_EQ(0, pthread_sigmask64(SIG_BLOCK, nullptr, &original_set));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800441 ASSERT_FALSE(sigismember64(&original_set, SIGRTMIN));
442
443 // Block SIGRTMIN.
444 sigset64_t set;
445 sigemptyset64(&set);
446 sigaddset64(&set, SIGRTMIN);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700447 ASSERT_EQ(0, pthread_sigmask64(SIG_BLOCK, &set, nullptr));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800448
449 // Check that SIGRTMIN is blocked.
450 sigset64_t final_set;
451 sigemptyset64(&final_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700452 ASSERT_EQ(0, pthread_sigmask64(SIG_BLOCK, nullptr, &final_set));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800453 ASSERT_TRUE(sigismember64(&final_set, SIGRTMIN));
454 // ...and that sigprocmask64 agrees with pthread_sigmask64.
455 sigemptyset64(&final_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700456 ASSERT_EQ(0, sigprocmask64(SIG_BLOCK, nullptr, &final_set));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800457 ASSERT_TRUE(sigismember64(&final_set, SIGRTMIN));
458
459 // Spawn a thread that calls sigwait64 and tells us what it received.
460 pthread_t signal_thread;
461 int received_signal = -1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700462 ASSERT_EQ(0, pthread_create(&signal_thread, nullptr, SignalHandlerFn, &received_signal));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800463
464 // Send that thread SIGRTMIN.
465 pthread_kill(signal_thread, SIGRTMIN);
466
467 // See what it got.
468 void* join_result;
469 ASSERT_EQ(0, pthread_join(signal_thread, &join_result));
470 ASSERT_EQ(SIGRTMIN, received_signal);
471 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
472
473 // Restore the original signal mask.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700474 ASSERT_EQ(0, pthread_sigmask64(SIG_SETMASK, &original_set, nullptr));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800475}
476
Elliott Hughes725b2a92016-03-23 11:20:47 -0700477static void test_pthread_setname_np__pthread_getname_np(pthread_t t) {
478 ASSERT_EQ(0, pthread_setname_np(t, "short"));
479 char name[32];
480 ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name)));
481 ASSERT_STREQ("short", name);
482
Elliott Hughesd1aea302015-04-25 10:05:24 -0700483 // The limit is 15 characters --- the kernel's buffer is 16, but includes a NUL.
Elliott Hughes725b2a92016-03-23 11:20:47 -0700484 ASSERT_EQ(0, pthread_setname_np(t, "123456789012345"));
485 ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name)));
486 ASSERT_STREQ("123456789012345", name);
487
488 ASSERT_EQ(ERANGE, pthread_setname_np(t, "1234567890123456"));
489
490 // The passed-in buffer should be at least 16 bytes.
491 ASSERT_EQ(0, pthread_getname_np(t, name, 16));
492 ASSERT_EQ(ERANGE, pthread_getname_np(t, name, 15));
Elliott Hughes3e898472013-02-12 16:40:24 +0000493}
494
Elliott Hughes725b2a92016-03-23 11:20:47 -0700495TEST(pthread, pthread_setname_np__pthread_getname_np__self) {
496 test_pthread_setname_np__pthread_getname_np(pthread_self());
Elliott Hughes3e898472013-02-12 16:40:24 +0000497}
498
Elliott Hughes725b2a92016-03-23 11:20:47 -0700499TEST(pthread, pthread_setname_np__pthread_getname_np__other) {
500 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800501
Elliott Hughes725b2a92016-03-23 11:20:47 -0700502 pthread_t t;
Elliott Hughes4d098ca2016-04-11 12:43:05 -0700503 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
504 test_pthread_setname_np__pthread_getname_np(t);
505 spin_helper.UnSpin();
506 ASSERT_EQ(0, pthread_join(t, nullptr));
507}
508
509// http://b/28051133: a kernel misfeature means that you can't change the
510// name of another thread if you've set PR_SET_DUMPABLE to 0.
511TEST(pthread, pthread_setname_np__pthread_getname_np__other_PR_SET_DUMPABLE) {
512 ASSERT_EQ(0, prctl(PR_SET_DUMPABLE, 0)) << strerror(errno);
513
514 SpinFunctionHelper spin_helper;
515
516 pthread_t t;
517 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
Elliott Hughes725b2a92016-03-23 11:20:47 -0700518 test_pthread_setname_np__pthread_getname_np(t);
519 spin_helper.UnSpin();
520 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes3e898472013-02-12 16:40:24 +0000521}
522
Elliott Hughes11859d42017-02-13 17:59:29 -0800523TEST_F(pthread_DeathTest, pthread_setname_np__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000524 pthread_t dead_thread;
525 MakeDeadThread(dead_thread);
526
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800527 EXPECT_DEATH(pthread_setname_np(dead_thread, "short 3"),
528 "invalid pthread_t (.*) passed to pthread_setname_np");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800529}
530
531TEST_F(pthread_DeathTest, pthread_setname_np__null_thread) {
532 pthread_t null_thread = 0;
533 EXPECT_EQ(ENOENT, pthread_setname_np(null_thread, "short 3"));
Elliott Hughes11859d42017-02-13 17:59:29 -0800534}
535
536TEST_F(pthread_DeathTest, pthread_getname_np__no_such_thread) {
537 pthread_t dead_thread;
538 MakeDeadThread(dead_thread);
539
Elliott Hughesbcb15292017-02-07 21:05:30 +0000540 char name[64];
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800541 EXPECT_DEATH(pthread_getname_np(dead_thread, name, sizeof(name)),
542 "invalid pthread_t (.*) passed to pthread_getname_np");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800543}
544
545TEST_F(pthread_DeathTest, pthread_getname_np__null_thread) {
546 pthread_t null_thread = 0;
547
548 char name[64];
549 EXPECT_EQ(ENOENT, pthread_getname_np(null_thread, name, sizeof(name)));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000550}
551
Elliott Hughes9d23e042013-02-15 19:21:51 -0800552TEST(pthread, pthread_kill__0) {
553 // Signal 0 just tests that the thread exists, so it's safe to call on ourselves.
554 ASSERT_EQ(0, pthread_kill(pthread_self(), 0));
555}
556
557TEST(pthread, pthread_kill__invalid_signal) {
558 ASSERT_EQ(EINVAL, pthread_kill(pthread_self(), -1));
559}
560
Elliott Hughesfae89fc2013-02-21 11:22:23 -0800561static void pthread_kill__in_signal_handler_helper(int signal_number) {
562 static int count = 0;
563 ASSERT_EQ(SIGALRM, signal_number);
564 if (++count == 1) {
565 // Can we call pthread_kill from a signal handler?
566 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
567 }
568}
569
570TEST(pthread, pthread_kill__in_signal_handler) {
Elliott Hughes4b558f52014-03-04 15:58:02 -0800571 ScopedSignalHandler ssh(SIGALRM, pthread_kill__in_signal_handler_helper);
Elliott Hughesfae89fc2013-02-21 11:22:23 -0800572 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
573}
574
Josh Gaoddf757e2018-10-17 15:23:03 -0700575TEST(pthread, pthread_kill__exited_thread) {
576 static std::promise<pid_t> tid_promise;
577 pthread_t thread;
578 ASSERT_EQ(0, pthread_create(&thread, nullptr,
579 [](void*) -> void* {
580 tid_promise.set_value(gettid());
581 return nullptr;
582 },
583 nullptr));
584
585 pid_t tid = tid_promise.get_future().get();
586 while (TEMP_FAILURE_RETRY(syscall(__NR_tgkill, getpid(), tid, 0)) != -1) {
587 continue;
588 }
Elliott Hughes95646e62023-09-21 14:11:19 -0700589 ASSERT_ERRNO(ESRCH);
Josh Gaoddf757e2018-10-17 15:23:03 -0700590
591 ASSERT_EQ(ESRCH, pthread_kill(thread, 0));
592}
593
Elliott Hughes11859d42017-02-13 17:59:29 -0800594TEST_F(pthread_DeathTest, pthread_detach__no_such_thread) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000595 pthread_t dead_thread;
596 MakeDeadThread(dead_thread);
597
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800598 EXPECT_DEATH(pthread_detach(dead_thread),
599 "invalid pthread_t (.*) passed to pthread_detach");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800600}
601
602TEST_F(pthread_DeathTest, pthread_detach__null_thread) {
603 pthread_t null_thread = 0;
604 EXPECT_EQ(ESRCH, pthread_detach(null_thread));
Elliott Hughes7484c212017-02-02 02:41:38 +0000605}
606
Jeff Hao9b06cc32013-08-15 14:51:16 -0700607TEST(pthread, pthread_getcpuclockid__clock_gettime) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700608 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800609
Jeff Hao9b06cc32013-08-15 14:51:16 -0700610 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700611 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
Jeff Hao9b06cc32013-08-15 14:51:16 -0700612
613 clockid_t c;
614 ASSERT_EQ(0, pthread_getcpuclockid(t, &c));
615 timespec ts;
616 ASSERT_EQ(0, clock_gettime(c, &ts));
Elliott Hughes725b2a92016-03-23 11:20:47 -0700617 spin_helper.UnSpin();
Yabin Cuia36158a2015-11-16 21:06:16 -0800618 ASSERT_EQ(0, pthread_join(t, nullptr));
Jeff Hao9b06cc32013-08-15 14:51:16 -0700619}
620
Elliott Hughes11859d42017-02-13 17:59:29 -0800621TEST_F(pthread_DeathTest, pthread_getcpuclockid__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000622 pthread_t dead_thread;
623 MakeDeadThread(dead_thread);
624
625 clockid_t c;
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800626 EXPECT_DEATH(pthread_getcpuclockid(dead_thread, &c),
627 "invalid pthread_t (.*) passed to pthread_getcpuclockid");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800628}
629
630TEST_F(pthread_DeathTest, pthread_getcpuclockid__null_thread) {
631 pthread_t null_thread = 0;
632 clockid_t c;
633 EXPECT_EQ(ESRCH, pthread_getcpuclockid(null_thread, &c));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000634}
635
Elliott Hughes11859d42017-02-13 17:59:29 -0800636TEST_F(pthread_DeathTest, pthread_getschedparam__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000637 pthread_t dead_thread;
638 MakeDeadThread(dead_thread);
639
640 int policy;
641 sched_param param;
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800642 EXPECT_DEATH(pthread_getschedparam(dead_thread, &policy, &param),
643 "invalid pthread_t (.*) passed to pthread_getschedparam");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800644}
645
646TEST_F(pthread_DeathTest, pthread_getschedparam__null_thread) {
647 pthread_t null_thread = 0;
648 int policy;
649 sched_param param;
650 EXPECT_EQ(ESRCH, pthread_getschedparam(null_thread, &policy, &param));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000651}
652
Elliott Hughes11859d42017-02-13 17:59:29 -0800653TEST_F(pthread_DeathTest, pthread_setschedparam__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000654 pthread_t dead_thread;
655 MakeDeadThread(dead_thread);
656
657 int policy = 0;
658 sched_param param;
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800659 EXPECT_DEATH(pthread_setschedparam(dead_thread, policy, &param),
660 "invalid pthread_t (.*) passed to pthread_setschedparam");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800661}
662
663TEST_F(pthread_DeathTest, pthread_setschedparam__null_thread) {
664 pthread_t null_thread = 0;
665 int policy = 0;
666 sched_param param;
667 EXPECT_EQ(ESRCH, pthread_setschedparam(null_thread, policy, &param));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000668}
669
Elliott Hughesdff08ce2017-10-16 09:58:45 -0700670TEST_F(pthread_DeathTest, pthread_setschedprio__no_such_thread) {
671 pthread_t dead_thread;
672 MakeDeadThread(dead_thread);
673
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800674 EXPECT_DEATH(pthread_setschedprio(dead_thread, 123),
675 "invalid pthread_t (.*) passed to pthread_setschedprio");
Elliott Hughesdff08ce2017-10-16 09:58:45 -0700676}
677
678TEST_F(pthread_DeathTest, pthread_setschedprio__null_thread) {
679 pthread_t null_thread = 0;
680 EXPECT_EQ(ESRCH, pthread_setschedprio(null_thread, 123));
681}
682
Elliott Hughes11859d42017-02-13 17:59:29 -0800683TEST_F(pthread_DeathTest, pthread_join__no_such_thread) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000684 pthread_t dead_thread;
685 MakeDeadThread(dead_thread);
686
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800687 EXPECT_DEATH(pthread_join(dead_thread, nullptr),
688 "invalid pthread_t (.*) passed to pthread_join");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800689}
690
691TEST_F(pthread_DeathTest, pthread_join__null_thread) {
692 pthread_t null_thread = 0;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700693 EXPECT_EQ(ESRCH, pthread_join(null_thread, nullptr));
Elliott Hughes7484c212017-02-02 02:41:38 +0000694}
695
Elliott Hughes11859d42017-02-13 17:59:29 -0800696TEST_F(pthread_DeathTest, pthread_kill__no_such_thread) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000697 pthread_t dead_thread;
698 MakeDeadThread(dead_thread);
699
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800700 EXPECT_DEATH(pthread_kill(dead_thread, 0),
701 "invalid pthread_t (.*) passed to pthread_kill");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800702}
703
704TEST_F(pthread_DeathTest, pthread_kill__null_thread) {
705 pthread_t null_thread = 0;
706 EXPECT_EQ(ESRCH, pthread_kill(null_thread, 0));
Elliott Hughes7484c212017-02-02 02:41:38 +0000707}
708
msg5550f020d12013-06-06 14:59:28 -0400709TEST(pthread, pthread_join__multijoin) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700710 SpinFunctionHelper spin_helper;
msg5550f020d12013-06-06 14:59:28 -0400711
712 pthread_t t1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700713 ASSERT_EQ(0, pthread_create(&t1, nullptr, spin_helper.GetFunction(), nullptr));
msg5550f020d12013-06-06 14:59:28 -0400714
715 pthread_t t2;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700716 ASSERT_EQ(0, pthread_create(&t2, nullptr, JoinFn, reinterpret_cast<void*>(t1)));
msg5550f020d12013-06-06 14:59:28 -0400717
718 sleep(1); // (Give t2 a chance to call pthread_join.)
719
720 // Multiple joins to the same thread should fail.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700721 ASSERT_EQ(EINVAL, pthread_join(t1, nullptr));
msg5550f020d12013-06-06 14:59:28 -0400722
Elliott Hughes725b2a92016-03-23 11:20:47 -0700723 spin_helper.UnSpin();
msg5550f020d12013-06-06 14:59:28 -0400724
725 // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes).
726 void* join_result;
727 ASSERT_EQ(0, pthread_join(t2, &join_result));
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700728 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
msg5550f020d12013-06-06 14:59:28 -0400729}
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700730
Elliott Hughes70b24b12013-11-15 11:51:07 -0800731TEST(pthread, pthread_join__race) {
732 // http://b/11693195 --- pthread_join could return before the thread had actually exited.
733 // If the joiner unmapped the thread's stack, that could lead to SIGSEGV in the thread.
734 for (size_t i = 0; i < 1024; ++i) {
Yabin Cuia36158a2015-11-16 21:06:16 -0800735 size_t stack_size = 640*1024;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700736 void* stack = mmap(nullptr, stack_size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
Elliott Hughes70b24b12013-11-15 11:51:07 -0800737
738 pthread_attr_t a;
739 pthread_attr_init(&a);
740 pthread_attr_setstack(&a, stack, stack_size);
741
742 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700743 ASSERT_EQ(0, pthread_create(&t, &a, IdFn, nullptr));
744 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes70b24b12013-11-15 11:51:07 -0800745 ASSERT_EQ(0, munmap(stack, stack_size));
746 }
747}
748
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700749static void* GetActualGuardSizeFn(void* arg) {
750 pthread_attr_t attributes;
751 pthread_getattr_np(pthread_self(), &attributes);
752 pthread_attr_getguardsize(&attributes, reinterpret_cast<size_t*>(arg));
Yi Kong32bc0fc2018-08-02 17:31:13 -0700753 return nullptr;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700754}
755
756static size_t GetActualGuardSize(const pthread_attr_t& attributes) {
757 size_t result;
758 pthread_t t;
759 pthread_create(&t, &attributes, GetActualGuardSizeFn, &result);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700760 pthread_join(t, nullptr);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700761 return result;
762}
763
764static void* GetActualStackSizeFn(void* arg) {
765 pthread_attr_t attributes;
766 pthread_getattr_np(pthread_self(), &attributes);
767 pthread_attr_getstacksize(&attributes, reinterpret_cast<size_t*>(arg));
Yi Kong32bc0fc2018-08-02 17:31:13 -0700768 return nullptr;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700769}
770
771static size_t GetActualStackSize(const pthread_attr_t& attributes) {
772 size_t result;
773 pthread_t t;
774 pthread_create(&t, &attributes, GetActualStackSizeFn, &result);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700775 pthread_join(t, nullptr);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700776 return result;
777}
778
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700779TEST(pthread, pthread_attr_setguardsize_tiny) {
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700780 pthread_attr_t attributes;
781 ASSERT_EQ(0, pthread_attr_init(&attributes));
782
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700783 // No such thing as too small: will be rounded up to one page by pthread_create.
784 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 128));
785 size_t guard_size;
786 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
787 ASSERT_EQ(128U, guard_size);
Juan Yescas65af9a82023-12-07 11:35:21 -0800788 ASSERT_EQ(static_cast<unsigned long>(getpagesize()), GetActualGuardSize(attributes));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700789}
790
791TEST(pthread, pthread_attr_setguardsize_reasonable) {
792 pthread_attr_t attributes;
793 ASSERT_EQ(0, pthread_attr_init(&attributes));
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700794
795 // Large enough and a multiple of the page size.
796 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700797 size_t guard_size;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700798 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
799 ASSERT_EQ(32*1024U, guard_size);
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700800 ASSERT_EQ(32*1024U, GetActualGuardSize(attributes));
801}
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700802
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700803TEST(pthread, pthread_attr_setguardsize_needs_rounding) {
804 pthread_attr_t attributes;
805 ASSERT_EQ(0, pthread_attr_init(&attributes));
806
807 // Large enough but not a multiple of the page size.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700808 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024 + 1));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700809 size_t guard_size;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700810 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
811 ASSERT_EQ(32*1024U + 1, guard_size);
Juan Yescas65af9a82023-12-07 11:35:21 -0800812 ASSERT_EQ(roundup(32 * 1024U + 1, getpagesize()), GetActualGuardSize(attributes));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700813}
814
815TEST(pthread, pthread_attr_setguardsize_enormous) {
816 pthread_attr_t attributes;
817 ASSERT_EQ(0, pthread_attr_init(&attributes));
818
819 // Larger than the stack itself. (Historically we mistakenly carved
820 // the guard out of the stack itself, rather than adding it after the
821 // end.)
822 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024*1024));
823 size_t guard_size;
824 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
825 ASSERT_EQ(32*1024*1024U, guard_size);
826 ASSERT_EQ(32*1024*1024U, GetActualGuardSize(attributes));
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700827}
828
829TEST(pthread, pthread_attr_setstacksize) {
830 pthread_attr_t attributes;
831 ASSERT_EQ(0, pthread_attr_init(&attributes));
832
833 // Get the default stack size.
834 size_t default_stack_size;
835 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &default_stack_size));
836
837 // Too small.
838 ASSERT_EQ(EINVAL, pthread_attr_setstacksize(&attributes, 128));
839 size_t stack_size;
840 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
841 ASSERT_EQ(default_stack_size, stack_size);
842 ASSERT_GE(GetActualStackSize(attributes), default_stack_size);
843
Yabin Cui917d3902015-01-08 12:32:42 -0800844 // Large enough and a multiple of the page size; may be rounded up by pthread_create.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700845 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024));
846 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
847 ASSERT_EQ(32*1024U, stack_size);
Yabin Cui917d3902015-01-08 12:32:42 -0800848 ASSERT_GE(GetActualStackSize(attributes), 32*1024U);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700849
Yabin Cui917d3902015-01-08 12:32:42 -0800850 // Large enough but not aligned; will be rounded up by pthread_create.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700851 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024 + 1));
852 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
853 ASSERT_EQ(32*1024U + 1, stack_size);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800854#if defined(__BIONIC__)
Yabin Cui917d3902015-01-08 12:32:42 -0800855 ASSERT_GT(GetActualStackSize(attributes), 32*1024U + 1);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800856#else // __BIONIC__
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700857 // glibc rounds down, in violation of POSIX. They document this in their BUGS section.
858 ASSERT_EQ(GetActualStackSize(attributes), 32*1024U);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800859#endif // __BIONIC__
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700860}
Elliott Hughesc3f11402013-10-30 14:40:09 -0700861
Yabin Cui76615da2015-03-17 14:22:09 -0700862TEST(pthread, pthread_rwlockattr_smoke) {
863 pthread_rwlockattr_t attr;
864 ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
865
866 int pshared_value_array[] = {PTHREAD_PROCESS_PRIVATE, PTHREAD_PROCESS_SHARED};
867 for (size_t i = 0; i < sizeof(pshared_value_array) / sizeof(pshared_value_array[0]); ++i) {
868 ASSERT_EQ(0, pthread_rwlockattr_setpshared(&attr, pshared_value_array[i]));
869 int pshared;
870 ASSERT_EQ(0, pthread_rwlockattr_getpshared(&attr, &pshared));
871 ASSERT_EQ(pshared_value_array[i], pshared);
872 }
873
Colin Cross4c5595c2021-08-16 15:51:59 -0700874#if !defined(ANDROID_HOST_MUSL)
Colin Cross7da20342021-07-28 11:18:11 -0700875 // musl doesn't have pthread_rwlockattr_setkind_np
Yabin Cui76615da2015-03-17 14:22:09 -0700876 int kind_array[] = {PTHREAD_RWLOCK_PREFER_READER_NP,
877 PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP};
878 for (size_t i = 0; i < sizeof(kind_array) / sizeof(kind_array[0]); ++i) {
879 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_array[i]));
880 int kind;
881 ASSERT_EQ(0, pthread_rwlockattr_getkind_np(&attr, &kind));
882 ASSERT_EQ(kind_array[i], kind);
883 }
Colin Cross7da20342021-07-28 11:18:11 -0700884#endif
Yabin Cui76615da2015-03-17 14:22:09 -0700885
886 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
887}
888
889TEST(pthread, pthread_rwlock_init_same_as_PTHREAD_RWLOCK_INITIALIZER) {
890 pthread_rwlock_t lock1 = PTHREAD_RWLOCK_INITIALIZER;
891 pthread_rwlock_t lock2;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700892 ASSERT_EQ(0, pthread_rwlock_init(&lock2, nullptr));
Yabin Cui76615da2015-03-17 14:22:09 -0700893 ASSERT_EQ(0, memcmp(&lock1, &lock2, sizeof(lock1)));
894}
895
Elliott Hughesc3f11402013-10-30 14:40:09 -0700896TEST(pthread, pthread_rwlock_smoke) {
897 pthread_rwlock_t l;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700898 ASSERT_EQ(0, pthread_rwlock_init(&l, nullptr));
Elliott Hughesc3f11402013-10-30 14:40:09 -0700899
Calin Juravle76f352e2014-05-19 13:41:10 +0100900 // Single read lock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700901 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
902 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
903
Calin Juravle76f352e2014-05-19 13:41:10 +0100904 // Multiple read lock
905 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
906 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
907 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
908 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
909
910 // Write lock
Calin Juravle92687e42014-05-22 19:21:22 +0100911 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
912 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100913
914 // Try writer lock
915 ASSERT_EQ(0, pthread_rwlock_trywrlock(&l));
916 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
917 ASSERT_EQ(EBUSY, pthread_rwlock_tryrdlock(&l));
918 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
919
920 // Try reader lock
921 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
922 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
923 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
924 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
925 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
926
927 // Try writer lock after unlock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700928 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
929 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
930
Calin Juravle76f352e2014-05-19 13:41:10 +0100931 // EDEADLK in "read after write"
932 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
933 ASSERT_EQ(EDEADLK, pthread_rwlock_rdlock(&l));
934 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
935
936 // EDEADLK in "write after write"
937 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
938 ASSERT_EQ(EDEADLK, pthread_rwlock_wrlock(&l));
939 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100940
Elliott Hughesc3f11402013-10-30 14:40:09 -0700941 ASSERT_EQ(0, pthread_rwlock_destroy(&l));
942}
943
Yabin Cui08ee8d22015-02-11 17:04:36 -0800944struct RwlockWakeupHelperArg {
945 pthread_rwlock_t lock;
946 enum Progress {
947 LOCK_INITIALIZED,
948 LOCK_WAITING,
949 LOCK_RELEASED,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800950 LOCK_ACCESSED,
951 LOCK_TIMEDOUT,
Yabin Cui08ee8d22015-02-11 17:04:36 -0800952 };
953 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -0700954 std::atomic<pid_t> tid;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800955 std::function<int (pthread_rwlock_t*)> trylock_function;
956 std::function<int (pthread_rwlock_t*)> lock_function;
957 std::function<int (pthread_rwlock_t*, const timespec*)> timed_lock_function;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -0800958 clockid_t clock;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800959};
960
Yabin Cuic9a659c2015-11-05 15:36:08 -0800961static void pthread_rwlock_wakeup_helper(RwlockWakeupHelperArg* arg) {
Yabin Cuif7969852015-04-02 17:47:48 -0700962 arg->tid = gettid();
Yabin Cui08ee8d22015-02-11 17:04:36 -0800963 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
964 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
965
Yabin Cuic9a659c2015-11-05 15:36:08 -0800966 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
967 ASSERT_EQ(0, arg->lock_function(&arg->lock));
Yabin Cui08ee8d22015-02-11 17:04:36 -0800968 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_RELEASED, arg->progress);
969 ASSERT_EQ(0, pthread_rwlock_unlock(&arg->lock));
970
971 arg->progress = RwlockWakeupHelperArg::LOCK_ACCESSED;
972}
973
Yabin Cuic9a659c2015-11-05 15:36:08 -0800974static void test_pthread_rwlock_reader_wakeup_writer(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -0800975 RwlockWakeupHelperArg wakeup_arg;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700976 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -0800977 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
978 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -0700979 wakeup_arg.tid = 0;
Tom Cherry60ddedf2018-02-20 15:40:02 -0800980 wakeup_arg.trylock_function = &pthread_rwlock_trywrlock;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800981 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800982
983 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700984 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800985 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -0700986 WaitUntilThreadSleep(wakeup_arg.tid);
987 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
988
Yabin Cui08ee8d22015-02-11 17:04:36 -0800989 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
990 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
991
Yi Kong32bc0fc2018-08-02 17:31:13 -0700992 ASSERT_EQ(0, pthread_join(thread, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -0800993 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
994 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
995}
996
Yabin Cuic9a659c2015-11-05 15:36:08 -0800997TEST(pthread, pthread_rwlock_reader_wakeup_writer) {
998 test_pthread_rwlock_reader_wakeup_writer(pthread_rwlock_wrlock);
Yabin Cui08ee8d22015-02-11 17:04:36 -0800999}
1000
Yabin Cuic9a659c2015-11-05 15:36:08 -08001001TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait) {
1002 timespec ts;
1003 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1004 ts.tv_sec += 1;
1005 test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) {
1006 return pthread_rwlock_timedwrlock(lock, &ts);
1007 });
1008}
1009
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001010TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait_monotonic_np) {
1011#if defined(__BIONIC__)
1012 timespec ts;
1013 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1014 ts.tv_sec += 1;
1015 test_pthread_rwlock_reader_wakeup_writer(
1016 [&](pthread_rwlock_t* lock) { return pthread_rwlock_timedwrlock_monotonic_np(lock, &ts); });
1017#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001018 GTEST_SKIP() << "pthread_rwlock_timedwrlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001019#endif // __BIONIC__
1020}
1021
Tom Cherry69010802019-05-07 20:33:05 -07001022TEST(pthread, pthread_rwlock_reader_wakeup_writer_clockwait) {
1023#if defined(__BIONIC__)
1024 timespec ts;
1025 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1026 ts.tv_sec += 1;
1027 test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) {
1028 return pthread_rwlock_clockwrlock(lock, CLOCK_MONOTONIC, &ts);
1029 });
1030
1031 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1032 ts.tv_sec += 1;
1033 test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) {
1034 return pthread_rwlock_clockwrlock(lock, CLOCK_REALTIME, &ts);
1035 });
1036#else // __BIONIC__
1037 GTEST_SKIP() << "pthread_rwlock_clockwrlock not available";
1038#endif // __BIONIC__
1039}
1040
Yabin Cuic9a659c2015-11-05 15:36:08 -08001041static void test_pthread_rwlock_writer_wakeup_reader(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -08001042 RwlockWakeupHelperArg wakeup_arg;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001043 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -08001044 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
1045 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -07001046 wakeup_arg.tid = 0;
Tom Cherry60ddedf2018-02-20 15:40:02 -08001047 wakeup_arg.trylock_function = &pthread_rwlock_tryrdlock;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001048 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -08001049
1050 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001051 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cuic9a659c2015-11-05 15:36:08 -08001052 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -07001053 WaitUntilThreadSleep(wakeup_arg.tid);
1054 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
1055
Yabin Cui08ee8d22015-02-11 17:04:36 -08001056 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
1057 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
1058
Yi Kong32bc0fc2018-08-02 17:31:13 -07001059 ASSERT_EQ(0, pthread_join(thread, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -08001060 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
1061 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
1062}
1063
Yabin Cuic9a659c2015-11-05 15:36:08 -08001064TEST(pthread, pthread_rwlock_writer_wakeup_reader) {
1065 test_pthread_rwlock_writer_wakeup_reader(pthread_rwlock_rdlock);
1066}
1067
1068TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait) {
1069 timespec ts;
1070 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1071 ts.tv_sec += 1;
1072 test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) {
1073 return pthread_rwlock_timedrdlock(lock, &ts);
1074 });
1075}
1076
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001077TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait_monotonic_np) {
1078#if defined(__BIONIC__)
1079 timespec ts;
1080 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1081 ts.tv_sec += 1;
1082 test_pthread_rwlock_writer_wakeup_reader(
1083 [&](pthread_rwlock_t* lock) { return pthread_rwlock_timedrdlock_monotonic_np(lock, &ts); });
1084#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001085 GTEST_SKIP() << "pthread_rwlock_timedrdlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001086#endif // __BIONIC__
1087}
1088
Tom Cherry69010802019-05-07 20:33:05 -07001089TEST(pthread, pthread_rwlock_writer_wakeup_reader_clockwait) {
1090#if defined(__BIONIC__)
1091 timespec ts;
1092 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1093 ts.tv_sec += 1;
1094 test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) {
1095 return pthread_rwlock_clockrdlock(lock, CLOCK_MONOTONIC, &ts);
1096 });
1097
1098 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1099 ts.tv_sec += 1;
1100 test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) {
1101 return pthread_rwlock_clockrdlock(lock, CLOCK_REALTIME, &ts);
1102 });
1103#else // __BIONIC__
1104 GTEST_SKIP() << "pthread_rwlock_clockrdlock not available";
1105#endif // __BIONIC__
1106}
1107
Yabin Cuic9a659c2015-11-05 15:36:08 -08001108static void pthread_rwlock_wakeup_timeout_helper(RwlockWakeupHelperArg* arg) {
1109 arg->tid = gettid();
1110 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
1111 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
1112
1113 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
1114
1115 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001116 ASSERT_EQ(0, clock_gettime(arg->clock, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001117 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
1118 ts.tv_nsec = -1;
1119 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
1120 ts.tv_nsec = NS_PER_S;
1121 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
1122 ts.tv_nsec = NS_PER_S - 1;
1123 ts.tv_sec = -1;
1124 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001125 ASSERT_EQ(0, clock_gettime(arg->clock, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001126 ts.tv_sec += 1;
1127 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
1128 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, arg->progress);
1129 arg->progress = RwlockWakeupHelperArg::LOCK_TIMEDOUT;
1130}
1131
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001132static void pthread_rwlock_timedrdlock_timeout_helper(
1133 clockid_t clock, int (*lock_function)(pthread_rwlock_t* __rwlock, const timespec* __timeout)) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001134 RwlockWakeupHelperArg wakeup_arg;
1135 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
1136 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
1137 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
1138 wakeup_arg.tid = 0;
Tom Cherry60ddedf2018-02-20 15:40:02 -08001139 wakeup_arg.trylock_function = &pthread_rwlock_tryrdlock;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001140 wakeup_arg.timed_lock_function = lock_function;
1141 wakeup_arg.clock = clock;
1142
1143 pthread_t thread;
1144 ASSERT_EQ(0, pthread_create(&thread, nullptr,
1145 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
1146 WaitUntilThreadSleep(wakeup_arg.tid);
1147 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
1148
1149 ASSERT_EQ(0, pthread_join(thread, nullptr));
1150 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
1151 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
1152 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
1153}
1154
1155TEST(pthread, pthread_rwlock_timedrdlock_timeout) {
1156 pthread_rwlock_timedrdlock_timeout_helper(CLOCK_REALTIME, pthread_rwlock_timedrdlock);
1157}
1158
1159TEST(pthread, pthread_rwlock_timedrdlock_monotonic_np_timeout) {
1160#if defined(__BIONIC__)
1161 pthread_rwlock_timedrdlock_timeout_helper(CLOCK_MONOTONIC,
1162 pthread_rwlock_timedrdlock_monotonic_np);
1163#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001164 GTEST_SKIP() << "pthread_rwlock_timedrdlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001165#endif // __BIONIC__
1166}
1167
Tom Cherry69010802019-05-07 20:33:05 -07001168TEST(pthread, pthread_rwlock_clockrdlock_monotonic_timeout) {
1169#if defined(__BIONIC__)
1170 pthread_rwlock_timedrdlock_timeout_helper(
1171 CLOCK_MONOTONIC, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) {
1172 return pthread_rwlock_clockrdlock(__rwlock, CLOCK_MONOTONIC, __timeout);
1173 });
1174#else // __BIONIC__
1175 GTEST_SKIP() << "pthread_rwlock_clockrdlock not available";
1176#endif // __BIONIC__
1177}
1178
1179TEST(pthread, pthread_rwlock_clockrdlock_realtime_timeout) {
1180#if defined(__BIONIC__)
1181 pthread_rwlock_timedrdlock_timeout_helper(
1182 CLOCK_REALTIME, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) {
1183 return pthread_rwlock_clockrdlock(__rwlock, CLOCK_REALTIME, __timeout);
1184 });
1185#else // __BIONIC__
1186 GTEST_SKIP() << "pthread_rwlock_clockrdlock not available";
1187#endif // __BIONIC__
1188}
1189
1190TEST(pthread, pthread_rwlock_clockrdlock_invalid) {
1191#if defined(__BIONIC__)
1192 pthread_rwlock_t lock = PTHREAD_RWLOCK_INITIALIZER;
1193 timespec ts;
1194 EXPECT_EQ(EINVAL, pthread_rwlock_clockrdlock(&lock, CLOCK_PROCESS_CPUTIME_ID, &ts));
1195#else // __BIONIC__
1196 GTEST_SKIP() << "pthread_rwlock_clockrdlock not available";
1197#endif // __BIONIC__
1198}
1199
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001200static void pthread_rwlock_timedwrlock_timeout_helper(
1201 clockid_t clock, int (*lock_function)(pthread_rwlock_t* __rwlock, const timespec* __timeout)) {
1202 RwlockWakeupHelperArg wakeup_arg;
1203 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
1204 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
1205 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
1206 wakeup_arg.tid = 0;
1207 wakeup_arg.trylock_function = &pthread_rwlock_trywrlock;
1208 wakeup_arg.timed_lock_function = lock_function;
1209 wakeup_arg.clock = clock;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001210
1211 pthread_t thread;
1212 ASSERT_EQ(0, pthread_create(&thread, nullptr,
1213 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
1214 WaitUntilThreadSleep(wakeup_arg.tid);
1215 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
1216
1217 ASSERT_EQ(0, pthread_join(thread, nullptr));
1218 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
1219 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
1220 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
1221}
1222
1223TEST(pthread, pthread_rwlock_timedwrlock_timeout) {
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001224 pthread_rwlock_timedwrlock_timeout_helper(CLOCK_REALTIME, pthread_rwlock_timedwrlock);
1225}
Yabin Cuic9a659c2015-11-05 15:36:08 -08001226
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001227TEST(pthread, pthread_rwlock_timedwrlock_monotonic_np_timeout) {
1228#if defined(__BIONIC__)
1229 pthread_rwlock_timedwrlock_timeout_helper(CLOCK_MONOTONIC,
1230 pthread_rwlock_timedwrlock_monotonic_np);
1231#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001232 GTEST_SKIP() << "pthread_rwlock_timedwrlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001233#endif // __BIONIC__
Yabin Cuic9a659c2015-11-05 15:36:08 -08001234}
1235
Tom Cherry69010802019-05-07 20:33:05 -07001236TEST(pthread, pthread_rwlock_clockwrlock_monotonic_timeout) {
1237#if defined(__BIONIC__)
1238 pthread_rwlock_timedwrlock_timeout_helper(
1239 CLOCK_MONOTONIC, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) {
1240 return pthread_rwlock_clockwrlock(__rwlock, CLOCK_MONOTONIC, __timeout);
1241 });
1242#else // __BIONIC__
1243 GTEST_SKIP() << "pthread_rwlock_clockwrlock not available";
1244#endif // __BIONIC__
1245}
1246
1247TEST(pthread, pthread_rwlock_clockwrlock_realtime_timeout) {
1248#if defined(__BIONIC__)
1249 pthread_rwlock_timedwrlock_timeout_helper(
1250 CLOCK_REALTIME, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) {
1251 return pthread_rwlock_clockwrlock(__rwlock, CLOCK_REALTIME, __timeout);
1252 });
1253#else // __BIONIC__
1254 GTEST_SKIP() << "pthread_rwlock_clockwrlock not available";
1255#endif // __BIONIC__
1256}
1257
1258TEST(pthread, pthread_rwlock_clockwrlock_invalid) {
1259#if defined(__BIONIC__)
1260 pthread_rwlock_t lock = PTHREAD_RWLOCK_INITIALIZER;
1261 timespec ts;
1262 EXPECT_EQ(EINVAL, pthread_rwlock_clockwrlock(&lock, CLOCK_PROCESS_CPUTIME_ID, &ts));
1263#else // __BIONIC__
1264 GTEST_SKIP() << "pthread_rwlock_clockrwlock not available";
1265#endif // __BIONIC__
1266}
1267
Colin Cross4c5595c2021-08-16 15:51:59 -07001268#if !defined(ANDROID_HOST_MUSL)
Colin Cross7da20342021-07-28 11:18:11 -07001269// musl doesn't have pthread_rwlockattr_setkind_np
Yabin Cui76615da2015-03-17 14:22:09 -07001270class RwlockKindTestHelper {
1271 private:
1272 struct ThreadArg {
1273 RwlockKindTestHelper* helper;
1274 std::atomic<pid_t>& tid;
1275
1276 ThreadArg(RwlockKindTestHelper* helper, std::atomic<pid_t>& tid)
1277 : helper(helper), tid(tid) { }
1278 };
1279
1280 public:
1281 pthread_rwlock_t lock;
1282
1283 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -07001284 explicit RwlockKindTestHelper(int kind_type) {
Yabin Cui76615da2015-03-17 14:22:09 -07001285 InitRwlock(kind_type);
1286 }
1287
1288 ~RwlockKindTestHelper() {
1289 DestroyRwlock();
1290 }
1291
1292 void CreateWriterThread(pthread_t& thread, std::atomic<pid_t>& tid) {
1293 tid = 0;
1294 ThreadArg* arg = new ThreadArg(this, tid);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001295 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui76615da2015-03-17 14:22:09 -07001296 reinterpret_cast<void* (*)(void*)>(WriterThreadFn), arg));
1297 }
1298
1299 void CreateReaderThread(pthread_t& thread, std::atomic<pid_t>& tid) {
1300 tid = 0;
1301 ThreadArg* arg = new ThreadArg(this, tid);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001302 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui76615da2015-03-17 14:22:09 -07001303 reinterpret_cast<void* (*)(void*)>(ReaderThreadFn), arg));
1304 }
1305
1306 private:
1307 void InitRwlock(int kind_type) {
1308 pthread_rwlockattr_t attr;
1309 ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
1310 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_type));
1311 ASSERT_EQ(0, pthread_rwlock_init(&lock, &attr));
1312 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
1313 }
1314
1315 void DestroyRwlock() {
1316 ASSERT_EQ(0, pthread_rwlock_destroy(&lock));
1317 }
1318
1319 static void WriterThreadFn(ThreadArg* arg) {
1320 arg->tid = gettid();
1321
1322 RwlockKindTestHelper* helper = arg->helper;
1323 ASSERT_EQ(0, pthread_rwlock_wrlock(&helper->lock));
1324 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
1325 delete arg;
1326 }
1327
1328 static void ReaderThreadFn(ThreadArg* arg) {
1329 arg->tid = gettid();
1330
1331 RwlockKindTestHelper* helper = arg->helper;
1332 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper->lock));
1333 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
1334 delete arg;
1335 }
1336};
Colin Cross7da20342021-07-28 11:18:11 -07001337#endif
Yabin Cui76615da2015-03-17 14:22:09 -07001338
1339TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_READER_NP) {
Colin Cross4c5595c2021-08-16 15:51:59 -07001340#if !defined(ANDROID_HOST_MUSL)
Yabin Cui76615da2015-03-17 14:22:09 -07001341 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_READER_NP);
1342 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
1343
1344 pthread_t writer_thread;
1345 std::atomic<pid_t> writer_tid;
1346 helper.CreateWriterThread(writer_thread, writer_tid);
1347 WaitUntilThreadSleep(writer_tid);
1348
1349 pthread_t reader_thread;
1350 std::atomic<pid_t> reader_tid;
1351 helper.CreateReaderThread(reader_thread, reader_tid);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001352 ASSERT_EQ(0, pthread_join(reader_thread, nullptr));
Yabin Cui76615da2015-03-17 14:22:09 -07001353
1354 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
Yi Kong32bc0fc2018-08-02 17:31:13 -07001355 ASSERT_EQ(0, pthread_join(writer_thread, nullptr));
Colin Cross7da20342021-07-28 11:18:11 -07001356#else
1357 GTEST_SKIP() << "musl doesn't have pthread_rwlockattr_setkind_np";
1358#endif
Yabin Cui76615da2015-03-17 14:22:09 -07001359}
1360
1361TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP) {
Colin Cross4c5595c2021-08-16 15:51:59 -07001362#if !defined(ANDROID_HOST_MUSL)
Yabin Cui76615da2015-03-17 14:22:09 -07001363 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
1364 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
1365
1366 pthread_t writer_thread;
1367 std::atomic<pid_t> writer_tid;
1368 helper.CreateWriterThread(writer_thread, writer_tid);
1369 WaitUntilThreadSleep(writer_tid);
1370
1371 pthread_t reader_thread;
1372 std::atomic<pid_t> reader_tid;
1373 helper.CreateReaderThread(reader_thread, reader_tid);
1374 WaitUntilThreadSleep(reader_tid);
1375
1376 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
Yi Kong32bc0fc2018-08-02 17:31:13 -07001377 ASSERT_EQ(0, pthread_join(writer_thread, nullptr));
1378 ASSERT_EQ(0, pthread_join(reader_thread, nullptr));
Colin Cross7da20342021-07-28 11:18:11 -07001379#else
1380 GTEST_SKIP() << "musl doesn't have pthread_rwlockattr_setkind_np";
1381#endif
Yabin Cui76615da2015-03-17 14:22:09 -07001382}
1383
Elliott Hughes1728b232014-05-14 10:02:03 -07001384static int g_once_fn_call_count = 0;
Elliott Hughesc3f11402013-10-30 14:40:09 -07001385static void OnceFn() {
Elliott Hughes1728b232014-05-14 10:02:03 -07001386 ++g_once_fn_call_count;
Elliott Hughesc3f11402013-10-30 14:40:09 -07001387}
1388
1389TEST(pthread, pthread_once_smoke) {
1390 pthread_once_t once_control = PTHREAD_ONCE_INIT;
1391 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
1392 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
Elliott Hughes1728b232014-05-14 10:02:03 -07001393 ASSERT_EQ(1, g_once_fn_call_count);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001394}
1395
Elliott Hughes3694ec62014-05-14 11:46:08 -07001396static std::string pthread_once_1934122_result = "";
1397
1398static void Routine2() {
1399 pthread_once_1934122_result += "2";
1400}
1401
1402static void Routine1() {
1403 pthread_once_t once_control_2 = PTHREAD_ONCE_INIT;
1404 pthread_once_1934122_result += "1";
1405 pthread_once(&once_control_2, &Routine2);
1406}
1407
1408TEST(pthread, pthread_once_1934122) {
1409 // Very old versions of Android couldn't call pthread_once from a
1410 // pthread_once init routine. http://b/1934122.
1411 pthread_once_t once_control_1 = PTHREAD_ONCE_INIT;
1412 ASSERT_EQ(0, pthread_once(&once_control_1, &Routine1));
1413 ASSERT_EQ("12", pthread_once_1934122_result);
1414}
1415
Elliott Hughes1728b232014-05-14 10:02:03 -07001416static int g_atfork_prepare_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001417static void AtForkPrepare1() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 1; }
1418static void AtForkPrepare2() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -07001419static int g_atfork_parent_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001420static void AtForkParent1() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 1; }
1421static void AtForkParent2() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -07001422static int g_atfork_child_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001423static void AtForkChild1() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 1; }
1424static void AtForkChild2() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 2; }
Elliott Hughesc3f11402013-10-30 14:40:09 -07001425
Dmitriy Ivanov00e37812014-11-20 16:53:47 -08001426TEST(pthread, pthread_atfork_smoke) {
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001427 ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1));
1428 ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2));
Elliott Hughesc3f11402013-10-30 14:40:09 -07001429
Elliott Hughes33697a02016-01-26 13:04:57 -08001430 pid_t pid = fork();
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001431 ASSERT_NE(-1, pid) << strerror(errno);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001432
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001433 // Child and parent calls are made in the order they were registered.
1434 if (pid == 0) {
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001435 ASSERT_EQ(12, g_atfork_child_calls);
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001436 _exit(0);
1437 }
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001438 ASSERT_EQ(12, g_atfork_parent_calls);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001439
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001440 // Prepare calls are made in the reverse order.
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001441 ASSERT_EQ(21, g_atfork_prepare_calls);
Elliott Hughes33697a02016-01-26 13:04:57 -08001442 AssertChildExited(pid, 0);
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001443}
1444
Elliott Hughesc3f11402013-10-30 14:40:09 -07001445TEST(pthread, pthread_attr_getscope) {
1446 pthread_attr_t attr;
1447 ASSERT_EQ(0, pthread_attr_init(&attr));
1448
1449 int scope;
1450 ASSERT_EQ(0, pthread_attr_getscope(&attr, &scope));
1451 ASSERT_EQ(PTHREAD_SCOPE_SYSTEM, scope);
1452}
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001453
1454TEST(pthread, pthread_condattr_init) {
1455 pthread_condattr_t attr;
1456 pthread_condattr_init(&attr);
1457
1458 clockid_t clock;
1459 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1460 ASSERT_EQ(CLOCK_REALTIME, clock);
1461
1462 int pshared;
1463 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1464 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
1465}
1466
1467TEST(pthread, pthread_condattr_setclock) {
1468 pthread_condattr_t attr;
1469 pthread_condattr_init(&attr);
1470
1471 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_REALTIME));
1472 clockid_t clock;
1473 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1474 ASSERT_EQ(CLOCK_REALTIME, clock);
1475
1476 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1477 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1478 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1479
1480 ASSERT_EQ(EINVAL, pthread_condattr_setclock(&attr, CLOCK_PROCESS_CPUTIME_ID));
1481}
1482
1483TEST(pthread, pthread_cond_broadcast__preserves_condattr_flags) {
Yabin Cui32651b82015-03-13 20:30:00 -07001484#if defined(__BIONIC__)
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001485 pthread_condattr_t attr;
1486 pthread_condattr_init(&attr);
1487
1488 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1489 ASSERT_EQ(0, pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
1490
1491 pthread_cond_t cond_var;
1492 ASSERT_EQ(0, pthread_cond_init(&cond_var, &attr));
1493
1494 ASSERT_EQ(0, pthread_cond_signal(&cond_var));
1495 ASSERT_EQ(0, pthread_cond_broadcast(&cond_var));
1496
Yabin Cui32651b82015-03-13 20:30:00 -07001497 attr = static_cast<pthread_condattr_t>(*reinterpret_cast<uint32_t*>(cond_var.__private));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001498 clockid_t clock;
1499 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1500 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1501 int pshared;
1502 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1503 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
Yabin Cui32651b82015-03-13 20:30:00 -07001504#else // !defined(__BIONIC__)
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001505 GTEST_SKIP() << "bionic-only test";
Yabin Cui32651b82015-03-13 20:30:00 -07001506#endif // !defined(__BIONIC__)
1507}
1508
1509class pthread_CondWakeupTest : public ::testing::Test {
1510 protected:
1511 pthread_mutex_t mutex;
1512 pthread_cond_t cond;
1513
1514 enum Progress {
1515 INITIALIZED,
1516 WAITING,
1517 SIGNALED,
1518 FINISHED,
1519 };
1520 std::atomic<Progress> progress;
1521 pthread_t thread;
Peter Collingbournec5b81842021-12-02 12:38:46 -08001522 timespec ts;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001523 std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function;
Yabin Cui32651b82015-03-13 20:30:00 -07001524
1525 protected:
Yabin Cuic9a659c2015-11-05 15:36:08 -08001526 void SetUp() override {
1527 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1528 }
1529
1530 void InitCond(clockid_t clock=CLOCK_REALTIME) {
1531 pthread_condattr_t attr;
1532 ASSERT_EQ(0, pthread_condattr_init(&attr));
1533 ASSERT_EQ(0, pthread_condattr_setclock(&attr, clock));
1534 ASSERT_EQ(0, pthread_cond_init(&cond, &attr));
1535 ASSERT_EQ(0, pthread_condattr_destroy(&attr));
1536 }
1537
Tom Cherry69010802019-05-07 20:33:05 -07001538 void StartWaitingThread(
1539 std::function<int(pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function) {
Yabin Cui32651b82015-03-13 20:30:00 -07001540 progress = INITIALIZED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001541 this->wait_function = wait_function;
Tom Cherry69010802019-05-07 20:33:05 -07001542 ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(WaitThreadFn),
1543 this));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001544 while (progress != WAITING) {
Yabin Cui32651b82015-03-13 20:30:00 -07001545 usleep(5000);
1546 }
1547 usleep(5000);
1548 }
1549
Tom Cherry69010802019-05-07 20:33:05 -07001550 void RunTimedTest(
1551 clockid_t clock,
1552 std::function<int(pthread_cond_t* cond, pthread_mutex_t* mutex, const timespec* timeout)>
1553 wait_function) {
Tom Cherry69010802019-05-07 20:33:05 -07001554 ASSERT_EQ(0, clock_gettime(clock, &ts));
1555 ts.tv_sec += 1;
1556
Peter Collingbournec5b81842021-12-02 12:38:46 -08001557 StartWaitingThread([&wait_function, this](pthread_cond_t* cond, pthread_mutex_t* mutex) {
Tom Cherry69010802019-05-07 20:33:05 -07001558 return wait_function(cond, mutex, &ts);
1559 });
1560
1561 progress = SIGNALED;
1562 ASSERT_EQ(0, pthread_cond_signal(&cond));
1563 }
1564
1565 void RunTimedTest(clockid_t clock, std::function<int(pthread_cond_t* cond, pthread_mutex_t* mutex,
1566 clockid_t clock, const timespec* timeout)>
1567 wait_function) {
1568 RunTimedTest(clock, [clock, &wait_function](pthread_cond_t* cond, pthread_mutex_t* mutex,
1569 const timespec* timeout) {
1570 return wait_function(cond, mutex, clock, timeout);
1571 });
1572 }
1573
Yabin Cuic9a659c2015-11-05 15:36:08 -08001574 void TearDown() override {
1575 ASSERT_EQ(0, pthread_join(thread, nullptr));
1576 ASSERT_EQ(FINISHED, progress);
1577 ASSERT_EQ(0, pthread_cond_destroy(&cond));
1578 ASSERT_EQ(0, pthread_mutex_destroy(&mutex));
1579 }
1580
Yabin Cui32651b82015-03-13 20:30:00 -07001581 private:
1582 static void WaitThreadFn(pthread_CondWakeupTest* test) {
1583 ASSERT_EQ(0, pthread_mutex_lock(&test->mutex));
1584 test->progress = WAITING;
1585 while (test->progress == WAITING) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001586 ASSERT_EQ(0, test->wait_function(&test->cond, &test->mutex));
Yabin Cui32651b82015-03-13 20:30:00 -07001587 }
1588 ASSERT_EQ(SIGNALED, test->progress);
1589 test->progress = FINISHED;
1590 ASSERT_EQ(0, pthread_mutex_unlock(&test->mutex));
1591 }
1592};
1593
Yabin Cuic9a659c2015-11-05 15:36:08 -08001594TEST_F(pthread_CondWakeupTest, signal_wait) {
1595 InitCond();
1596 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1597 return pthread_cond_wait(cond, mutex);
1598 });
Yabin Cui32651b82015-03-13 20:30:00 -07001599 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001600 ASSERT_EQ(0, pthread_cond_signal(&cond));
Yabin Cui32651b82015-03-13 20:30:00 -07001601}
1602
Yabin Cuic9a659c2015-11-05 15:36:08 -08001603TEST_F(pthread_CondWakeupTest, broadcast_wait) {
1604 InitCond();
1605 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1606 return pthread_cond_wait(cond, mutex);
1607 });
Yabin Cui32651b82015-03-13 20:30:00 -07001608 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001609 ASSERT_EQ(0, pthread_cond_broadcast(&cond));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001610}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001611
Yabin Cuic9a659c2015-11-05 15:36:08 -08001612TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_REALTIME) {
1613 InitCond(CLOCK_REALTIME);
Tom Cherry69010802019-05-07 20:33:05 -07001614 RunTimedTest(CLOCK_REALTIME, pthread_cond_timedwait);
Yabin Cuic9a659c2015-11-05 15:36:08 -08001615}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001616
Yabin Cuic9a659c2015-11-05 15:36:08 -08001617TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC) {
1618 InitCond(CLOCK_MONOTONIC);
Tom Cherry69010802019-05-07 20:33:05 -07001619 RunTimedTest(CLOCK_MONOTONIC, pthread_cond_timedwait);
Yabin Cuic9a659c2015-11-05 15:36:08 -08001620}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001621
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001622TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC_np) {
1623#if defined(__BIONIC__)
1624 InitCond(CLOCK_REALTIME);
Tom Cherry69010802019-05-07 20:33:05 -07001625 RunTimedTest(CLOCK_MONOTONIC, pthread_cond_timedwait_monotonic_np);
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001626#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001627 GTEST_SKIP() << "pthread_cond_timedwait_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001628#endif // __BIONIC__
1629}
1630
Tom Cherry69010802019-05-07 20:33:05 -07001631TEST_F(pthread_CondWakeupTest, signal_clockwait_monotonic_monotonic) {
1632#if defined(__BIONIC__)
1633 InitCond(CLOCK_MONOTONIC);
1634 RunTimedTest(CLOCK_MONOTONIC, pthread_cond_clockwait);
1635#else // __BIONIC__
1636 GTEST_SKIP() << "pthread_cond_clockwait not available";
1637#endif // __BIONIC__
1638}
1639
1640TEST_F(pthread_CondWakeupTest, signal_clockwait_monotonic_realtime) {
1641#if defined(__BIONIC__)
1642 InitCond(CLOCK_MONOTONIC);
1643 RunTimedTest(CLOCK_REALTIME, pthread_cond_clockwait);
1644#else // __BIONIC__
1645 GTEST_SKIP() << "pthread_cond_clockwait not available";
1646#endif // __BIONIC__
1647}
1648
1649TEST_F(pthread_CondWakeupTest, signal_clockwait_realtime_monotonic) {
1650#if defined(__BIONIC__)
1651 InitCond(CLOCK_REALTIME);
1652 RunTimedTest(CLOCK_MONOTONIC, pthread_cond_clockwait);
1653#else // __BIONIC__
1654 GTEST_SKIP() << "pthread_cond_clockwait not available";
1655#endif // __BIONIC__
1656}
1657
1658TEST_F(pthread_CondWakeupTest, signal_clockwait_realtime_realtime) {
1659#if defined(__BIONIC__)
1660 InitCond(CLOCK_REALTIME);
1661 RunTimedTest(CLOCK_REALTIME, pthread_cond_clockwait);
1662#else // __BIONIC__
1663 GTEST_SKIP() << "pthread_cond_clockwait not available";
1664#endif // __BIONIC__
1665}
1666
Tom Cherry800c1a92019-07-17 10:45:18 -07001667static void pthread_cond_timedwait_timeout_helper(bool init_monotonic, clockid_t clock,
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001668 int (*wait_function)(pthread_cond_t* __cond,
1669 pthread_mutex_t* __mutex,
1670 const timespec* __timeout)) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001671 pthread_mutex_t mutex;
1672 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1673 pthread_cond_t cond;
Tom Cherry800c1a92019-07-17 10:45:18 -07001674
1675 if (init_monotonic) {
1676 pthread_condattr_t attr;
1677 pthread_condattr_init(&attr);
1678
1679 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1680 clockid_t clock;
1681 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1682 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1683
1684 ASSERT_EQ(0, pthread_cond_init(&cond, &attr));
1685 } else {
1686 ASSERT_EQ(0, pthread_cond_init(&cond, nullptr));
1687 }
Yabin Cuic9a659c2015-11-05 15:36:08 -08001688 ASSERT_EQ(0, pthread_mutex_lock(&mutex));
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001689
Yabin Cuic9a659c2015-11-05 15:36:08 -08001690 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001691 ASSERT_EQ(0, clock_gettime(clock, &ts));
1692 ASSERT_EQ(ETIMEDOUT, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001693 ts.tv_nsec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001694 ASSERT_EQ(EINVAL, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001695 ts.tv_nsec = NS_PER_S;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001696 ASSERT_EQ(EINVAL, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001697 ts.tv_nsec = NS_PER_S - 1;
1698 ts.tv_sec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001699 ASSERT_EQ(ETIMEDOUT, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001700 ASSERT_EQ(0, pthread_mutex_unlock(&mutex));
Elliott Hughes0e714a52014-03-03 16:42:47 -08001701}
Elliott Hughes57b7a612014-08-25 17:26:50 -07001702
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001703TEST(pthread, pthread_cond_timedwait_timeout) {
Tom Cherry800c1a92019-07-17 10:45:18 -07001704 pthread_cond_timedwait_timeout_helper(false, CLOCK_REALTIME, pthread_cond_timedwait);
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001705}
1706
1707TEST(pthread, pthread_cond_timedwait_monotonic_np_timeout) {
1708#if defined(__BIONIC__)
Tom Cherry800c1a92019-07-17 10:45:18 -07001709 pthread_cond_timedwait_timeout_helper(false, CLOCK_MONOTONIC, pthread_cond_timedwait_monotonic_np);
1710 pthread_cond_timedwait_timeout_helper(true, CLOCK_MONOTONIC, pthread_cond_timedwait_monotonic_np);
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001711#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001712 GTEST_SKIP() << "pthread_cond_timedwait_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001713#endif // __BIONIC__
1714}
1715
Tom Cherry69010802019-05-07 20:33:05 -07001716TEST(pthread, pthread_cond_clockwait_timeout) {
1717#if defined(__BIONIC__)
1718 pthread_cond_timedwait_timeout_helper(
Tom Cherry800c1a92019-07-17 10:45:18 -07001719 false, CLOCK_MONOTONIC,
Tom Cherry69010802019-05-07 20:33:05 -07001720 [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) {
1721 return pthread_cond_clockwait(__cond, __mutex, CLOCK_MONOTONIC, __timeout);
1722 });
1723 pthread_cond_timedwait_timeout_helper(
Tom Cherry800c1a92019-07-17 10:45:18 -07001724 true, CLOCK_MONOTONIC,
1725 [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) {
1726 return pthread_cond_clockwait(__cond, __mutex, CLOCK_MONOTONIC, __timeout);
1727 });
1728 pthread_cond_timedwait_timeout_helper(
1729 false, CLOCK_REALTIME,
1730 [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) {
1731 return pthread_cond_clockwait(__cond, __mutex, CLOCK_REALTIME, __timeout);
1732 });
1733 pthread_cond_timedwait_timeout_helper(
1734 true, CLOCK_REALTIME,
Tom Cherry69010802019-05-07 20:33:05 -07001735 [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) {
1736 return pthread_cond_clockwait(__cond, __mutex, CLOCK_REALTIME, __timeout);
1737 });
1738#else // __BIONIC__
1739 GTEST_SKIP() << "pthread_cond_clockwait not available";
1740#endif // __BIONIC__
1741}
1742
1743TEST(pthread, pthread_cond_clockwait_invalid) {
1744#if defined(__BIONIC__)
1745 pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
1746 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
1747 timespec ts;
1748 EXPECT_EQ(EINVAL, pthread_cond_clockwait(&cond, &mutex, CLOCK_PROCESS_CPUTIME_ID, &ts));
1749
1750#else // __BIONIC__
1751 GTEST_SKIP() << "pthread_cond_clockwait not available";
1752#endif // __BIONIC__
1753}
1754
Elliott Hughes57b7a612014-08-25 17:26:50 -07001755TEST(pthread, pthread_attr_getstack__main_thread) {
1756 // This test is only meaningful for the main thread, so make sure we're running on it!
1757 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1758
1759 // Get the main thread's attributes.
1760 pthread_attr_t attributes;
1761 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1762
1763 // Check that we correctly report that the main thread has no guard page.
1764 size_t guard_size;
1765 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
1766 ASSERT_EQ(0U, guard_size); // The main thread has no guard page.
1767
1768 // Get the stack base and the stack size (both ways).
1769 void* stack_base;
1770 size_t stack_size;
1771 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1772 size_t stack_size2;
1773 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1774
1775 // The two methods of asking for the stack size should agree.
1776 EXPECT_EQ(stack_size, stack_size2);
1777
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001778#if defined(__BIONIC__)
dimitry6dfa5b52018-01-30 13:24:28 +01001779 // Find stack in /proc/self/maps using a pointer to the stack.
1780 //
1781 // We do not use "[stack]" label because in native-bridge environment it is not
1782 // guaranteed to point to the right stack. A native bridge implementation may
1783 // keep separate stack for the guest code.
Yi Kong32bc0fc2018-08-02 17:31:13 -07001784 void* maps_stack_hi = nullptr;
Elliott Hughes15dfd632015-09-22 16:40:14 -07001785 std::vector<map_record> maps;
1786 ASSERT_TRUE(Maps::parse_maps(&maps));
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08001787 uintptr_t stack_address = reinterpret_cast<uintptr_t>(untag_address(&maps_stack_hi));
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07001788 for (const auto& map : maps) {
dimitry6dfa5b52018-01-30 13:24:28 +01001789 if (map.addr_start <= stack_address && map.addr_end > stack_address){
Elliott Hughes15dfd632015-09-22 16:40:14 -07001790 maps_stack_hi = reinterpret_cast<void*>(map.addr_end);
Elliott Hughes57b7a612014-08-25 17:26:50 -07001791 break;
1792 }
1793 }
Elliott Hughes57b7a612014-08-25 17:26:50 -07001794
dimitry6dfa5b52018-01-30 13:24:28 +01001795 // The high address of the /proc/self/maps stack region should equal stack_base + stack_size.
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001796 // Remember that the stack grows down (and is mapped in on demand), so the low address of the
1797 // region isn't very interesting.
1798 EXPECT_EQ(maps_stack_hi, reinterpret_cast<uint8_t*>(stack_base) + stack_size);
1799
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001800 // The stack size should correspond to RLIMIT_STACK.
Elliott Hughes57b7a612014-08-25 17:26:50 -07001801 rlimit rl;
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001802 ASSERT_EQ(0, getrlimit(RLIMIT_STACK, &rl));
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001803 uint64_t original_rlim_cur = rl.rlim_cur;
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001804 if (rl.rlim_cur == RLIM_INFINITY) {
1805 rl.rlim_cur = 8 * 1024 * 1024; // Bionic reports unlimited stacks as 8MiB.
1806 }
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001807 EXPECT_EQ(rl.rlim_cur, stack_size);
1808
Tom Cherryb8ab6182017-04-05 16:20:29 -07001809 auto guard = android::base::make_scope_guard([&rl, original_rlim_cur]() {
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001810 rl.rlim_cur = original_rlim_cur;
1811 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1812 });
1813
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001814 //
1815 // What if RLIMIT_STACK is smaller than the stack's current extent?
1816 //
Elliott Hughes57b7a612014-08-25 17:26:50 -07001817 rl.rlim_cur = rl.rlim_max = 1024; // 1KiB. We know the stack must be at least a page already.
1818 rl.rlim_max = RLIM_INFINITY;
1819 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1820
1821 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1822 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1823 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1824
1825 EXPECT_EQ(stack_size, stack_size2);
1826 ASSERT_EQ(1024U, stack_size);
1827
1828 //
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001829 // What if RLIMIT_STACK isn't a whole number of pages?
Elliott Hughes57b7a612014-08-25 17:26:50 -07001830 //
1831 rl.rlim_cur = rl.rlim_max = 6666; // Not a whole number of pages.
1832 rl.rlim_max = RLIM_INFINITY;
1833 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1834
1835 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1836 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1837 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1838
1839 EXPECT_EQ(stack_size, stack_size2);
1840 ASSERT_EQ(6666U, stack_size);
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001841#endif
Elliott Hughes57b7a612014-08-25 17:26:50 -07001842}
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001843
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001844struct GetStackSignalHandlerArg {
1845 volatile bool done;
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001846 void* signal_stack_base;
1847 size_t signal_stack_size;
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001848 void* main_stack_base;
1849 size_t main_stack_size;
1850};
1851
1852static GetStackSignalHandlerArg getstack_signal_handler_arg;
1853
1854static void getstack_signal_handler(int sig) {
1855 ASSERT_EQ(SIGUSR1, sig);
1856 // Use sleep() to make current thread be switched out by the kernel to provoke the error.
1857 sleep(1);
1858 pthread_attr_t attr;
1859 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1860 void* stack_base;
1861 size_t stack_size;
1862 ASSERT_EQ(0, pthread_attr_getstack(&attr, &stack_base, &stack_size));
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001863
1864 // Verify if the stack used by the signal handler is the alternate stack just registered.
1865 ASSERT_LE(getstack_signal_handler_arg.signal_stack_base, &attr);
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08001866 ASSERT_LT(static_cast<void*>(untag_address(&attr)),
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001867 static_cast<char*>(getstack_signal_handler_arg.signal_stack_base) +
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08001868 getstack_signal_handler_arg.signal_stack_size);
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001869
1870 // Verify if the main thread's stack got in the signal handler is correct.
1871 ASSERT_EQ(getstack_signal_handler_arg.main_stack_base, stack_base);
1872 ASSERT_LE(getstack_signal_handler_arg.main_stack_size, stack_size);
1873
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001874 getstack_signal_handler_arg.done = true;
1875}
1876
1877// The previous code obtained the main thread's stack by reading the entry in
1878// /proc/self/task/<pid>/maps that was labeled [stack]. Unfortunately, on x86/x86_64, the kernel
1879// relies on sp0 in task state segment(tss) to label the stack map with [stack]. If the kernel
1880// switches a process while the main thread is in an alternate stack, then the kernel will label
1881// the wrong map with [stack]. This test verifies that when the above situation happens, the main
1882// thread's stack is found correctly.
1883TEST(pthread, pthread_attr_getstack_in_signal_handler) {
Yabin Cui61e4d462016-03-07 17:44:58 -08001884 // This test is only meaningful for the main thread, so make sure we're running on it!
1885 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1886
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001887 const size_t sig_stack_size = 16 * 1024;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001888 void* sig_stack = mmap(nullptr, sig_stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS,
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001889 -1, 0);
1890 ASSERT_NE(MAP_FAILED, sig_stack);
1891 stack_t ss;
1892 ss.ss_sp = sig_stack;
1893 ss.ss_size = sig_stack_size;
1894 ss.ss_flags = 0;
1895 stack_t oss;
1896 ASSERT_EQ(0, sigaltstack(&ss, &oss));
1897
Yabin Cui61e4d462016-03-07 17:44:58 -08001898 pthread_attr_t attr;
1899 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1900 void* main_stack_base;
1901 size_t main_stack_size;
1902 ASSERT_EQ(0, pthread_attr_getstack(&attr, &main_stack_base, &main_stack_size));
1903
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001904 ScopedSignalHandler handler(SIGUSR1, getstack_signal_handler, SA_ONSTACK);
1905 getstack_signal_handler_arg.done = false;
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001906 getstack_signal_handler_arg.signal_stack_base = sig_stack;
1907 getstack_signal_handler_arg.signal_stack_size = sig_stack_size;
1908 getstack_signal_handler_arg.main_stack_base = main_stack_base;
1909 getstack_signal_handler_arg.main_stack_size = main_stack_size;
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001910 kill(getpid(), SIGUSR1);
1911 ASSERT_EQ(true, getstack_signal_handler_arg.done);
1912
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001913 ASSERT_EQ(0, sigaltstack(&oss, nullptr));
1914 ASSERT_EQ(0, munmap(sig_stack, sig_stack_size));
1915}
1916
Yabin Cui917d3902015-01-08 12:32:42 -08001917static void pthread_attr_getstack_18908062_helper(void*) {
1918 char local_variable;
1919 pthread_attr_t attributes;
1920 pthread_getattr_np(pthread_self(), &attributes);
1921 void* stack_base;
1922 size_t stack_size;
1923 pthread_attr_getstack(&attributes, &stack_base, &stack_size);
1924
1925 // Test whether &local_variable is in [stack_base, stack_base + stack_size).
1926 ASSERT_LE(reinterpret_cast<char*>(stack_base), &local_variable);
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08001927 ASSERT_LT(untag_address(&local_variable), reinterpret_cast<char*>(stack_base) + stack_size);
Yabin Cui917d3902015-01-08 12:32:42 -08001928}
1929
1930// Check whether something on stack is in the range of
1931// [stack_base, stack_base + stack_size). see b/18908062.
1932TEST(pthread, pthread_attr_getstack_18908062) {
1933 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001934 ASSERT_EQ(0, pthread_create(&t, nullptr,
Yabin Cui917d3902015-01-08 12:32:42 -08001935 reinterpret_cast<void* (*)(void*)>(pthread_attr_getstack_18908062_helper),
Yi Kong32bc0fc2018-08-02 17:31:13 -07001936 nullptr));
1937 ASSERT_EQ(0, pthread_join(t, nullptr));
Yabin Cui917d3902015-01-08 12:32:42 -08001938}
1939
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001940#if defined(__BIONIC__)
Elliott Hughesf2083612015-11-11 13:32:28 -08001941static pthread_mutex_t pthread_gettid_np_mutex = PTHREAD_MUTEX_INITIALIZER;
1942
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001943static void* pthread_gettid_np_helper(void* arg) {
1944 *reinterpret_cast<pid_t*>(arg) = gettid();
Elliott Hughesf2083612015-11-11 13:32:28 -08001945
1946 // Wait for our parent to call pthread_gettid_np on us before exiting.
1947 pthread_mutex_lock(&pthread_gettid_np_mutex);
1948 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001949 return nullptr;
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001950}
1951#endif
1952
1953TEST(pthread, pthread_gettid_np) {
1954#if defined(__BIONIC__)
1955 ASSERT_EQ(gettid(), pthread_gettid_np(pthread_self()));
1956
Elliott Hughesf2083612015-11-11 13:32:28 -08001957 // Ensure the other thread doesn't exit until after we've called
1958 // pthread_gettid_np on it.
1959 pthread_mutex_lock(&pthread_gettid_np_mutex);
1960
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001961 pid_t t_gettid_result;
1962 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001963 pthread_create(&t, nullptr, pthread_gettid_np_helper, &t_gettid_result);
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001964
1965 pid_t t_pthread_gettid_np_result = pthread_gettid_np(t);
1966
Elliott Hughesf2083612015-11-11 13:32:28 -08001967 // Release the other thread and wait for it to exit.
1968 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001969 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001970
1971 ASSERT_EQ(t_gettid_result, t_pthread_gettid_np_result);
1972#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001973 GTEST_SKIP() << "pthread_gettid_np not available";
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001974#endif
1975}
Elliott Hughes34c987a2014-09-22 16:01:26 -07001976
1977static size_t cleanup_counter = 0;
1978
Derek Xue41996952014-09-25 11:05:32 +01001979static void AbortCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001980 abort();
1981}
1982
Derek Xue41996952014-09-25 11:05:32 +01001983static void CountCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001984 ++cleanup_counter;
1985}
1986
Derek Xue41996952014-09-25 11:05:32 +01001987static void PthreadCleanupTester() {
Yi Kong32bc0fc2018-08-02 17:31:13 -07001988 pthread_cleanup_push(CountCleanupRoutine, nullptr);
1989 pthread_cleanup_push(CountCleanupRoutine, nullptr);
1990 pthread_cleanup_push(AbortCleanupRoutine, nullptr);
Elliott Hughes34c987a2014-09-22 16:01:26 -07001991
1992 pthread_cleanup_pop(0); // Pop the abort without executing it.
1993 pthread_cleanup_pop(1); // Pop one count while executing it.
1994 ASSERT_EQ(1U, cleanup_counter);
1995 // Exit while the other count is still on the cleanup stack.
Yi Kong32bc0fc2018-08-02 17:31:13 -07001996 pthread_exit(nullptr);
Elliott Hughes34c987a2014-09-22 16:01:26 -07001997
1998 // Calls to pthread_cleanup_pop/pthread_cleanup_push must always be balanced.
1999 pthread_cleanup_pop(0);
2000}
2001
Derek Xue41996952014-09-25 11:05:32 +01002002static void* PthreadCleanupStartRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07002003 PthreadCleanupTester();
Yi Kong32bc0fc2018-08-02 17:31:13 -07002004 return nullptr;
Elliott Hughes34c987a2014-09-22 16:01:26 -07002005}
2006
2007TEST(pthread, pthread_cleanup_push__pthread_cleanup_pop) {
2008 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002009 ASSERT_EQ(0, pthread_create(&t, nullptr, PthreadCleanupStartRoutine, nullptr));
2010 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes34c987a2014-09-22 16:01:26 -07002011 ASSERT_EQ(2U, cleanup_counter);
2012}
Derek Xue41996952014-09-25 11:05:32 +01002013
2014TEST(pthread, PTHREAD_MUTEX_DEFAULT_is_PTHREAD_MUTEX_NORMAL) {
2015 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_DEFAULT);
2016}
2017
2018TEST(pthread, pthread_mutexattr_gettype) {
2019 pthread_mutexattr_t attr;
2020 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
2021
2022 int attr_type;
2023
2024 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL));
2025 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
2026 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, attr_type);
2027
2028 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK));
2029 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
2030 ASSERT_EQ(PTHREAD_MUTEX_ERRORCHECK, attr_type);
2031
2032 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE));
2033 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
2034 ASSERT_EQ(PTHREAD_MUTEX_RECURSIVE, attr_type);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002035
2036 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
2037}
2038
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002039TEST(pthread, pthread_mutexattr_protocol) {
2040 pthread_mutexattr_t attr;
2041 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
2042
2043 int protocol;
2044 ASSERT_EQ(0, pthread_mutexattr_getprotocol(&attr, &protocol));
2045 ASSERT_EQ(PTHREAD_PRIO_NONE, protocol);
2046 for (size_t repeat = 0; repeat < 2; ++repeat) {
2047 for (int set_protocol : {PTHREAD_PRIO_NONE, PTHREAD_PRIO_INHERIT}) {
2048 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, set_protocol));
2049 ASSERT_EQ(0, pthread_mutexattr_getprotocol(&attr, &protocol));
2050 ASSERT_EQ(protocol, set_protocol);
2051 }
2052 }
2053}
2054
Yabin Cui17393b02015-03-21 15:08:25 -07002055struct PthreadMutex {
2056 pthread_mutex_t lock;
2057
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002058 explicit PthreadMutex(int mutex_type, int protocol = PTHREAD_PRIO_NONE) {
2059 init(mutex_type, protocol);
Yabin Cui17393b02015-03-21 15:08:25 -07002060 }
2061
2062 ~PthreadMutex() {
2063 destroy();
2064 }
2065
2066 private:
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002067 void init(int mutex_type, int protocol) {
Yabin Cui17393b02015-03-21 15:08:25 -07002068 pthread_mutexattr_t attr;
2069 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
2070 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, mutex_type));
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002071 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, protocol));
Yabin Cui17393b02015-03-21 15:08:25 -07002072 ASSERT_EQ(0, pthread_mutex_init(&lock, &attr));
2073 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
2074 }
2075
2076 void destroy() {
2077 ASSERT_EQ(0, pthread_mutex_destroy(&lock));
2078 }
2079
2080 DISALLOW_COPY_AND_ASSIGN(PthreadMutex);
2081};
Derek Xue41996952014-09-25 11:05:32 +01002082
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002083static int UnlockFromAnotherThread(pthread_mutex_t* mutex) {
2084 pthread_t thread;
2085 pthread_create(&thread, nullptr, [](void* mutex_voidp) -> void* {
2086 pthread_mutex_t* mutex = static_cast<pthread_mutex_t*>(mutex_voidp);
2087 intptr_t result = pthread_mutex_unlock(mutex);
2088 return reinterpret_cast<void*>(result);
2089 }, mutex);
2090 void* result;
2091 EXPECT_EQ(0, pthread_join(thread, &result));
2092 return reinterpret_cast<intptr_t>(result);
2093};
2094
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002095static void TestPthreadMutexLockNormal(int protocol) {
2096 PthreadMutex m(PTHREAD_MUTEX_NORMAL, protocol);
Derek Xue41996952014-09-25 11:05:32 +01002097
Yabin Cui17393b02015-03-21 15:08:25 -07002098 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002099 if (protocol == PTHREAD_PRIO_INHERIT) {
2100 ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock));
2101 }
Yabin Cui17393b02015-03-21 15:08:25 -07002102 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08002103 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
2104 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
2105 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01002106}
2107
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002108static void TestPthreadMutexLockErrorCheck(int protocol) {
2109 PthreadMutex m(PTHREAD_MUTEX_ERRORCHECK, protocol);
Derek Xue41996952014-09-25 11:05:32 +01002110
Yabin Cui17393b02015-03-21 15:08:25 -07002111 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002112 ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07002113 ASSERT_EQ(EDEADLK, pthread_mutex_lock(&m.lock));
2114 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2115 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002116 if (protocol == PTHREAD_PRIO_NONE) {
2117 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
2118 } else {
2119 ASSERT_EQ(EDEADLK, pthread_mutex_trylock(&m.lock));
2120 }
Yabin Cui17393b02015-03-21 15:08:25 -07002121 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2122 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01002123}
2124
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002125static void TestPthreadMutexLockRecursive(int protocol) {
2126 PthreadMutex m(PTHREAD_MUTEX_RECURSIVE, protocol);
Derek Xue41996952014-09-25 11:05:32 +01002127
Yabin Cui17393b02015-03-21 15:08:25 -07002128 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002129 ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07002130 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002131 ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07002132 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2133 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2134 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08002135 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
2136 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07002137 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2138 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
2139}
2140
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002141TEST(pthread, pthread_mutex_lock_NORMAL) {
2142 TestPthreadMutexLockNormal(PTHREAD_PRIO_NONE);
2143}
2144
2145TEST(pthread, pthread_mutex_lock_ERRORCHECK) {
2146 TestPthreadMutexLockErrorCheck(PTHREAD_PRIO_NONE);
2147}
2148
2149TEST(pthread, pthread_mutex_lock_RECURSIVE) {
2150 TestPthreadMutexLockRecursive(PTHREAD_PRIO_NONE);
2151}
2152
2153TEST(pthread, pthread_mutex_lock_pi) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002154 TestPthreadMutexLockNormal(PTHREAD_PRIO_INHERIT);
2155 TestPthreadMutexLockErrorCheck(PTHREAD_PRIO_INHERIT);
2156 TestPthreadMutexLockRecursive(PTHREAD_PRIO_INHERIT);
2157}
2158
Yabin Cui5a00ba72018-01-26 17:32:31 -08002159TEST(pthread, pthread_mutex_pi_count_limit) {
2160#if defined(__BIONIC__) && !defined(__LP64__)
2161 // Bionic only supports 65536 pi mutexes in 32-bit programs.
2162 pthread_mutexattr_t attr;
2163 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
2164 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT));
2165 std::vector<pthread_mutex_t> mutexes(65536);
2166 // Test if we can use 65536 pi mutexes at the same time.
2167 // Run 2 times to check if freed pi mutexes can be recycled.
2168 for (int repeat = 0; repeat < 2; ++repeat) {
2169 for (auto& m : mutexes) {
2170 ASSERT_EQ(0, pthread_mutex_init(&m, &attr));
2171 }
2172 pthread_mutex_t m;
2173 ASSERT_EQ(ENOMEM, pthread_mutex_init(&m, &attr));
2174 for (auto& m : mutexes) {
2175 ASSERT_EQ(0, pthread_mutex_lock(&m));
2176 }
2177 for (auto& m : mutexes) {
2178 ASSERT_EQ(0, pthread_mutex_unlock(&m));
2179 }
2180 for (auto& m : mutexes) {
2181 ASSERT_EQ(0, pthread_mutex_destroy(&m));
2182 }
2183 }
2184 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
2185#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002186 GTEST_SKIP() << "pi mutex count not limited to 64Ki";
Yabin Cui5a00ba72018-01-26 17:32:31 -08002187#endif
2188}
2189
Yabin Cui17393b02015-03-21 15:08:25 -07002190TEST(pthread, pthread_mutex_init_same_as_static_initializers) {
2191 pthread_mutex_t lock_normal = PTHREAD_MUTEX_INITIALIZER;
2192 PthreadMutex m1(PTHREAD_MUTEX_NORMAL);
2193 ASSERT_EQ(0, memcmp(&lock_normal, &m1.lock, sizeof(pthread_mutex_t)));
2194 pthread_mutex_destroy(&lock_normal);
2195
Colin Cross4c5595c2021-08-16 15:51:59 -07002196#if !defined(ANDROID_HOST_MUSL)
Colin Cross7da20342021-07-28 11:18:11 -07002197 // musl doesn't support PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP or
2198 // PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP.
Yabin Cui17393b02015-03-21 15:08:25 -07002199 pthread_mutex_t lock_errorcheck = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
2200 PthreadMutex m2(PTHREAD_MUTEX_ERRORCHECK);
2201 ASSERT_EQ(0, memcmp(&lock_errorcheck, &m2.lock, sizeof(pthread_mutex_t)));
2202 pthread_mutex_destroy(&lock_errorcheck);
2203
2204 pthread_mutex_t lock_recursive = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
2205 PthreadMutex m3(PTHREAD_MUTEX_RECURSIVE);
2206 ASSERT_EQ(0, memcmp(&lock_recursive, &m3.lock, sizeof(pthread_mutex_t)));
2207 ASSERT_EQ(0, pthread_mutex_destroy(&lock_recursive));
Colin Cross7da20342021-07-28 11:18:11 -07002208#endif
Derek Xue41996952014-09-25 11:05:32 +01002209}
Yabin Cui5a00ba72018-01-26 17:32:31 -08002210
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002211class MutexWakeupHelper {
2212 private:
Yabin Cui17393b02015-03-21 15:08:25 -07002213 PthreadMutex m;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002214 enum Progress {
2215 LOCK_INITIALIZED,
2216 LOCK_WAITING,
2217 LOCK_RELEASED,
2218 LOCK_ACCESSED
2219 };
2220 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -07002221 std::atomic<pid_t> tid;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002222
2223 static void thread_fn(MutexWakeupHelper* helper) {
Yabin Cuif7969852015-04-02 17:47:48 -07002224 helper->tid = gettid();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002225 ASSERT_EQ(LOCK_INITIALIZED, helper->progress);
2226 helper->progress = LOCK_WAITING;
2227
Yabin Cui17393b02015-03-21 15:08:25 -07002228 ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002229 ASSERT_EQ(LOCK_RELEASED, helper->progress);
Yabin Cui17393b02015-03-21 15:08:25 -07002230 ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002231
2232 helper->progress = LOCK_ACCESSED;
2233 }
2234
2235 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -07002236 explicit MutexWakeupHelper(int mutex_type) : m(mutex_type) {
Yabin Cui17393b02015-03-21 15:08:25 -07002237 }
2238
2239 void test() {
2240 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002241 progress = LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -07002242 tid = 0;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002243
2244 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002245 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002246 reinterpret_cast<void* (*)(void*)>(MutexWakeupHelper::thread_fn), this));
2247
Yabin Cuif7969852015-04-02 17:47:48 -07002248 WaitUntilThreadSleep(tid);
2249 ASSERT_EQ(LOCK_WAITING, progress);
2250
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002251 progress = LOCK_RELEASED;
Yabin Cui17393b02015-03-21 15:08:25 -07002252 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002253
Yi Kong32bc0fc2018-08-02 17:31:13 -07002254 ASSERT_EQ(0, pthread_join(thread, nullptr));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002255 ASSERT_EQ(LOCK_ACCESSED, progress);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002256 }
2257};
2258
2259TEST(pthread, pthread_mutex_NORMAL_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07002260 MutexWakeupHelper helper(PTHREAD_MUTEX_NORMAL);
2261 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002262}
2263
2264TEST(pthread, pthread_mutex_ERRORCHECK_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07002265 MutexWakeupHelper helper(PTHREAD_MUTEX_ERRORCHECK);
2266 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002267}
2268
2269TEST(pthread, pthread_mutex_RECURSIVE_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07002270 MutexWakeupHelper helper(PTHREAD_MUTEX_RECURSIVE);
2271 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002272}
2273
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002274static int GetThreadPriority(pid_t tid) {
2275 // sched_getparam() returns the static priority of a thread, which can't reflect a thread's
2276 // priority after priority inheritance. So read /proc/<pid>/stat to get the dynamic priority.
2277 std::string filename = android::base::StringPrintf("/proc/%d/stat", tid);
2278 std::string content;
2279 int result = INT_MAX;
2280 if (!android::base::ReadFileToString(filename, &content)) {
2281 return result;
2282 }
2283 std::vector<std::string> strs = android::base::Split(content, " ");
2284 if (strs.size() < 18) {
2285 return result;
2286 }
2287 if (!android::base::ParseInt(strs[17], &result)) {
2288 return INT_MAX;
2289 }
2290 return result;
2291}
2292
2293class PIMutexWakeupHelper {
2294private:
2295 PthreadMutex m;
2296 int protocol;
2297 enum Progress {
2298 LOCK_INITIALIZED,
2299 LOCK_CHILD_READY,
2300 LOCK_WAITING,
2301 LOCK_RELEASED,
2302 };
2303 std::atomic<Progress> progress;
2304 std::atomic<pid_t> main_tid;
2305 std::atomic<pid_t> child_tid;
2306 PthreadMutex start_thread_m;
2307
2308 static void thread_fn(PIMutexWakeupHelper* helper) {
2309 helper->child_tid = gettid();
2310 ASSERT_EQ(LOCK_INITIALIZED, helper->progress);
2311 ASSERT_EQ(0, setpriority(PRIO_PROCESS, gettid(), 1));
2312 ASSERT_EQ(21, GetThreadPriority(gettid()));
2313 ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock));
2314 helper->progress = LOCK_CHILD_READY;
2315 ASSERT_EQ(0, pthread_mutex_lock(&helper->start_thread_m.lock));
2316
2317 ASSERT_EQ(0, pthread_mutex_unlock(&helper->start_thread_m.lock));
2318 WaitUntilThreadSleep(helper->main_tid);
2319 ASSERT_EQ(LOCK_WAITING, helper->progress);
2320
2321 if (helper->protocol == PTHREAD_PRIO_INHERIT) {
2322 ASSERT_EQ(20, GetThreadPriority(gettid()));
2323 } else {
2324 ASSERT_EQ(21, GetThreadPriority(gettid()));
2325 }
2326 helper->progress = LOCK_RELEASED;
2327 ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock));
2328 }
2329
2330public:
2331 explicit PIMutexWakeupHelper(int mutex_type, int protocol)
2332 : m(mutex_type, protocol), protocol(protocol), start_thread_m(PTHREAD_MUTEX_NORMAL) {
2333 }
2334
2335 void test() {
2336 ASSERT_EQ(0, pthread_mutex_lock(&start_thread_m.lock));
2337 main_tid = gettid();
2338 ASSERT_EQ(20, GetThreadPriority(main_tid));
2339 progress = LOCK_INITIALIZED;
2340 child_tid = 0;
2341
2342 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002343 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002344 reinterpret_cast<void* (*)(void*)>(PIMutexWakeupHelper::thread_fn), this));
2345
2346 WaitUntilThreadSleep(child_tid);
2347 ASSERT_EQ(LOCK_CHILD_READY, progress);
2348 ASSERT_EQ(0, pthread_mutex_unlock(&start_thread_m.lock));
2349 progress = LOCK_WAITING;
2350 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
2351
2352 ASSERT_EQ(LOCK_RELEASED, progress);
2353 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2354 ASSERT_EQ(0, pthread_join(thread, nullptr));
2355 }
2356};
2357
2358TEST(pthread, pthread_mutex_pi_wakeup) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002359 for (int type : {PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_RECURSIVE, PTHREAD_MUTEX_ERRORCHECK}) {
2360 for (int protocol : {PTHREAD_PRIO_INHERIT}) {
2361 PIMutexWakeupHelper helper(type, protocol);
2362 helper.test();
2363 }
2364 }
2365}
2366
Yabin Cui140f3672015-02-03 10:32:00 -08002367TEST(pthread, pthread_mutex_owner_tid_limit) {
Yabin Cuie69c2452015-02-13 16:21:25 -08002368#if defined(__BIONIC__) && !defined(__LP64__)
Yabin Cui140f3672015-02-03 10:32:00 -08002369 FILE* fp = fopen("/proc/sys/kernel/pid_max", "r");
Yi Kong32bc0fc2018-08-02 17:31:13 -07002370 ASSERT_TRUE(fp != nullptr);
Yabin Cui140f3672015-02-03 10:32:00 -08002371 long pid_max;
2372 ASSERT_EQ(1, fscanf(fp, "%ld", &pid_max));
2373 fclose(fp);
Yabin Cuie69c2452015-02-13 16:21:25 -08002374 // Bionic's pthread_mutex implementation on 32-bit devices uses 16 bits to represent owner tid.
Yabin Cui140f3672015-02-03 10:32:00 -08002375 ASSERT_LE(pid_max, 65536);
Yabin Cuie69c2452015-02-13 16:21:25 -08002376#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002377 GTEST_SKIP() << "pthread_mutex supports 32-bit tid";
Yabin Cuie69c2452015-02-13 16:21:25 -08002378#endif
Yabin Cui140f3672015-02-03 10:32:00 -08002379}
Yabin Cuib5845722015-03-16 22:46:42 -07002380
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002381static void pthread_mutex_timedlock_helper(clockid_t clock,
2382 int (*lock_function)(pthread_mutex_t* __mutex,
2383 const timespec* __timeout)) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08002384 pthread_mutex_t m;
2385 ASSERT_EQ(0, pthread_mutex_init(&m, nullptr));
2386
2387 // If the mutex is already locked, pthread_mutex_timedlock should time out.
2388 ASSERT_EQ(0, pthread_mutex_lock(&m));
2389
2390 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002391 ASSERT_EQ(0, clock_gettime(clock, &ts));
2392 ASSERT_EQ(ETIMEDOUT, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002393 ts.tv_nsec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002394 ASSERT_EQ(EINVAL, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002395 ts.tv_nsec = NS_PER_S;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002396 ASSERT_EQ(EINVAL, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002397 ts.tv_nsec = NS_PER_S - 1;
2398 ts.tv_sec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002399 ASSERT_EQ(ETIMEDOUT, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002400
Andy Hung5e19b182023-12-11 19:28:02 -08002401 // check we wait long enough for the lock.
2402 ASSERT_EQ(0, clock_gettime(clock, &ts));
2403 const int64_t start_ns = ts.tv_sec * NS_PER_S + ts.tv_nsec;
2404
2405 // add a second to get deadline.
2406 ts.tv_sec += 1;
2407
2408 ASSERT_EQ(ETIMEDOUT, lock_function(&m, &ts));
2409
2410 // The timedlock must have waited at least 1 second before returning.
2411 clock_gettime(clock, &ts);
2412 const int64_t end_ns = ts.tv_sec * NS_PER_S + ts.tv_nsec;
2413 ASSERT_GT(end_ns - start_ns, NS_PER_S);
2414
Yabin Cuic9a659c2015-11-05 15:36:08 -08002415 // If the mutex is unlocked, pthread_mutex_timedlock should succeed.
2416 ASSERT_EQ(0, pthread_mutex_unlock(&m));
2417
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002418 ASSERT_EQ(0, clock_gettime(clock, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002419 ts.tv_sec += 1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002420 ASSERT_EQ(0, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002421
2422 ASSERT_EQ(0, pthread_mutex_unlock(&m));
2423 ASSERT_EQ(0, pthread_mutex_destroy(&m));
2424}
2425
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002426TEST(pthread, pthread_mutex_timedlock) {
2427 pthread_mutex_timedlock_helper(CLOCK_REALTIME, pthread_mutex_timedlock);
2428}
2429
2430TEST(pthread, pthread_mutex_timedlock_monotonic_np) {
2431#if defined(__BIONIC__)
2432 pthread_mutex_timedlock_helper(CLOCK_MONOTONIC, pthread_mutex_timedlock_monotonic_np);
2433#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002434 GTEST_SKIP() << "pthread_mutex_timedlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002435#endif // __BIONIC__
2436}
2437
Tom Cherry69010802019-05-07 20:33:05 -07002438TEST(pthread, pthread_mutex_clocklock) {
2439#if defined(__BIONIC__)
2440 pthread_mutex_timedlock_helper(
2441 CLOCK_MONOTONIC, [](pthread_mutex_t* __mutex, const timespec* __timeout) {
2442 return pthread_mutex_clocklock(__mutex, CLOCK_MONOTONIC, __timeout);
2443 });
2444 pthread_mutex_timedlock_helper(
2445 CLOCK_REALTIME, [](pthread_mutex_t* __mutex, const timespec* __timeout) {
2446 return pthread_mutex_clocklock(__mutex, CLOCK_REALTIME, __timeout);
2447 });
2448#else // __BIONIC__
2449 GTEST_SKIP() << "pthread_mutex_clocklock not available";
2450#endif // __BIONIC__
2451}
2452
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002453static void pthread_mutex_timedlock_pi_helper(clockid_t clock,
2454 int (*lock_function)(pthread_mutex_t* __mutex,
2455 const timespec* __timeout)) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002456 PthreadMutex m(PTHREAD_MUTEX_NORMAL, PTHREAD_PRIO_INHERIT);
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002457
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002458 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002459 clock_gettime(clock, &ts);
Andy Hung5e19b182023-12-11 19:28:02 -08002460 const int64_t start_ns = ts.tv_sec * NS_PER_S + ts.tv_nsec;
2461
2462 // add a second to get deadline.
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002463 ts.tv_sec += 1;
Andy Hung5e19b182023-12-11 19:28:02 -08002464
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002465 ASSERT_EQ(0, lock_function(&m.lock, &ts));
2466
2467 struct ThreadArgs {
2468 clockid_t clock;
2469 int (*lock_function)(pthread_mutex_t* __mutex, const timespec* __timeout);
2470 PthreadMutex& m;
2471 };
2472
2473 ThreadArgs thread_args = {
2474 .clock = clock,
2475 .lock_function = lock_function,
2476 .m = m,
2477 };
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002478
2479 auto ThreadFn = [](void* arg) -> void* {
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002480 auto args = static_cast<ThreadArgs*>(arg);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002481 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002482 clock_gettime(args->clock, &ts);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002483 ts.tv_sec += 1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002484 intptr_t result = args->lock_function(&args->m.lock, &ts);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002485 return reinterpret_cast<void*>(result);
2486 };
2487
2488 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002489 ASSERT_EQ(0, pthread_create(&thread, nullptr, ThreadFn, &thread_args));
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002490 void* result;
2491 ASSERT_EQ(0, pthread_join(thread, &result));
2492 ASSERT_EQ(ETIMEDOUT, reinterpret_cast<intptr_t>(result));
Andy Hung5e19b182023-12-11 19:28:02 -08002493
2494 // The timedlock must have waited at least 1 second before returning.
2495 clock_gettime(clock, &ts);
2496 const int64_t end_ns = ts.tv_sec * NS_PER_S + ts.tv_nsec;
2497 ASSERT_GT(end_ns - start_ns, NS_PER_S);
2498
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002499 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2500}
2501
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002502TEST(pthread, pthread_mutex_timedlock_pi) {
2503 pthread_mutex_timedlock_pi_helper(CLOCK_REALTIME, pthread_mutex_timedlock);
2504}
2505
2506TEST(pthread, pthread_mutex_timedlock_monotonic_np_pi) {
2507#if defined(__BIONIC__)
2508 pthread_mutex_timedlock_pi_helper(CLOCK_MONOTONIC, pthread_mutex_timedlock_monotonic_np);
2509#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002510 GTEST_SKIP() << "pthread_mutex_timedlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002511#endif // __BIONIC__
2512}
2513
Tom Cherry69010802019-05-07 20:33:05 -07002514TEST(pthread, pthread_mutex_clocklock_pi) {
2515#if defined(__BIONIC__)
2516 pthread_mutex_timedlock_pi_helper(
2517 CLOCK_MONOTONIC, [](pthread_mutex_t* __mutex, const timespec* __timeout) {
2518 return pthread_mutex_clocklock(__mutex, CLOCK_MONOTONIC, __timeout);
2519 });
2520 pthread_mutex_timedlock_pi_helper(
2521 CLOCK_REALTIME, [](pthread_mutex_t* __mutex, const timespec* __timeout) {
2522 return pthread_mutex_clocklock(__mutex, CLOCK_REALTIME, __timeout);
2523 });
2524#else // __BIONIC__
2525 GTEST_SKIP() << "pthread_mutex_clocklock not available";
2526#endif // __BIONIC__
2527}
2528
2529TEST(pthread, pthread_mutex_clocklock_invalid) {
2530#if defined(__BIONIC__)
2531 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
2532 timespec ts;
2533 EXPECT_EQ(EINVAL, pthread_mutex_clocklock(&mutex, CLOCK_PROCESS_CPUTIME_ID, &ts));
2534#else // __BIONIC__
2535 GTEST_SKIP() << "pthread_mutex_clocklock not available";
2536#endif // __BIONIC__
2537}
2538
Elliott Hughese657eb42021-02-18 17:11:56 -08002539TEST_F(pthread_DeathTest, pthread_mutex_using_destroyed_mutex) {
Yabin Cui9651fdf2018-03-14 12:02:21 -07002540#if defined(__BIONIC__)
2541 pthread_mutex_t m;
2542 ASSERT_EQ(0, pthread_mutex_init(&m, nullptr));
2543 ASSERT_EQ(0, pthread_mutex_destroy(&m));
2544 ASSERT_EXIT(pthread_mutex_lock(&m), ::testing::KilledBySignal(SIGABRT),
2545 "pthread_mutex_lock called on a destroyed mutex");
2546 ASSERT_EXIT(pthread_mutex_unlock(&m), ::testing::KilledBySignal(SIGABRT),
2547 "pthread_mutex_unlock called on a destroyed mutex");
2548 ASSERT_EXIT(pthread_mutex_trylock(&m), ::testing::KilledBySignal(SIGABRT),
2549 "pthread_mutex_trylock called on a destroyed mutex");
2550 timespec ts;
2551 ASSERT_EXIT(pthread_mutex_timedlock(&m, &ts), ::testing::KilledBySignal(SIGABRT),
2552 "pthread_mutex_timedlock called on a destroyed mutex");
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002553 ASSERT_EXIT(pthread_mutex_timedlock_monotonic_np(&m, &ts), ::testing::KilledBySignal(SIGABRT),
2554 "pthread_mutex_timedlock_monotonic_np called on a destroyed mutex");
Tom Cherry69010802019-05-07 20:33:05 -07002555 ASSERT_EXIT(pthread_mutex_clocklock(&m, CLOCK_MONOTONIC, &ts), ::testing::KilledBySignal(SIGABRT),
2556 "pthread_mutex_clocklock called on a destroyed mutex");
2557 ASSERT_EXIT(pthread_mutex_clocklock(&m, CLOCK_REALTIME, &ts), ::testing::KilledBySignal(SIGABRT),
2558 "pthread_mutex_clocklock called on a destroyed mutex");
2559 ASSERT_EXIT(pthread_mutex_clocklock(&m, CLOCK_PROCESS_CPUTIME_ID, &ts),
2560 ::testing::KilledBySignal(SIGABRT),
2561 "pthread_mutex_clocklock called on a destroyed mutex");
Yabin Cui9651fdf2018-03-14 12:02:21 -07002562 ASSERT_EXIT(pthread_mutex_destroy(&m), ::testing::KilledBySignal(SIGABRT),
2563 "pthread_mutex_destroy called on a destroyed mutex");
2564#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002565 GTEST_SKIP() << "bionic-only test";
Yabin Cui9651fdf2018-03-14 12:02:21 -07002566#endif
2567}
2568
Yabin Cuib5845722015-03-16 22:46:42 -07002569class StrictAlignmentAllocator {
2570 public:
2571 void* allocate(size_t size, size_t alignment) {
2572 char* p = new char[size + alignment * 2];
2573 allocated_array.push_back(p);
2574 while (!is_strict_aligned(p, alignment)) {
2575 ++p;
2576 }
2577 return p;
2578 }
2579
2580 ~StrictAlignmentAllocator() {
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07002581 for (const auto& p : allocated_array) {
2582 delete[] p;
Yabin Cuib5845722015-03-16 22:46:42 -07002583 }
2584 }
2585
2586 private:
2587 bool is_strict_aligned(char* p, size_t alignment) {
2588 return (reinterpret_cast<uintptr_t>(p) % (alignment * 2)) == alignment;
2589 }
2590
2591 std::vector<char*> allocated_array;
2592};
2593
2594TEST(pthread, pthread_types_allow_four_bytes_alignment) {
2595#if defined(__BIONIC__)
2596 // For binary compatibility with old version, we need to allow 4-byte aligned data for pthread types.
2597 StrictAlignmentAllocator allocator;
2598 pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(
2599 allocator.allocate(sizeof(pthread_mutex_t), 4));
Yi Kong32bc0fc2018-08-02 17:31:13 -07002600 ASSERT_EQ(0, pthread_mutex_init(mutex, nullptr));
Yabin Cuib5845722015-03-16 22:46:42 -07002601 ASSERT_EQ(0, pthread_mutex_lock(mutex));
2602 ASSERT_EQ(0, pthread_mutex_unlock(mutex));
2603 ASSERT_EQ(0, pthread_mutex_destroy(mutex));
2604
2605 pthread_cond_t* cond = reinterpret_cast<pthread_cond_t*>(
2606 allocator.allocate(sizeof(pthread_cond_t), 4));
Yi Kong32bc0fc2018-08-02 17:31:13 -07002607 ASSERT_EQ(0, pthread_cond_init(cond, nullptr));
Yabin Cuib5845722015-03-16 22:46:42 -07002608 ASSERT_EQ(0, pthread_cond_signal(cond));
2609 ASSERT_EQ(0, pthread_cond_broadcast(cond));
2610 ASSERT_EQ(0, pthread_cond_destroy(cond));
2611
2612 pthread_rwlock_t* rwlock = reinterpret_cast<pthread_rwlock_t*>(
2613 allocator.allocate(sizeof(pthread_rwlock_t), 4));
Yi Kong32bc0fc2018-08-02 17:31:13 -07002614 ASSERT_EQ(0, pthread_rwlock_init(rwlock, nullptr));
Yabin Cuib5845722015-03-16 22:46:42 -07002615 ASSERT_EQ(0, pthread_rwlock_rdlock(rwlock));
2616 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
2617 ASSERT_EQ(0, pthread_rwlock_wrlock(rwlock));
2618 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
2619 ASSERT_EQ(0, pthread_rwlock_destroy(rwlock));
2620
2621#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002622 GTEST_SKIP() << "bionic-only test";
Yabin Cuib5845722015-03-16 22:46:42 -07002623#endif
2624}
Christopher Ferris60907c72015-06-09 18:46:15 -07002625
2626TEST(pthread, pthread_mutex_lock_null_32) {
2627#if defined(__BIONIC__) && !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -07002628 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return
2629 // EINVAL in that case: http://b/19995172.
2630 //
2631 // We decorate the public defintion with _Nonnull so that people recompiling
2632 // their code with get a warning and might fix their bug, but need to pass
2633 // NULL here to test that we remain compatible.
2634 pthread_mutex_t* null_value = nullptr;
2635 ASSERT_EQ(EINVAL, pthread_mutex_lock(null_value));
Christopher Ferris60907c72015-06-09 18:46:15 -07002636#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002637 GTEST_SKIP() << "32-bit bionic-only test";
Christopher Ferris60907c72015-06-09 18:46:15 -07002638#endif
2639}
2640
2641TEST(pthread, pthread_mutex_unlock_null_32) {
2642#if defined(__BIONIC__) && !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -07002643 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return
2644 // EINVAL in that case: http://b/19995172.
2645 //
2646 // We decorate the public defintion with _Nonnull so that people recompiling
2647 // their code with get a warning and might fix their bug, but need to pass
2648 // NULL here to test that we remain compatible.
2649 pthread_mutex_t* null_value = nullptr;
2650 ASSERT_EQ(EINVAL, pthread_mutex_unlock(null_value));
Christopher Ferris60907c72015-06-09 18:46:15 -07002651#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002652 GTEST_SKIP() << "32-bit bionic-only test";
Christopher Ferris60907c72015-06-09 18:46:15 -07002653#endif
2654}
2655
2656TEST_F(pthread_DeathTest, pthread_mutex_lock_null_64) {
2657#if defined(__BIONIC__) && defined(__LP64__)
2658 pthread_mutex_t* null_value = nullptr;
2659 ASSERT_EXIT(pthread_mutex_lock(null_value), testing::KilledBySignal(SIGSEGV), "");
2660#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002661 GTEST_SKIP() << "64-bit bionic-only test";
Christopher Ferris60907c72015-06-09 18:46:15 -07002662#endif
2663}
2664
2665TEST_F(pthread_DeathTest, pthread_mutex_unlock_null_64) {
2666#if defined(__BIONIC__) && defined(__LP64__)
2667 pthread_mutex_t* null_value = nullptr;
2668 ASSERT_EXIT(pthread_mutex_unlock(null_value), testing::KilledBySignal(SIGSEGV), "");
2669#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002670 GTEST_SKIP() << "64-bit bionic-only test";
Christopher Ferris60907c72015-06-09 18:46:15 -07002671#endif
2672}
Yabin Cui33ac04a2015-09-22 11:16:15 -07002673
2674extern _Unwind_Reason_Code FrameCounter(_Unwind_Context* ctx, void* arg);
2675
2676static volatile bool signal_handler_on_altstack_done;
2677
Josh Gao61db9ac2017-03-15 19:42:05 -07002678__attribute__((__noinline__))
2679static void signal_handler_backtrace() {
2680 // Check if we have enough stack space for unwinding.
2681 int count = 0;
2682 _Unwind_Backtrace(FrameCounter, &count);
2683 ASSERT_GT(count, 0);
2684}
2685
2686__attribute__((__noinline__))
2687static void signal_handler_logging() {
2688 // Check if we have enough stack space for logging.
2689 std::string s(2048, '*');
2690 GTEST_LOG_(INFO) << s;
2691 signal_handler_on_altstack_done = true;
2692}
2693
2694__attribute__((__noinline__))
2695static void signal_handler_snprintf() {
2696 // Check if we have enough stack space for snprintf to a PATH_MAX buffer, plus some extra.
2697 char buf[PATH_MAX + 2048];
2698 ASSERT_GT(snprintf(buf, sizeof(buf), "/proc/%d/status", getpid()), 0);
2699}
2700
Yabin Cui33ac04a2015-09-22 11:16:15 -07002701static void SignalHandlerOnAltStack(int signo, siginfo_t*, void*) {
2702 ASSERT_EQ(SIGUSR1, signo);
Josh Gao61db9ac2017-03-15 19:42:05 -07002703 signal_handler_backtrace();
2704 signal_handler_logging();
2705 signal_handler_snprintf();
Yabin Cui33ac04a2015-09-22 11:16:15 -07002706}
2707
Josh Gao415daa82017-03-06 17:45:33 -08002708TEST(pthread, big_enough_signal_stack) {
Yabin Cui33ac04a2015-09-22 11:16:15 -07002709 signal_handler_on_altstack_done = false;
2710 ScopedSignalHandler handler(SIGUSR1, SignalHandlerOnAltStack, SA_SIGINFO | SA_ONSTACK);
2711 kill(getpid(), SIGUSR1);
2712 ASSERT_TRUE(signal_handler_on_altstack_done);
2713}
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002714
2715TEST(pthread, pthread_barrierattr_smoke) {
2716 pthread_barrierattr_t attr;
2717 ASSERT_EQ(0, pthread_barrierattr_init(&attr));
2718 int pshared;
2719 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
2720 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
2721 ASSERT_EQ(0, pthread_barrierattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
2722 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
2723 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
2724 ASSERT_EQ(0, pthread_barrierattr_destroy(&attr));
2725}
2726
Yabin Cui81d27972016-03-22 13:45:55 -07002727struct BarrierTestHelperData {
2728 size_t thread_count;
2729 pthread_barrier_t barrier;
2730 std::atomic<int> finished_mask;
2731 std::atomic<int> serial_thread_count;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002732 size_t iteration_count;
Yabin Cui81d27972016-03-22 13:45:55 -07002733 std::atomic<size_t> finished_iteration_count;
2734
2735 BarrierTestHelperData(size_t thread_count, size_t iteration_count)
2736 : thread_count(thread_count), finished_mask(0), serial_thread_count(0),
2737 iteration_count(iteration_count), finished_iteration_count(0) {
2738 }
2739};
2740
2741struct BarrierTestHelperArg {
2742 int id;
2743 BarrierTestHelperData* data;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002744};
2745
2746static void BarrierTestHelper(BarrierTestHelperArg* arg) {
Yabin Cui81d27972016-03-22 13:45:55 -07002747 for (size_t i = 0; i < arg->data->iteration_count; ++i) {
2748 int result = pthread_barrier_wait(&arg->data->barrier);
2749 if (result == PTHREAD_BARRIER_SERIAL_THREAD) {
2750 arg->data->serial_thread_count++;
2751 } else {
2752 ASSERT_EQ(0, result);
2753 }
Yabin Cuid5c04c52017-05-02 12:57:39 -07002754 int mask = arg->data->finished_mask.fetch_or(1 << arg->id);
Yabin Cuiab4cddc2017-05-02 16:18:13 -07002755 mask |= 1 << arg->id;
Yabin Cuid5c04c52017-05-02 12:57:39 -07002756 if (mask == ((1 << arg->data->thread_count) - 1)) {
Yabin Cui81d27972016-03-22 13:45:55 -07002757 ASSERT_EQ(1, arg->data->serial_thread_count);
2758 arg->data->finished_iteration_count++;
2759 arg->data->finished_mask = 0;
2760 arg->data->serial_thread_count = 0;
2761 }
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002762 }
2763}
2764
2765TEST(pthread, pthread_barrier_smoke) {
2766 const size_t BARRIER_ITERATION_COUNT = 10;
2767 const size_t BARRIER_THREAD_COUNT = 10;
Yabin Cui81d27972016-03-22 13:45:55 -07002768 BarrierTestHelperData data(BARRIER_THREAD_COUNT, BARRIER_ITERATION_COUNT);
2769 ASSERT_EQ(0, pthread_barrier_init(&data.barrier, nullptr, data.thread_count));
2770 std::vector<pthread_t> threads(data.thread_count);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002771 std::vector<BarrierTestHelperArg> args(threads.size());
2772 for (size_t i = 0; i < threads.size(); ++i) {
Yabin Cui81d27972016-03-22 13:45:55 -07002773 args[i].id = i;
2774 args[i].data = &data;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002775 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
2776 reinterpret_cast<void* (*)(void*)>(BarrierTestHelper), &args[i]));
2777 }
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002778 for (size_t i = 0; i < threads.size(); ++i) {
2779 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
2780 }
Yabin Cui81d27972016-03-22 13:45:55 -07002781 ASSERT_EQ(data.iteration_count, data.finished_iteration_count);
2782 ASSERT_EQ(0, pthread_barrier_destroy(&data.barrier));
2783}
2784
2785struct BarrierDestroyTestArg {
2786 std::atomic<int> tid;
2787 pthread_barrier_t* barrier;
2788};
2789
2790static void BarrierDestroyTestHelper(BarrierDestroyTestArg* arg) {
2791 arg->tid = gettid();
2792 ASSERT_EQ(0, pthread_barrier_wait(arg->barrier));
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002793}
2794
2795TEST(pthread, pthread_barrier_destroy) {
2796 pthread_barrier_t barrier;
2797 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, 2));
2798 pthread_t thread;
Yabin Cui81d27972016-03-22 13:45:55 -07002799 BarrierDestroyTestArg arg;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002800 arg.tid = 0;
2801 arg.barrier = &barrier;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002802 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui81d27972016-03-22 13:45:55 -07002803 reinterpret_cast<void* (*)(void*)>(BarrierDestroyTestHelper), &arg));
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002804 WaitUntilThreadSleep(arg.tid);
2805 ASSERT_EQ(EBUSY, pthread_barrier_destroy(&barrier));
2806 ASSERT_EQ(PTHREAD_BARRIER_SERIAL_THREAD, pthread_barrier_wait(&barrier));
2807 // Verify if the barrier can be destroyed directly after pthread_barrier_wait().
2808 ASSERT_EQ(0, pthread_barrier_destroy(&barrier));
2809 ASSERT_EQ(0, pthread_join(thread, nullptr));
2810#if defined(__BIONIC__)
2811 ASSERT_EQ(EINVAL, pthread_barrier_destroy(&barrier));
2812#endif
2813}
2814
2815struct BarrierOrderingTestHelperArg {
2816 pthread_barrier_t* barrier;
2817 size_t* array;
2818 size_t array_length;
2819 size_t id;
2820};
2821
2822void BarrierOrderingTestHelper(BarrierOrderingTestHelperArg* arg) {
2823 const size_t ITERATION_COUNT = 10000;
2824 for (size_t i = 1; i <= ITERATION_COUNT; ++i) {
2825 arg->array[arg->id] = i;
Yabin Cuic9a659c2015-11-05 15:36:08 -08002826 int result = pthread_barrier_wait(arg->barrier);
2827 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002828 for (size_t j = 0; j < arg->array_length; ++j) {
2829 ASSERT_EQ(i, arg->array[j]);
2830 }
Yabin Cuic9a659c2015-11-05 15:36:08 -08002831 result = pthread_barrier_wait(arg->barrier);
2832 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002833 }
2834}
2835
2836TEST(pthread, pthread_barrier_check_ordering) {
2837 const size_t THREAD_COUNT = 4;
2838 pthread_barrier_t barrier;
2839 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, THREAD_COUNT));
2840 size_t array[THREAD_COUNT];
2841 std::vector<pthread_t> threads(THREAD_COUNT);
2842 std::vector<BarrierOrderingTestHelperArg> args(THREAD_COUNT);
2843 for (size_t i = 0; i < THREAD_COUNT; ++i) {
2844 args[i].barrier = &barrier;
2845 args[i].array = array;
2846 args[i].array_length = THREAD_COUNT;
2847 args[i].id = i;
2848 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
2849 reinterpret_cast<void* (*)(void*)>(BarrierOrderingTestHelper),
2850 &args[i]));
2851 }
2852 for (size_t i = 0; i < THREAD_COUNT; ++i) {
2853 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
2854 }
2855}
Yabin Cuife3a83a2015-11-17 16:03:18 -08002856
Elliott Hughes463faad2018-07-06 14:34:49 -07002857TEST(pthread, pthread_barrier_init_zero_count) {
2858 pthread_barrier_t barrier;
2859 ASSERT_EQ(EINVAL, pthread_barrier_init(&barrier, nullptr, 0));
2860}
2861
Yabin Cuife3a83a2015-11-17 16:03:18 -08002862TEST(pthread, pthread_spinlock_smoke) {
2863 pthread_spinlock_t lock;
2864 ASSERT_EQ(0, pthread_spin_init(&lock, 0));
2865 ASSERT_EQ(0, pthread_spin_trylock(&lock));
2866 ASSERT_EQ(0, pthread_spin_unlock(&lock));
2867 ASSERT_EQ(0, pthread_spin_lock(&lock));
2868 ASSERT_EQ(EBUSY, pthread_spin_trylock(&lock));
2869 ASSERT_EQ(0, pthread_spin_unlock(&lock));
2870 ASSERT_EQ(0, pthread_spin_destroy(&lock));
2871}
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002872
Elliott Hughes8aecba72017-10-17 15:34:41 -07002873TEST(pthread, pthread_attr_getdetachstate__pthread_attr_setdetachstate) {
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002874 pthread_attr_t attr;
2875 ASSERT_EQ(0, pthread_attr_init(&attr));
2876
Elliott Hughes8aecba72017-10-17 15:34:41 -07002877 int state;
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002878 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002879 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2880 ASSERT_EQ(PTHREAD_CREATE_DETACHED, state);
2881
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002882 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002883 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2884 ASSERT_EQ(PTHREAD_CREATE_JOINABLE, state);
2885
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002886 ASSERT_EQ(EINVAL, pthread_attr_setdetachstate(&attr, 123));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002887 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2888 ASSERT_EQ(PTHREAD_CREATE_JOINABLE, state);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002889}
2890
2891TEST(pthread, pthread_create__mmap_failures) {
Evgeny Eltsinb4f7aaa2020-06-09 15:49:20 +02002892 // After thread is successfully created, native_bridge might need more memory to run it.
2893 SKIP_WITH_NATIVE_BRIDGE;
2894
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002895 pthread_attr_t attr;
2896 ASSERT_EQ(0, pthread_attr_init(&attr));
2897 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
2898
2899 const auto kPageSize = sysconf(_SC_PAGE_SIZE);
2900
Elliott Hughes57512982017-10-02 22:49:18 -07002901 // Use up all the VMAs. By default this is 64Ki (though some will already be in use).
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002902 std::vector<void*> pages;
Elliott Hughes57512982017-10-02 22:49:18 -07002903 pages.reserve(64 * 1024);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002904 int prot = PROT_NONE;
2905 while (true) {
2906 void* page = mmap(nullptr, kPageSize, prot, MAP_ANON|MAP_PRIVATE, -1, 0);
2907 if (page == MAP_FAILED) break;
2908 pages.push_back(page);
2909 prot = (prot == PROT_NONE) ? PROT_READ : PROT_NONE;
2910 }
2911
2912 // Try creating threads, freeing up a page each time we fail.
2913 size_t EAGAIN_count = 0;
2914 size_t i = 0;
2915 for (; i < pages.size(); ++i) {
2916 pthread_t t;
2917 int status = pthread_create(&t, &attr, IdFn, nullptr);
2918 if (status != EAGAIN) break;
2919 ++EAGAIN_count;
2920 ASSERT_EQ(0, munmap(pages[i], kPageSize));
2921 }
2922
Ryan Prichard45d13492019-01-03 02:51:30 -08002923 // Creating a thread uses at least three VMAs: the combined stack and TLS, and a guard on each
2924 // side. So we should have seen at least three failures.
2925 ASSERT_GE(EAGAIN_count, 3U);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002926
2927 for (; i < pages.size(); ++i) {
2928 ASSERT_EQ(0, munmap(pages[i], kPageSize));
2929 }
2930}
Elliott Hughesdff08ce2017-10-16 09:58:45 -07002931
2932TEST(pthread, pthread_setschedparam) {
2933 sched_param p = { .sched_priority = INT_MIN };
2934 ASSERT_EQ(EINVAL, pthread_setschedparam(pthread_self(), INT_MIN, &p));
2935}
2936
2937TEST(pthread, pthread_setschedprio) {
2938 ASSERT_EQ(EINVAL, pthread_setschedprio(pthread_self(), INT_MIN));
2939}
Elliott Hughes8aecba72017-10-17 15:34:41 -07002940
2941TEST(pthread, pthread_attr_getinheritsched__pthread_attr_setinheritsched) {
2942 pthread_attr_t attr;
2943 ASSERT_EQ(0, pthread_attr_init(&attr));
2944
2945 int state;
2946 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2947 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
2948 ASSERT_EQ(PTHREAD_INHERIT_SCHED, state);
2949
2950 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
2951 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
2952 ASSERT_EQ(PTHREAD_EXPLICIT_SCHED, state);
2953
2954 ASSERT_EQ(EINVAL, pthread_attr_setinheritsched(&attr, 123));
2955 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
2956 ASSERT_EQ(PTHREAD_EXPLICIT_SCHED, state);
2957}
2958
2959TEST(pthread, pthread_attr_setinheritsched__PTHREAD_INHERIT_SCHED__PTHREAD_EXPLICIT_SCHED) {
2960 pthread_attr_t attr;
2961 ASSERT_EQ(0, pthread_attr_init(&attr));
2962
2963 // If we set invalid scheduling attributes but choose to inherit, everything's fine...
2964 sched_param param = { .sched_priority = sched_get_priority_max(SCHED_FIFO) + 1 };
2965 ASSERT_EQ(0, pthread_attr_setschedparam(&attr, &param));
2966 ASSERT_EQ(0, pthread_attr_setschedpolicy(&attr, SCHED_FIFO));
2967 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2968
2969 pthread_t t;
2970 ASSERT_EQ(0, pthread_create(&t, &attr, IdFn, nullptr));
2971 ASSERT_EQ(0, pthread_join(t, nullptr));
2972
Elliott Hughes7a660662017-10-30 09:26:06 -07002973#if defined(__LP64__)
2974 // If we ask to use them, though, we'll see a failure...
Elliott Hughes8aecba72017-10-17 15:34:41 -07002975 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
2976 ASSERT_EQ(EINVAL, pthread_create(&t, &attr, IdFn, nullptr));
Elliott Hughes7a660662017-10-30 09:26:06 -07002977#else
2978 // For backwards compatibility with broken apps, we just ignore failures
2979 // to set scheduler attributes on LP32.
2980#endif
Elliott Hughes8aecba72017-10-17 15:34:41 -07002981}
2982
2983TEST(pthread, pthread_attr_setinheritsched_PTHREAD_INHERIT_SCHED_takes_effect) {
2984 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
2985 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO, &param);
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002986 if (rc == EPERM) GTEST_SKIP() << "pthread_setschedparam failed with EPERM";
Elliott Hughes8aecba72017-10-17 15:34:41 -07002987 ASSERT_EQ(0, rc);
2988
2989 pthread_attr_t attr;
2990 ASSERT_EQ(0, pthread_attr_init(&attr));
2991 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2992
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002993 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07002994 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002995 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002996 int actual_policy;
2997 sched_param actual_param;
2998 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
2999 ASSERT_EQ(SCHED_FIFO, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003000 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07003001 ASSERT_EQ(0, pthread_join(t, nullptr));
3002}
3003
3004TEST(pthread, pthread_attr_setinheritsched_PTHREAD_EXPLICIT_SCHED_takes_effect) {
3005 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
3006 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO, &param);
Elliott Hughesbcaa4542019-03-08 15:20:23 -08003007 if (rc == EPERM) GTEST_SKIP() << "pthread_setschedparam failed with EPERM";
Elliott Hughes8aecba72017-10-17 15:34:41 -07003008 ASSERT_EQ(0, rc);
3009
3010 pthread_attr_t attr;
3011 ASSERT_EQ(0, pthread_attr_init(&attr));
3012 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
3013 ASSERT_EQ(0, pthread_attr_setschedpolicy(&attr, SCHED_OTHER));
3014
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003015 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07003016 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003017 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07003018 int actual_policy;
3019 sched_param actual_param;
3020 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
3021 ASSERT_EQ(SCHED_OTHER, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003022 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07003023 ASSERT_EQ(0, pthread_join(t, nullptr));
3024}
3025
3026TEST(pthread, pthread_attr_setinheritsched__takes_effect_despite_SCHED_RESET_ON_FORK) {
3027 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
3028 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param);
Elliott Hughesbcaa4542019-03-08 15:20:23 -08003029 if (rc == EPERM) GTEST_SKIP() << "pthread_setschedparam failed with EPERM";
Elliott Hughes8aecba72017-10-17 15:34:41 -07003030 ASSERT_EQ(0, rc);
3031
3032 pthread_attr_t attr;
3033 ASSERT_EQ(0, pthread_attr_init(&attr));
3034 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
3035
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003036 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07003037 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003038 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07003039 int actual_policy;
3040 sched_param actual_param;
3041 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
3042 ASSERT_EQ(SCHED_FIFO | SCHED_RESET_ON_FORK, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003043 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07003044 ASSERT_EQ(0, pthread_join(t, nullptr));
3045}
Peter Collingbourne5d3aa862020-09-11 15:05:17 -07003046
3047extern "C" bool android_run_on_all_threads(bool (*func)(void*), void* arg);
3048
3049TEST(pthread, run_on_all_threads) {
3050#if defined(__BIONIC__)
3051 pthread_t t;
3052 ASSERT_EQ(
3053 0, pthread_create(
3054 &t, nullptr,
3055 [](void*) -> void* {
3056 pthread_attr_t detached;
3057 if (pthread_attr_init(&detached) != 0 ||
3058 pthread_attr_setdetachstate(&detached, PTHREAD_CREATE_DETACHED) != 0) {
3059 return reinterpret_cast<void*>(errno);
3060 }
3061
3062 for (int i = 0; i != 1000; ++i) {
3063 pthread_t t1, t2;
3064 if (pthread_create(
3065 &t1, &detached, [](void*) -> void* { return nullptr; }, nullptr) != 0 ||
3066 pthread_create(
3067 &t2, nullptr, [](void*) -> void* { return nullptr; }, nullptr) != 0 ||
3068 pthread_join(t2, nullptr) != 0) {
3069 return reinterpret_cast<void*>(errno);
3070 }
3071 }
3072
3073 if (pthread_attr_destroy(&detached) != 0) {
3074 return reinterpret_cast<void*>(errno);
3075 }
3076 return nullptr;
3077 },
3078 nullptr));
3079
3080 for (int i = 0; i != 1000; ++i) {
3081 ASSERT_TRUE(android_run_on_all_threads([](void* arg) { return arg == nullptr; }, nullptr));
3082 }
3083
3084 void *retval;
3085 ASSERT_EQ(0, pthread_join(t, &retval));
3086 ASSERT_EQ(nullptr, retval);
3087#else
3088 GTEST_SKIP() << "bionic-only test";
3089#endif
3090}