blob: 2bf755b44120acb8452dd57bb94d4637455e9702 [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
Elliott Hughes2411fff2024-02-24 23:55:58 +00001426TEST(pthread, pthread_atfork_smoke_fork) {
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 Hughes2411fff2024-02-24 23:55:58 +00001430 g_atfork_prepare_calls = g_atfork_parent_calls = g_atfork_child_calls = 0;
Elliott Hughes33697a02016-01-26 13:04:57 -08001431 pid_t pid = fork();
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001432 ASSERT_NE(-1, pid) << strerror(errno);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001433
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001434 // Child and parent calls are made in the order they were registered.
1435 if (pid == 0) {
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001436 ASSERT_EQ(12, g_atfork_child_calls);
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001437 _exit(0);
1438 }
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001439 ASSERT_EQ(12, g_atfork_parent_calls);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001440
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001441 // Prepare calls are made in the reverse order.
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001442 ASSERT_EQ(21, g_atfork_prepare_calls);
Elliott Hughes33697a02016-01-26 13:04:57 -08001443 AssertChildExited(pid, 0);
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001444}
1445
Elliott Hughes2411fff2024-02-24 23:55:58 +00001446TEST(pthread, pthread_atfork_smoke_vfork) {
1447 ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1));
1448 ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2));
1449
1450 g_atfork_prepare_calls = g_atfork_parent_calls = g_atfork_child_calls = 0;
1451 pid_t pid = vfork();
1452 ASSERT_NE(-1, pid) << strerror(errno);
1453
1454 // atfork handlers are not called.
1455 if (pid == 0) {
1456 ASSERT_EQ(0, g_atfork_child_calls);
1457 _exit(0);
1458 }
1459 ASSERT_EQ(0, g_atfork_parent_calls);
1460 ASSERT_EQ(0, g_atfork_prepare_calls);
1461 AssertChildExited(pid, 0);
1462}
1463
1464TEST(pthread, pthread_atfork_smoke__Fork) {
1465#if defined(__BIONIC__)
1466 ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1));
1467 ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2));
1468
1469 g_atfork_prepare_calls = g_atfork_parent_calls = g_atfork_child_calls = 0;
1470 pid_t pid = _Fork();
1471 ASSERT_NE(-1, pid) << strerror(errno);
1472
1473 // atfork handlers are not called.
1474 if (pid == 0) {
1475 ASSERT_EQ(0, g_atfork_child_calls);
1476 _exit(0);
1477 }
1478 ASSERT_EQ(0, g_atfork_parent_calls);
1479 ASSERT_EQ(0, g_atfork_prepare_calls);
1480 AssertChildExited(pid, 0);
1481#endif
1482}
1483
Elliott Hughesc3f11402013-10-30 14:40:09 -07001484TEST(pthread, pthread_attr_getscope) {
1485 pthread_attr_t attr;
1486 ASSERT_EQ(0, pthread_attr_init(&attr));
1487
1488 int scope;
1489 ASSERT_EQ(0, pthread_attr_getscope(&attr, &scope));
1490 ASSERT_EQ(PTHREAD_SCOPE_SYSTEM, scope);
1491}
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001492
1493TEST(pthread, pthread_condattr_init) {
1494 pthread_condattr_t attr;
1495 pthread_condattr_init(&attr);
1496
1497 clockid_t clock;
1498 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1499 ASSERT_EQ(CLOCK_REALTIME, clock);
1500
1501 int pshared;
1502 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1503 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
1504}
1505
1506TEST(pthread, pthread_condattr_setclock) {
1507 pthread_condattr_t attr;
1508 pthread_condattr_init(&attr);
1509
1510 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_REALTIME));
1511 clockid_t clock;
1512 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1513 ASSERT_EQ(CLOCK_REALTIME, clock);
1514
1515 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1516 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1517 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1518
1519 ASSERT_EQ(EINVAL, pthread_condattr_setclock(&attr, CLOCK_PROCESS_CPUTIME_ID));
1520}
1521
1522TEST(pthread, pthread_cond_broadcast__preserves_condattr_flags) {
Yabin Cui32651b82015-03-13 20:30:00 -07001523#if defined(__BIONIC__)
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001524 pthread_condattr_t attr;
1525 pthread_condattr_init(&attr);
1526
1527 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1528 ASSERT_EQ(0, pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
1529
1530 pthread_cond_t cond_var;
1531 ASSERT_EQ(0, pthread_cond_init(&cond_var, &attr));
1532
1533 ASSERT_EQ(0, pthread_cond_signal(&cond_var));
1534 ASSERT_EQ(0, pthread_cond_broadcast(&cond_var));
1535
Yabin Cui32651b82015-03-13 20:30:00 -07001536 attr = static_cast<pthread_condattr_t>(*reinterpret_cast<uint32_t*>(cond_var.__private));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001537 clockid_t clock;
1538 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1539 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1540 int pshared;
1541 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1542 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
Yabin Cui32651b82015-03-13 20:30:00 -07001543#else // !defined(__BIONIC__)
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001544 GTEST_SKIP() << "bionic-only test";
Yabin Cui32651b82015-03-13 20:30:00 -07001545#endif // !defined(__BIONIC__)
1546}
1547
1548class pthread_CondWakeupTest : public ::testing::Test {
1549 protected:
1550 pthread_mutex_t mutex;
1551 pthread_cond_t cond;
1552
1553 enum Progress {
1554 INITIALIZED,
1555 WAITING,
1556 SIGNALED,
1557 FINISHED,
1558 };
1559 std::atomic<Progress> progress;
1560 pthread_t thread;
Peter Collingbournec5b81842021-12-02 12:38:46 -08001561 timespec ts;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001562 std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function;
Yabin Cui32651b82015-03-13 20:30:00 -07001563
1564 protected:
Yabin Cuic9a659c2015-11-05 15:36:08 -08001565 void SetUp() override {
1566 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1567 }
1568
1569 void InitCond(clockid_t clock=CLOCK_REALTIME) {
1570 pthread_condattr_t attr;
1571 ASSERT_EQ(0, pthread_condattr_init(&attr));
1572 ASSERT_EQ(0, pthread_condattr_setclock(&attr, clock));
1573 ASSERT_EQ(0, pthread_cond_init(&cond, &attr));
1574 ASSERT_EQ(0, pthread_condattr_destroy(&attr));
1575 }
1576
Tom Cherry69010802019-05-07 20:33:05 -07001577 void StartWaitingThread(
1578 std::function<int(pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function) {
Yabin Cui32651b82015-03-13 20:30:00 -07001579 progress = INITIALIZED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001580 this->wait_function = wait_function;
Tom Cherry69010802019-05-07 20:33:05 -07001581 ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(WaitThreadFn),
1582 this));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001583 while (progress != WAITING) {
Yabin Cui32651b82015-03-13 20:30:00 -07001584 usleep(5000);
1585 }
1586 usleep(5000);
1587 }
1588
Tom Cherry69010802019-05-07 20:33:05 -07001589 void RunTimedTest(
1590 clockid_t clock,
1591 std::function<int(pthread_cond_t* cond, pthread_mutex_t* mutex, const timespec* timeout)>
1592 wait_function) {
Tom Cherry69010802019-05-07 20:33:05 -07001593 ASSERT_EQ(0, clock_gettime(clock, &ts));
1594 ts.tv_sec += 1;
1595
Peter Collingbournec5b81842021-12-02 12:38:46 -08001596 StartWaitingThread([&wait_function, this](pthread_cond_t* cond, pthread_mutex_t* mutex) {
Tom Cherry69010802019-05-07 20:33:05 -07001597 return wait_function(cond, mutex, &ts);
1598 });
1599
1600 progress = SIGNALED;
1601 ASSERT_EQ(0, pthread_cond_signal(&cond));
1602 }
1603
1604 void RunTimedTest(clockid_t clock, std::function<int(pthread_cond_t* cond, pthread_mutex_t* mutex,
1605 clockid_t clock, const timespec* timeout)>
1606 wait_function) {
1607 RunTimedTest(clock, [clock, &wait_function](pthread_cond_t* cond, pthread_mutex_t* mutex,
1608 const timespec* timeout) {
1609 return wait_function(cond, mutex, clock, timeout);
1610 });
1611 }
1612
Yabin Cuic9a659c2015-11-05 15:36:08 -08001613 void TearDown() override {
1614 ASSERT_EQ(0, pthread_join(thread, nullptr));
1615 ASSERT_EQ(FINISHED, progress);
1616 ASSERT_EQ(0, pthread_cond_destroy(&cond));
1617 ASSERT_EQ(0, pthread_mutex_destroy(&mutex));
1618 }
1619
Yabin Cui32651b82015-03-13 20:30:00 -07001620 private:
1621 static void WaitThreadFn(pthread_CondWakeupTest* test) {
1622 ASSERT_EQ(0, pthread_mutex_lock(&test->mutex));
1623 test->progress = WAITING;
1624 while (test->progress == WAITING) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001625 ASSERT_EQ(0, test->wait_function(&test->cond, &test->mutex));
Yabin Cui32651b82015-03-13 20:30:00 -07001626 }
1627 ASSERT_EQ(SIGNALED, test->progress);
1628 test->progress = FINISHED;
1629 ASSERT_EQ(0, pthread_mutex_unlock(&test->mutex));
1630 }
1631};
1632
Yabin Cuic9a659c2015-11-05 15:36:08 -08001633TEST_F(pthread_CondWakeupTest, signal_wait) {
1634 InitCond();
1635 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1636 return pthread_cond_wait(cond, mutex);
1637 });
Yabin Cui32651b82015-03-13 20:30:00 -07001638 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001639 ASSERT_EQ(0, pthread_cond_signal(&cond));
Yabin Cui32651b82015-03-13 20:30:00 -07001640}
1641
Yabin Cuic9a659c2015-11-05 15:36:08 -08001642TEST_F(pthread_CondWakeupTest, broadcast_wait) {
1643 InitCond();
1644 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1645 return pthread_cond_wait(cond, mutex);
1646 });
Yabin Cui32651b82015-03-13 20:30:00 -07001647 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001648 ASSERT_EQ(0, pthread_cond_broadcast(&cond));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001649}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001650
Yabin Cuic9a659c2015-11-05 15:36:08 -08001651TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_REALTIME) {
1652 InitCond(CLOCK_REALTIME);
Tom Cherry69010802019-05-07 20:33:05 -07001653 RunTimedTest(CLOCK_REALTIME, pthread_cond_timedwait);
Yabin Cuic9a659c2015-11-05 15:36:08 -08001654}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001655
Yabin Cuic9a659c2015-11-05 15:36:08 -08001656TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC) {
1657 InitCond(CLOCK_MONOTONIC);
Tom Cherry69010802019-05-07 20:33:05 -07001658 RunTimedTest(CLOCK_MONOTONIC, pthread_cond_timedwait);
Yabin Cuic9a659c2015-11-05 15:36:08 -08001659}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001660
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001661TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC_np) {
1662#if defined(__BIONIC__)
1663 InitCond(CLOCK_REALTIME);
Tom Cherry69010802019-05-07 20:33:05 -07001664 RunTimedTest(CLOCK_MONOTONIC, pthread_cond_timedwait_monotonic_np);
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001665#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001666 GTEST_SKIP() << "pthread_cond_timedwait_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001667#endif // __BIONIC__
1668}
1669
Tom Cherry69010802019-05-07 20:33:05 -07001670TEST_F(pthread_CondWakeupTest, signal_clockwait_monotonic_monotonic) {
1671#if defined(__BIONIC__)
1672 InitCond(CLOCK_MONOTONIC);
1673 RunTimedTest(CLOCK_MONOTONIC, pthread_cond_clockwait);
1674#else // __BIONIC__
1675 GTEST_SKIP() << "pthread_cond_clockwait not available";
1676#endif // __BIONIC__
1677}
1678
1679TEST_F(pthread_CondWakeupTest, signal_clockwait_monotonic_realtime) {
1680#if defined(__BIONIC__)
1681 InitCond(CLOCK_MONOTONIC);
1682 RunTimedTest(CLOCK_REALTIME, pthread_cond_clockwait);
1683#else // __BIONIC__
1684 GTEST_SKIP() << "pthread_cond_clockwait not available";
1685#endif // __BIONIC__
1686}
1687
1688TEST_F(pthread_CondWakeupTest, signal_clockwait_realtime_monotonic) {
1689#if defined(__BIONIC__)
1690 InitCond(CLOCK_REALTIME);
1691 RunTimedTest(CLOCK_MONOTONIC, pthread_cond_clockwait);
1692#else // __BIONIC__
1693 GTEST_SKIP() << "pthread_cond_clockwait not available";
1694#endif // __BIONIC__
1695}
1696
1697TEST_F(pthread_CondWakeupTest, signal_clockwait_realtime_realtime) {
1698#if defined(__BIONIC__)
1699 InitCond(CLOCK_REALTIME);
1700 RunTimedTest(CLOCK_REALTIME, pthread_cond_clockwait);
1701#else // __BIONIC__
1702 GTEST_SKIP() << "pthread_cond_clockwait not available";
1703#endif // __BIONIC__
1704}
1705
Tom Cherry800c1a92019-07-17 10:45:18 -07001706static void pthread_cond_timedwait_timeout_helper(bool init_monotonic, clockid_t clock,
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001707 int (*wait_function)(pthread_cond_t* __cond,
1708 pthread_mutex_t* __mutex,
1709 const timespec* __timeout)) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001710 pthread_mutex_t mutex;
1711 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1712 pthread_cond_t cond;
Tom Cherry800c1a92019-07-17 10:45:18 -07001713
1714 if (init_monotonic) {
1715 pthread_condattr_t attr;
1716 pthread_condattr_init(&attr);
1717
1718 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1719 clockid_t clock;
1720 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1721 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1722
1723 ASSERT_EQ(0, pthread_cond_init(&cond, &attr));
1724 } else {
1725 ASSERT_EQ(0, pthread_cond_init(&cond, nullptr));
1726 }
Yabin Cuic9a659c2015-11-05 15:36:08 -08001727 ASSERT_EQ(0, pthread_mutex_lock(&mutex));
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001728
Yabin Cuic9a659c2015-11-05 15:36:08 -08001729 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001730 ASSERT_EQ(0, clock_gettime(clock, &ts));
1731 ASSERT_EQ(ETIMEDOUT, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001732 ts.tv_nsec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001733 ASSERT_EQ(EINVAL, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001734 ts.tv_nsec = NS_PER_S;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001735 ASSERT_EQ(EINVAL, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001736 ts.tv_nsec = NS_PER_S - 1;
1737 ts.tv_sec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001738 ASSERT_EQ(ETIMEDOUT, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001739 ASSERT_EQ(0, pthread_mutex_unlock(&mutex));
Elliott Hughes0e714a52014-03-03 16:42:47 -08001740}
Elliott Hughes57b7a612014-08-25 17:26:50 -07001741
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001742TEST(pthread, pthread_cond_timedwait_timeout) {
Tom Cherry800c1a92019-07-17 10:45:18 -07001743 pthread_cond_timedwait_timeout_helper(false, CLOCK_REALTIME, pthread_cond_timedwait);
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001744}
1745
1746TEST(pthread, pthread_cond_timedwait_monotonic_np_timeout) {
1747#if defined(__BIONIC__)
Tom Cherry800c1a92019-07-17 10:45:18 -07001748 pthread_cond_timedwait_timeout_helper(false, CLOCK_MONOTONIC, pthread_cond_timedwait_monotonic_np);
1749 pthread_cond_timedwait_timeout_helper(true, CLOCK_MONOTONIC, pthread_cond_timedwait_monotonic_np);
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001750#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001751 GTEST_SKIP() << "pthread_cond_timedwait_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001752#endif // __BIONIC__
1753}
1754
Tom Cherry69010802019-05-07 20:33:05 -07001755TEST(pthread, pthread_cond_clockwait_timeout) {
1756#if defined(__BIONIC__)
1757 pthread_cond_timedwait_timeout_helper(
Tom Cherry800c1a92019-07-17 10:45:18 -07001758 false, CLOCK_MONOTONIC,
Tom Cherry69010802019-05-07 20:33:05 -07001759 [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) {
1760 return pthread_cond_clockwait(__cond, __mutex, CLOCK_MONOTONIC, __timeout);
1761 });
1762 pthread_cond_timedwait_timeout_helper(
Tom Cherry800c1a92019-07-17 10:45:18 -07001763 true, CLOCK_MONOTONIC,
1764 [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) {
1765 return pthread_cond_clockwait(__cond, __mutex, CLOCK_MONOTONIC, __timeout);
1766 });
1767 pthread_cond_timedwait_timeout_helper(
1768 false, CLOCK_REALTIME,
1769 [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) {
1770 return pthread_cond_clockwait(__cond, __mutex, CLOCK_REALTIME, __timeout);
1771 });
1772 pthread_cond_timedwait_timeout_helper(
1773 true, CLOCK_REALTIME,
Tom Cherry69010802019-05-07 20:33:05 -07001774 [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) {
1775 return pthread_cond_clockwait(__cond, __mutex, CLOCK_REALTIME, __timeout);
1776 });
1777#else // __BIONIC__
1778 GTEST_SKIP() << "pthread_cond_clockwait not available";
1779#endif // __BIONIC__
1780}
1781
1782TEST(pthread, pthread_cond_clockwait_invalid) {
1783#if defined(__BIONIC__)
1784 pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
1785 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
1786 timespec ts;
1787 EXPECT_EQ(EINVAL, pthread_cond_clockwait(&cond, &mutex, CLOCK_PROCESS_CPUTIME_ID, &ts));
1788
1789#else // __BIONIC__
1790 GTEST_SKIP() << "pthread_cond_clockwait not available";
1791#endif // __BIONIC__
1792}
1793
Elliott Hughes57b7a612014-08-25 17:26:50 -07001794TEST(pthread, pthread_attr_getstack__main_thread) {
1795 // This test is only meaningful for the main thread, so make sure we're running on it!
1796 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1797
1798 // Get the main thread's attributes.
1799 pthread_attr_t attributes;
1800 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1801
1802 // Check that we correctly report that the main thread has no guard page.
1803 size_t guard_size;
1804 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
1805 ASSERT_EQ(0U, guard_size); // The main thread has no guard page.
1806
1807 // Get the stack base and the stack size (both ways).
1808 void* stack_base;
1809 size_t stack_size;
1810 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1811 size_t stack_size2;
1812 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1813
1814 // The two methods of asking for the stack size should agree.
1815 EXPECT_EQ(stack_size, stack_size2);
1816
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001817#if defined(__BIONIC__)
dimitry6dfa5b52018-01-30 13:24:28 +01001818 // Find stack in /proc/self/maps using a pointer to the stack.
1819 //
1820 // We do not use "[stack]" label because in native-bridge environment it is not
1821 // guaranteed to point to the right stack. A native bridge implementation may
1822 // keep separate stack for the guest code.
Yi Kong32bc0fc2018-08-02 17:31:13 -07001823 void* maps_stack_hi = nullptr;
Elliott Hughes15dfd632015-09-22 16:40:14 -07001824 std::vector<map_record> maps;
1825 ASSERT_TRUE(Maps::parse_maps(&maps));
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08001826 uintptr_t stack_address = reinterpret_cast<uintptr_t>(untag_address(&maps_stack_hi));
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07001827 for (const auto& map : maps) {
dimitry6dfa5b52018-01-30 13:24:28 +01001828 if (map.addr_start <= stack_address && map.addr_end > stack_address){
Elliott Hughes15dfd632015-09-22 16:40:14 -07001829 maps_stack_hi = reinterpret_cast<void*>(map.addr_end);
Elliott Hughes57b7a612014-08-25 17:26:50 -07001830 break;
1831 }
1832 }
Elliott Hughes57b7a612014-08-25 17:26:50 -07001833
dimitry6dfa5b52018-01-30 13:24:28 +01001834 // The high address of the /proc/self/maps stack region should equal stack_base + stack_size.
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001835 // Remember that the stack grows down (and is mapped in on demand), so the low address of the
1836 // region isn't very interesting.
1837 EXPECT_EQ(maps_stack_hi, reinterpret_cast<uint8_t*>(stack_base) + stack_size);
1838
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001839 // The stack size should correspond to RLIMIT_STACK.
Elliott Hughes57b7a612014-08-25 17:26:50 -07001840 rlimit rl;
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001841 ASSERT_EQ(0, getrlimit(RLIMIT_STACK, &rl));
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001842 uint64_t original_rlim_cur = rl.rlim_cur;
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001843 if (rl.rlim_cur == RLIM_INFINITY) {
1844 rl.rlim_cur = 8 * 1024 * 1024; // Bionic reports unlimited stacks as 8MiB.
1845 }
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001846 EXPECT_EQ(rl.rlim_cur, stack_size);
1847
Tom Cherryb8ab6182017-04-05 16:20:29 -07001848 auto guard = android::base::make_scope_guard([&rl, original_rlim_cur]() {
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001849 rl.rlim_cur = original_rlim_cur;
1850 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1851 });
1852
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001853 //
1854 // What if RLIMIT_STACK is smaller than the stack's current extent?
1855 //
Elliott Hughes57b7a612014-08-25 17:26:50 -07001856 rl.rlim_cur = rl.rlim_max = 1024; // 1KiB. We know the stack must be at least a page already.
1857 rl.rlim_max = RLIM_INFINITY;
1858 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1859
1860 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1861 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1862 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1863
1864 EXPECT_EQ(stack_size, stack_size2);
1865 ASSERT_EQ(1024U, stack_size);
1866
1867 //
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001868 // What if RLIMIT_STACK isn't a whole number of pages?
Elliott Hughes57b7a612014-08-25 17:26:50 -07001869 //
1870 rl.rlim_cur = rl.rlim_max = 6666; // Not a whole number of pages.
1871 rl.rlim_max = RLIM_INFINITY;
1872 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1873
1874 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1875 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1876 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1877
1878 EXPECT_EQ(stack_size, stack_size2);
1879 ASSERT_EQ(6666U, stack_size);
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001880#endif
Elliott Hughes57b7a612014-08-25 17:26:50 -07001881}
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001882
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001883struct GetStackSignalHandlerArg {
1884 volatile bool done;
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001885 void* signal_stack_base;
1886 size_t signal_stack_size;
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001887 void* main_stack_base;
1888 size_t main_stack_size;
1889};
1890
1891static GetStackSignalHandlerArg getstack_signal_handler_arg;
1892
1893static void getstack_signal_handler(int sig) {
1894 ASSERT_EQ(SIGUSR1, sig);
1895 // Use sleep() to make current thread be switched out by the kernel to provoke the error.
1896 sleep(1);
1897 pthread_attr_t attr;
1898 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1899 void* stack_base;
1900 size_t stack_size;
1901 ASSERT_EQ(0, pthread_attr_getstack(&attr, &stack_base, &stack_size));
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001902
1903 // Verify if the stack used by the signal handler is the alternate stack just registered.
1904 ASSERT_LE(getstack_signal_handler_arg.signal_stack_base, &attr);
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08001905 ASSERT_LT(static_cast<void*>(untag_address(&attr)),
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001906 static_cast<char*>(getstack_signal_handler_arg.signal_stack_base) +
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08001907 getstack_signal_handler_arg.signal_stack_size);
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001908
1909 // Verify if the main thread's stack got in the signal handler is correct.
1910 ASSERT_EQ(getstack_signal_handler_arg.main_stack_base, stack_base);
1911 ASSERT_LE(getstack_signal_handler_arg.main_stack_size, stack_size);
1912
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001913 getstack_signal_handler_arg.done = true;
1914}
1915
1916// The previous code obtained the main thread's stack by reading the entry in
1917// /proc/self/task/<pid>/maps that was labeled [stack]. Unfortunately, on x86/x86_64, the kernel
1918// relies on sp0 in task state segment(tss) to label the stack map with [stack]. If the kernel
1919// switches a process while the main thread is in an alternate stack, then the kernel will label
1920// the wrong map with [stack]. This test verifies that when the above situation happens, the main
1921// thread's stack is found correctly.
1922TEST(pthread, pthread_attr_getstack_in_signal_handler) {
Yabin Cui61e4d462016-03-07 17:44:58 -08001923 // This test is only meaningful for the main thread, so make sure we're running on it!
1924 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1925
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001926 const size_t sig_stack_size = 16 * 1024;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001927 void* sig_stack = mmap(nullptr, sig_stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS,
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001928 -1, 0);
1929 ASSERT_NE(MAP_FAILED, sig_stack);
1930 stack_t ss;
1931 ss.ss_sp = sig_stack;
1932 ss.ss_size = sig_stack_size;
1933 ss.ss_flags = 0;
1934 stack_t oss;
1935 ASSERT_EQ(0, sigaltstack(&ss, &oss));
1936
Yabin Cui61e4d462016-03-07 17:44:58 -08001937 pthread_attr_t attr;
1938 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1939 void* main_stack_base;
1940 size_t main_stack_size;
1941 ASSERT_EQ(0, pthread_attr_getstack(&attr, &main_stack_base, &main_stack_size));
1942
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001943 ScopedSignalHandler handler(SIGUSR1, getstack_signal_handler, SA_ONSTACK);
1944 getstack_signal_handler_arg.done = false;
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001945 getstack_signal_handler_arg.signal_stack_base = sig_stack;
1946 getstack_signal_handler_arg.signal_stack_size = sig_stack_size;
1947 getstack_signal_handler_arg.main_stack_base = main_stack_base;
1948 getstack_signal_handler_arg.main_stack_size = main_stack_size;
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001949 kill(getpid(), SIGUSR1);
1950 ASSERT_EQ(true, getstack_signal_handler_arg.done);
1951
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001952 ASSERT_EQ(0, sigaltstack(&oss, nullptr));
1953 ASSERT_EQ(0, munmap(sig_stack, sig_stack_size));
1954}
1955
Yabin Cui917d3902015-01-08 12:32:42 -08001956static void pthread_attr_getstack_18908062_helper(void*) {
1957 char local_variable;
1958 pthread_attr_t attributes;
1959 pthread_getattr_np(pthread_self(), &attributes);
1960 void* stack_base;
1961 size_t stack_size;
1962 pthread_attr_getstack(&attributes, &stack_base, &stack_size);
1963
1964 // Test whether &local_variable is in [stack_base, stack_base + stack_size).
1965 ASSERT_LE(reinterpret_cast<char*>(stack_base), &local_variable);
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08001966 ASSERT_LT(untag_address(&local_variable), reinterpret_cast<char*>(stack_base) + stack_size);
Yabin Cui917d3902015-01-08 12:32:42 -08001967}
1968
1969// Check whether something on stack is in the range of
1970// [stack_base, stack_base + stack_size). see b/18908062.
1971TEST(pthread, pthread_attr_getstack_18908062) {
1972 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001973 ASSERT_EQ(0, pthread_create(&t, nullptr,
Yabin Cui917d3902015-01-08 12:32:42 -08001974 reinterpret_cast<void* (*)(void*)>(pthread_attr_getstack_18908062_helper),
Yi Kong32bc0fc2018-08-02 17:31:13 -07001975 nullptr));
1976 ASSERT_EQ(0, pthread_join(t, nullptr));
Yabin Cui917d3902015-01-08 12:32:42 -08001977}
1978
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001979#if defined(__BIONIC__)
Elliott Hughesf2083612015-11-11 13:32:28 -08001980static pthread_mutex_t pthread_gettid_np_mutex = PTHREAD_MUTEX_INITIALIZER;
1981
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001982static void* pthread_gettid_np_helper(void* arg) {
1983 *reinterpret_cast<pid_t*>(arg) = gettid();
Elliott Hughesf2083612015-11-11 13:32:28 -08001984
1985 // Wait for our parent to call pthread_gettid_np on us before exiting.
1986 pthread_mutex_lock(&pthread_gettid_np_mutex);
1987 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001988 return nullptr;
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001989}
1990#endif
1991
1992TEST(pthread, pthread_gettid_np) {
1993#if defined(__BIONIC__)
1994 ASSERT_EQ(gettid(), pthread_gettid_np(pthread_self()));
1995
Elliott Hughesf2083612015-11-11 13:32:28 -08001996 // Ensure the other thread doesn't exit until after we've called
1997 // pthread_gettid_np on it.
1998 pthread_mutex_lock(&pthread_gettid_np_mutex);
1999
Elliott Hughes8fb639c2014-09-12 14:43:07 -07002000 pid_t t_gettid_result;
2001 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002002 pthread_create(&t, nullptr, pthread_gettid_np_helper, &t_gettid_result);
Elliott Hughes8fb639c2014-09-12 14:43:07 -07002003
2004 pid_t t_pthread_gettid_np_result = pthread_gettid_np(t);
2005
Elliott Hughesf2083612015-11-11 13:32:28 -08002006 // Release the other thread and wait for it to exit.
2007 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Yi Kong32bc0fc2018-08-02 17:31:13 -07002008 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes8fb639c2014-09-12 14:43:07 -07002009
2010 ASSERT_EQ(t_gettid_result, t_pthread_gettid_np_result);
2011#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002012 GTEST_SKIP() << "pthread_gettid_np not available";
Elliott Hughes8fb639c2014-09-12 14:43:07 -07002013#endif
2014}
Elliott Hughes34c987a2014-09-22 16:01:26 -07002015
2016static size_t cleanup_counter = 0;
2017
Derek Xue41996952014-09-25 11:05:32 +01002018static void AbortCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07002019 abort();
2020}
2021
Derek Xue41996952014-09-25 11:05:32 +01002022static void CountCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07002023 ++cleanup_counter;
2024}
2025
Derek Xue41996952014-09-25 11:05:32 +01002026static void PthreadCleanupTester() {
Yi Kong32bc0fc2018-08-02 17:31:13 -07002027 pthread_cleanup_push(CountCleanupRoutine, nullptr);
2028 pthread_cleanup_push(CountCleanupRoutine, nullptr);
2029 pthread_cleanup_push(AbortCleanupRoutine, nullptr);
Elliott Hughes34c987a2014-09-22 16:01:26 -07002030
2031 pthread_cleanup_pop(0); // Pop the abort without executing it.
2032 pthread_cleanup_pop(1); // Pop one count while executing it.
2033 ASSERT_EQ(1U, cleanup_counter);
2034 // Exit while the other count is still on the cleanup stack.
Yi Kong32bc0fc2018-08-02 17:31:13 -07002035 pthread_exit(nullptr);
Elliott Hughes34c987a2014-09-22 16:01:26 -07002036
2037 // Calls to pthread_cleanup_pop/pthread_cleanup_push must always be balanced.
2038 pthread_cleanup_pop(0);
2039}
2040
Derek Xue41996952014-09-25 11:05:32 +01002041static void* PthreadCleanupStartRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07002042 PthreadCleanupTester();
Yi Kong32bc0fc2018-08-02 17:31:13 -07002043 return nullptr;
Elliott Hughes34c987a2014-09-22 16:01:26 -07002044}
2045
2046TEST(pthread, pthread_cleanup_push__pthread_cleanup_pop) {
2047 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002048 ASSERT_EQ(0, pthread_create(&t, nullptr, PthreadCleanupStartRoutine, nullptr));
2049 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes34c987a2014-09-22 16:01:26 -07002050 ASSERT_EQ(2U, cleanup_counter);
2051}
Derek Xue41996952014-09-25 11:05:32 +01002052
2053TEST(pthread, PTHREAD_MUTEX_DEFAULT_is_PTHREAD_MUTEX_NORMAL) {
2054 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_DEFAULT);
2055}
2056
2057TEST(pthread, pthread_mutexattr_gettype) {
2058 pthread_mutexattr_t attr;
2059 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
2060
2061 int attr_type;
2062
2063 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL));
2064 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
2065 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, attr_type);
2066
2067 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK));
2068 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
2069 ASSERT_EQ(PTHREAD_MUTEX_ERRORCHECK, attr_type);
2070
2071 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE));
2072 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
2073 ASSERT_EQ(PTHREAD_MUTEX_RECURSIVE, attr_type);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002074
2075 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
2076}
2077
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002078TEST(pthread, pthread_mutexattr_protocol) {
2079 pthread_mutexattr_t attr;
2080 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
2081
2082 int protocol;
2083 ASSERT_EQ(0, pthread_mutexattr_getprotocol(&attr, &protocol));
2084 ASSERT_EQ(PTHREAD_PRIO_NONE, protocol);
2085 for (size_t repeat = 0; repeat < 2; ++repeat) {
2086 for (int set_protocol : {PTHREAD_PRIO_NONE, PTHREAD_PRIO_INHERIT}) {
2087 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, set_protocol));
2088 ASSERT_EQ(0, pthread_mutexattr_getprotocol(&attr, &protocol));
2089 ASSERT_EQ(protocol, set_protocol);
2090 }
2091 }
2092}
2093
Yabin Cui17393b02015-03-21 15:08:25 -07002094struct PthreadMutex {
2095 pthread_mutex_t lock;
2096
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002097 explicit PthreadMutex(int mutex_type, int protocol = PTHREAD_PRIO_NONE) {
2098 init(mutex_type, protocol);
Yabin Cui17393b02015-03-21 15:08:25 -07002099 }
2100
2101 ~PthreadMutex() {
2102 destroy();
2103 }
2104
2105 private:
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002106 void init(int mutex_type, int protocol) {
Yabin Cui17393b02015-03-21 15:08:25 -07002107 pthread_mutexattr_t attr;
2108 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
2109 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, mutex_type));
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002110 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, protocol));
Yabin Cui17393b02015-03-21 15:08:25 -07002111 ASSERT_EQ(0, pthread_mutex_init(&lock, &attr));
2112 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
2113 }
2114
2115 void destroy() {
2116 ASSERT_EQ(0, pthread_mutex_destroy(&lock));
2117 }
2118
2119 DISALLOW_COPY_AND_ASSIGN(PthreadMutex);
2120};
Derek Xue41996952014-09-25 11:05:32 +01002121
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002122static int UnlockFromAnotherThread(pthread_mutex_t* mutex) {
2123 pthread_t thread;
2124 pthread_create(&thread, nullptr, [](void* mutex_voidp) -> void* {
2125 pthread_mutex_t* mutex = static_cast<pthread_mutex_t*>(mutex_voidp);
2126 intptr_t result = pthread_mutex_unlock(mutex);
2127 return reinterpret_cast<void*>(result);
2128 }, mutex);
2129 void* result;
2130 EXPECT_EQ(0, pthread_join(thread, &result));
2131 return reinterpret_cast<intptr_t>(result);
2132};
2133
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002134static void TestPthreadMutexLockNormal(int protocol) {
2135 PthreadMutex m(PTHREAD_MUTEX_NORMAL, protocol);
Derek Xue41996952014-09-25 11:05:32 +01002136
Yabin Cui17393b02015-03-21 15:08:25 -07002137 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002138 if (protocol == PTHREAD_PRIO_INHERIT) {
2139 ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock));
2140 }
Yabin Cui17393b02015-03-21 15:08:25 -07002141 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08002142 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
2143 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
2144 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01002145}
2146
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002147static void TestPthreadMutexLockErrorCheck(int protocol) {
2148 PthreadMutex m(PTHREAD_MUTEX_ERRORCHECK, protocol);
Derek Xue41996952014-09-25 11:05:32 +01002149
Yabin Cui17393b02015-03-21 15:08:25 -07002150 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002151 ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07002152 ASSERT_EQ(EDEADLK, pthread_mutex_lock(&m.lock));
2153 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2154 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002155 if (protocol == PTHREAD_PRIO_NONE) {
2156 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
2157 } else {
2158 ASSERT_EQ(EDEADLK, pthread_mutex_trylock(&m.lock));
2159 }
Yabin Cui17393b02015-03-21 15:08:25 -07002160 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2161 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01002162}
2163
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002164static void TestPthreadMutexLockRecursive(int protocol) {
2165 PthreadMutex m(PTHREAD_MUTEX_RECURSIVE, protocol);
Derek Xue41996952014-09-25 11:05:32 +01002166
Yabin Cui17393b02015-03-21 15:08:25 -07002167 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002168 ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07002169 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002170 ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07002171 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2172 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2173 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08002174 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
2175 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07002176 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2177 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
2178}
2179
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002180TEST(pthread, pthread_mutex_lock_NORMAL) {
2181 TestPthreadMutexLockNormal(PTHREAD_PRIO_NONE);
2182}
2183
2184TEST(pthread, pthread_mutex_lock_ERRORCHECK) {
2185 TestPthreadMutexLockErrorCheck(PTHREAD_PRIO_NONE);
2186}
2187
2188TEST(pthread, pthread_mutex_lock_RECURSIVE) {
2189 TestPthreadMutexLockRecursive(PTHREAD_PRIO_NONE);
2190}
2191
2192TEST(pthread, pthread_mutex_lock_pi) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002193 TestPthreadMutexLockNormal(PTHREAD_PRIO_INHERIT);
2194 TestPthreadMutexLockErrorCheck(PTHREAD_PRIO_INHERIT);
2195 TestPthreadMutexLockRecursive(PTHREAD_PRIO_INHERIT);
2196}
2197
Yabin Cui5a00ba72018-01-26 17:32:31 -08002198TEST(pthread, pthread_mutex_pi_count_limit) {
2199#if defined(__BIONIC__) && !defined(__LP64__)
2200 // Bionic only supports 65536 pi mutexes in 32-bit programs.
2201 pthread_mutexattr_t attr;
2202 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
2203 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT));
2204 std::vector<pthread_mutex_t> mutexes(65536);
2205 // Test if we can use 65536 pi mutexes at the same time.
2206 // Run 2 times to check if freed pi mutexes can be recycled.
2207 for (int repeat = 0; repeat < 2; ++repeat) {
2208 for (auto& m : mutexes) {
2209 ASSERT_EQ(0, pthread_mutex_init(&m, &attr));
2210 }
2211 pthread_mutex_t m;
2212 ASSERT_EQ(ENOMEM, pthread_mutex_init(&m, &attr));
2213 for (auto& m : mutexes) {
2214 ASSERT_EQ(0, pthread_mutex_lock(&m));
2215 }
2216 for (auto& m : mutexes) {
2217 ASSERT_EQ(0, pthread_mutex_unlock(&m));
2218 }
2219 for (auto& m : mutexes) {
2220 ASSERT_EQ(0, pthread_mutex_destroy(&m));
2221 }
2222 }
2223 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
2224#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002225 GTEST_SKIP() << "pi mutex count not limited to 64Ki";
Yabin Cui5a00ba72018-01-26 17:32:31 -08002226#endif
2227}
2228
Yabin Cui17393b02015-03-21 15:08:25 -07002229TEST(pthread, pthread_mutex_init_same_as_static_initializers) {
2230 pthread_mutex_t lock_normal = PTHREAD_MUTEX_INITIALIZER;
2231 PthreadMutex m1(PTHREAD_MUTEX_NORMAL);
2232 ASSERT_EQ(0, memcmp(&lock_normal, &m1.lock, sizeof(pthread_mutex_t)));
2233 pthread_mutex_destroy(&lock_normal);
2234
Colin Cross4c5595c2021-08-16 15:51:59 -07002235#if !defined(ANDROID_HOST_MUSL)
Colin Cross7da20342021-07-28 11:18:11 -07002236 // musl doesn't support PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP or
2237 // PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP.
Yabin Cui17393b02015-03-21 15:08:25 -07002238 pthread_mutex_t lock_errorcheck = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
2239 PthreadMutex m2(PTHREAD_MUTEX_ERRORCHECK);
2240 ASSERT_EQ(0, memcmp(&lock_errorcheck, &m2.lock, sizeof(pthread_mutex_t)));
2241 pthread_mutex_destroy(&lock_errorcheck);
2242
2243 pthread_mutex_t lock_recursive = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
2244 PthreadMutex m3(PTHREAD_MUTEX_RECURSIVE);
2245 ASSERT_EQ(0, memcmp(&lock_recursive, &m3.lock, sizeof(pthread_mutex_t)));
2246 ASSERT_EQ(0, pthread_mutex_destroy(&lock_recursive));
Colin Cross7da20342021-07-28 11:18:11 -07002247#endif
Derek Xue41996952014-09-25 11:05:32 +01002248}
Yabin Cui5a00ba72018-01-26 17:32:31 -08002249
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002250class MutexWakeupHelper {
2251 private:
Yabin Cui17393b02015-03-21 15:08:25 -07002252 PthreadMutex m;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002253 enum Progress {
2254 LOCK_INITIALIZED,
2255 LOCK_WAITING,
2256 LOCK_RELEASED,
2257 LOCK_ACCESSED
2258 };
2259 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -07002260 std::atomic<pid_t> tid;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002261
2262 static void thread_fn(MutexWakeupHelper* helper) {
Yabin Cuif7969852015-04-02 17:47:48 -07002263 helper->tid = gettid();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002264 ASSERT_EQ(LOCK_INITIALIZED, helper->progress);
2265 helper->progress = LOCK_WAITING;
2266
Yabin Cui17393b02015-03-21 15:08:25 -07002267 ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002268 ASSERT_EQ(LOCK_RELEASED, helper->progress);
Yabin Cui17393b02015-03-21 15:08:25 -07002269 ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002270
2271 helper->progress = LOCK_ACCESSED;
2272 }
2273
2274 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -07002275 explicit MutexWakeupHelper(int mutex_type) : m(mutex_type) {
Yabin Cui17393b02015-03-21 15:08:25 -07002276 }
2277
2278 void test() {
2279 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002280 progress = LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -07002281 tid = 0;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002282
2283 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002284 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002285 reinterpret_cast<void* (*)(void*)>(MutexWakeupHelper::thread_fn), this));
2286
Yabin Cuif7969852015-04-02 17:47:48 -07002287 WaitUntilThreadSleep(tid);
2288 ASSERT_EQ(LOCK_WAITING, progress);
2289
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002290 progress = LOCK_RELEASED;
Yabin Cui17393b02015-03-21 15:08:25 -07002291 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002292
Yi Kong32bc0fc2018-08-02 17:31:13 -07002293 ASSERT_EQ(0, pthread_join(thread, nullptr));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002294 ASSERT_EQ(LOCK_ACCESSED, progress);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002295 }
2296};
2297
2298TEST(pthread, pthread_mutex_NORMAL_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07002299 MutexWakeupHelper helper(PTHREAD_MUTEX_NORMAL);
2300 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002301}
2302
2303TEST(pthread, pthread_mutex_ERRORCHECK_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07002304 MutexWakeupHelper helper(PTHREAD_MUTEX_ERRORCHECK);
2305 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002306}
2307
2308TEST(pthread, pthread_mutex_RECURSIVE_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07002309 MutexWakeupHelper helper(PTHREAD_MUTEX_RECURSIVE);
2310 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002311}
2312
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002313static int GetThreadPriority(pid_t tid) {
2314 // sched_getparam() returns the static priority of a thread, which can't reflect a thread's
2315 // priority after priority inheritance. So read /proc/<pid>/stat to get the dynamic priority.
2316 std::string filename = android::base::StringPrintf("/proc/%d/stat", tid);
2317 std::string content;
2318 int result = INT_MAX;
2319 if (!android::base::ReadFileToString(filename, &content)) {
2320 return result;
2321 }
2322 std::vector<std::string> strs = android::base::Split(content, " ");
2323 if (strs.size() < 18) {
2324 return result;
2325 }
2326 if (!android::base::ParseInt(strs[17], &result)) {
2327 return INT_MAX;
2328 }
2329 return result;
2330}
2331
2332class PIMutexWakeupHelper {
2333private:
2334 PthreadMutex m;
2335 int protocol;
2336 enum Progress {
2337 LOCK_INITIALIZED,
2338 LOCK_CHILD_READY,
2339 LOCK_WAITING,
2340 LOCK_RELEASED,
2341 };
2342 std::atomic<Progress> progress;
2343 std::atomic<pid_t> main_tid;
2344 std::atomic<pid_t> child_tid;
2345 PthreadMutex start_thread_m;
2346
2347 static void thread_fn(PIMutexWakeupHelper* helper) {
2348 helper->child_tid = gettid();
2349 ASSERT_EQ(LOCK_INITIALIZED, helper->progress);
2350 ASSERT_EQ(0, setpriority(PRIO_PROCESS, gettid(), 1));
2351 ASSERT_EQ(21, GetThreadPriority(gettid()));
2352 ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock));
2353 helper->progress = LOCK_CHILD_READY;
2354 ASSERT_EQ(0, pthread_mutex_lock(&helper->start_thread_m.lock));
2355
2356 ASSERT_EQ(0, pthread_mutex_unlock(&helper->start_thread_m.lock));
2357 WaitUntilThreadSleep(helper->main_tid);
2358 ASSERT_EQ(LOCK_WAITING, helper->progress);
2359
2360 if (helper->protocol == PTHREAD_PRIO_INHERIT) {
2361 ASSERT_EQ(20, GetThreadPriority(gettid()));
2362 } else {
2363 ASSERT_EQ(21, GetThreadPriority(gettid()));
2364 }
2365 helper->progress = LOCK_RELEASED;
2366 ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock));
2367 }
2368
2369public:
2370 explicit PIMutexWakeupHelper(int mutex_type, int protocol)
2371 : m(mutex_type, protocol), protocol(protocol), start_thread_m(PTHREAD_MUTEX_NORMAL) {
2372 }
2373
2374 void test() {
2375 ASSERT_EQ(0, pthread_mutex_lock(&start_thread_m.lock));
2376 main_tid = gettid();
2377 ASSERT_EQ(20, GetThreadPriority(main_tid));
2378 progress = LOCK_INITIALIZED;
2379 child_tid = 0;
2380
2381 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002382 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002383 reinterpret_cast<void* (*)(void*)>(PIMutexWakeupHelper::thread_fn), this));
2384
2385 WaitUntilThreadSleep(child_tid);
2386 ASSERT_EQ(LOCK_CHILD_READY, progress);
2387 ASSERT_EQ(0, pthread_mutex_unlock(&start_thread_m.lock));
2388 progress = LOCK_WAITING;
2389 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
2390
2391 ASSERT_EQ(LOCK_RELEASED, progress);
2392 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2393 ASSERT_EQ(0, pthread_join(thread, nullptr));
2394 }
2395};
2396
2397TEST(pthread, pthread_mutex_pi_wakeup) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002398 for (int type : {PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_RECURSIVE, PTHREAD_MUTEX_ERRORCHECK}) {
2399 for (int protocol : {PTHREAD_PRIO_INHERIT}) {
2400 PIMutexWakeupHelper helper(type, protocol);
2401 helper.test();
2402 }
2403 }
2404}
2405
Yabin Cui140f3672015-02-03 10:32:00 -08002406TEST(pthread, pthread_mutex_owner_tid_limit) {
Yabin Cuie69c2452015-02-13 16:21:25 -08002407#if defined(__BIONIC__) && !defined(__LP64__)
Yabin Cui140f3672015-02-03 10:32:00 -08002408 FILE* fp = fopen("/proc/sys/kernel/pid_max", "r");
Yi Kong32bc0fc2018-08-02 17:31:13 -07002409 ASSERT_TRUE(fp != nullptr);
Yabin Cui140f3672015-02-03 10:32:00 -08002410 long pid_max;
2411 ASSERT_EQ(1, fscanf(fp, "%ld", &pid_max));
2412 fclose(fp);
Yabin Cuie69c2452015-02-13 16:21:25 -08002413 // Bionic's pthread_mutex implementation on 32-bit devices uses 16 bits to represent owner tid.
Yabin Cui140f3672015-02-03 10:32:00 -08002414 ASSERT_LE(pid_max, 65536);
Yabin Cuie69c2452015-02-13 16:21:25 -08002415#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002416 GTEST_SKIP() << "pthread_mutex supports 32-bit tid";
Yabin Cuie69c2452015-02-13 16:21:25 -08002417#endif
Yabin Cui140f3672015-02-03 10:32:00 -08002418}
Yabin Cuib5845722015-03-16 22:46:42 -07002419
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002420static void pthread_mutex_timedlock_helper(clockid_t clock,
2421 int (*lock_function)(pthread_mutex_t* __mutex,
2422 const timespec* __timeout)) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08002423 pthread_mutex_t m;
2424 ASSERT_EQ(0, pthread_mutex_init(&m, nullptr));
2425
2426 // If the mutex is already locked, pthread_mutex_timedlock should time out.
2427 ASSERT_EQ(0, pthread_mutex_lock(&m));
2428
2429 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002430 ASSERT_EQ(0, clock_gettime(clock, &ts));
2431 ASSERT_EQ(ETIMEDOUT, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002432 ts.tv_nsec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002433 ASSERT_EQ(EINVAL, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002434 ts.tv_nsec = NS_PER_S;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002435 ASSERT_EQ(EINVAL, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002436 ts.tv_nsec = NS_PER_S - 1;
2437 ts.tv_sec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002438 ASSERT_EQ(ETIMEDOUT, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002439
Andy Hung5e19b182023-12-11 19:28:02 -08002440 // check we wait long enough for the lock.
2441 ASSERT_EQ(0, clock_gettime(clock, &ts));
2442 const int64_t start_ns = ts.tv_sec * NS_PER_S + ts.tv_nsec;
2443
2444 // add a second to get deadline.
2445 ts.tv_sec += 1;
2446
2447 ASSERT_EQ(ETIMEDOUT, lock_function(&m, &ts));
2448
2449 // The timedlock must have waited at least 1 second before returning.
2450 clock_gettime(clock, &ts);
2451 const int64_t end_ns = ts.tv_sec * NS_PER_S + ts.tv_nsec;
2452 ASSERT_GT(end_ns - start_ns, NS_PER_S);
2453
Yabin Cuic9a659c2015-11-05 15:36:08 -08002454 // If the mutex is unlocked, pthread_mutex_timedlock should succeed.
2455 ASSERT_EQ(0, pthread_mutex_unlock(&m));
2456
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002457 ASSERT_EQ(0, clock_gettime(clock, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002458 ts.tv_sec += 1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002459 ASSERT_EQ(0, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002460
2461 ASSERT_EQ(0, pthread_mutex_unlock(&m));
2462 ASSERT_EQ(0, pthread_mutex_destroy(&m));
2463}
2464
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002465TEST(pthread, pthread_mutex_timedlock) {
2466 pthread_mutex_timedlock_helper(CLOCK_REALTIME, pthread_mutex_timedlock);
2467}
2468
2469TEST(pthread, pthread_mutex_timedlock_monotonic_np) {
2470#if defined(__BIONIC__)
2471 pthread_mutex_timedlock_helper(CLOCK_MONOTONIC, pthread_mutex_timedlock_monotonic_np);
2472#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002473 GTEST_SKIP() << "pthread_mutex_timedlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002474#endif // __BIONIC__
2475}
2476
Tom Cherry69010802019-05-07 20:33:05 -07002477TEST(pthread, pthread_mutex_clocklock) {
2478#if defined(__BIONIC__)
2479 pthread_mutex_timedlock_helper(
2480 CLOCK_MONOTONIC, [](pthread_mutex_t* __mutex, const timespec* __timeout) {
2481 return pthread_mutex_clocklock(__mutex, CLOCK_MONOTONIC, __timeout);
2482 });
2483 pthread_mutex_timedlock_helper(
2484 CLOCK_REALTIME, [](pthread_mutex_t* __mutex, const timespec* __timeout) {
2485 return pthread_mutex_clocklock(__mutex, CLOCK_REALTIME, __timeout);
2486 });
2487#else // __BIONIC__
2488 GTEST_SKIP() << "pthread_mutex_clocklock not available";
2489#endif // __BIONIC__
2490}
2491
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002492static void pthread_mutex_timedlock_pi_helper(clockid_t clock,
2493 int (*lock_function)(pthread_mutex_t* __mutex,
2494 const timespec* __timeout)) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002495 PthreadMutex m(PTHREAD_MUTEX_NORMAL, PTHREAD_PRIO_INHERIT);
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002496
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002497 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002498 clock_gettime(clock, &ts);
Andy Hung5e19b182023-12-11 19:28:02 -08002499 const int64_t start_ns = ts.tv_sec * NS_PER_S + ts.tv_nsec;
2500
2501 // add a second to get deadline.
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002502 ts.tv_sec += 1;
Andy Hung5e19b182023-12-11 19:28:02 -08002503
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002504 ASSERT_EQ(0, lock_function(&m.lock, &ts));
2505
2506 struct ThreadArgs {
2507 clockid_t clock;
2508 int (*lock_function)(pthread_mutex_t* __mutex, const timespec* __timeout);
2509 PthreadMutex& m;
2510 };
2511
2512 ThreadArgs thread_args = {
2513 .clock = clock,
2514 .lock_function = lock_function,
2515 .m = m,
2516 };
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002517
2518 auto ThreadFn = [](void* arg) -> void* {
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002519 auto args = static_cast<ThreadArgs*>(arg);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002520 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002521 clock_gettime(args->clock, &ts);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002522 ts.tv_sec += 1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002523 intptr_t result = args->lock_function(&args->m.lock, &ts);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002524 return reinterpret_cast<void*>(result);
2525 };
2526
2527 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002528 ASSERT_EQ(0, pthread_create(&thread, nullptr, ThreadFn, &thread_args));
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002529 void* result;
2530 ASSERT_EQ(0, pthread_join(thread, &result));
2531 ASSERT_EQ(ETIMEDOUT, reinterpret_cast<intptr_t>(result));
Andy Hung5e19b182023-12-11 19:28:02 -08002532
2533 // The timedlock must have waited at least 1 second before returning.
2534 clock_gettime(clock, &ts);
2535 const int64_t end_ns = ts.tv_sec * NS_PER_S + ts.tv_nsec;
2536 ASSERT_GT(end_ns - start_ns, NS_PER_S);
2537
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002538 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2539}
2540
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002541TEST(pthread, pthread_mutex_timedlock_pi) {
2542 pthread_mutex_timedlock_pi_helper(CLOCK_REALTIME, pthread_mutex_timedlock);
2543}
2544
2545TEST(pthread, pthread_mutex_timedlock_monotonic_np_pi) {
2546#if defined(__BIONIC__)
2547 pthread_mutex_timedlock_pi_helper(CLOCK_MONOTONIC, pthread_mutex_timedlock_monotonic_np);
2548#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002549 GTEST_SKIP() << "pthread_mutex_timedlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002550#endif // __BIONIC__
2551}
2552
Tom Cherry69010802019-05-07 20:33:05 -07002553TEST(pthread, pthread_mutex_clocklock_pi) {
2554#if defined(__BIONIC__)
2555 pthread_mutex_timedlock_pi_helper(
2556 CLOCK_MONOTONIC, [](pthread_mutex_t* __mutex, const timespec* __timeout) {
2557 return pthread_mutex_clocklock(__mutex, CLOCK_MONOTONIC, __timeout);
2558 });
2559 pthread_mutex_timedlock_pi_helper(
2560 CLOCK_REALTIME, [](pthread_mutex_t* __mutex, const timespec* __timeout) {
2561 return pthread_mutex_clocklock(__mutex, CLOCK_REALTIME, __timeout);
2562 });
2563#else // __BIONIC__
2564 GTEST_SKIP() << "pthread_mutex_clocklock not available";
2565#endif // __BIONIC__
2566}
2567
2568TEST(pthread, pthread_mutex_clocklock_invalid) {
2569#if defined(__BIONIC__)
2570 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
2571 timespec ts;
2572 EXPECT_EQ(EINVAL, pthread_mutex_clocklock(&mutex, CLOCK_PROCESS_CPUTIME_ID, &ts));
2573#else // __BIONIC__
2574 GTEST_SKIP() << "pthread_mutex_clocklock not available";
2575#endif // __BIONIC__
2576}
2577
Elliott Hughese657eb42021-02-18 17:11:56 -08002578TEST_F(pthread_DeathTest, pthread_mutex_using_destroyed_mutex) {
Yabin Cui9651fdf2018-03-14 12:02:21 -07002579#if defined(__BIONIC__)
2580 pthread_mutex_t m;
2581 ASSERT_EQ(0, pthread_mutex_init(&m, nullptr));
2582 ASSERT_EQ(0, pthread_mutex_destroy(&m));
2583 ASSERT_EXIT(pthread_mutex_lock(&m), ::testing::KilledBySignal(SIGABRT),
2584 "pthread_mutex_lock called on a destroyed mutex");
2585 ASSERT_EXIT(pthread_mutex_unlock(&m), ::testing::KilledBySignal(SIGABRT),
2586 "pthread_mutex_unlock called on a destroyed mutex");
2587 ASSERT_EXIT(pthread_mutex_trylock(&m), ::testing::KilledBySignal(SIGABRT),
2588 "pthread_mutex_trylock called on a destroyed mutex");
2589 timespec ts;
2590 ASSERT_EXIT(pthread_mutex_timedlock(&m, &ts), ::testing::KilledBySignal(SIGABRT),
2591 "pthread_mutex_timedlock called on a destroyed mutex");
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002592 ASSERT_EXIT(pthread_mutex_timedlock_monotonic_np(&m, &ts), ::testing::KilledBySignal(SIGABRT),
2593 "pthread_mutex_timedlock_monotonic_np called on a destroyed mutex");
Tom Cherry69010802019-05-07 20:33:05 -07002594 ASSERT_EXIT(pthread_mutex_clocklock(&m, CLOCK_MONOTONIC, &ts), ::testing::KilledBySignal(SIGABRT),
2595 "pthread_mutex_clocklock called on a destroyed mutex");
2596 ASSERT_EXIT(pthread_mutex_clocklock(&m, CLOCK_REALTIME, &ts), ::testing::KilledBySignal(SIGABRT),
2597 "pthread_mutex_clocklock called on a destroyed mutex");
2598 ASSERT_EXIT(pthread_mutex_clocklock(&m, CLOCK_PROCESS_CPUTIME_ID, &ts),
2599 ::testing::KilledBySignal(SIGABRT),
2600 "pthread_mutex_clocklock called on a destroyed mutex");
Yabin Cui9651fdf2018-03-14 12:02:21 -07002601 ASSERT_EXIT(pthread_mutex_destroy(&m), ::testing::KilledBySignal(SIGABRT),
2602 "pthread_mutex_destroy called on a destroyed mutex");
2603#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002604 GTEST_SKIP() << "bionic-only test";
Yabin Cui9651fdf2018-03-14 12:02:21 -07002605#endif
2606}
2607
Yabin Cuib5845722015-03-16 22:46:42 -07002608class StrictAlignmentAllocator {
2609 public:
2610 void* allocate(size_t size, size_t alignment) {
2611 char* p = new char[size + alignment * 2];
2612 allocated_array.push_back(p);
2613 while (!is_strict_aligned(p, alignment)) {
2614 ++p;
2615 }
2616 return p;
2617 }
2618
2619 ~StrictAlignmentAllocator() {
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07002620 for (const auto& p : allocated_array) {
2621 delete[] p;
Yabin Cuib5845722015-03-16 22:46:42 -07002622 }
2623 }
2624
2625 private:
2626 bool is_strict_aligned(char* p, size_t alignment) {
2627 return (reinterpret_cast<uintptr_t>(p) % (alignment * 2)) == alignment;
2628 }
2629
2630 std::vector<char*> allocated_array;
2631};
2632
2633TEST(pthread, pthread_types_allow_four_bytes_alignment) {
2634#if defined(__BIONIC__)
2635 // For binary compatibility with old version, we need to allow 4-byte aligned data for pthread types.
2636 StrictAlignmentAllocator allocator;
2637 pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(
2638 allocator.allocate(sizeof(pthread_mutex_t), 4));
Yi Kong32bc0fc2018-08-02 17:31:13 -07002639 ASSERT_EQ(0, pthread_mutex_init(mutex, nullptr));
Yabin Cuib5845722015-03-16 22:46:42 -07002640 ASSERT_EQ(0, pthread_mutex_lock(mutex));
2641 ASSERT_EQ(0, pthread_mutex_unlock(mutex));
2642 ASSERT_EQ(0, pthread_mutex_destroy(mutex));
2643
2644 pthread_cond_t* cond = reinterpret_cast<pthread_cond_t*>(
2645 allocator.allocate(sizeof(pthread_cond_t), 4));
Yi Kong32bc0fc2018-08-02 17:31:13 -07002646 ASSERT_EQ(0, pthread_cond_init(cond, nullptr));
Yabin Cuib5845722015-03-16 22:46:42 -07002647 ASSERT_EQ(0, pthread_cond_signal(cond));
2648 ASSERT_EQ(0, pthread_cond_broadcast(cond));
2649 ASSERT_EQ(0, pthread_cond_destroy(cond));
2650
2651 pthread_rwlock_t* rwlock = reinterpret_cast<pthread_rwlock_t*>(
2652 allocator.allocate(sizeof(pthread_rwlock_t), 4));
Yi Kong32bc0fc2018-08-02 17:31:13 -07002653 ASSERT_EQ(0, pthread_rwlock_init(rwlock, nullptr));
Yabin Cuib5845722015-03-16 22:46:42 -07002654 ASSERT_EQ(0, pthread_rwlock_rdlock(rwlock));
2655 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
2656 ASSERT_EQ(0, pthread_rwlock_wrlock(rwlock));
2657 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
2658 ASSERT_EQ(0, pthread_rwlock_destroy(rwlock));
2659
2660#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002661 GTEST_SKIP() << "bionic-only test";
Yabin Cuib5845722015-03-16 22:46:42 -07002662#endif
2663}
Christopher Ferris60907c72015-06-09 18:46:15 -07002664
2665TEST(pthread, pthread_mutex_lock_null_32) {
2666#if defined(__BIONIC__) && !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -07002667 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return
2668 // EINVAL in that case: http://b/19995172.
2669 //
2670 // We decorate the public defintion with _Nonnull so that people recompiling
2671 // their code with get a warning and might fix their bug, but need to pass
2672 // NULL here to test that we remain compatible.
2673 pthread_mutex_t* null_value = nullptr;
2674 ASSERT_EQ(EINVAL, pthread_mutex_lock(null_value));
Christopher Ferris60907c72015-06-09 18:46:15 -07002675#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002676 GTEST_SKIP() << "32-bit bionic-only test";
Christopher Ferris60907c72015-06-09 18:46:15 -07002677#endif
2678}
2679
2680TEST(pthread, pthread_mutex_unlock_null_32) {
2681#if defined(__BIONIC__) && !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -07002682 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return
2683 // EINVAL in that case: http://b/19995172.
2684 //
2685 // We decorate the public defintion with _Nonnull so that people recompiling
2686 // their code with get a warning and might fix their bug, but need to pass
2687 // NULL here to test that we remain compatible.
2688 pthread_mutex_t* null_value = nullptr;
2689 ASSERT_EQ(EINVAL, pthread_mutex_unlock(null_value));
Christopher Ferris60907c72015-06-09 18:46:15 -07002690#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002691 GTEST_SKIP() << "32-bit bionic-only test";
Christopher Ferris60907c72015-06-09 18:46:15 -07002692#endif
2693}
2694
2695TEST_F(pthread_DeathTest, pthread_mutex_lock_null_64) {
2696#if defined(__BIONIC__) && defined(__LP64__)
2697 pthread_mutex_t* null_value = nullptr;
2698 ASSERT_EXIT(pthread_mutex_lock(null_value), testing::KilledBySignal(SIGSEGV), "");
2699#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002700 GTEST_SKIP() << "64-bit bionic-only test";
Christopher Ferris60907c72015-06-09 18:46:15 -07002701#endif
2702}
2703
2704TEST_F(pthread_DeathTest, pthread_mutex_unlock_null_64) {
2705#if defined(__BIONIC__) && defined(__LP64__)
2706 pthread_mutex_t* null_value = nullptr;
2707 ASSERT_EXIT(pthread_mutex_unlock(null_value), testing::KilledBySignal(SIGSEGV), "");
2708#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002709 GTEST_SKIP() << "64-bit bionic-only test";
Christopher Ferris60907c72015-06-09 18:46:15 -07002710#endif
2711}
Yabin Cui33ac04a2015-09-22 11:16:15 -07002712
2713extern _Unwind_Reason_Code FrameCounter(_Unwind_Context* ctx, void* arg);
2714
2715static volatile bool signal_handler_on_altstack_done;
2716
Josh Gao61db9ac2017-03-15 19:42:05 -07002717__attribute__((__noinline__))
2718static void signal_handler_backtrace() {
2719 // Check if we have enough stack space for unwinding.
2720 int count = 0;
2721 _Unwind_Backtrace(FrameCounter, &count);
2722 ASSERT_GT(count, 0);
2723}
2724
2725__attribute__((__noinline__))
2726static void signal_handler_logging() {
2727 // Check if we have enough stack space for logging.
2728 std::string s(2048, '*');
2729 GTEST_LOG_(INFO) << s;
2730 signal_handler_on_altstack_done = true;
2731}
2732
2733__attribute__((__noinline__))
2734static void signal_handler_snprintf() {
2735 // Check if we have enough stack space for snprintf to a PATH_MAX buffer, plus some extra.
2736 char buf[PATH_MAX + 2048];
2737 ASSERT_GT(snprintf(buf, sizeof(buf), "/proc/%d/status", getpid()), 0);
2738}
2739
Yabin Cui33ac04a2015-09-22 11:16:15 -07002740static void SignalHandlerOnAltStack(int signo, siginfo_t*, void*) {
2741 ASSERT_EQ(SIGUSR1, signo);
Josh Gao61db9ac2017-03-15 19:42:05 -07002742 signal_handler_backtrace();
2743 signal_handler_logging();
2744 signal_handler_snprintf();
Yabin Cui33ac04a2015-09-22 11:16:15 -07002745}
2746
Josh Gao415daa82017-03-06 17:45:33 -08002747TEST(pthread, big_enough_signal_stack) {
Yabin Cui33ac04a2015-09-22 11:16:15 -07002748 signal_handler_on_altstack_done = false;
2749 ScopedSignalHandler handler(SIGUSR1, SignalHandlerOnAltStack, SA_SIGINFO | SA_ONSTACK);
2750 kill(getpid(), SIGUSR1);
2751 ASSERT_TRUE(signal_handler_on_altstack_done);
2752}
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002753
2754TEST(pthread, pthread_barrierattr_smoke) {
2755 pthread_barrierattr_t attr;
2756 ASSERT_EQ(0, pthread_barrierattr_init(&attr));
2757 int pshared;
2758 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
2759 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
2760 ASSERT_EQ(0, pthread_barrierattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
2761 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
2762 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
2763 ASSERT_EQ(0, pthread_barrierattr_destroy(&attr));
2764}
2765
Yabin Cui81d27972016-03-22 13:45:55 -07002766struct BarrierTestHelperData {
2767 size_t thread_count;
2768 pthread_barrier_t barrier;
2769 std::atomic<int> finished_mask;
2770 std::atomic<int> serial_thread_count;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002771 size_t iteration_count;
Yabin Cui81d27972016-03-22 13:45:55 -07002772 std::atomic<size_t> finished_iteration_count;
2773
2774 BarrierTestHelperData(size_t thread_count, size_t iteration_count)
2775 : thread_count(thread_count), finished_mask(0), serial_thread_count(0),
2776 iteration_count(iteration_count), finished_iteration_count(0) {
2777 }
2778};
2779
2780struct BarrierTestHelperArg {
2781 int id;
2782 BarrierTestHelperData* data;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002783};
2784
2785static void BarrierTestHelper(BarrierTestHelperArg* arg) {
Yabin Cui81d27972016-03-22 13:45:55 -07002786 for (size_t i = 0; i < arg->data->iteration_count; ++i) {
2787 int result = pthread_barrier_wait(&arg->data->barrier);
2788 if (result == PTHREAD_BARRIER_SERIAL_THREAD) {
2789 arg->data->serial_thread_count++;
2790 } else {
2791 ASSERT_EQ(0, result);
2792 }
Yabin Cuid5c04c52017-05-02 12:57:39 -07002793 int mask = arg->data->finished_mask.fetch_or(1 << arg->id);
Yabin Cuiab4cddc2017-05-02 16:18:13 -07002794 mask |= 1 << arg->id;
Yabin Cuid5c04c52017-05-02 12:57:39 -07002795 if (mask == ((1 << arg->data->thread_count) - 1)) {
Yabin Cui81d27972016-03-22 13:45:55 -07002796 ASSERT_EQ(1, arg->data->serial_thread_count);
2797 arg->data->finished_iteration_count++;
2798 arg->data->finished_mask = 0;
2799 arg->data->serial_thread_count = 0;
2800 }
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002801 }
2802}
2803
2804TEST(pthread, pthread_barrier_smoke) {
2805 const size_t BARRIER_ITERATION_COUNT = 10;
2806 const size_t BARRIER_THREAD_COUNT = 10;
Yabin Cui81d27972016-03-22 13:45:55 -07002807 BarrierTestHelperData data(BARRIER_THREAD_COUNT, BARRIER_ITERATION_COUNT);
2808 ASSERT_EQ(0, pthread_barrier_init(&data.barrier, nullptr, data.thread_count));
2809 std::vector<pthread_t> threads(data.thread_count);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002810 std::vector<BarrierTestHelperArg> args(threads.size());
2811 for (size_t i = 0; i < threads.size(); ++i) {
Yabin Cui81d27972016-03-22 13:45:55 -07002812 args[i].id = i;
2813 args[i].data = &data;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002814 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
2815 reinterpret_cast<void* (*)(void*)>(BarrierTestHelper), &args[i]));
2816 }
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002817 for (size_t i = 0; i < threads.size(); ++i) {
2818 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
2819 }
Yabin Cui81d27972016-03-22 13:45:55 -07002820 ASSERT_EQ(data.iteration_count, data.finished_iteration_count);
2821 ASSERT_EQ(0, pthread_barrier_destroy(&data.barrier));
2822}
2823
2824struct BarrierDestroyTestArg {
2825 std::atomic<int> tid;
2826 pthread_barrier_t* barrier;
2827};
2828
2829static void BarrierDestroyTestHelper(BarrierDestroyTestArg* arg) {
2830 arg->tid = gettid();
2831 ASSERT_EQ(0, pthread_barrier_wait(arg->barrier));
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002832}
2833
2834TEST(pthread, pthread_barrier_destroy) {
2835 pthread_barrier_t barrier;
2836 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, 2));
2837 pthread_t thread;
Yabin Cui81d27972016-03-22 13:45:55 -07002838 BarrierDestroyTestArg arg;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002839 arg.tid = 0;
2840 arg.barrier = &barrier;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002841 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui81d27972016-03-22 13:45:55 -07002842 reinterpret_cast<void* (*)(void*)>(BarrierDestroyTestHelper), &arg));
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002843 WaitUntilThreadSleep(arg.tid);
2844 ASSERT_EQ(EBUSY, pthread_barrier_destroy(&barrier));
2845 ASSERT_EQ(PTHREAD_BARRIER_SERIAL_THREAD, pthread_barrier_wait(&barrier));
2846 // Verify if the barrier can be destroyed directly after pthread_barrier_wait().
2847 ASSERT_EQ(0, pthread_barrier_destroy(&barrier));
2848 ASSERT_EQ(0, pthread_join(thread, nullptr));
2849#if defined(__BIONIC__)
2850 ASSERT_EQ(EINVAL, pthread_barrier_destroy(&barrier));
2851#endif
2852}
2853
2854struct BarrierOrderingTestHelperArg {
2855 pthread_barrier_t* barrier;
2856 size_t* array;
2857 size_t array_length;
2858 size_t id;
2859};
2860
2861void BarrierOrderingTestHelper(BarrierOrderingTestHelperArg* arg) {
2862 const size_t ITERATION_COUNT = 10000;
2863 for (size_t i = 1; i <= ITERATION_COUNT; ++i) {
2864 arg->array[arg->id] = i;
Yabin Cuic9a659c2015-11-05 15:36:08 -08002865 int result = pthread_barrier_wait(arg->barrier);
2866 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002867 for (size_t j = 0; j < arg->array_length; ++j) {
2868 ASSERT_EQ(i, arg->array[j]);
2869 }
Yabin Cuic9a659c2015-11-05 15:36:08 -08002870 result = pthread_barrier_wait(arg->barrier);
2871 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002872 }
2873}
2874
2875TEST(pthread, pthread_barrier_check_ordering) {
2876 const size_t THREAD_COUNT = 4;
2877 pthread_barrier_t barrier;
2878 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, THREAD_COUNT));
2879 size_t array[THREAD_COUNT];
2880 std::vector<pthread_t> threads(THREAD_COUNT);
2881 std::vector<BarrierOrderingTestHelperArg> args(THREAD_COUNT);
2882 for (size_t i = 0; i < THREAD_COUNT; ++i) {
2883 args[i].barrier = &barrier;
2884 args[i].array = array;
2885 args[i].array_length = THREAD_COUNT;
2886 args[i].id = i;
2887 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
2888 reinterpret_cast<void* (*)(void*)>(BarrierOrderingTestHelper),
2889 &args[i]));
2890 }
2891 for (size_t i = 0; i < THREAD_COUNT; ++i) {
2892 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
2893 }
2894}
Yabin Cuife3a83a2015-11-17 16:03:18 -08002895
Elliott Hughes463faad2018-07-06 14:34:49 -07002896TEST(pthread, pthread_barrier_init_zero_count) {
2897 pthread_barrier_t barrier;
2898 ASSERT_EQ(EINVAL, pthread_barrier_init(&barrier, nullptr, 0));
2899}
2900
Yabin Cuife3a83a2015-11-17 16:03:18 -08002901TEST(pthread, pthread_spinlock_smoke) {
2902 pthread_spinlock_t lock;
2903 ASSERT_EQ(0, pthread_spin_init(&lock, 0));
2904 ASSERT_EQ(0, pthread_spin_trylock(&lock));
2905 ASSERT_EQ(0, pthread_spin_unlock(&lock));
2906 ASSERT_EQ(0, pthread_spin_lock(&lock));
2907 ASSERT_EQ(EBUSY, pthread_spin_trylock(&lock));
2908 ASSERT_EQ(0, pthread_spin_unlock(&lock));
2909 ASSERT_EQ(0, pthread_spin_destroy(&lock));
2910}
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002911
Elliott Hughes8aecba72017-10-17 15:34:41 -07002912TEST(pthread, pthread_attr_getdetachstate__pthread_attr_setdetachstate) {
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002913 pthread_attr_t attr;
2914 ASSERT_EQ(0, pthread_attr_init(&attr));
2915
Elliott Hughes8aecba72017-10-17 15:34:41 -07002916 int state;
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002917 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002918 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2919 ASSERT_EQ(PTHREAD_CREATE_DETACHED, state);
2920
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002921 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002922 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2923 ASSERT_EQ(PTHREAD_CREATE_JOINABLE, state);
2924
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002925 ASSERT_EQ(EINVAL, pthread_attr_setdetachstate(&attr, 123));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002926 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2927 ASSERT_EQ(PTHREAD_CREATE_JOINABLE, state);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002928}
2929
2930TEST(pthread, pthread_create__mmap_failures) {
Evgeny Eltsinb4f7aaa2020-06-09 15:49:20 +02002931 // After thread is successfully created, native_bridge might need more memory to run it.
2932 SKIP_WITH_NATIVE_BRIDGE;
2933
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002934 pthread_attr_t attr;
2935 ASSERT_EQ(0, pthread_attr_init(&attr));
2936 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
2937
2938 const auto kPageSize = sysconf(_SC_PAGE_SIZE);
2939
Elliott Hughes57512982017-10-02 22:49:18 -07002940 // Use up all the VMAs. By default this is 64Ki (though some will already be in use).
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002941 std::vector<void*> pages;
Elliott Hughes57512982017-10-02 22:49:18 -07002942 pages.reserve(64 * 1024);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002943 int prot = PROT_NONE;
2944 while (true) {
2945 void* page = mmap(nullptr, kPageSize, prot, MAP_ANON|MAP_PRIVATE, -1, 0);
2946 if (page == MAP_FAILED) break;
2947 pages.push_back(page);
2948 prot = (prot == PROT_NONE) ? PROT_READ : PROT_NONE;
2949 }
2950
2951 // Try creating threads, freeing up a page each time we fail.
2952 size_t EAGAIN_count = 0;
2953 size_t i = 0;
2954 for (; i < pages.size(); ++i) {
2955 pthread_t t;
2956 int status = pthread_create(&t, &attr, IdFn, nullptr);
2957 if (status != EAGAIN) break;
2958 ++EAGAIN_count;
2959 ASSERT_EQ(0, munmap(pages[i], kPageSize));
2960 }
2961
Ryan Prichard45d13492019-01-03 02:51:30 -08002962 // Creating a thread uses at least three VMAs: the combined stack and TLS, and a guard on each
2963 // side. So we should have seen at least three failures.
2964 ASSERT_GE(EAGAIN_count, 3U);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002965
2966 for (; i < pages.size(); ++i) {
2967 ASSERT_EQ(0, munmap(pages[i], kPageSize));
2968 }
2969}
Elliott Hughesdff08ce2017-10-16 09:58:45 -07002970
2971TEST(pthread, pthread_setschedparam) {
2972 sched_param p = { .sched_priority = INT_MIN };
2973 ASSERT_EQ(EINVAL, pthread_setschedparam(pthread_self(), INT_MIN, &p));
2974}
2975
2976TEST(pthread, pthread_setschedprio) {
2977 ASSERT_EQ(EINVAL, pthread_setschedprio(pthread_self(), INT_MIN));
2978}
Elliott Hughes8aecba72017-10-17 15:34:41 -07002979
2980TEST(pthread, pthread_attr_getinheritsched__pthread_attr_setinheritsched) {
2981 pthread_attr_t attr;
2982 ASSERT_EQ(0, pthread_attr_init(&attr));
2983
2984 int state;
2985 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2986 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
2987 ASSERT_EQ(PTHREAD_INHERIT_SCHED, state);
2988
2989 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
2990 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
2991 ASSERT_EQ(PTHREAD_EXPLICIT_SCHED, state);
2992
2993 ASSERT_EQ(EINVAL, pthread_attr_setinheritsched(&attr, 123));
2994 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
2995 ASSERT_EQ(PTHREAD_EXPLICIT_SCHED, state);
2996}
2997
2998TEST(pthread, pthread_attr_setinheritsched__PTHREAD_INHERIT_SCHED__PTHREAD_EXPLICIT_SCHED) {
2999 pthread_attr_t attr;
3000 ASSERT_EQ(0, pthread_attr_init(&attr));
3001
3002 // If we set invalid scheduling attributes but choose to inherit, everything's fine...
3003 sched_param param = { .sched_priority = sched_get_priority_max(SCHED_FIFO) + 1 };
3004 ASSERT_EQ(0, pthread_attr_setschedparam(&attr, &param));
3005 ASSERT_EQ(0, pthread_attr_setschedpolicy(&attr, SCHED_FIFO));
3006 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
3007
3008 pthread_t t;
3009 ASSERT_EQ(0, pthread_create(&t, &attr, IdFn, nullptr));
3010 ASSERT_EQ(0, pthread_join(t, nullptr));
3011
Elliott Hughes7a660662017-10-30 09:26:06 -07003012#if defined(__LP64__)
3013 // If we ask to use them, though, we'll see a failure...
Elliott Hughes8aecba72017-10-17 15:34:41 -07003014 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
3015 ASSERT_EQ(EINVAL, pthread_create(&t, &attr, IdFn, nullptr));
Elliott Hughes7a660662017-10-30 09:26:06 -07003016#else
3017 // For backwards compatibility with broken apps, we just ignore failures
3018 // to set scheduler attributes on LP32.
3019#endif
Elliott Hughes8aecba72017-10-17 15:34:41 -07003020}
3021
3022TEST(pthread, pthread_attr_setinheritsched_PTHREAD_INHERIT_SCHED_takes_effect) {
3023 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
3024 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO, &param);
Elliott Hughesbcaa4542019-03-08 15:20:23 -08003025 if (rc == EPERM) GTEST_SKIP() << "pthread_setschedparam failed with EPERM";
Elliott Hughes8aecba72017-10-17 15:34:41 -07003026 ASSERT_EQ(0, rc);
3027
3028 pthread_attr_t attr;
3029 ASSERT_EQ(0, pthread_attr_init(&attr));
3030 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
3031
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003032 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07003033 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003034 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07003035 int actual_policy;
3036 sched_param actual_param;
3037 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
3038 ASSERT_EQ(SCHED_FIFO, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003039 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07003040 ASSERT_EQ(0, pthread_join(t, nullptr));
3041}
3042
3043TEST(pthread, pthread_attr_setinheritsched_PTHREAD_EXPLICIT_SCHED_takes_effect) {
3044 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
3045 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO, &param);
Elliott Hughesbcaa4542019-03-08 15:20:23 -08003046 if (rc == EPERM) GTEST_SKIP() << "pthread_setschedparam failed with EPERM";
Elliott Hughes8aecba72017-10-17 15:34:41 -07003047 ASSERT_EQ(0, rc);
3048
3049 pthread_attr_t attr;
3050 ASSERT_EQ(0, pthread_attr_init(&attr));
3051 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
3052 ASSERT_EQ(0, pthread_attr_setschedpolicy(&attr, SCHED_OTHER));
3053
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003054 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07003055 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003056 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07003057 int actual_policy;
3058 sched_param actual_param;
3059 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
3060 ASSERT_EQ(SCHED_OTHER, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003061 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07003062 ASSERT_EQ(0, pthread_join(t, nullptr));
3063}
3064
3065TEST(pthread, pthread_attr_setinheritsched__takes_effect_despite_SCHED_RESET_ON_FORK) {
3066 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
3067 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param);
Elliott Hughesbcaa4542019-03-08 15:20:23 -08003068 if (rc == EPERM) GTEST_SKIP() << "pthread_setschedparam failed with EPERM";
Elliott Hughes8aecba72017-10-17 15:34:41 -07003069 ASSERT_EQ(0, rc);
3070
3071 pthread_attr_t attr;
3072 ASSERT_EQ(0, pthread_attr_init(&attr));
3073 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
3074
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003075 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07003076 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003077 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07003078 int actual_policy;
3079 sched_param actual_param;
3080 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
3081 ASSERT_EQ(SCHED_FIFO | SCHED_RESET_ON_FORK, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003082 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07003083 ASSERT_EQ(0, pthread_join(t, nullptr));
3084}
Peter Collingbourne5d3aa862020-09-11 15:05:17 -07003085
3086extern "C" bool android_run_on_all_threads(bool (*func)(void*), void* arg);
3087
3088TEST(pthread, run_on_all_threads) {
3089#if defined(__BIONIC__)
3090 pthread_t t;
3091 ASSERT_EQ(
3092 0, pthread_create(
3093 &t, nullptr,
3094 [](void*) -> void* {
3095 pthread_attr_t detached;
3096 if (pthread_attr_init(&detached) != 0 ||
3097 pthread_attr_setdetachstate(&detached, PTHREAD_CREATE_DETACHED) != 0) {
3098 return reinterpret_cast<void*>(errno);
3099 }
3100
3101 for (int i = 0; i != 1000; ++i) {
3102 pthread_t t1, t2;
3103 if (pthread_create(
3104 &t1, &detached, [](void*) -> void* { return nullptr; }, nullptr) != 0 ||
3105 pthread_create(
3106 &t2, nullptr, [](void*) -> void* { return nullptr; }, nullptr) != 0 ||
3107 pthread_join(t2, nullptr) != 0) {
3108 return reinterpret_cast<void*>(errno);
3109 }
3110 }
3111
3112 if (pthread_attr_destroy(&detached) != 0) {
3113 return reinterpret_cast<void*>(errno);
3114 }
3115 return nullptr;
3116 },
3117 nullptr));
3118
3119 for (int i = 0; i != 1000; ++i) {
3120 ASSERT_TRUE(android_run_on_all_threads([](void* arg) { return arg == nullptr; }, nullptr));
3121 }
3122
3123 void *retval;
3124 ASSERT_EQ(0, pthread_join(t, &retval));
3125 ASSERT_EQ(nullptr, retval);
3126#else
3127 GTEST_SKIP() << "bionic-only test";
3128#endif
3129}