blob: 680ef6e4cc354fd3721f9edabdba040ff3b5a0d7 [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 Hugheseabc47b2024-11-08 22:05:00 +000048#include "private/bionic_time_conversions.h"
Elliott Hughes71ba5892018-02-07 12:44:45 -080049#include "SignalUtils.h"
Elliott Hughes15dfd632015-09-22 16:40:14 -070050#include "utils.h"
51
Elliott Hughes141b9172021-04-09 17:13:09 -070052using pthread_DeathTest = SilentDeathTest;
Elliott Hughese657eb42021-02-18 17:11:56 -080053
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070054TEST(pthread, pthread_key_create) {
55 pthread_key_t key;
Yi Kong32bc0fc2018-08-02 17:31:13 -070056 ASSERT_EQ(0, pthread_key_create(&key, nullptr));
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070057 ASSERT_EQ(0, pthread_key_delete(key));
58 // Can't delete a key that's already been deleted.
59 ASSERT_EQ(EINVAL, pthread_key_delete(key));
60}
Elliott Hughes4d014e12012-09-07 16:47:54 -070061
Elliott Hughes1960f1c2025-02-26 14:46:52 -080062static std::vector<void*> example_key_destructor_data;
63static pthread_key_t example_key;
64static void example_key_destructor(void *data) {
65 // By the time the destructor function is running,
66 // this thread's value for the key should have been zeroed.
67 ASSERT_EQ(NULL, pthread_getspecific(example_key));
68
69 // Store the value so we can check we got the expected result.
70 example_key_destructor_data.push_back(data);
71}
72
73TEST(pthread, pthread_key_destructors) {
74 ASSERT_EQ(0, pthread_key_create(&example_key, example_key_destructor));
75
76 // Check that the destructor isn't called for a default null value.
77 std::thread([]() {}).join();
78 ASSERT_TRUE(example_key_destructor_data.empty());
79
80 // Check that the destructor isn't called for an explicit null value.
81 std::thread([]() {
82 ASSERT_EQ(0, pthread_setspecific(example_key, (void*) 1234));
83 ASSERT_EQ(0, pthread_setspecific(example_key, nullptr));
84 }).join();
85 ASSERT_TRUE(example_key_destructor_data.empty());
86
87 // Check that the destructor is called for a non-null value.
88 std::thread([]() { ASSERT_EQ(0, pthread_setspecific(example_key, (void*) 1234)); }).join();
89 ASSERT_EQ(1u, example_key_destructor_data.size());
90 ASSERT_EQ((void*) 1234, example_key_destructor_data[0]);
91
92 ASSERT_EQ(0, pthread_key_delete(example_key));
93}
94
Dan Albertc4bcc752014-09-30 11:48:24 -070095TEST(pthread, pthread_keys_max) {
Yabin Cui6c238f22014-12-11 20:50:41 -080096 // POSIX says PTHREAD_KEYS_MAX should be at least _POSIX_THREAD_KEYS_MAX.
97 ASSERT_GE(PTHREAD_KEYS_MAX, _POSIX_THREAD_KEYS_MAX);
Dan Albertc4bcc752014-09-30 11:48:24 -070098}
Elliott Hughes718a5b52014-01-28 17:02:03 -080099
Yabin Cui6c238f22014-12-11 20:50:41 -0800100TEST(pthread, sysconf_SC_THREAD_KEYS_MAX_eq_PTHREAD_KEYS_MAX) {
Dan Albertc4bcc752014-09-30 11:48:24 -0700101 int sysconf_max = sysconf(_SC_THREAD_KEYS_MAX);
Yabin Cui6c238f22014-12-11 20:50:41 -0800102 ASSERT_EQ(sysconf_max, PTHREAD_KEYS_MAX);
Dan Albertc4bcc752014-09-30 11:48:24 -0700103}
104
105TEST(pthread, pthread_key_many_distinct) {
Yabin Cui6c238f22014-12-11 20:50:41 -0800106 // As gtest uses pthread keys, we can't allocate exactly PTHREAD_KEYS_MAX
107 // pthread keys, but We should be able to allocate at least this many keys.
108 int nkeys = PTHREAD_KEYS_MAX / 2;
Dan Albertc4bcc752014-09-30 11:48:24 -0700109 std::vector<pthread_key_t> keys;
110
Tom Cherryb8ab6182017-04-05 16:20:29 -0700111 auto scope_guard = android::base::make_scope_guard([&keys] {
Elliott Hughes0b2acdf2015-10-02 18:25:19 -0700112 for (const auto& key : keys) {
Dan Albertc4bcc752014-09-30 11:48:24 -0700113 EXPECT_EQ(0, pthread_key_delete(key));
114 }
115 });
116
117 for (int i = 0; i < nkeys; ++i) {
118 pthread_key_t key;
Elliott Hughes61706932015-03-31 10:56:58 -0700119 // If this fails, it's likely that LIBC_PTHREAD_KEY_RESERVED_COUNT is wrong.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700120 ASSERT_EQ(0, pthread_key_create(&key, nullptr)) << i << " of " << nkeys;
Dan Albertc4bcc752014-09-30 11:48:24 -0700121 keys.push_back(key);
122 ASSERT_EQ(0, pthread_setspecific(key, reinterpret_cast<void*>(i)));
123 }
124
125 for (int i = keys.size() - 1; i >= 0; --i) {
126 ASSERT_EQ(reinterpret_cast<void*>(i), pthread_getspecific(keys.back()));
127 pthread_key_t key = keys.back();
128 keys.pop_back();
129 ASSERT_EQ(0, pthread_key_delete(key));
130 }
131}
132
Yabin Cui6c238f22014-12-11 20:50:41 -0800133TEST(pthread, pthread_key_not_exceed_PTHREAD_KEYS_MAX) {
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000134 std::vector<pthread_key_t> keys;
Dan Albertc4bcc752014-09-30 11:48:24 -0700135 int rv = 0;
Yabin Cui6c238f22014-12-11 20:50:41 -0800136
137 // Pthread keys are used by gtest, so PTHREAD_KEYS_MAX should
138 // be more than we are allowed to allocate now.
139 for (int i = 0; i < PTHREAD_KEYS_MAX; i++) {
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000140 pthread_key_t key;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700141 rv = pthread_key_create(&key, nullptr);
Dan Albertc4bcc752014-09-30 11:48:24 -0700142 if (rv == EAGAIN) {
143 break;
144 }
145 EXPECT_EQ(0, rv);
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000146 keys.push_back(key);
147 }
148
Dan Albertc4bcc752014-09-30 11:48:24 -0700149 // Don't leak keys.
Elliott Hughes0b2acdf2015-10-02 18:25:19 -0700150 for (const auto& key : keys) {
Dan Albertc4bcc752014-09-30 11:48:24 -0700151 EXPECT_EQ(0, pthread_key_delete(key));
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000152 }
Dan Albertc4bcc752014-09-30 11:48:24 -0700153 keys.clear();
154
155 // We should have eventually reached the maximum number of keys and received
156 // EAGAIN.
157 ASSERT_EQ(EAGAIN, rv);
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000158}
159
Elliott Hughesebb770f2014-06-25 13:46:46 -0700160TEST(pthread, pthread_key_delete) {
161 void* expected = reinterpret_cast<void*>(1234);
162 pthread_key_t key;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700163 ASSERT_EQ(0, pthread_key_create(&key, nullptr));
Elliott Hughesebb770f2014-06-25 13:46:46 -0700164 ASSERT_EQ(0, pthread_setspecific(key, expected));
165 ASSERT_EQ(expected, pthread_getspecific(key));
166 ASSERT_EQ(0, pthread_key_delete(key));
Yi Kong32bc0fc2018-08-02 17:31:13 -0700167 // After deletion, pthread_getspecific returns nullptr.
168 ASSERT_EQ(nullptr, pthread_getspecific(key));
Elliott Hughesebb770f2014-06-25 13:46:46 -0700169 // And you can't use pthread_setspecific with the deleted key.
170 ASSERT_EQ(EINVAL, pthread_setspecific(key, expected));
171}
172
Elliott Hughes40a52172014-07-30 14:48:10 -0700173TEST(pthread, pthread_key_fork) {
174 void* expected = reinterpret_cast<void*>(1234);
175 pthread_key_t key;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700176 ASSERT_EQ(0, pthread_key_create(&key, nullptr));
Elliott Hughes40a52172014-07-30 14:48:10 -0700177 ASSERT_EQ(0, pthread_setspecific(key, expected));
178 ASSERT_EQ(expected, pthread_getspecific(key));
179
180 pid_t pid = fork();
181 ASSERT_NE(-1, pid) << strerror(errno);
182
183 if (pid == 0) {
184 // The surviving thread inherits all the forking thread's TLS values...
185 ASSERT_EQ(expected, pthread_getspecific(key));
186 _exit(99);
187 }
188
Elliott Hughes33697a02016-01-26 13:04:57 -0800189 AssertChildExited(pid, 99);
Elliott Hughes40a52172014-07-30 14:48:10 -0700190
191 ASSERT_EQ(expected, pthread_getspecific(key));
Dan Albert1d53ae22014-09-02 15:24:26 -0700192 ASSERT_EQ(0, pthread_key_delete(key));
Elliott Hughes40a52172014-07-30 14:48:10 -0700193}
194
195static void* DirtyKeyFn(void* key) {
196 return pthread_getspecific(*reinterpret_cast<pthread_key_t*>(key));
197}
198
199TEST(pthread, pthread_key_dirty) {
200 pthread_key_t key;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700201 ASSERT_EQ(0, pthread_key_create(&key, nullptr));
Elliott Hughes40a52172014-07-30 14:48:10 -0700202
Yabin Cuia36158a2015-11-16 21:06:16 -0800203 size_t stack_size = 640 * 1024;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700204 void* stack = mmap(nullptr, stack_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
Elliott Hughes40a52172014-07-30 14:48:10 -0700205 ASSERT_NE(MAP_FAILED, stack);
206 memset(stack, 0xff, stack_size);
207
208 pthread_attr_t attr;
209 ASSERT_EQ(0, pthread_attr_init(&attr));
210 ASSERT_EQ(0, pthread_attr_setstack(&attr, stack, stack_size));
211
212 pthread_t t;
213 ASSERT_EQ(0, pthread_create(&t, &attr, DirtyKeyFn, &key));
214
215 void* result;
216 ASSERT_EQ(0, pthread_join(t, &result));
217 ASSERT_EQ(nullptr, result); // Not ~0!
218
219 ASSERT_EQ(0, munmap(stack, stack_size));
Dan Albert1d53ae22014-09-02 15:24:26 -0700220 ASSERT_EQ(0, pthread_key_delete(key));
Elliott Hughes40a52172014-07-30 14:48:10 -0700221}
222
Florian Mayerf9666202023-02-28 14:26:06 -0800223static void* FnWithStackFrame(void*) {
224 int x;
225 *const_cast<volatile int*>(&x) = 1;
226 return nullptr;
227}
228
229TEST(pthread, pthread_heap_allocated_stack) {
230 SKIP_WITH_HWASAN; // TODO(b/148982147): Re-enable when fixed.
231
232 size_t stack_size = 640 * 1024;
Elliott Hughes18e335b2023-04-21 11:18:40 -0700233 std::unique_ptr<char[]> stack(new (std::align_val_t(getpagesize())) char[stack_size]);
234 memset(stack.get(), '\xff', stack_size);
Florian Mayerf9666202023-02-28 14:26:06 -0800235
236 pthread_attr_t attr;
237 ASSERT_EQ(0, pthread_attr_init(&attr));
Elliott Hughes18e335b2023-04-21 11:18:40 -0700238 ASSERT_EQ(0, pthread_attr_setstack(&attr, stack.get(), stack_size));
Florian Mayerf9666202023-02-28 14:26:06 -0800239
240 pthread_t t;
241 ASSERT_EQ(0, pthread_create(&t, &attr, FnWithStackFrame, nullptr));
242
243 void* result;
244 ASSERT_EQ(0, pthread_join(t, &result));
245}
246
Yabin Cui5ddbb3f2015-03-05 20:35:32 -0800247TEST(pthread, static_pthread_key_used_before_creation) {
248#if defined(__BIONIC__)
249 // See http://b/19625804. The bug is about a static/global pthread key being used before creation.
250 // So here tests if the static/global default value 0 can be detected as invalid key.
251 static pthread_key_t key;
252 ASSERT_EQ(nullptr, pthread_getspecific(key));
253 ASSERT_EQ(EINVAL, pthread_setspecific(key, nullptr));
254 ASSERT_EQ(EINVAL, pthread_key_delete(key));
255#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -0800256 GTEST_SKIP() << "bionic-only test";
Yabin Cui5ddbb3f2015-03-05 20:35:32 -0800257#endif
258}
259
Elliott Hughes4d014e12012-09-07 16:47:54 -0700260static void* IdFn(void* arg) {
261 return arg;
262}
263
Yabin Cui63481602014-12-01 17:41:04 -0800264class SpinFunctionHelper {
265 public:
266 SpinFunctionHelper() {
267 SpinFunctionHelper::spin_flag_ = true;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400268 }
Elliott Hughes0bd9d132017-11-02 13:11:13 -0700269
Yabin Cui63481602014-12-01 17:41:04 -0800270 ~SpinFunctionHelper() {
271 UnSpin();
272 }
Elliott Hughes0bd9d132017-11-02 13:11:13 -0700273
Yabin Cui63481602014-12-01 17:41:04 -0800274 auto GetFunction() -> void* (*)(void*) {
275 return SpinFunctionHelper::SpinFn;
276 }
277
278 void UnSpin() {
279 SpinFunctionHelper::spin_flag_ = false;
280 }
281
282 private:
283 static void* SpinFn(void*) {
284 while (spin_flag_) {}
Yi Kong32bc0fc2018-08-02 17:31:13 -0700285 return nullptr;
Yabin Cui63481602014-12-01 17:41:04 -0800286 }
Yabin Cuia36158a2015-11-16 21:06:16 -0800287 static std::atomic<bool> spin_flag_;
Yabin Cui63481602014-12-01 17:41:04 -0800288};
289
290// It doesn't matter if spin_flag_ is used in several tests,
291// because it is always set to false after each test. Each thread
292// loops on spin_flag_ can find it becomes false at some time.
Yabin Cuia36158a2015-11-16 21:06:16 -0800293std::atomic<bool> SpinFunctionHelper::spin_flag_;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400294
Elliott Hughes4d014e12012-09-07 16:47:54 -0700295static void* JoinFn(void* arg) {
Yi Kong32bc0fc2018-08-02 17:31:13 -0700296 return reinterpret_cast<void*>(pthread_join(reinterpret_cast<pthread_t>(arg), nullptr));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700297}
298
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400299static void AssertDetached(pthread_t t, bool is_detached) {
300 pthread_attr_t attr;
301 ASSERT_EQ(0, pthread_getattr_np(t, &attr));
302 int detach_state;
303 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &detach_state));
304 pthread_attr_destroy(&attr);
305 ASSERT_EQ(is_detached, (detach_state == PTHREAD_CREATE_DETACHED));
306}
307
Elliott Hughes7484c212017-02-02 02:41:38 +0000308static void MakeDeadThread(pthread_t& t) {
Yi Kong32bc0fc2018-08-02 17:31:13 -0700309 ASSERT_EQ(0, pthread_create(&t, nullptr, IdFn, nullptr));
310 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes7484c212017-02-02 02:41:38 +0000311}
312
Elliott Hughes4d014e12012-09-07 16:47:54 -0700313TEST(pthread, pthread_create) {
314 void* expected_result = reinterpret_cast<void*>(123);
315 // Can we create a thread?
316 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700317 ASSERT_EQ(0, pthread_create(&t, nullptr, IdFn, expected_result));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700318 // If we join, do we get the expected value back?
319 void* result;
320 ASSERT_EQ(0, pthread_join(t, &result));
321 ASSERT_EQ(expected_result, result);
322}
323
Elliott Hughes3e898472013-02-12 16:40:24 +0000324TEST(pthread, pthread_create_EAGAIN) {
325 pthread_attr_t attributes;
326 ASSERT_EQ(0, pthread_attr_init(&attributes));
327 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, static_cast<size_t>(-1) & ~(getpagesize() - 1)));
328
329 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700330 ASSERT_EQ(EAGAIN, pthread_create(&t, &attributes, IdFn, nullptr));
Elliott Hughes3e898472013-02-12 16:40:24 +0000331}
332
Elliott Hughes4d014e12012-09-07 16:47:54 -0700333TEST(pthread, pthread_no_join_after_detach) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700334 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800335
Elliott Hughes4d014e12012-09-07 16:47:54 -0700336 pthread_t t1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700337 ASSERT_EQ(0, pthread_create(&t1, nullptr, spin_helper.GetFunction(), nullptr));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700338
339 // After a pthread_detach...
340 ASSERT_EQ(0, pthread_detach(t1));
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400341 AssertDetached(t1, true);
Elliott Hughes4d014e12012-09-07 16:47:54 -0700342
343 // ...pthread_join should fail.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700344 ASSERT_EQ(EINVAL, pthread_join(t1, nullptr));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700345}
346
347TEST(pthread, pthread_no_op_detach_after_join) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700348 SpinFunctionHelper spin_helper;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400349
Elliott Hughes4d014e12012-09-07 16:47:54 -0700350 pthread_t t1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700351 ASSERT_EQ(0, pthread_create(&t1, nullptr, spin_helper.GetFunction(), nullptr));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700352
353 // If thread 2 is already waiting to join thread 1...
354 pthread_t t2;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700355 ASSERT_EQ(0, pthread_create(&t2, nullptr, JoinFn, reinterpret_cast<void*>(t1)));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700356
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400357 sleep(1); // (Give t2 a chance to call pthread_join.)
Elliott Hughes4d014e12012-09-07 16:47:54 -0700358
Yabin Cuibbb04322015-03-19 15:19:25 -0700359#if defined(__BIONIC__)
360 ASSERT_EQ(EINVAL, pthread_detach(t1));
361#else
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400362 ASSERT_EQ(0, pthread_detach(t1));
Yabin Cuibbb04322015-03-19 15:19:25 -0700363#endif
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400364 AssertDetached(t1, false);
365
Elliott Hughes725b2a92016-03-23 11:20:47 -0700366 spin_helper.UnSpin();
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400367
368 // ...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 -0700369 void* join_result;
370 ASSERT_EQ(0, pthread_join(t2, &join_result));
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700371 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700372}
Elliott Hughes14f19592012-10-29 10:19:44 -0700373
374TEST(pthread, pthread_join_self) {
Yi Kong32bc0fc2018-08-02 17:31:13 -0700375 ASSERT_EQ(EDEADLK, pthread_join(pthread_self(), nullptr));
Elliott Hughes14f19592012-10-29 10:19:44 -0700376}
Elliott Hughes4f251be2012-11-01 16:33:29 -0700377
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800378struct TestBug37410 {
379 pthread_t main_thread;
380 pthread_mutex_t mutex;
Elliott Hughes4f251be2012-11-01 16:33:29 -0700381
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800382 static void main() {
383 TestBug37410 data;
384 data.main_thread = pthread_self();
Yi Kong32bc0fc2018-08-02 17:31:13 -0700385 ASSERT_EQ(0, pthread_mutex_init(&data.mutex, nullptr));
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800386 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
387
388 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700389 ASSERT_EQ(0, pthread_create(&t, nullptr, TestBug37410::thread_fn, reinterpret_cast<void*>(&data)));
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800390
391 // Wait for the thread to be running...
392 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
393 ASSERT_EQ(0, pthread_mutex_unlock(&data.mutex));
394
395 // ...and exit.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700396 pthread_exit(nullptr);
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800397 }
398
399 private:
400 static void* thread_fn(void* arg) {
401 TestBug37410* data = reinterpret_cast<TestBug37410*>(arg);
402
Evgenii Stepanov352853a2019-02-05 17:37:37 -0800403 // Unlocking data->mutex will cause the main thread to exit, invalidating *data. Save the handle.
404 pthread_t main_thread = data->main_thread;
405
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800406 // Let the main thread know we're running.
407 pthread_mutex_unlock(&data->mutex);
408
409 // And wait for the main thread to exit.
Evgenii Stepanov352853a2019-02-05 17:37:37 -0800410 pthread_join(main_thread, nullptr);
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800411
Yi Kong32bc0fc2018-08-02 17:31:13 -0700412 return nullptr;
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800413 }
414};
Elliott Hughes4f251be2012-11-01 16:33:29 -0700415
Elliott Hughes7fd803c2013-02-14 16:33:52 -0800416// Even though this isn't really a death test, we have to say "DeathTest" here so gtest knows to
417// run this test (which exits normally) in its own process.
Yabin Cui9df70402014-11-05 18:01:01 -0800418TEST_F(pthread_DeathTest, pthread_bug_37410) {
Elliott Hughes4f251be2012-11-01 16:33:29 -0700419 // http://code.google.com/p/android/issues/detail?id=37410
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800420 ASSERT_EXIT(TestBug37410::main(), ::testing::ExitedWithCode(0), "");
Elliott Hughes4f251be2012-11-01 16:33:29 -0700421}
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800422
423static void* SignalHandlerFn(void* arg) {
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800424 sigset64_t wait_set;
425 sigfillset64(&wait_set);
426 return reinterpret_cast<void*>(sigwait64(&wait_set, reinterpret_cast<int*>(arg)));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800427}
428
429TEST(pthread, pthread_sigmask) {
Elliott Hughes19e62322013-10-15 11:23:57 -0700430 // Check that SIGUSR1 isn't blocked.
431 sigset_t original_set;
432 sigemptyset(&original_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700433 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, nullptr, &original_set));
Elliott Hughes19e62322013-10-15 11:23:57 -0700434 ASSERT_FALSE(sigismember(&original_set, SIGUSR1));
435
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800436 // Block SIGUSR1.
437 sigset_t set;
438 sigemptyset(&set);
439 sigaddset(&set, SIGUSR1);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700440 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, &set, nullptr));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800441
Elliott Hughes19e62322013-10-15 11:23:57 -0700442 // Check that SIGUSR1 is blocked.
443 sigset_t final_set;
444 sigemptyset(&final_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700445 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, nullptr, &final_set));
Elliott Hughes19e62322013-10-15 11:23:57 -0700446 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
447 // ...and that sigprocmask agrees with pthread_sigmask.
448 sigemptyset(&final_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700449 ASSERT_EQ(0, sigprocmask(SIG_BLOCK, nullptr, &final_set));
Elliott Hughes19e62322013-10-15 11:23:57 -0700450 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
451
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800452 // Spawn a thread that calls sigwait and tells us what it received.
453 pthread_t signal_thread;
454 int received_signal = -1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700455 ASSERT_EQ(0, pthread_create(&signal_thread, nullptr, SignalHandlerFn, &received_signal));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800456
457 // Send that thread SIGUSR1.
458 pthread_kill(signal_thread, SIGUSR1);
459
460 // See what it got.
461 void* join_result;
462 ASSERT_EQ(0, pthread_join(signal_thread, &join_result));
463 ASSERT_EQ(SIGUSR1, received_signal);
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700464 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
Elliott Hughes19e62322013-10-15 11:23:57 -0700465
466 // Restore the original signal mask.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700467 ASSERT_EQ(0, pthread_sigmask(SIG_SETMASK, &original_set, nullptr));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800468}
Elliott Hughes5e3fc432013-02-11 16:36:48 -0800469
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800470TEST(pthread, pthread_sigmask64_SIGTRMIN) {
471 // Check that SIGRTMIN isn't blocked.
472 sigset64_t original_set;
473 sigemptyset64(&original_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700474 ASSERT_EQ(0, pthread_sigmask64(SIG_BLOCK, nullptr, &original_set));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800475 ASSERT_FALSE(sigismember64(&original_set, SIGRTMIN));
476
477 // Block SIGRTMIN.
478 sigset64_t set;
479 sigemptyset64(&set);
480 sigaddset64(&set, SIGRTMIN);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700481 ASSERT_EQ(0, pthread_sigmask64(SIG_BLOCK, &set, nullptr));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800482
483 // Check that SIGRTMIN is blocked.
484 sigset64_t final_set;
485 sigemptyset64(&final_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700486 ASSERT_EQ(0, pthread_sigmask64(SIG_BLOCK, nullptr, &final_set));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800487 ASSERT_TRUE(sigismember64(&final_set, SIGRTMIN));
488 // ...and that sigprocmask64 agrees with pthread_sigmask64.
489 sigemptyset64(&final_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700490 ASSERT_EQ(0, sigprocmask64(SIG_BLOCK, nullptr, &final_set));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800491 ASSERT_TRUE(sigismember64(&final_set, SIGRTMIN));
492
493 // Spawn a thread that calls sigwait64 and tells us what it received.
494 pthread_t signal_thread;
495 int received_signal = -1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700496 ASSERT_EQ(0, pthread_create(&signal_thread, nullptr, SignalHandlerFn, &received_signal));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800497
498 // Send that thread SIGRTMIN.
499 pthread_kill(signal_thread, SIGRTMIN);
500
501 // See what it got.
502 void* join_result;
503 ASSERT_EQ(0, pthread_join(signal_thread, &join_result));
504 ASSERT_EQ(SIGRTMIN, received_signal);
505 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
506
507 // Restore the original signal mask.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700508 ASSERT_EQ(0, pthread_sigmask64(SIG_SETMASK, &original_set, nullptr));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800509}
510
Elliott Hughes725b2a92016-03-23 11:20:47 -0700511static void test_pthread_setname_np__pthread_getname_np(pthread_t t) {
512 ASSERT_EQ(0, pthread_setname_np(t, "short"));
513 char name[32];
514 ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name)));
515 ASSERT_STREQ("short", name);
516
Elliott Hughesd1aea302015-04-25 10:05:24 -0700517 // The limit is 15 characters --- the kernel's buffer is 16, but includes a NUL.
Elliott Hughes725b2a92016-03-23 11:20:47 -0700518 ASSERT_EQ(0, pthread_setname_np(t, "123456789012345"));
519 ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name)));
520 ASSERT_STREQ("123456789012345", name);
521
522 ASSERT_EQ(ERANGE, pthread_setname_np(t, "1234567890123456"));
523
524 // The passed-in buffer should be at least 16 bytes.
525 ASSERT_EQ(0, pthread_getname_np(t, name, 16));
526 ASSERT_EQ(ERANGE, pthread_getname_np(t, name, 15));
Elliott Hughes3e898472013-02-12 16:40:24 +0000527}
528
Elliott Hughes725b2a92016-03-23 11:20:47 -0700529TEST(pthread, pthread_setname_np__pthread_getname_np__self) {
530 test_pthread_setname_np__pthread_getname_np(pthread_self());
Elliott Hughes3e898472013-02-12 16:40:24 +0000531}
532
Elliott Hughes725b2a92016-03-23 11:20:47 -0700533TEST(pthread, pthread_setname_np__pthread_getname_np__other) {
534 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800535
Elliott Hughes725b2a92016-03-23 11:20:47 -0700536 pthread_t t;
Elliott Hughes4d098ca2016-04-11 12:43:05 -0700537 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
538 test_pthread_setname_np__pthread_getname_np(t);
539 spin_helper.UnSpin();
540 ASSERT_EQ(0, pthread_join(t, nullptr));
541}
542
543// http://b/28051133: a kernel misfeature means that you can't change the
544// name of another thread if you've set PR_SET_DUMPABLE to 0.
545TEST(pthread, pthread_setname_np__pthread_getname_np__other_PR_SET_DUMPABLE) {
546 ASSERT_EQ(0, prctl(PR_SET_DUMPABLE, 0)) << strerror(errno);
547
548 SpinFunctionHelper spin_helper;
549
550 pthread_t t;
551 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
Elliott Hughes725b2a92016-03-23 11:20:47 -0700552 test_pthread_setname_np__pthread_getname_np(t);
553 spin_helper.UnSpin();
554 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes3e898472013-02-12 16:40:24 +0000555}
556
Elliott Hughes11859d42017-02-13 17:59:29 -0800557TEST_F(pthread_DeathTest, pthread_setname_np__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000558 pthread_t dead_thread;
559 MakeDeadThread(dead_thread);
560
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800561 EXPECT_DEATH(pthread_setname_np(dead_thread, "short 3"),
562 "invalid pthread_t (.*) passed to pthread_setname_np");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800563}
564
565TEST_F(pthread_DeathTest, pthread_setname_np__null_thread) {
566 pthread_t null_thread = 0;
567 EXPECT_EQ(ENOENT, pthread_setname_np(null_thread, "short 3"));
Elliott Hughes11859d42017-02-13 17:59:29 -0800568}
569
570TEST_F(pthread_DeathTest, pthread_getname_np__no_such_thread) {
571 pthread_t dead_thread;
572 MakeDeadThread(dead_thread);
573
Elliott Hughesbcb15292017-02-07 21:05:30 +0000574 char name[64];
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800575 EXPECT_DEATH(pthread_getname_np(dead_thread, name, sizeof(name)),
576 "invalid pthread_t (.*) passed to pthread_getname_np");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800577}
578
579TEST_F(pthread_DeathTest, pthread_getname_np__null_thread) {
580 pthread_t null_thread = 0;
581
582 char name[64];
583 EXPECT_EQ(ENOENT, pthread_getname_np(null_thread, name, sizeof(name)));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000584}
585
Elliott Hughes9d23e042013-02-15 19:21:51 -0800586TEST(pthread, pthread_kill__0) {
587 // Signal 0 just tests that the thread exists, so it's safe to call on ourselves.
588 ASSERT_EQ(0, pthread_kill(pthread_self(), 0));
589}
590
591TEST(pthread, pthread_kill__invalid_signal) {
592 ASSERT_EQ(EINVAL, pthread_kill(pthread_self(), -1));
593}
594
Elliott Hughesfae89fc2013-02-21 11:22:23 -0800595static void pthread_kill__in_signal_handler_helper(int signal_number) {
596 static int count = 0;
597 ASSERT_EQ(SIGALRM, signal_number);
598 if (++count == 1) {
599 // Can we call pthread_kill from a signal handler?
600 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
601 }
602}
603
604TEST(pthread, pthread_kill__in_signal_handler) {
Elliott Hughes4b558f52014-03-04 15:58:02 -0800605 ScopedSignalHandler ssh(SIGALRM, pthread_kill__in_signal_handler_helper);
Elliott Hughesfae89fc2013-02-21 11:22:23 -0800606 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
607}
608
Josh Gaoddf757e2018-10-17 15:23:03 -0700609TEST(pthread, pthread_kill__exited_thread) {
610 static std::promise<pid_t> tid_promise;
611 pthread_t thread;
612 ASSERT_EQ(0, pthread_create(&thread, nullptr,
613 [](void*) -> void* {
614 tid_promise.set_value(gettid());
615 return nullptr;
616 },
617 nullptr));
618
619 pid_t tid = tid_promise.get_future().get();
620 while (TEMP_FAILURE_RETRY(syscall(__NR_tgkill, getpid(), tid, 0)) != -1) {
621 continue;
622 }
Elliott Hughes95646e62023-09-21 14:11:19 -0700623 ASSERT_ERRNO(ESRCH);
Josh Gaoddf757e2018-10-17 15:23:03 -0700624
625 ASSERT_EQ(ESRCH, pthread_kill(thread, 0));
626}
627
Elliott Hughes11859d42017-02-13 17:59:29 -0800628TEST_F(pthread_DeathTest, pthread_detach__no_such_thread) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000629 pthread_t dead_thread;
630 MakeDeadThread(dead_thread);
631
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800632 EXPECT_DEATH(pthread_detach(dead_thread),
633 "invalid pthread_t (.*) passed to pthread_detach");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800634}
635
636TEST_F(pthread_DeathTest, pthread_detach__null_thread) {
637 pthread_t null_thread = 0;
638 EXPECT_EQ(ESRCH, pthread_detach(null_thread));
Elliott Hughes7484c212017-02-02 02:41:38 +0000639}
640
Jeff Hao9b06cc32013-08-15 14:51:16 -0700641TEST(pthread, pthread_getcpuclockid__clock_gettime) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700642 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800643
Jeff Hao9b06cc32013-08-15 14:51:16 -0700644 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700645 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
Jeff Hao9b06cc32013-08-15 14:51:16 -0700646
647 clockid_t c;
648 ASSERT_EQ(0, pthread_getcpuclockid(t, &c));
649 timespec ts;
650 ASSERT_EQ(0, clock_gettime(c, &ts));
Elliott Hughes725b2a92016-03-23 11:20:47 -0700651 spin_helper.UnSpin();
Yabin Cuia36158a2015-11-16 21:06:16 -0800652 ASSERT_EQ(0, pthread_join(t, nullptr));
Jeff Hao9b06cc32013-08-15 14:51:16 -0700653}
654
Elliott Hughes11859d42017-02-13 17:59:29 -0800655TEST_F(pthread_DeathTest, pthread_getcpuclockid__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000656 pthread_t dead_thread;
657 MakeDeadThread(dead_thread);
658
659 clockid_t c;
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800660 EXPECT_DEATH(pthread_getcpuclockid(dead_thread, &c),
661 "invalid pthread_t (.*) passed to pthread_getcpuclockid");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800662}
663
664TEST_F(pthread_DeathTest, pthread_getcpuclockid__null_thread) {
665 pthread_t null_thread = 0;
666 clockid_t c;
667 EXPECT_EQ(ESRCH, pthread_getcpuclockid(null_thread, &c));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000668}
669
Elliott Hughes11859d42017-02-13 17:59:29 -0800670TEST_F(pthread_DeathTest, pthread_getschedparam__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000671 pthread_t dead_thread;
672 MakeDeadThread(dead_thread);
673
674 int policy;
675 sched_param param;
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800676 EXPECT_DEATH(pthread_getschedparam(dead_thread, &policy, &param),
677 "invalid pthread_t (.*) passed to pthread_getschedparam");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800678}
679
680TEST_F(pthread_DeathTest, pthread_getschedparam__null_thread) {
681 pthread_t null_thread = 0;
682 int policy;
683 sched_param param;
684 EXPECT_EQ(ESRCH, pthread_getschedparam(null_thread, &policy, &param));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000685}
686
Elliott Hughes11859d42017-02-13 17:59:29 -0800687TEST_F(pthread_DeathTest, pthread_setschedparam__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000688 pthread_t dead_thread;
689 MakeDeadThread(dead_thread);
690
691 int policy = 0;
692 sched_param param;
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800693 EXPECT_DEATH(pthread_setschedparam(dead_thread, policy, &param),
694 "invalid pthread_t (.*) passed to pthread_setschedparam");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800695}
696
697TEST_F(pthread_DeathTest, pthread_setschedparam__null_thread) {
698 pthread_t null_thread = 0;
699 int policy = 0;
700 sched_param param;
701 EXPECT_EQ(ESRCH, pthread_setschedparam(null_thread, policy, &param));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000702}
703
Elliott Hughesdff08ce2017-10-16 09:58:45 -0700704TEST_F(pthread_DeathTest, pthread_setschedprio__no_such_thread) {
705 pthread_t dead_thread;
706 MakeDeadThread(dead_thread);
707
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800708 EXPECT_DEATH(pthread_setschedprio(dead_thread, 123),
709 "invalid pthread_t (.*) passed to pthread_setschedprio");
Elliott Hughesdff08ce2017-10-16 09:58:45 -0700710}
711
712TEST_F(pthread_DeathTest, pthread_setschedprio__null_thread) {
713 pthread_t null_thread = 0;
714 EXPECT_EQ(ESRCH, pthread_setschedprio(null_thread, 123));
715}
716
Elliott Hughes11859d42017-02-13 17:59:29 -0800717TEST_F(pthread_DeathTest, pthread_join__no_such_thread) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000718 pthread_t dead_thread;
719 MakeDeadThread(dead_thread);
720
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800721 EXPECT_DEATH(pthread_join(dead_thread, nullptr),
722 "invalid pthread_t (.*) passed to pthread_join");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800723}
724
725TEST_F(pthread_DeathTest, pthread_join__null_thread) {
726 pthread_t null_thread = 0;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700727 EXPECT_EQ(ESRCH, pthread_join(null_thread, nullptr));
Elliott Hughes7484c212017-02-02 02:41:38 +0000728}
729
Elliott Hughes11859d42017-02-13 17:59:29 -0800730TEST_F(pthread_DeathTest, pthread_kill__no_such_thread) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000731 pthread_t dead_thread;
732 MakeDeadThread(dead_thread);
733
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800734 EXPECT_DEATH(pthread_kill(dead_thread, 0),
735 "invalid pthread_t (.*) passed to pthread_kill");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800736}
737
738TEST_F(pthread_DeathTest, pthread_kill__null_thread) {
739 pthread_t null_thread = 0;
740 EXPECT_EQ(ESRCH, pthread_kill(null_thread, 0));
Elliott Hughes7484c212017-02-02 02:41:38 +0000741}
742
msg5550f020d12013-06-06 14:59:28 -0400743TEST(pthread, pthread_join__multijoin) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700744 SpinFunctionHelper spin_helper;
msg5550f020d12013-06-06 14:59:28 -0400745
746 pthread_t t1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700747 ASSERT_EQ(0, pthread_create(&t1, nullptr, spin_helper.GetFunction(), nullptr));
msg5550f020d12013-06-06 14:59:28 -0400748
749 pthread_t t2;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700750 ASSERT_EQ(0, pthread_create(&t2, nullptr, JoinFn, reinterpret_cast<void*>(t1)));
msg5550f020d12013-06-06 14:59:28 -0400751
752 sleep(1); // (Give t2 a chance to call pthread_join.)
753
754 // Multiple joins to the same thread should fail.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700755 ASSERT_EQ(EINVAL, pthread_join(t1, nullptr));
msg5550f020d12013-06-06 14:59:28 -0400756
Elliott Hughes725b2a92016-03-23 11:20:47 -0700757 spin_helper.UnSpin();
msg5550f020d12013-06-06 14:59:28 -0400758
759 // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes).
760 void* join_result;
761 ASSERT_EQ(0, pthread_join(t2, &join_result));
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700762 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
msg5550f020d12013-06-06 14:59:28 -0400763}
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700764
Elliott Hughes70b24b12013-11-15 11:51:07 -0800765TEST(pthread, pthread_join__race) {
766 // http://b/11693195 --- pthread_join could return before the thread had actually exited.
767 // If the joiner unmapped the thread's stack, that could lead to SIGSEGV in the thread.
768 for (size_t i = 0; i < 1024; ++i) {
Yabin Cuia36158a2015-11-16 21:06:16 -0800769 size_t stack_size = 640*1024;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700770 void* stack = mmap(nullptr, stack_size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
Elliott Hughes70b24b12013-11-15 11:51:07 -0800771
772 pthread_attr_t a;
773 pthread_attr_init(&a);
774 pthread_attr_setstack(&a, stack, stack_size);
775
776 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700777 ASSERT_EQ(0, pthread_create(&t, &a, IdFn, nullptr));
778 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes70b24b12013-11-15 11:51:07 -0800779 ASSERT_EQ(0, munmap(stack, stack_size));
780 }
781}
782
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700783static void* GetActualGuardSizeFn(void* arg) {
784 pthread_attr_t attributes;
785 pthread_getattr_np(pthread_self(), &attributes);
786 pthread_attr_getguardsize(&attributes, reinterpret_cast<size_t*>(arg));
Yi Kong32bc0fc2018-08-02 17:31:13 -0700787 return nullptr;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700788}
789
790static size_t GetActualGuardSize(const pthread_attr_t& attributes) {
791 size_t result;
792 pthread_t t;
793 pthread_create(&t, &attributes, GetActualGuardSizeFn, &result);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700794 pthread_join(t, nullptr);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700795 return result;
796}
797
798static void* GetActualStackSizeFn(void* arg) {
799 pthread_attr_t attributes;
800 pthread_getattr_np(pthread_self(), &attributes);
801 pthread_attr_getstacksize(&attributes, reinterpret_cast<size_t*>(arg));
Yi Kong32bc0fc2018-08-02 17:31:13 -0700802 return nullptr;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700803}
804
805static size_t GetActualStackSize(const pthread_attr_t& attributes) {
806 size_t result;
807 pthread_t t;
808 pthread_create(&t, &attributes, GetActualStackSizeFn, &result);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700809 pthread_join(t, nullptr);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700810 return result;
811}
812
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700813TEST(pthread, pthread_attr_setguardsize_tiny) {
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700814 pthread_attr_t attributes;
815 ASSERT_EQ(0, pthread_attr_init(&attributes));
816
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700817 // No such thing as too small: will be rounded up to one page by pthread_create.
818 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 128));
819 size_t guard_size;
820 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
821 ASSERT_EQ(128U, guard_size);
Juan Yescas65af9a82023-12-07 11:35:21 -0800822 ASSERT_EQ(static_cast<unsigned long>(getpagesize()), GetActualGuardSize(attributes));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700823}
824
825TEST(pthread, pthread_attr_setguardsize_reasonable) {
826 pthread_attr_t attributes;
827 ASSERT_EQ(0, pthread_attr_init(&attributes));
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700828
829 // Large enough and a multiple of the page size.
830 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700831 size_t guard_size;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700832 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
833 ASSERT_EQ(32*1024U, guard_size);
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700834 ASSERT_EQ(32*1024U, GetActualGuardSize(attributes));
835}
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700836
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700837TEST(pthread, pthread_attr_setguardsize_needs_rounding) {
838 pthread_attr_t attributes;
839 ASSERT_EQ(0, pthread_attr_init(&attributes));
840
841 // Large enough but not a multiple of the page size.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700842 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024 + 1));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700843 size_t guard_size;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700844 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
845 ASSERT_EQ(32*1024U + 1, guard_size);
Juan Yescas65af9a82023-12-07 11:35:21 -0800846 ASSERT_EQ(roundup(32 * 1024U + 1, getpagesize()), GetActualGuardSize(attributes));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700847}
848
849TEST(pthread, pthread_attr_setguardsize_enormous) {
850 pthread_attr_t attributes;
851 ASSERT_EQ(0, pthread_attr_init(&attributes));
852
853 // Larger than the stack itself. (Historically we mistakenly carved
854 // the guard out of the stack itself, rather than adding it after the
855 // end.)
856 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024*1024));
857 size_t guard_size;
858 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
859 ASSERT_EQ(32*1024*1024U, guard_size);
860 ASSERT_EQ(32*1024*1024U, GetActualGuardSize(attributes));
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700861}
862
863TEST(pthread, pthread_attr_setstacksize) {
864 pthread_attr_t attributes;
865 ASSERT_EQ(0, pthread_attr_init(&attributes));
866
867 // Get the default stack size.
868 size_t default_stack_size;
869 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &default_stack_size));
870
871 // Too small.
872 ASSERT_EQ(EINVAL, pthread_attr_setstacksize(&attributes, 128));
873 size_t stack_size;
874 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
875 ASSERT_EQ(default_stack_size, stack_size);
876 ASSERT_GE(GetActualStackSize(attributes), default_stack_size);
877
Yabin Cui917d3902015-01-08 12:32:42 -0800878 // Large enough and a multiple of the page size; may be rounded up by pthread_create.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700879 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024));
880 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
881 ASSERT_EQ(32*1024U, stack_size);
Yabin Cui917d3902015-01-08 12:32:42 -0800882 ASSERT_GE(GetActualStackSize(attributes), 32*1024U);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700883
Yabin Cui917d3902015-01-08 12:32:42 -0800884 // Large enough but not aligned; will be rounded up by pthread_create.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700885 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024 + 1));
886 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
887 ASSERT_EQ(32*1024U + 1, stack_size);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800888#if defined(__BIONIC__)
Yabin Cui917d3902015-01-08 12:32:42 -0800889 ASSERT_GT(GetActualStackSize(attributes), 32*1024U + 1);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800890#else // __BIONIC__
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700891 // glibc rounds down, in violation of POSIX. They document this in their BUGS section.
892 ASSERT_EQ(GetActualStackSize(attributes), 32*1024U);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800893#endif // __BIONIC__
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700894}
Elliott Hughesc3f11402013-10-30 14:40:09 -0700895
Yabin Cui76615da2015-03-17 14:22:09 -0700896TEST(pthread, pthread_rwlockattr_smoke) {
897 pthread_rwlockattr_t attr;
898 ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
899
900 int pshared_value_array[] = {PTHREAD_PROCESS_PRIVATE, PTHREAD_PROCESS_SHARED};
901 for (size_t i = 0; i < sizeof(pshared_value_array) / sizeof(pshared_value_array[0]); ++i) {
902 ASSERT_EQ(0, pthread_rwlockattr_setpshared(&attr, pshared_value_array[i]));
903 int pshared;
904 ASSERT_EQ(0, pthread_rwlockattr_getpshared(&attr, &pshared));
905 ASSERT_EQ(pshared_value_array[i], pshared);
906 }
907
Colin Cross4c5595c2021-08-16 15:51:59 -0700908#if !defined(ANDROID_HOST_MUSL)
Colin Cross7da20342021-07-28 11:18:11 -0700909 // musl doesn't have pthread_rwlockattr_setkind_np
Yabin Cui76615da2015-03-17 14:22:09 -0700910 int kind_array[] = {PTHREAD_RWLOCK_PREFER_READER_NP,
911 PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP};
912 for (size_t i = 0; i < sizeof(kind_array) / sizeof(kind_array[0]); ++i) {
913 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_array[i]));
914 int kind;
915 ASSERT_EQ(0, pthread_rwlockattr_getkind_np(&attr, &kind));
916 ASSERT_EQ(kind_array[i], kind);
917 }
Colin Cross7da20342021-07-28 11:18:11 -0700918#endif
Yabin Cui76615da2015-03-17 14:22:09 -0700919
920 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
921}
922
923TEST(pthread, pthread_rwlock_init_same_as_PTHREAD_RWLOCK_INITIALIZER) {
924 pthread_rwlock_t lock1 = PTHREAD_RWLOCK_INITIALIZER;
925 pthread_rwlock_t lock2;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700926 ASSERT_EQ(0, pthread_rwlock_init(&lock2, nullptr));
Yabin Cui76615da2015-03-17 14:22:09 -0700927 ASSERT_EQ(0, memcmp(&lock1, &lock2, sizeof(lock1)));
928}
929
Elliott Hughesc3f11402013-10-30 14:40:09 -0700930TEST(pthread, pthread_rwlock_smoke) {
931 pthread_rwlock_t l;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700932 ASSERT_EQ(0, pthread_rwlock_init(&l, nullptr));
Elliott Hughesc3f11402013-10-30 14:40:09 -0700933
Calin Juravle76f352e2014-05-19 13:41:10 +0100934 // Single read lock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700935 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
936 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
937
Calin Juravle76f352e2014-05-19 13:41:10 +0100938 // Multiple read lock
939 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
940 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
941 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
942 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
943
944 // Write lock
Calin Juravle92687e42014-05-22 19:21:22 +0100945 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
946 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100947
948 // Try writer lock
949 ASSERT_EQ(0, pthread_rwlock_trywrlock(&l));
950 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
951 ASSERT_EQ(EBUSY, pthread_rwlock_tryrdlock(&l));
952 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
953
954 // Try reader lock
955 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
956 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
957 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
958 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
959 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
960
961 // Try writer lock after unlock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700962 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
963 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
964
Calin Juravle76f352e2014-05-19 13:41:10 +0100965 // EDEADLK in "read after write"
966 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
967 ASSERT_EQ(EDEADLK, pthread_rwlock_rdlock(&l));
968 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
969
970 // EDEADLK in "write after write"
971 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
972 ASSERT_EQ(EDEADLK, pthread_rwlock_wrlock(&l));
973 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100974
Elliott Hughesc3f11402013-10-30 14:40:09 -0700975 ASSERT_EQ(0, pthread_rwlock_destroy(&l));
976}
977
Yabin Cui08ee8d22015-02-11 17:04:36 -0800978struct RwlockWakeupHelperArg {
979 pthread_rwlock_t lock;
980 enum Progress {
981 LOCK_INITIALIZED,
982 LOCK_WAITING,
983 LOCK_RELEASED,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800984 LOCK_ACCESSED,
985 LOCK_TIMEDOUT,
Yabin Cui08ee8d22015-02-11 17:04:36 -0800986 };
987 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -0700988 std::atomic<pid_t> tid;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800989 std::function<int (pthread_rwlock_t*)> trylock_function;
990 std::function<int (pthread_rwlock_t*)> lock_function;
991 std::function<int (pthread_rwlock_t*, const timespec*)> timed_lock_function;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -0800992 clockid_t clock;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800993};
994
Yabin Cuic9a659c2015-11-05 15:36:08 -0800995static void pthread_rwlock_wakeup_helper(RwlockWakeupHelperArg* arg) {
Yabin Cuif7969852015-04-02 17:47:48 -0700996 arg->tid = gettid();
Yabin Cui08ee8d22015-02-11 17:04:36 -0800997 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
998 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
999
Yabin Cuic9a659c2015-11-05 15:36:08 -08001000 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
1001 ASSERT_EQ(0, arg->lock_function(&arg->lock));
Yabin Cui08ee8d22015-02-11 17:04:36 -08001002 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_RELEASED, arg->progress);
1003 ASSERT_EQ(0, pthread_rwlock_unlock(&arg->lock));
1004
1005 arg->progress = RwlockWakeupHelperArg::LOCK_ACCESSED;
1006}
1007
Yabin Cuic9a659c2015-11-05 15:36:08 -08001008static void test_pthread_rwlock_reader_wakeup_writer(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -08001009 RwlockWakeupHelperArg wakeup_arg;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001010 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -08001011 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
1012 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -07001013 wakeup_arg.tid = 0;
Tom Cherry60ddedf2018-02-20 15:40:02 -08001014 wakeup_arg.trylock_function = &pthread_rwlock_trywrlock;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001015 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -08001016
1017 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001018 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cuic9a659c2015-11-05 15:36:08 -08001019 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -07001020 WaitUntilThreadSleep(wakeup_arg.tid);
1021 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
1022
Yabin Cui08ee8d22015-02-11 17:04:36 -08001023 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
1024 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
1025
Yi Kong32bc0fc2018-08-02 17:31:13 -07001026 ASSERT_EQ(0, pthread_join(thread, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -08001027 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
1028 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
1029}
1030
Yabin Cuic9a659c2015-11-05 15:36:08 -08001031TEST(pthread, pthread_rwlock_reader_wakeup_writer) {
1032 test_pthread_rwlock_reader_wakeup_writer(pthread_rwlock_wrlock);
Yabin Cui08ee8d22015-02-11 17:04:36 -08001033}
1034
Yabin Cuic9a659c2015-11-05 15:36:08 -08001035TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait) {
1036 timespec ts;
1037 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1038 ts.tv_sec += 1;
1039 test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) {
1040 return pthread_rwlock_timedwrlock(lock, &ts);
1041 });
1042}
1043
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001044TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait_monotonic_np) {
1045#if defined(__BIONIC__)
1046 timespec ts;
1047 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1048 ts.tv_sec += 1;
1049 test_pthread_rwlock_reader_wakeup_writer(
1050 [&](pthread_rwlock_t* lock) { return pthread_rwlock_timedwrlock_monotonic_np(lock, &ts); });
1051#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001052 GTEST_SKIP() << "pthread_rwlock_timedwrlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001053#endif // __BIONIC__
1054}
1055
Tom Cherry69010802019-05-07 20:33:05 -07001056TEST(pthread, pthread_rwlock_reader_wakeup_writer_clockwait) {
1057#if defined(__BIONIC__)
1058 timespec ts;
1059 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1060 ts.tv_sec += 1;
1061 test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) {
1062 return pthread_rwlock_clockwrlock(lock, CLOCK_MONOTONIC, &ts);
1063 });
1064
1065 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1066 ts.tv_sec += 1;
1067 test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) {
1068 return pthread_rwlock_clockwrlock(lock, CLOCK_REALTIME, &ts);
1069 });
1070#else // __BIONIC__
1071 GTEST_SKIP() << "pthread_rwlock_clockwrlock not available";
1072#endif // __BIONIC__
1073}
1074
Yabin Cuic9a659c2015-11-05 15:36:08 -08001075static void test_pthread_rwlock_writer_wakeup_reader(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -08001076 RwlockWakeupHelperArg wakeup_arg;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001077 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -08001078 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
1079 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -07001080 wakeup_arg.tid = 0;
Tom Cherry60ddedf2018-02-20 15:40:02 -08001081 wakeup_arg.trylock_function = &pthread_rwlock_tryrdlock;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001082 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -08001083
1084 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001085 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cuic9a659c2015-11-05 15:36:08 -08001086 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -07001087 WaitUntilThreadSleep(wakeup_arg.tid);
1088 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
1089
Yabin Cui08ee8d22015-02-11 17:04:36 -08001090 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
1091 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
1092
Yi Kong32bc0fc2018-08-02 17:31:13 -07001093 ASSERT_EQ(0, pthread_join(thread, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -08001094 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
1095 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
1096}
1097
Yabin Cuic9a659c2015-11-05 15:36:08 -08001098TEST(pthread, pthread_rwlock_writer_wakeup_reader) {
1099 test_pthread_rwlock_writer_wakeup_reader(pthread_rwlock_rdlock);
1100}
1101
1102TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait) {
1103 timespec ts;
1104 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1105 ts.tv_sec += 1;
1106 test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) {
1107 return pthread_rwlock_timedrdlock(lock, &ts);
1108 });
1109}
1110
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001111TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait_monotonic_np) {
1112#if defined(__BIONIC__)
1113 timespec ts;
1114 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1115 ts.tv_sec += 1;
1116 test_pthread_rwlock_writer_wakeup_reader(
1117 [&](pthread_rwlock_t* lock) { return pthread_rwlock_timedrdlock_monotonic_np(lock, &ts); });
1118#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001119 GTEST_SKIP() << "pthread_rwlock_timedrdlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001120#endif // __BIONIC__
1121}
1122
Tom Cherry69010802019-05-07 20:33:05 -07001123TEST(pthread, pthread_rwlock_writer_wakeup_reader_clockwait) {
1124#if defined(__BIONIC__)
1125 timespec ts;
1126 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1127 ts.tv_sec += 1;
1128 test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) {
1129 return pthread_rwlock_clockrdlock(lock, CLOCK_MONOTONIC, &ts);
1130 });
1131
1132 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1133 ts.tv_sec += 1;
1134 test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) {
1135 return pthread_rwlock_clockrdlock(lock, CLOCK_REALTIME, &ts);
1136 });
1137#else // __BIONIC__
1138 GTEST_SKIP() << "pthread_rwlock_clockrdlock not available";
1139#endif // __BIONIC__
1140}
1141
Yabin Cuic9a659c2015-11-05 15:36:08 -08001142static void pthread_rwlock_wakeup_timeout_helper(RwlockWakeupHelperArg* arg) {
1143 arg->tid = gettid();
1144 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
1145 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
1146
1147 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
1148
1149 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001150 ASSERT_EQ(0, clock_gettime(arg->clock, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001151 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
1152 ts.tv_nsec = -1;
1153 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
1154 ts.tv_nsec = NS_PER_S;
1155 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
1156 ts.tv_nsec = NS_PER_S - 1;
1157 ts.tv_sec = -1;
1158 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001159 ASSERT_EQ(0, clock_gettime(arg->clock, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001160 ts.tv_sec += 1;
1161 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
1162 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, arg->progress);
1163 arg->progress = RwlockWakeupHelperArg::LOCK_TIMEDOUT;
1164}
1165
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001166static void pthread_rwlock_timedrdlock_timeout_helper(
1167 clockid_t clock, int (*lock_function)(pthread_rwlock_t* __rwlock, const timespec* __timeout)) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001168 RwlockWakeupHelperArg wakeup_arg;
1169 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
1170 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
1171 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
1172 wakeup_arg.tid = 0;
Tom Cherry60ddedf2018-02-20 15:40:02 -08001173 wakeup_arg.trylock_function = &pthread_rwlock_tryrdlock;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001174 wakeup_arg.timed_lock_function = lock_function;
1175 wakeup_arg.clock = clock;
1176
1177 pthread_t thread;
1178 ASSERT_EQ(0, pthread_create(&thread, nullptr,
1179 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
1180 WaitUntilThreadSleep(wakeup_arg.tid);
1181 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
1182
1183 ASSERT_EQ(0, pthread_join(thread, nullptr));
1184 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
1185 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
1186 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
1187}
1188
1189TEST(pthread, pthread_rwlock_timedrdlock_timeout) {
1190 pthread_rwlock_timedrdlock_timeout_helper(CLOCK_REALTIME, pthread_rwlock_timedrdlock);
1191}
1192
1193TEST(pthread, pthread_rwlock_timedrdlock_monotonic_np_timeout) {
1194#if defined(__BIONIC__)
1195 pthread_rwlock_timedrdlock_timeout_helper(CLOCK_MONOTONIC,
1196 pthread_rwlock_timedrdlock_monotonic_np);
1197#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001198 GTEST_SKIP() << "pthread_rwlock_timedrdlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001199#endif // __BIONIC__
1200}
1201
Tom Cherry69010802019-05-07 20:33:05 -07001202TEST(pthread, pthread_rwlock_clockrdlock_monotonic_timeout) {
1203#if defined(__BIONIC__)
1204 pthread_rwlock_timedrdlock_timeout_helper(
1205 CLOCK_MONOTONIC, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) {
1206 return pthread_rwlock_clockrdlock(__rwlock, CLOCK_MONOTONIC, __timeout);
1207 });
1208#else // __BIONIC__
1209 GTEST_SKIP() << "pthread_rwlock_clockrdlock not available";
1210#endif // __BIONIC__
1211}
1212
1213TEST(pthread, pthread_rwlock_clockrdlock_realtime_timeout) {
1214#if defined(__BIONIC__)
1215 pthread_rwlock_timedrdlock_timeout_helper(
1216 CLOCK_REALTIME, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) {
1217 return pthread_rwlock_clockrdlock(__rwlock, CLOCK_REALTIME, __timeout);
1218 });
1219#else // __BIONIC__
1220 GTEST_SKIP() << "pthread_rwlock_clockrdlock not available";
1221#endif // __BIONIC__
1222}
1223
1224TEST(pthread, pthread_rwlock_clockrdlock_invalid) {
1225#if defined(__BIONIC__)
1226 pthread_rwlock_t lock = PTHREAD_RWLOCK_INITIALIZER;
1227 timespec ts;
1228 EXPECT_EQ(EINVAL, pthread_rwlock_clockrdlock(&lock, CLOCK_PROCESS_CPUTIME_ID, &ts));
1229#else // __BIONIC__
1230 GTEST_SKIP() << "pthread_rwlock_clockrdlock not available";
1231#endif // __BIONIC__
1232}
1233
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001234static void pthread_rwlock_timedwrlock_timeout_helper(
1235 clockid_t clock, int (*lock_function)(pthread_rwlock_t* __rwlock, const timespec* __timeout)) {
1236 RwlockWakeupHelperArg wakeup_arg;
1237 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
1238 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
1239 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
1240 wakeup_arg.tid = 0;
1241 wakeup_arg.trylock_function = &pthread_rwlock_trywrlock;
1242 wakeup_arg.timed_lock_function = lock_function;
1243 wakeup_arg.clock = clock;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001244
1245 pthread_t thread;
1246 ASSERT_EQ(0, pthread_create(&thread, nullptr,
1247 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
1248 WaitUntilThreadSleep(wakeup_arg.tid);
1249 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
1250
1251 ASSERT_EQ(0, pthread_join(thread, nullptr));
1252 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
1253 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
1254 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
1255}
1256
1257TEST(pthread, pthread_rwlock_timedwrlock_timeout) {
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001258 pthread_rwlock_timedwrlock_timeout_helper(CLOCK_REALTIME, pthread_rwlock_timedwrlock);
1259}
Yabin Cuic9a659c2015-11-05 15:36:08 -08001260
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001261TEST(pthread, pthread_rwlock_timedwrlock_monotonic_np_timeout) {
1262#if defined(__BIONIC__)
1263 pthread_rwlock_timedwrlock_timeout_helper(CLOCK_MONOTONIC,
1264 pthread_rwlock_timedwrlock_monotonic_np);
1265#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001266 GTEST_SKIP() << "pthread_rwlock_timedwrlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001267#endif // __BIONIC__
Yabin Cuic9a659c2015-11-05 15:36:08 -08001268}
1269
Tom Cherry69010802019-05-07 20:33:05 -07001270TEST(pthread, pthread_rwlock_clockwrlock_monotonic_timeout) {
1271#if defined(__BIONIC__)
1272 pthread_rwlock_timedwrlock_timeout_helper(
1273 CLOCK_MONOTONIC, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) {
1274 return pthread_rwlock_clockwrlock(__rwlock, CLOCK_MONOTONIC, __timeout);
1275 });
1276#else // __BIONIC__
1277 GTEST_SKIP() << "pthread_rwlock_clockwrlock not available";
1278#endif // __BIONIC__
1279}
1280
1281TEST(pthread, pthread_rwlock_clockwrlock_realtime_timeout) {
1282#if defined(__BIONIC__)
1283 pthread_rwlock_timedwrlock_timeout_helper(
1284 CLOCK_REALTIME, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) {
1285 return pthread_rwlock_clockwrlock(__rwlock, CLOCK_REALTIME, __timeout);
1286 });
1287#else // __BIONIC__
1288 GTEST_SKIP() << "pthread_rwlock_clockwrlock not available";
1289#endif // __BIONIC__
1290}
1291
1292TEST(pthread, pthread_rwlock_clockwrlock_invalid) {
1293#if defined(__BIONIC__)
1294 pthread_rwlock_t lock = PTHREAD_RWLOCK_INITIALIZER;
1295 timespec ts;
1296 EXPECT_EQ(EINVAL, pthread_rwlock_clockwrlock(&lock, CLOCK_PROCESS_CPUTIME_ID, &ts));
1297#else // __BIONIC__
1298 GTEST_SKIP() << "pthread_rwlock_clockrwlock not available";
1299#endif // __BIONIC__
1300}
1301
Colin Cross4c5595c2021-08-16 15:51:59 -07001302#if !defined(ANDROID_HOST_MUSL)
Colin Cross7da20342021-07-28 11:18:11 -07001303// musl doesn't have pthread_rwlockattr_setkind_np
Yabin Cui76615da2015-03-17 14:22:09 -07001304class RwlockKindTestHelper {
1305 private:
1306 struct ThreadArg {
1307 RwlockKindTestHelper* helper;
1308 std::atomic<pid_t>& tid;
1309
1310 ThreadArg(RwlockKindTestHelper* helper, std::atomic<pid_t>& tid)
1311 : helper(helper), tid(tid) { }
1312 };
1313
1314 public:
1315 pthread_rwlock_t lock;
1316
1317 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -07001318 explicit RwlockKindTestHelper(int kind_type) {
Yabin Cui76615da2015-03-17 14:22:09 -07001319 InitRwlock(kind_type);
1320 }
1321
1322 ~RwlockKindTestHelper() {
1323 DestroyRwlock();
1324 }
1325
1326 void CreateWriterThread(pthread_t& thread, std::atomic<pid_t>& tid) {
1327 tid = 0;
1328 ThreadArg* arg = new ThreadArg(this, tid);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001329 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui76615da2015-03-17 14:22:09 -07001330 reinterpret_cast<void* (*)(void*)>(WriterThreadFn), arg));
1331 }
1332
1333 void CreateReaderThread(pthread_t& thread, std::atomic<pid_t>& tid) {
1334 tid = 0;
1335 ThreadArg* arg = new ThreadArg(this, tid);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001336 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui76615da2015-03-17 14:22:09 -07001337 reinterpret_cast<void* (*)(void*)>(ReaderThreadFn), arg));
1338 }
1339
1340 private:
1341 void InitRwlock(int kind_type) {
1342 pthread_rwlockattr_t attr;
1343 ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
1344 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_type));
1345 ASSERT_EQ(0, pthread_rwlock_init(&lock, &attr));
1346 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
1347 }
1348
1349 void DestroyRwlock() {
1350 ASSERT_EQ(0, pthread_rwlock_destroy(&lock));
1351 }
1352
1353 static void WriterThreadFn(ThreadArg* arg) {
1354 arg->tid = gettid();
1355
1356 RwlockKindTestHelper* helper = arg->helper;
1357 ASSERT_EQ(0, pthread_rwlock_wrlock(&helper->lock));
1358 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
1359 delete arg;
1360 }
1361
1362 static void ReaderThreadFn(ThreadArg* arg) {
1363 arg->tid = gettid();
1364
1365 RwlockKindTestHelper* helper = arg->helper;
1366 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper->lock));
1367 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
1368 delete arg;
1369 }
1370};
Colin Cross7da20342021-07-28 11:18:11 -07001371#endif
Yabin Cui76615da2015-03-17 14:22:09 -07001372
1373TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_READER_NP) {
Colin Cross4c5595c2021-08-16 15:51:59 -07001374#if !defined(ANDROID_HOST_MUSL)
Yabin Cui76615da2015-03-17 14:22:09 -07001375 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_READER_NP);
1376 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
1377
1378 pthread_t writer_thread;
1379 std::atomic<pid_t> writer_tid;
1380 helper.CreateWriterThread(writer_thread, writer_tid);
1381 WaitUntilThreadSleep(writer_tid);
1382
1383 pthread_t reader_thread;
1384 std::atomic<pid_t> reader_tid;
1385 helper.CreateReaderThread(reader_thread, reader_tid);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001386 ASSERT_EQ(0, pthread_join(reader_thread, nullptr));
Yabin Cui76615da2015-03-17 14:22:09 -07001387
1388 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
Yi Kong32bc0fc2018-08-02 17:31:13 -07001389 ASSERT_EQ(0, pthread_join(writer_thread, nullptr));
Colin Cross7da20342021-07-28 11:18:11 -07001390#else
1391 GTEST_SKIP() << "musl doesn't have pthread_rwlockattr_setkind_np";
1392#endif
Yabin Cui76615da2015-03-17 14:22:09 -07001393}
1394
1395TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP) {
Colin Cross4c5595c2021-08-16 15:51:59 -07001396#if !defined(ANDROID_HOST_MUSL)
Yabin Cui76615da2015-03-17 14:22:09 -07001397 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
1398 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
1399
1400 pthread_t writer_thread;
1401 std::atomic<pid_t> writer_tid;
1402 helper.CreateWriterThread(writer_thread, writer_tid);
1403 WaitUntilThreadSleep(writer_tid);
1404
1405 pthread_t reader_thread;
1406 std::atomic<pid_t> reader_tid;
1407 helper.CreateReaderThread(reader_thread, reader_tid);
1408 WaitUntilThreadSleep(reader_tid);
1409
1410 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
Yi Kong32bc0fc2018-08-02 17:31:13 -07001411 ASSERT_EQ(0, pthread_join(writer_thread, nullptr));
1412 ASSERT_EQ(0, pthread_join(reader_thread, nullptr));
Colin Cross7da20342021-07-28 11:18:11 -07001413#else
1414 GTEST_SKIP() << "musl doesn't have pthread_rwlockattr_setkind_np";
1415#endif
Yabin Cui76615da2015-03-17 14:22:09 -07001416}
1417
Elliott Hughes1728b232014-05-14 10:02:03 -07001418static int g_once_fn_call_count = 0;
Elliott Hughesc3f11402013-10-30 14:40:09 -07001419static void OnceFn() {
Elliott Hughes1728b232014-05-14 10:02:03 -07001420 ++g_once_fn_call_count;
Elliott Hughesc3f11402013-10-30 14:40:09 -07001421}
1422
1423TEST(pthread, pthread_once_smoke) {
1424 pthread_once_t once_control = PTHREAD_ONCE_INIT;
1425 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
1426 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
Elliott Hughes1728b232014-05-14 10:02:03 -07001427 ASSERT_EQ(1, g_once_fn_call_count);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001428}
1429
Elliott Hughes3694ec62014-05-14 11:46:08 -07001430static std::string pthread_once_1934122_result = "";
1431
1432static void Routine2() {
1433 pthread_once_1934122_result += "2";
1434}
1435
1436static void Routine1() {
1437 pthread_once_t once_control_2 = PTHREAD_ONCE_INIT;
1438 pthread_once_1934122_result += "1";
1439 pthread_once(&once_control_2, &Routine2);
1440}
1441
1442TEST(pthread, pthread_once_1934122) {
1443 // Very old versions of Android couldn't call pthread_once from a
1444 // pthread_once init routine. http://b/1934122.
1445 pthread_once_t once_control_1 = PTHREAD_ONCE_INIT;
1446 ASSERT_EQ(0, pthread_once(&once_control_1, &Routine1));
1447 ASSERT_EQ("12", pthread_once_1934122_result);
1448}
1449
Elliott Hughes1728b232014-05-14 10:02:03 -07001450static int g_atfork_prepare_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001451static void AtForkPrepare1() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 1; }
1452static void AtForkPrepare2() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -07001453static int g_atfork_parent_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001454static void AtForkParent1() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 1; }
1455static void AtForkParent2() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -07001456static int g_atfork_child_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001457static void AtForkChild1() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 1; }
1458static void AtForkChild2() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 2; }
Elliott Hughesc3f11402013-10-30 14:40:09 -07001459
Elliott Hughes2411fff2024-02-24 23:55:58 +00001460TEST(pthread, pthread_atfork_smoke_fork) {
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001461 ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1));
1462 ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2));
Elliott Hughesc3f11402013-10-30 14:40:09 -07001463
Elliott Hughes2411fff2024-02-24 23:55:58 +00001464 g_atfork_prepare_calls = g_atfork_parent_calls = g_atfork_child_calls = 0;
Elliott Hughes33697a02016-01-26 13:04:57 -08001465 pid_t pid = fork();
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001466 ASSERT_NE(-1, pid) << strerror(errno);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001467
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001468 // Child and parent calls are made in the order they were registered.
1469 if (pid == 0) {
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001470 ASSERT_EQ(12, g_atfork_child_calls);
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001471 _exit(0);
1472 }
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001473 ASSERT_EQ(12, g_atfork_parent_calls);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001474
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001475 // Prepare calls are made in the reverse order.
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001476 ASSERT_EQ(21, g_atfork_prepare_calls);
Elliott Hughes33697a02016-01-26 13:04:57 -08001477 AssertChildExited(pid, 0);
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001478}
1479
Elliott Hughes2411fff2024-02-24 23:55:58 +00001480TEST(pthread, pthread_atfork_smoke_vfork) {
1481 ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1));
1482 ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2));
1483
1484 g_atfork_prepare_calls = g_atfork_parent_calls = g_atfork_child_calls = 0;
1485 pid_t pid = vfork();
1486 ASSERT_NE(-1, pid) << strerror(errno);
1487
1488 // atfork handlers are not called.
1489 if (pid == 0) {
1490 ASSERT_EQ(0, g_atfork_child_calls);
1491 _exit(0);
1492 }
1493 ASSERT_EQ(0, g_atfork_parent_calls);
1494 ASSERT_EQ(0, g_atfork_prepare_calls);
1495 AssertChildExited(pid, 0);
1496}
1497
1498TEST(pthread, pthread_atfork_smoke__Fork) {
1499#if defined(__BIONIC__)
1500 ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1));
1501 ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2));
1502
1503 g_atfork_prepare_calls = g_atfork_parent_calls = g_atfork_child_calls = 0;
1504 pid_t pid = _Fork();
1505 ASSERT_NE(-1, pid) << strerror(errno);
1506
1507 // atfork handlers are not called.
1508 if (pid == 0) {
1509 ASSERT_EQ(0, g_atfork_child_calls);
1510 _exit(0);
1511 }
1512 ASSERT_EQ(0, g_atfork_parent_calls);
1513 ASSERT_EQ(0, g_atfork_prepare_calls);
1514 AssertChildExited(pid, 0);
1515#endif
1516}
1517
Elliott Hughesc3f11402013-10-30 14:40:09 -07001518TEST(pthread, pthread_attr_getscope) {
1519 pthread_attr_t attr;
1520 ASSERT_EQ(0, pthread_attr_init(&attr));
1521
1522 int scope;
1523 ASSERT_EQ(0, pthread_attr_getscope(&attr, &scope));
1524 ASSERT_EQ(PTHREAD_SCOPE_SYSTEM, scope);
1525}
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001526
1527TEST(pthread, pthread_condattr_init) {
1528 pthread_condattr_t attr;
1529 pthread_condattr_init(&attr);
1530
1531 clockid_t clock;
1532 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1533 ASSERT_EQ(CLOCK_REALTIME, clock);
1534
1535 int pshared;
1536 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1537 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
1538}
1539
1540TEST(pthread, pthread_condattr_setclock) {
1541 pthread_condattr_t attr;
1542 pthread_condattr_init(&attr);
1543
1544 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_REALTIME));
1545 clockid_t clock;
1546 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1547 ASSERT_EQ(CLOCK_REALTIME, clock);
1548
1549 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1550 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1551 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1552
1553 ASSERT_EQ(EINVAL, pthread_condattr_setclock(&attr, CLOCK_PROCESS_CPUTIME_ID));
1554}
1555
1556TEST(pthread, pthread_cond_broadcast__preserves_condattr_flags) {
Yabin Cui32651b82015-03-13 20:30:00 -07001557#if defined(__BIONIC__)
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001558 pthread_condattr_t attr;
1559 pthread_condattr_init(&attr);
1560
1561 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1562 ASSERT_EQ(0, pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
1563
1564 pthread_cond_t cond_var;
1565 ASSERT_EQ(0, pthread_cond_init(&cond_var, &attr));
1566
1567 ASSERT_EQ(0, pthread_cond_signal(&cond_var));
1568 ASSERT_EQ(0, pthread_cond_broadcast(&cond_var));
1569
Yabin Cui32651b82015-03-13 20:30:00 -07001570 attr = static_cast<pthread_condattr_t>(*reinterpret_cast<uint32_t*>(cond_var.__private));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001571 clockid_t clock;
1572 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1573 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1574 int pshared;
1575 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1576 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
Yabin Cui32651b82015-03-13 20:30:00 -07001577#else // !defined(__BIONIC__)
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001578 GTEST_SKIP() << "bionic-only test";
Yabin Cui32651b82015-03-13 20:30:00 -07001579#endif // !defined(__BIONIC__)
1580}
1581
1582class pthread_CondWakeupTest : public ::testing::Test {
1583 protected:
1584 pthread_mutex_t mutex;
1585 pthread_cond_t cond;
1586
1587 enum Progress {
1588 INITIALIZED,
1589 WAITING,
1590 SIGNALED,
1591 FINISHED,
1592 };
1593 std::atomic<Progress> progress;
1594 pthread_t thread;
Peter Collingbournec5b81842021-12-02 12:38:46 -08001595 timespec ts;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001596 std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function;
Yabin Cui32651b82015-03-13 20:30:00 -07001597
1598 protected:
Yabin Cuic9a659c2015-11-05 15:36:08 -08001599 void SetUp() override {
1600 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1601 }
1602
1603 void InitCond(clockid_t clock=CLOCK_REALTIME) {
1604 pthread_condattr_t attr;
1605 ASSERT_EQ(0, pthread_condattr_init(&attr));
1606 ASSERT_EQ(0, pthread_condattr_setclock(&attr, clock));
1607 ASSERT_EQ(0, pthread_cond_init(&cond, &attr));
1608 ASSERT_EQ(0, pthread_condattr_destroy(&attr));
1609 }
1610
Tom Cherry69010802019-05-07 20:33:05 -07001611 void StartWaitingThread(
1612 std::function<int(pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function) {
Yabin Cui32651b82015-03-13 20:30:00 -07001613 progress = INITIALIZED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001614 this->wait_function = wait_function;
Tom Cherry69010802019-05-07 20:33:05 -07001615 ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(WaitThreadFn),
1616 this));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001617 while (progress != WAITING) {
Yabin Cui32651b82015-03-13 20:30:00 -07001618 usleep(5000);
1619 }
1620 usleep(5000);
1621 }
1622
Tom Cherry69010802019-05-07 20:33:05 -07001623 void RunTimedTest(
1624 clockid_t clock,
1625 std::function<int(pthread_cond_t* cond, pthread_mutex_t* mutex, const timespec* timeout)>
1626 wait_function) {
Tom Cherry69010802019-05-07 20:33:05 -07001627 ASSERT_EQ(0, clock_gettime(clock, &ts));
1628 ts.tv_sec += 1;
1629
Peter Collingbournec5b81842021-12-02 12:38:46 -08001630 StartWaitingThread([&wait_function, this](pthread_cond_t* cond, pthread_mutex_t* mutex) {
Tom Cherry69010802019-05-07 20:33:05 -07001631 return wait_function(cond, mutex, &ts);
1632 });
1633
1634 progress = SIGNALED;
1635 ASSERT_EQ(0, pthread_cond_signal(&cond));
1636 }
1637
1638 void RunTimedTest(clockid_t clock, std::function<int(pthread_cond_t* cond, pthread_mutex_t* mutex,
1639 clockid_t clock, const timespec* timeout)>
1640 wait_function) {
1641 RunTimedTest(clock, [clock, &wait_function](pthread_cond_t* cond, pthread_mutex_t* mutex,
1642 const timespec* timeout) {
1643 return wait_function(cond, mutex, clock, timeout);
1644 });
1645 }
1646
Yabin Cuic9a659c2015-11-05 15:36:08 -08001647 void TearDown() override {
1648 ASSERT_EQ(0, pthread_join(thread, nullptr));
1649 ASSERT_EQ(FINISHED, progress);
1650 ASSERT_EQ(0, pthread_cond_destroy(&cond));
1651 ASSERT_EQ(0, pthread_mutex_destroy(&mutex));
1652 }
1653
Yabin Cui32651b82015-03-13 20:30:00 -07001654 private:
1655 static void WaitThreadFn(pthread_CondWakeupTest* test) {
1656 ASSERT_EQ(0, pthread_mutex_lock(&test->mutex));
1657 test->progress = WAITING;
1658 while (test->progress == WAITING) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001659 ASSERT_EQ(0, test->wait_function(&test->cond, &test->mutex));
Yabin Cui32651b82015-03-13 20:30:00 -07001660 }
1661 ASSERT_EQ(SIGNALED, test->progress);
1662 test->progress = FINISHED;
1663 ASSERT_EQ(0, pthread_mutex_unlock(&test->mutex));
1664 }
1665};
1666
Yabin Cuic9a659c2015-11-05 15:36:08 -08001667TEST_F(pthread_CondWakeupTest, signal_wait) {
1668 InitCond();
1669 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1670 return pthread_cond_wait(cond, mutex);
1671 });
Yabin Cui32651b82015-03-13 20:30:00 -07001672 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001673 ASSERT_EQ(0, pthread_cond_signal(&cond));
Yabin Cui32651b82015-03-13 20:30:00 -07001674}
1675
Yabin Cuic9a659c2015-11-05 15:36:08 -08001676TEST_F(pthread_CondWakeupTest, broadcast_wait) {
1677 InitCond();
1678 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1679 return pthread_cond_wait(cond, mutex);
1680 });
Yabin Cui32651b82015-03-13 20:30:00 -07001681 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001682 ASSERT_EQ(0, pthread_cond_broadcast(&cond));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001683}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001684
Yabin Cuic9a659c2015-11-05 15:36:08 -08001685TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_REALTIME) {
1686 InitCond(CLOCK_REALTIME);
Tom Cherry69010802019-05-07 20:33:05 -07001687 RunTimedTest(CLOCK_REALTIME, pthread_cond_timedwait);
Yabin Cuic9a659c2015-11-05 15:36:08 -08001688}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001689
Yabin Cuic9a659c2015-11-05 15:36:08 -08001690TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC) {
1691 InitCond(CLOCK_MONOTONIC);
Tom Cherry69010802019-05-07 20:33:05 -07001692 RunTimedTest(CLOCK_MONOTONIC, pthread_cond_timedwait);
Yabin Cuic9a659c2015-11-05 15:36:08 -08001693}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001694
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001695TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC_np) {
1696#if defined(__BIONIC__)
1697 InitCond(CLOCK_REALTIME);
Tom Cherry69010802019-05-07 20:33:05 -07001698 RunTimedTest(CLOCK_MONOTONIC, pthread_cond_timedwait_monotonic_np);
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001699#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001700 GTEST_SKIP() << "pthread_cond_timedwait_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001701#endif // __BIONIC__
1702}
1703
Tom Cherry69010802019-05-07 20:33:05 -07001704TEST_F(pthread_CondWakeupTest, signal_clockwait_monotonic_monotonic) {
1705#if defined(__BIONIC__)
1706 InitCond(CLOCK_MONOTONIC);
1707 RunTimedTest(CLOCK_MONOTONIC, pthread_cond_clockwait);
1708#else // __BIONIC__
1709 GTEST_SKIP() << "pthread_cond_clockwait not available";
1710#endif // __BIONIC__
1711}
1712
1713TEST_F(pthread_CondWakeupTest, signal_clockwait_monotonic_realtime) {
1714#if defined(__BIONIC__)
1715 InitCond(CLOCK_MONOTONIC);
1716 RunTimedTest(CLOCK_REALTIME, pthread_cond_clockwait);
1717#else // __BIONIC__
1718 GTEST_SKIP() << "pthread_cond_clockwait not available";
1719#endif // __BIONIC__
1720}
1721
1722TEST_F(pthread_CondWakeupTest, signal_clockwait_realtime_monotonic) {
1723#if defined(__BIONIC__)
1724 InitCond(CLOCK_REALTIME);
1725 RunTimedTest(CLOCK_MONOTONIC, pthread_cond_clockwait);
1726#else // __BIONIC__
1727 GTEST_SKIP() << "pthread_cond_clockwait not available";
1728#endif // __BIONIC__
1729}
1730
1731TEST_F(pthread_CondWakeupTest, signal_clockwait_realtime_realtime) {
1732#if defined(__BIONIC__)
1733 InitCond(CLOCK_REALTIME);
1734 RunTimedTest(CLOCK_REALTIME, pthread_cond_clockwait);
1735#else // __BIONIC__
1736 GTEST_SKIP() << "pthread_cond_clockwait not available";
1737#endif // __BIONIC__
1738}
1739
Tom Cherry800c1a92019-07-17 10:45:18 -07001740static void pthread_cond_timedwait_timeout_helper(bool init_monotonic, clockid_t clock,
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001741 int (*wait_function)(pthread_cond_t* __cond,
1742 pthread_mutex_t* __mutex,
1743 const timespec* __timeout)) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001744 pthread_mutex_t mutex;
1745 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1746 pthread_cond_t cond;
Tom Cherry800c1a92019-07-17 10:45:18 -07001747
1748 if (init_monotonic) {
1749 pthread_condattr_t attr;
1750 pthread_condattr_init(&attr);
1751
1752 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1753 clockid_t clock;
1754 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1755 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1756
1757 ASSERT_EQ(0, pthread_cond_init(&cond, &attr));
1758 } else {
1759 ASSERT_EQ(0, pthread_cond_init(&cond, nullptr));
1760 }
Yabin Cuic9a659c2015-11-05 15:36:08 -08001761 ASSERT_EQ(0, pthread_mutex_lock(&mutex));
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001762
Yabin Cuic9a659c2015-11-05 15:36:08 -08001763 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001764 ASSERT_EQ(0, clock_gettime(clock, &ts));
1765 ASSERT_EQ(ETIMEDOUT, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001766 ts.tv_nsec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001767 ASSERT_EQ(EINVAL, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001768 ts.tv_nsec = NS_PER_S;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001769 ASSERT_EQ(EINVAL, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001770 ts.tv_nsec = NS_PER_S - 1;
1771 ts.tv_sec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001772 ASSERT_EQ(ETIMEDOUT, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001773 ASSERT_EQ(0, pthread_mutex_unlock(&mutex));
Elliott Hughes0e714a52014-03-03 16:42:47 -08001774}
Elliott Hughes57b7a612014-08-25 17:26:50 -07001775
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001776TEST(pthread, pthread_cond_timedwait_timeout) {
Tom Cherry800c1a92019-07-17 10:45:18 -07001777 pthread_cond_timedwait_timeout_helper(false, CLOCK_REALTIME, pthread_cond_timedwait);
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001778}
1779
1780TEST(pthread, pthread_cond_timedwait_monotonic_np_timeout) {
1781#if defined(__BIONIC__)
Tom Cherry800c1a92019-07-17 10:45:18 -07001782 pthread_cond_timedwait_timeout_helper(false, CLOCK_MONOTONIC, pthread_cond_timedwait_monotonic_np);
1783 pthread_cond_timedwait_timeout_helper(true, CLOCK_MONOTONIC, pthread_cond_timedwait_monotonic_np);
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001784#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001785 GTEST_SKIP() << "pthread_cond_timedwait_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001786#endif // __BIONIC__
1787}
1788
Tom Cherry69010802019-05-07 20:33:05 -07001789TEST(pthread, pthread_cond_clockwait_timeout) {
1790#if defined(__BIONIC__)
1791 pthread_cond_timedwait_timeout_helper(
Tom Cherry800c1a92019-07-17 10:45:18 -07001792 false, CLOCK_MONOTONIC,
Tom Cherry69010802019-05-07 20:33:05 -07001793 [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) {
1794 return pthread_cond_clockwait(__cond, __mutex, CLOCK_MONOTONIC, __timeout);
1795 });
1796 pthread_cond_timedwait_timeout_helper(
Tom Cherry800c1a92019-07-17 10:45:18 -07001797 true, CLOCK_MONOTONIC,
1798 [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) {
1799 return pthread_cond_clockwait(__cond, __mutex, CLOCK_MONOTONIC, __timeout);
1800 });
1801 pthread_cond_timedwait_timeout_helper(
1802 false, CLOCK_REALTIME,
1803 [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) {
1804 return pthread_cond_clockwait(__cond, __mutex, CLOCK_REALTIME, __timeout);
1805 });
1806 pthread_cond_timedwait_timeout_helper(
1807 true, CLOCK_REALTIME,
Tom Cherry69010802019-05-07 20:33:05 -07001808 [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) {
1809 return pthread_cond_clockwait(__cond, __mutex, CLOCK_REALTIME, __timeout);
1810 });
1811#else // __BIONIC__
1812 GTEST_SKIP() << "pthread_cond_clockwait not available";
1813#endif // __BIONIC__
1814}
1815
1816TEST(pthread, pthread_cond_clockwait_invalid) {
1817#if defined(__BIONIC__)
1818 pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
1819 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
1820 timespec ts;
1821 EXPECT_EQ(EINVAL, pthread_cond_clockwait(&cond, &mutex, CLOCK_PROCESS_CPUTIME_ID, &ts));
1822
1823#else // __BIONIC__
1824 GTEST_SKIP() << "pthread_cond_clockwait not available";
1825#endif // __BIONIC__
1826}
1827
Elliott Hughes57b7a612014-08-25 17:26:50 -07001828TEST(pthread, pthread_attr_getstack__main_thread) {
1829 // This test is only meaningful for the main thread, so make sure we're running on it!
1830 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1831
1832 // Get the main thread's attributes.
1833 pthread_attr_t attributes;
1834 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1835
1836 // Check that we correctly report that the main thread has no guard page.
1837 size_t guard_size;
1838 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
1839 ASSERT_EQ(0U, guard_size); // The main thread has no guard page.
1840
1841 // Get the stack base and the stack size (both ways).
1842 void* stack_base;
1843 size_t stack_size;
1844 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1845 size_t stack_size2;
1846 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1847
1848 // The two methods of asking for the stack size should agree.
1849 EXPECT_EQ(stack_size, stack_size2);
1850
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001851#if defined(__BIONIC__)
dimitry6dfa5b52018-01-30 13:24:28 +01001852 // Find stack in /proc/self/maps using a pointer to the stack.
1853 //
1854 // We do not use "[stack]" label because in native-bridge environment it is not
1855 // guaranteed to point to the right stack. A native bridge implementation may
1856 // keep separate stack for the guest code.
Yi Kong32bc0fc2018-08-02 17:31:13 -07001857 void* maps_stack_hi = nullptr;
Elliott Hughes15dfd632015-09-22 16:40:14 -07001858 std::vector<map_record> maps;
1859 ASSERT_TRUE(Maps::parse_maps(&maps));
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08001860 uintptr_t stack_address = reinterpret_cast<uintptr_t>(untag_address(&maps_stack_hi));
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07001861 for (const auto& map : maps) {
dimitry6dfa5b52018-01-30 13:24:28 +01001862 if (map.addr_start <= stack_address && map.addr_end > stack_address){
Elliott Hughes15dfd632015-09-22 16:40:14 -07001863 maps_stack_hi = reinterpret_cast<void*>(map.addr_end);
Elliott Hughes57b7a612014-08-25 17:26:50 -07001864 break;
1865 }
1866 }
Elliott Hughes57b7a612014-08-25 17:26:50 -07001867
dimitry6dfa5b52018-01-30 13:24:28 +01001868 // The high address of the /proc/self/maps stack region should equal stack_base + stack_size.
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001869 // Remember that the stack grows down (and is mapped in on demand), so the low address of the
1870 // region isn't very interesting.
1871 EXPECT_EQ(maps_stack_hi, reinterpret_cast<uint8_t*>(stack_base) + stack_size);
1872
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001873 // The stack size should correspond to RLIMIT_STACK.
Elliott Hughes57b7a612014-08-25 17:26:50 -07001874 rlimit rl;
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001875 ASSERT_EQ(0, getrlimit(RLIMIT_STACK, &rl));
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001876 uint64_t original_rlim_cur = rl.rlim_cur;
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001877 if (rl.rlim_cur == RLIM_INFINITY) {
1878 rl.rlim_cur = 8 * 1024 * 1024; // Bionic reports unlimited stacks as 8MiB.
1879 }
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001880 EXPECT_EQ(rl.rlim_cur, stack_size);
1881
Tom Cherryb8ab6182017-04-05 16:20:29 -07001882 auto guard = android::base::make_scope_guard([&rl, original_rlim_cur]() {
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001883 rl.rlim_cur = original_rlim_cur;
1884 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1885 });
1886
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001887 //
1888 // What if RLIMIT_STACK is smaller than the stack's current extent?
1889 //
Elliott Hughes57b7a612014-08-25 17:26:50 -07001890 rl.rlim_cur = rl.rlim_max = 1024; // 1KiB. We know the stack must be at least a page already.
1891 rl.rlim_max = RLIM_INFINITY;
1892 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1893
1894 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1895 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1896 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1897
1898 EXPECT_EQ(stack_size, stack_size2);
1899 ASSERT_EQ(1024U, stack_size);
1900
1901 //
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001902 // What if RLIMIT_STACK isn't a whole number of pages?
Elliott Hughes57b7a612014-08-25 17:26:50 -07001903 //
1904 rl.rlim_cur = rl.rlim_max = 6666; // Not a whole number of pages.
1905 rl.rlim_max = RLIM_INFINITY;
1906 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1907
1908 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1909 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1910 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1911
1912 EXPECT_EQ(stack_size, stack_size2);
1913 ASSERT_EQ(6666U, stack_size);
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001914#endif
Elliott Hughes57b7a612014-08-25 17:26:50 -07001915}
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001916
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001917struct GetStackSignalHandlerArg {
1918 volatile bool done;
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001919 void* signal_stack_base;
1920 size_t signal_stack_size;
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001921 void* main_stack_base;
1922 size_t main_stack_size;
1923};
1924
1925static GetStackSignalHandlerArg getstack_signal_handler_arg;
1926
1927static void getstack_signal_handler(int sig) {
1928 ASSERT_EQ(SIGUSR1, sig);
1929 // Use sleep() to make current thread be switched out by the kernel to provoke the error.
1930 sleep(1);
1931 pthread_attr_t attr;
1932 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1933 void* stack_base;
1934 size_t stack_size;
1935 ASSERT_EQ(0, pthread_attr_getstack(&attr, &stack_base, &stack_size));
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001936
1937 // Verify if the stack used by the signal handler is the alternate stack just registered.
1938 ASSERT_LE(getstack_signal_handler_arg.signal_stack_base, &attr);
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08001939 ASSERT_LT(static_cast<void*>(untag_address(&attr)),
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001940 static_cast<char*>(getstack_signal_handler_arg.signal_stack_base) +
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08001941 getstack_signal_handler_arg.signal_stack_size);
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001942
1943 // Verify if the main thread's stack got in the signal handler is correct.
1944 ASSERT_EQ(getstack_signal_handler_arg.main_stack_base, stack_base);
1945 ASSERT_LE(getstack_signal_handler_arg.main_stack_size, stack_size);
1946
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001947 getstack_signal_handler_arg.done = true;
1948}
1949
1950// The previous code obtained the main thread's stack by reading the entry in
1951// /proc/self/task/<pid>/maps that was labeled [stack]. Unfortunately, on x86/x86_64, the kernel
1952// relies on sp0 in task state segment(tss) to label the stack map with [stack]. If the kernel
1953// switches a process while the main thread is in an alternate stack, then the kernel will label
1954// the wrong map with [stack]. This test verifies that when the above situation happens, the main
1955// thread's stack is found correctly.
1956TEST(pthread, pthread_attr_getstack_in_signal_handler) {
Yabin Cui61e4d462016-03-07 17:44:58 -08001957 // This test is only meaningful for the main thread, so make sure we're running on it!
1958 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1959
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001960 const size_t sig_stack_size = 16 * 1024;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001961 void* sig_stack = mmap(nullptr, sig_stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS,
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001962 -1, 0);
1963 ASSERT_NE(MAP_FAILED, sig_stack);
1964 stack_t ss;
1965 ss.ss_sp = sig_stack;
1966 ss.ss_size = sig_stack_size;
1967 ss.ss_flags = 0;
1968 stack_t oss;
1969 ASSERT_EQ(0, sigaltstack(&ss, &oss));
1970
Yabin Cui61e4d462016-03-07 17:44:58 -08001971 pthread_attr_t attr;
1972 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1973 void* main_stack_base;
1974 size_t main_stack_size;
1975 ASSERT_EQ(0, pthread_attr_getstack(&attr, &main_stack_base, &main_stack_size));
1976
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001977 ScopedSignalHandler handler(SIGUSR1, getstack_signal_handler, SA_ONSTACK);
1978 getstack_signal_handler_arg.done = false;
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001979 getstack_signal_handler_arg.signal_stack_base = sig_stack;
1980 getstack_signal_handler_arg.signal_stack_size = sig_stack_size;
1981 getstack_signal_handler_arg.main_stack_base = main_stack_base;
1982 getstack_signal_handler_arg.main_stack_size = main_stack_size;
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001983 kill(getpid(), SIGUSR1);
1984 ASSERT_EQ(true, getstack_signal_handler_arg.done);
1985
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001986 ASSERT_EQ(0, sigaltstack(&oss, nullptr));
1987 ASSERT_EQ(0, munmap(sig_stack, sig_stack_size));
1988}
1989
Yabin Cui917d3902015-01-08 12:32:42 -08001990static void pthread_attr_getstack_18908062_helper(void*) {
1991 char local_variable;
1992 pthread_attr_t attributes;
1993 pthread_getattr_np(pthread_self(), &attributes);
1994 void* stack_base;
1995 size_t stack_size;
1996 pthread_attr_getstack(&attributes, &stack_base, &stack_size);
1997
1998 // Test whether &local_variable is in [stack_base, stack_base + stack_size).
1999 ASSERT_LE(reinterpret_cast<char*>(stack_base), &local_variable);
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08002000 ASSERT_LT(untag_address(&local_variable), reinterpret_cast<char*>(stack_base) + stack_size);
Yabin Cui917d3902015-01-08 12:32:42 -08002001}
2002
2003// Check whether something on stack is in the range of
2004// [stack_base, stack_base + stack_size). see b/18908062.
2005TEST(pthread, pthread_attr_getstack_18908062) {
2006 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002007 ASSERT_EQ(0, pthread_create(&t, nullptr,
Yabin Cui917d3902015-01-08 12:32:42 -08002008 reinterpret_cast<void* (*)(void*)>(pthread_attr_getstack_18908062_helper),
Yi Kong32bc0fc2018-08-02 17:31:13 -07002009 nullptr));
2010 ASSERT_EQ(0, pthread_join(t, nullptr));
Yabin Cui917d3902015-01-08 12:32:42 -08002011}
2012
Elliott Hughes8fb639c2014-09-12 14:43:07 -07002013#if defined(__BIONIC__)
Elliott Hughesf2083612015-11-11 13:32:28 -08002014static pthread_mutex_t pthread_gettid_np_mutex = PTHREAD_MUTEX_INITIALIZER;
2015
Elliott Hughes8fb639c2014-09-12 14:43:07 -07002016static void* pthread_gettid_np_helper(void* arg) {
2017 *reinterpret_cast<pid_t*>(arg) = gettid();
Elliott Hughesf2083612015-11-11 13:32:28 -08002018
2019 // Wait for our parent to call pthread_gettid_np on us before exiting.
2020 pthread_mutex_lock(&pthread_gettid_np_mutex);
2021 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Yi Kong32bc0fc2018-08-02 17:31:13 -07002022 return nullptr;
Elliott Hughes8fb639c2014-09-12 14:43:07 -07002023}
2024#endif
2025
2026TEST(pthread, pthread_gettid_np) {
2027#if defined(__BIONIC__)
2028 ASSERT_EQ(gettid(), pthread_gettid_np(pthread_self()));
2029
Elliott Hughesf2083612015-11-11 13:32:28 -08002030 // Ensure the other thread doesn't exit until after we've called
2031 // pthread_gettid_np on it.
2032 pthread_mutex_lock(&pthread_gettid_np_mutex);
2033
Elliott Hughes8fb639c2014-09-12 14:43:07 -07002034 pid_t t_gettid_result;
2035 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002036 pthread_create(&t, nullptr, pthread_gettid_np_helper, &t_gettid_result);
Elliott Hughes8fb639c2014-09-12 14:43:07 -07002037
2038 pid_t t_pthread_gettid_np_result = pthread_gettid_np(t);
2039
Elliott Hughesf2083612015-11-11 13:32:28 -08002040 // Release the other thread and wait for it to exit.
2041 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Yi Kong32bc0fc2018-08-02 17:31:13 -07002042 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes8fb639c2014-09-12 14:43:07 -07002043
2044 ASSERT_EQ(t_gettid_result, t_pthread_gettid_np_result);
2045#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002046 GTEST_SKIP() << "pthread_gettid_np not available";
Elliott Hughes8fb639c2014-09-12 14:43:07 -07002047#endif
2048}
Elliott Hughes34c987a2014-09-22 16:01:26 -07002049
2050static size_t cleanup_counter = 0;
2051
Derek Xue41996952014-09-25 11:05:32 +01002052static void AbortCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07002053 abort();
2054}
2055
Derek Xue41996952014-09-25 11:05:32 +01002056static void CountCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07002057 ++cleanup_counter;
2058}
2059
Derek Xue41996952014-09-25 11:05:32 +01002060static void PthreadCleanupTester() {
Yi Kong32bc0fc2018-08-02 17:31:13 -07002061 pthread_cleanup_push(CountCleanupRoutine, nullptr);
2062 pthread_cleanup_push(CountCleanupRoutine, nullptr);
2063 pthread_cleanup_push(AbortCleanupRoutine, nullptr);
Elliott Hughes34c987a2014-09-22 16:01:26 -07002064
2065 pthread_cleanup_pop(0); // Pop the abort without executing it.
2066 pthread_cleanup_pop(1); // Pop one count while executing it.
2067 ASSERT_EQ(1U, cleanup_counter);
2068 // Exit while the other count is still on the cleanup stack.
Yi Kong32bc0fc2018-08-02 17:31:13 -07002069 pthread_exit(nullptr);
Elliott Hughes34c987a2014-09-22 16:01:26 -07002070
2071 // Calls to pthread_cleanup_pop/pthread_cleanup_push must always be balanced.
2072 pthread_cleanup_pop(0);
2073}
2074
Derek Xue41996952014-09-25 11:05:32 +01002075static void* PthreadCleanupStartRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07002076 PthreadCleanupTester();
Yi Kong32bc0fc2018-08-02 17:31:13 -07002077 return nullptr;
Elliott Hughes34c987a2014-09-22 16:01:26 -07002078}
2079
2080TEST(pthread, pthread_cleanup_push__pthread_cleanup_pop) {
2081 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002082 ASSERT_EQ(0, pthread_create(&t, nullptr, PthreadCleanupStartRoutine, nullptr));
2083 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes34c987a2014-09-22 16:01:26 -07002084 ASSERT_EQ(2U, cleanup_counter);
2085}
Derek Xue41996952014-09-25 11:05:32 +01002086
2087TEST(pthread, PTHREAD_MUTEX_DEFAULT_is_PTHREAD_MUTEX_NORMAL) {
2088 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_DEFAULT);
2089}
2090
2091TEST(pthread, pthread_mutexattr_gettype) {
2092 pthread_mutexattr_t attr;
2093 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
2094
2095 int attr_type;
2096
2097 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL));
2098 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
2099 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, attr_type);
2100
2101 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK));
2102 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
2103 ASSERT_EQ(PTHREAD_MUTEX_ERRORCHECK, attr_type);
2104
2105 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE));
2106 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
2107 ASSERT_EQ(PTHREAD_MUTEX_RECURSIVE, attr_type);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002108
2109 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
2110}
2111
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002112TEST(pthread, pthread_mutexattr_protocol) {
2113 pthread_mutexattr_t attr;
2114 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
2115
2116 int protocol;
2117 ASSERT_EQ(0, pthread_mutexattr_getprotocol(&attr, &protocol));
2118 ASSERT_EQ(PTHREAD_PRIO_NONE, protocol);
2119 for (size_t repeat = 0; repeat < 2; ++repeat) {
2120 for (int set_protocol : {PTHREAD_PRIO_NONE, PTHREAD_PRIO_INHERIT}) {
2121 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, set_protocol));
2122 ASSERT_EQ(0, pthread_mutexattr_getprotocol(&attr, &protocol));
2123 ASSERT_EQ(protocol, set_protocol);
2124 }
2125 }
2126}
2127
Yabin Cui17393b02015-03-21 15:08:25 -07002128struct PthreadMutex {
2129 pthread_mutex_t lock;
2130
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002131 explicit PthreadMutex(int mutex_type, int protocol = PTHREAD_PRIO_NONE) {
2132 init(mutex_type, protocol);
Yabin Cui17393b02015-03-21 15:08:25 -07002133 }
2134
2135 ~PthreadMutex() {
2136 destroy();
2137 }
2138
2139 private:
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002140 void init(int mutex_type, int protocol) {
Yabin Cui17393b02015-03-21 15:08:25 -07002141 pthread_mutexattr_t attr;
2142 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
2143 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, mutex_type));
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002144 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, protocol));
Yabin Cui17393b02015-03-21 15:08:25 -07002145 ASSERT_EQ(0, pthread_mutex_init(&lock, &attr));
2146 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
2147 }
2148
2149 void destroy() {
2150 ASSERT_EQ(0, pthread_mutex_destroy(&lock));
2151 }
2152
2153 DISALLOW_COPY_AND_ASSIGN(PthreadMutex);
2154};
Derek Xue41996952014-09-25 11:05:32 +01002155
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002156static int UnlockFromAnotherThread(pthread_mutex_t* mutex) {
2157 pthread_t thread;
2158 pthread_create(&thread, nullptr, [](void* mutex_voidp) -> void* {
2159 pthread_mutex_t* mutex = static_cast<pthread_mutex_t*>(mutex_voidp);
2160 intptr_t result = pthread_mutex_unlock(mutex);
2161 return reinterpret_cast<void*>(result);
2162 }, mutex);
2163 void* result;
2164 EXPECT_EQ(0, pthread_join(thread, &result));
2165 return reinterpret_cast<intptr_t>(result);
2166};
2167
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002168static void TestPthreadMutexLockNormal(int protocol) {
2169 PthreadMutex m(PTHREAD_MUTEX_NORMAL, protocol);
Derek Xue41996952014-09-25 11:05:32 +01002170
Yabin Cui17393b02015-03-21 15:08:25 -07002171 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002172 if (protocol == PTHREAD_PRIO_INHERIT) {
2173 ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock));
2174 }
Yabin Cui17393b02015-03-21 15:08:25 -07002175 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08002176 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
2177 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
2178 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01002179}
2180
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002181static void TestPthreadMutexLockErrorCheck(int protocol) {
2182 PthreadMutex m(PTHREAD_MUTEX_ERRORCHECK, protocol);
Derek Xue41996952014-09-25 11:05:32 +01002183
Yabin Cui17393b02015-03-21 15:08:25 -07002184 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002185 ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07002186 ASSERT_EQ(EDEADLK, pthread_mutex_lock(&m.lock));
2187 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2188 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002189 if (protocol == PTHREAD_PRIO_NONE) {
2190 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
2191 } else {
2192 ASSERT_EQ(EDEADLK, pthread_mutex_trylock(&m.lock));
2193 }
Yabin Cui17393b02015-03-21 15:08:25 -07002194 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2195 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01002196}
2197
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002198static void TestPthreadMutexLockRecursive(int protocol) {
2199 PthreadMutex m(PTHREAD_MUTEX_RECURSIVE, protocol);
Derek Xue41996952014-09-25 11:05:32 +01002200
Yabin Cui17393b02015-03-21 15:08:25 -07002201 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002202 ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07002203 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002204 ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07002205 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2206 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2207 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08002208 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
2209 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07002210 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2211 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
2212}
2213
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002214TEST(pthread, pthread_mutex_lock_NORMAL) {
2215 TestPthreadMutexLockNormal(PTHREAD_PRIO_NONE);
2216}
2217
2218TEST(pthread, pthread_mutex_lock_ERRORCHECK) {
2219 TestPthreadMutexLockErrorCheck(PTHREAD_PRIO_NONE);
2220}
2221
2222TEST(pthread, pthread_mutex_lock_RECURSIVE) {
2223 TestPthreadMutexLockRecursive(PTHREAD_PRIO_NONE);
2224}
2225
2226TEST(pthread, pthread_mutex_lock_pi) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002227 TestPthreadMutexLockNormal(PTHREAD_PRIO_INHERIT);
2228 TestPthreadMutexLockErrorCheck(PTHREAD_PRIO_INHERIT);
2229 TestPthreadMutexLockRecursive(PTHREAD_PRIO_INHERIT);
2230}
2231
Yabin Cui5a00ba72018-01-26 17:32:31 -08002232TEST(pthread, pthread_mutex_pi_count_limit) {
2233#if defined(__BIONIC__) && !defined(__LP64__)
2234 // Bionic only supports 65536 pi mutexes in 32-bit programs.
2235 pthread_mutexattr_t attr;
2236 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
2237 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT));
2238 std::vector<pthread_mutex_t> mutexes(65536);
2239 // Test if we can use 65536 pi mutexes at the same time.
2240 // Run 2 times to check if freed pi mutexes can be recycled.
2241 for (int repeat = 0; repeat < 2; ++repeat) {
2242 for (auto& m : mutexes) {
2243 ASSERT_EQ(0, pthread_mutex_init(&m, &attr));
2244 }
2245 pthread_mutex_t m;
2246 ASSERT_EQ(ENOMEM, pthread_mutex_init(&m, &attr));
2247 for (auto& m : mutexes) {
2248 ASSERT_EQ(0, pthread_mutex_lock(&m));
2249 }
2250 for (auto& m : mutexes) {
2251 ASSERT_EQ(0, pthread_mutex_unlock(&m));
2252 }
2253 for (auto& m : mutexes) {
2254 ASSERT_EQ(0, pthread_mutex_destroy(&m));
2255 }
2256 }
2257 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
2258#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002259 GTEST_SKIP() << "pi mutex count not limited to 64Ki";
Yabin Cui5a00ba72018-01-26 17:32:31 -08002260#endif
2261}
2262
Yabin Cui17393b02015-03-21 15:08:25 -07002263TEST(pthread, pthread_mutex_init_same_as_static_initializers) {
2264 pthread_mutex_t lock_normal = PTHREAD_MUTEX_INITIALIZER;
2265 PthreadMutex m1(PTHREAD_MUTEX_NORMAL);
2266 ASSERT_EQ(0, memcmp(&lock_normal, &m1.lock, sizeof(pthread_mutex_t)));
2267 pthread_mutex_destroy(&lock_normal);
2268
Colin Cross4c5595c2021-08-16 15:51:59 -07002269#if !defined(ANDROID_HOST_MUSL)
Colin Cross7da20342021-07-28 11:18:11 -07002270 // musl doesn't support PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP or
2271 // PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP.
Yabin Cui17393b02015-03-21 15:08:25 -07002272 pthread_mutex_t lock_errorcheck = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
2273 PthreadMutex m2(PTHREAD_MUTEX_ERRORCHECK);
2274 ASSERT_EQ(0, memcmp(&lock_errorcheck, &m2.lock, sizeof(pthread_mutex_t)));
2275 pthread_mutex_destroy(&lock_errorcheck);
2276
2277 pthread_mutex_t lock_recursive = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
2278 PthreadMutex m3(PTHREAD_MUTEX_RECURSIVE);
2279 ASSERT_EQ(0, memcmp(&lock_recursive, &m3.lock, sizeof(pthread_mutex_t)));
2280 ASSERT_EQ(0, pthread_mutex_destroy(&lock_recursive));
Colin Cross7da20342021-07-28 11:18:11 -07002281#endif
Derek Xue41996952014-09-25 11:05:32 +01002282}
Yabin Cui5a00ba72018-01-26 17:32:31 -08002283
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002284class MutexWakeupHelper {
2285 private:
Yabin Cui17393b02015-03-21 15:08:25 -07002286 PthreadMutex m;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002287 enum Progress {
2288 LOCK_INITIALIZED,
2289 LOCK_WAITING,
2290 LOCK_RELEASED,
2291 LOCK_ACCESSED
2292 };
2293 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -07002294 std::atomic<pid_t> tid;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002295
2296 static void thread_fn(MutexWakeupHelper* helper) {
Yabin Cuif7969852015-04-02 17:47:48 -07002297 helper->tid = gettid();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002298 ASSERT_EQ(LOCK_INITIALIZED, helper->progress);
2299 helper->progress = LOCK_WAITING;
2300
Yabin Cui17393b02015-03-21 15:08:25 -07002301 ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002302 ASSERT_EQ(LOCK_RELEASED, helper->progress);
Yabin Cui17393b02015-03-21 15:08:25 -07002303 ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002304
2305 helper->progress = LOCK_ACCESSED;
2306 }
2307
2308 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -07002309 explicit MutexWakeupHelper(int mutex_type) : m(mutex_type) {
Yabin Cui17393b02015-03-21 15:08:25 -07002310 }
2311
2312 void test() {
2313 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002314 progress = LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -07002315 tid = 0;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002316
2317 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002318 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002319 reinterpret_cast<void* (*)(void*)>(MutexWakeupHelper::thread_fn), this));
2320
Yabin Cuif7969852015-04-02 17:47:48 -07002321 WaitUntilThreadSleep(tid);
2322 ASSERT_EQ(LOCK_WAITING, progress);
2323
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002324 progress = LOCK_RELEASED;
Yabin Cui17393b02015-03-21 15:08:25 -07002325 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002326
Yi Kong32bc0fc2018-08-02 17:31:13 -07002327 ASSERT_EQ(0, pthread_join(thread, nullptr));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002328 ASSERT_EQ(LOCK_ACCESSED, progress);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002329 }
2330};
2331
2332TEST(pthread, pthread_mutex_NORMAL_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07002333 MutexWakeupHelper helper(PTHREAD_MUTEX_NORMAL);
2334 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002335}
2336
2337TEST(pthread, pthread_mutex_ERRORCHECK_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07002338 MutexWakeupHelper helper(PTHREAD_MUTEX_ERRORCHECK);
2339 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002340}
2341
2342TEST(pthread, pthread_mutex_RECURSIVE_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07002343 MutexWakeupHelper helper(PTHREAD_MUTEX_RECURSIVE);
2344 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002345}
2346
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002347static int GetThreadPriority(pid_t tid) {
2348 // sched_getparam() returns the static priority of a thread, which can't reflect a thread's
2349 // priority after priority inheritance. So read /proc/<pid>/stat to get the dynamic priority.
2350 std::string filename = android::base::StringPrintf("/proc/%d/stat", tid);
2351 std::string content;
2352 int result = INT_MAX;
2353 if (!android::base::ReadFileToString(filename, &content)) {
2354 return result;
2355 }
2356 std::vector<std::string> strs = android::base::Split(content, " ");
2357 if (strs.size() < 18) {
2358 return result;
2359 }
2360 if (!android::base::ParseInt(strs[17], &result)) {
2361 return INT_MAX;
2362 }
2363 return result;
2364}
2365
2366class PIMutexWakeupHelper {
2367private:
2368 PthreadMutex m;
2369 int protocol;
2370 enum Progress {
2371 LOCK_INITIALIZED,
2372 LOCK_CHILD_READY,
2373 LOCK_WAITING,
2374 LOCK_RELEASED,
2375 };
2376 std::atomic<Progress> progress;
2377 std::atomic<pid_t> main_tid;
2378 std::atomic<pid_t> child_tid;
2379 PthreadMutex start_thread_m;
2380
2381 static void thread_fn(PIMutexWakeupHelper* helper) {
2382 helper->child_tid = gettid();
2383 ASSERT_EQ(LOCK_INITIALIZED, helper->progress);
2384 ASSERT_EQ(0, setpriority(PRIO_PROCESS, gettid(), 1));
2385 ASSERT_EQ(21, GetThreadPriority(gettid()));
2386 ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock));
2387 helper->progress = LOCK_CHILD_READY;
2388 ASSERT_EQ(0, pthread_mutex_lock(&helper->start_thread_m.lock));
2389
2390 ASSERT_EQ(0, pthread_mutex_unlock(&helper->start_thread_m.lock));
2391 WaitUntilThreadSleep(helper->main_tid);
2392 ASSERT_EQ(LOCK_WAITING, helper->progress);
2393
2394 if (helper->protocol == PTHREAD_PRIO_INHERIT) {
2395 ASSERT_EQ(20, GetThreadPriority(gettid()));
2396 } else {
2397 ASSERT_EQ(21, GetThreadPriority(gettid()));
2398 }
2399 helper->progress = LOCK_RELEASED;
2400 ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock));
2401 }
2402
2403public:
2404 explicit PIMutexWakeupHelper(int mutex_type, int protocol)
2405 : m(mutex_type, protocol), protocol(protocol), start_thread_m(PTHREAD_MUTEX_NORMAL) {
2406 }
2407
2408 void test() {
2409 ASSERT_EQ(0, pthread_mutex_lock(&start_thread_m.lock));
2410 main_tid = gettid();
2411 ASSERT_EQ(20, GetThreadPriority(main_tid));
2412 progress = LOCK_INITIALIZED;
2413 child_tid = 0;
2414
2415 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002416 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002417 reinterpret_cast<void* (*)(void*)>(PIMutexWakeupHelper::thread_fn), this));
2418
2419 WaitUntilThreadSleep(child_tid);
2420 ASSERT_EQ(LOCK_CHILD_READY, progress);
2421 ASSERT_EQ(0, pthread_mutex_unlock(&start_thread_m.lock));
2422 progress = LOCK_WAITING;
2423 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
2424
2425 ASSERT_EQ(LOCK_RELEASED, progress);
2426 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2427 ASSERT_EQ(0, pthread_join(thread, nullptr));
2428 }
2429};
2430
2431TEST(pthread, pthread_mutex_pi_wakeup) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002432 for (int type : {PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_RECURSIVE, PTHREAD_MUTEX_ERRORCHECK}) {
2433 for (int protocol : {PTHREAD_PRIO_INHERIT}) {
2434 PIMutexWakeupHelper helper(type, protocol);
2435 helper.test();
2436 }
2437 }
2438}
2439
Yabin Cui140f3672015-02-03 10:32:00 -08002440TEST(pthread, pthread_mutex_owner_tid_limit) {
Yabin Cuie69c2452015-02-13 16:21:25 -08002441#if defined(__BIONIC__) && !defined(__LP64__)
Yabin Cui140f3672015-02-03 10:32:00 -08002442 FILE* fp = fopen("/proc/sys/kernel/pid_max", "r");
Yi Kong32bc0fc2018-08-02 17:31:13 -07002443 ASSERT_TRUE(fp != nullptr);
Yabin Cui140f3672015-02-03 10:32:00 -08002444 long pid_max;
2445 ASSERT_EQ(1, fscanf(fp, "%ld", &pid_max));
2446 fclose(fp);
Yabin Cuie69c2452015-02-13 16:21:25 -08002447 // Bionic's pthread_mutex implementation on 32-bit devices uses 16 bits to represent owner tid.
Yabin Cui140f3672015-02-03 10:32:00 -08002448 ASSERT_LE(pid_max, 65536);
Yabin Cuie69c2452015-02-13 16:21:25 -08002449#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002450 GTEST_SKIP() << "pthread_mutex supports 32-bit tid";
Yabin Cuie69c2452015-02-13 16:21:25 -08002451#endif
Yabin Cui140f3672015-02-03 10:32:00 -08002452}
Yabin Cuib5845722015-03-16 22:46:42 -07002453
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002454static void pthread_mutex_timedlock_helper(clockid_t clock,
2455 int (*lock_function)(pthread_mutex_t* __mutex,
2456 const timespec* __timeout)) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08002457 pthread_mutex_t m;
2458 ASSERT_EQ(0, pthread_mutex_init(&m, nullptr));
2459
2460 // If the mutex is already locked, pthread_mutex_timedlock should time out.
2461 ASSERT_EQ(0, pthread_mutex_lock(&m));
2462
2463 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002464 ASSERT_EQ(0, clock_gettime(clock, &ts));
2465 ASSERT_EQ(ETIMEDOUT, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002466 ts.tv_nsec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002467 ASSERT_EQ(EINVAL, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002468 ts.tv_nsec = NS_PER_S;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002469 ASSERT_EQ(EINVAL, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002470 ts.tv_nsec = NS_PER_S - 1;
2471 ts.tv_sec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002472 ASSERT_EQ(ETIMEDOUT, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002473
Elliott Hugheseabc47b2024-11-08 22:05:00 +00002474 // Check we wait long enough for the lock before timing out...
2475
2476 // What time is it before we start?
Andy Hung5e19b182023-12-11 19:28:02 -08002477 ASSERT_EQ(0, clock_gettime(clock, &ts));
Elliott Hugheseabc47b2024-11-08 22:05:00 +00002478 const int64_t start_ns = to_ns(ts);
2479 // Add a second to get deadline, and wait until we time out.
Andy Hung5e19b182023-12-11 19:28:02 -08002480 ts.tv_sec += 1;
Andy Hung5e19b182023-12-11 19:28:02 -08002481 ASSERT_EQ(ETIMEDOUT, lock_function(&m, &ts));
2482
Elliott Hugheseabc47b2024-11-08 22:05:00 +00002483 // What time is it now we've timed out?
2484 timespec ts2;
2485 clock_gettime(clock, &ts2);
2486 const int64_t end_ns = to_ns(ts2);
2487
Andy Hung5e19b182023-12-11 19:28:02 -08002488 // The timedlock must have waited at least 1 second before returning.
Elliott Hugheseabc47b2024-11-08 22:05:00 +00002489 ASSERT_GE(end_ns - start_ns, NS_PER_S);
Andy Hung5e19b182023-12-11 19:28:02 -08002490
Yabin Cuic9a659c2015-11-05 15:36:08 -08002491 // If the mutex is unlocked, pthread_mutex_timedlock should succeed.
2492 ASSERT_EQ(0, pthread_mutex_unlock(&m));
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002493 ASSERT_EQ(0, clock_gettime(clock, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002494 ts.tv_sec += 1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002495 ASSERT_EQ(0, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002496
2497 ASSERT_EQ(0, pthread_mutex_unlock(&m));
2498 ASSERT_EQ(0, pthread_mutex_destroy(&m));
2499}
2500
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002501TEST(pthread, pthread_mutex_timedlock) {
2502 pthread_mutex_timedlock_helper(CLOCK_REALTIME, pthread_mutex_timedlock);
2503}
2504
2505TEST(pthread, pthread_mutex_timedlock_monotonic_np) {
2506#if defined(__BIONIC__)
2507 pthread_mutex_timedlock_helper(CLOCK_MONOTONIC, pthread_mutex_timedlock_monotonic_np);
2508#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002509 GTEST_SKIP() << "pthread_mutex_timedlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002510#endif // __BIONIC__
2511}
2512
Elliott Hugheseabc47b2024-11-08 22:05:00 +00002513TEST(pthread, pthread_mutex_clocklock_MONOTONIC) {
Tom Cherry69010802019-05-07 20:33:05 -07002514#if defined(__BIONIC__)
2515 pthread_mutex_timedlock_helper(
2516 CLOCK_MONOTONIC, [](pthread_mutex_t* __mutex, const timespec* __timeout) {
2517 return pthread_mutex_clocklock(__mutex, CLOCK_MONOTONIC, __timeout);
2518 });
Elliott Hugheseabc47b2024-11-08 22:05:00 +00002519#else // __BIONIC__
2520 GTEST_SKIP() << "pthread_mutex_clocklock not available";
2521#endif // __BIONIC__
2522}
2523
2524TEST(pthread, pthread_mutex_clocklock_REALTIME) {
2525#if defined(__BIONIC__)
Tom Cherry69010802019-05-07 20:33:05 -07002526 pthread_mutex_timedlock_helper(
2527 CLOCK_REALTIME, [](pthread_mutex_t* __mutex, const timespec* __timeout) {
2528 return pthread_mutex_clocklock(__mutex, CLOCK_REALTIME, __timeout);
2529 });
2530#else // __BIONIC__
2531 GTEST_SKIP() << "pthread_mutex_clocklock not available";
2532#endif // __BIONIC__
2533}
2534
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002535static void pthread_mutex_timedlock_pi_helper(clockid_t clock,
2536 int (*lock_function)(pthread_mutex_t* __mutex,
2537 const timespec* __timeout)) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002538 PthreadMutex m(PTHREAD_MUTEX_NORMAL, PTHREAD_PRIO_INHERIT);
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002539
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002540 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002541 clock_gettime(clock, &ts);
Andy Hung5e19b182023-12-11 19:28:02 -08002542 const int64_t start_ns = ts.tv_sec * NS_PER_S + ts.tv_nsec;
2543
2544 // add a second to get deadline.
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002545 ts.tv_sec += 1;
Andy Hung5e19b182023-12-11 19:28:02 -08002546
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002547 ASSERT_EQ(0, lock_function(&m.lock, &ts));
2548
2549 struct ThreadArgs {
2550 clockid_t clock;
2551 int (*lock_function)(pthread_mutex_t* __mutex, const timespec* __timeout);
2552 PthreadMutex& m;
2553 };
2554
2555 ThreadArgs thread_args = {
2556 .clock = clock,
2557 .lock_function = lock_function,
2558 .m = m,
2559 };
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002560
2561 auto ThreadFn = [](void* arg) -> void* {
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002562 auto args = static_cast<ThreadArgs*>(arg);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002563 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002564 clock_gettime(args->clock, &ts);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002565 ts.tv_sec += 1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002566 intptr_t result = args->lock_function(&args->m.lock, &ts);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002567 return reinterpret_cast<void*>(result);
2568 };
2569
2570 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002571 ASSERT_EQ(0, pthread_create(&thread, nullptr, ThreadFn, &thread_args));
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002572 void* result;
2573 ASSERT_EQ(0, pthread_join(thread, &result));
2574 ASSERT_EQ(ETIMEDOUT, reinterpret_cast<intptr_t>(result));
Andy Hung5e19b182023-12-11 19:28:02 -08002575
2576 // The timedlock must have waited at least 1 second before returning.
2577 clock_gettime(clock, &ts);
2578 const int64_t end_ns = ts.tv_sec * NS_PER_S + ts.tv_nsec;
2579 ASSERT_GT(end_ns - start_ns, NS_PER_S);
2580
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002581 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2582}
2583
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002584TEST(pthread, pthread_mutex_timedlock_pi) {
2585 pthread_mutex_timedlock_pi_helper(CLOCK_REALTIME, pthread_mutex_timedlock);
2586}
2587
2588TEST(pthread, pthread_mutex_timedlock_monotonic_np_pi) {
2589#if defined(__BIONIC__)
2590 pthread_mutex_timedlock_pi_helper(CLOCK_MONOTONIC, pthread_mutex_timedlock_monotonic_np);
2591#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002592 GTEST_SKIP() << "pthread_mutex_timedlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002593#endif // __BIONIC__
2594}
2595
Tom Cherry69010802019-05-07 20:33:05 -07002596TEST(pthread, pthread_mutex_clocklock_pi) {
2597#if defined(__BIONIC__)
2598 pthread_mutex_timedlock_pi_helper(
2599 CLOCK_MONOTONIC, [](pthread_mutex_t* __mutex, const timespec* __timeout) {
2600 return pthread_mutex_clocklock(__mutex, CLOCK_MONOTONIC, __timeout);
2601 });
2602 pthread_mutex_timedlock_pi_helper(
2603 CLOCK_REALTIME, [](pthread_mutex_t* __mutex, const timespec* __timeout) {
2604 return pthread_mutex_clocklock(__mutex, CLOCK_REALTIME, __timeout);
2605 });
2606#else // __BIONIC__
2607 GTEST_SKIP() << "pthread_mutex_clocklock not available";
2608#endif // __BIONIC__
2609}
2610
2611TEST(pthread, pthread_mutex_clocklock_invalid) {
2612#if defined(__BIONIC__)
2613 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
2614 timespec ts;
2615 EXPECT_EQ(EINVAL, pthread_mutex_clocklock(&mutex, CLOCK_PROCESS_CPUTIME_ID, &ts));
2616#else // __BIONIC__
2617 GTEST_SKIP() << "pthread_mutex_clocklock not available";
2618#endif // __BIONIC__
2619}
2620
Elliott Hughese657eb42021-02-18 17:11:56 -08002621TEST_F(pthread_DeathTest, pthread_mutex_using_destroyed_mutex) {
Yabin Cui9651fdf2018-03-14 12:02:21 -07002622#if defined(__BIONIC__)
2623 pthread_mutex_t m;
2624 ASSERT_EQ(0, pthread_mutex_init(&m, nullptr));
2625 ASSERT_EQ(0, pthread_mutex_destroy(&m));
2626 ASSERT_EXIT(pthread_mutex_lock(&m), ::testing::KilledBySignal(SIGABRT),
2627 "pthread_mutex_lock called on a destroyed mutex");
2628 ASSERT_EXIT(pthread_mutex_unlock(&m), ::testing::KilledBySignal(SIGABRT),
2629 "pthread_mutex_unlock called on a destroyed mutex");
2630 ASSERT_EXIT(pthread_mutex_trylock(&m), ::testing::KilledBySignal(SIGABRT),
2631 "pthread_mutex_trylock called on a destroyed mutex");
2632 timespec ts;
2633 ASSERT_EXIT(pthread_mutex_timedlock(&m, &ts), ::testing::KilledBySignal(SIGABRT),
2634 "pthread_mutex_timedlock called on a destroyed mutex");
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002635 ASSERT_EXIT(pthread_mutex_timedlock_monotonic_np(&m, &ts), ::testing::KilledBySignal(SIGABRT),
2636 "pthread_mutex_timedlock_monotonic_np called on a destroyed mutex");
Tom Cherry69010802019-05-07 20:33:05 -07002637 ASSERT_EXIT(pthread_mutex_clocklock(&m, CLOCK_MONOTONIC, &ts), ::testing::KilledBySignal(SIGABRT),
2638 "pthread_mutex_clocklock called on a destroyed mutex");
2639 ASSERT_EXIT(pthread_mutex_clocklock(&m, CLOCK_REALTIME, &ts), ::testing::KilledBySignal(SIGABRT),
2640 "pthread_mutex_clocklock called on a destroyed mutex");
2641 ASSERT_EXIT(pthread_mutex_clocklock(&m, CLOCK_PROCESS_CPUTIME_ID, &ts),
2642 ::testing::KilledBySignal(SIGABRT),
2643 "pthread_mutex_clocklock called on a destroyed mutex");
Yabin Cui9651fdf2018-03-14 12:02:21 -07002644 ASSERT_EXIT(pthread_mutex_destroy(&m), ::testing::KilledBySignal(SIGABRT),
2645 "pthread_mutex_destroy called on a destroyed mutex");
2646#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002647 GTEST_SKIP() << "bionic-only test";
Yabin Cui9651fdf2018-03-14 12:02:21 -07002648#endif
2649}
2650
Yabin Cuib5845722015-03-16 22:46:42 -07002651class StrictAlignmentAllocator {
2652 public:
2653 void* allocate(size_t size, size_t alignment) {
2654 char* p = new char[size + alignment * 2];
2655 allocated_array.push_back(p);
2656 while (!is_strict_aligned(p, alignment)) {
2657 ++p;
2658 }
2659 return p;
2660 }
2661
2662 ~StrictAlignmentAllocator() {
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07002663 for (const auto& p : allocated_array) {
2664 delete[] p;
Yabin Cuib5845722015-03-16 22:46:42 -07002665 }
2666 }
2667
2668 private:
2669 bool is_strict_aligned(char* p, size_t alignment) {
2670 return (reinterpret_cast<uintptr_t>(p) % (alignment * 2)) == alignment;
2671 }
2672
2673 std::vector<char*> allocated_array;
2674};
2675
2676TEST(pthread, pthread_types_allow_four_bytes_alignment) {
2677#if defined(__BIONIC__)
2678 // For binary compatibility with old version, we need to allow 4-byte aligned data for pthread types.
2679 StrictAlignmentAllocator allocator;
2680 pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(
2681 allocator.allocate(sizeof(pthread_mutex_t), 4));
Yi Kong32bc0fc2018-08-02 17:31:13 -07002682 ASSERT_EQ(0, pthread_mutex_init(mutex, nullptr));
Yabin Cuib5845722015-03-16 22:46:42 -07002683 ASSERT_EQ(0, pthread_mutex_lock(mutex));
2684 ASSERT_EQ(0, pthread_mutex_unlock(mutex));
2685 ASSERT_EQ(0, pthread_mutex_destroy(mutex));
2686
2687 pthread_cond_t* cond = reinterpret_cast<pthread_cond_t*>(
2688 allocator.allocate(sizeof(pthread_cond_t), 4));
Yi Kong32bc0fc2018-08-02 17:31:13 -07002689 ASSERT_EQ(0, pthread_cond_init(cond, nullptr));
Yabin Cuib5845722015-03-16 22:46:42 -07002690 ASSERT_EQ(0, pthread_cond_signal(cond));
2691 ASSERT_EQ(0, pthread_cond_broadcast(cond));
2692 ASSERT_EQ(0, pthread_cond_destroy(cond));
2693
2694 pthread_rwlock_t* rwlock = reinterpret_cast<pthread_rwlock_t*>(
2695 allocator.allocate(sizeof(pthread_rwlock_t), 4));
Yi Kong32bc0fc2018-08-02 17:31:13 -07002696 ASSERT_EQ(0, pthread_rwlock_init(rwlock, nullptr));
Yabin Cuib5845722015-03-16 22:46:42 -07002697 ASSERT_EQ(0, pthread_rwlock_rdlock(rwlock));
2698 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
2699 ASSERT_EQ(0, pthread_rwlock_wrlock(rwlock));
2700 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
2701 ASSERT_EQ(0, pthread_rwlock_destroy(rwlock));
2702
2703#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002704 GTEST_SKIP() << "bionic-only test";
Yabin Cuib5845722015-03-16 22:46:42 -07002705#endif
2706}
Christopher Ferris60907c72015-06-09 18:46:15 -07002707
2708TEST(pthread, pthread_mutex_lock_null_32) {
2709#if defined(__BIONIC__) && !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -07002710 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return
2711 // EINVAL in that case: http://b/19995172.
2712 //
2713 // We decorate the public defintion with _Nonnull so that people recompiling
2714 // their code with get a warning and might fix their bug, but need to pass
2715 // NULL here to test that we remain compatible.
2716 pthread_mutex_t* null_value = nullptr;
2717 ASSERT_EQ(EINVAL, pthread_mutex_lock(null_value));
Christopher Ferris60907c72015-06-09 18:46:15 -07002718#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002719 GTEST_SKIP() << "32-bit bionic-only test";
Christopher Ferris60907c72015-06-09 18:46:15 -07002720#endif
2721}
2722
2723TEST(pthread, pthread_mutex_unlock_null_32) {
2724#if defined(__BIONIC__) && !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -07002725 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return
2726 // EINVAL in that case: http://b/19995172.
2727 //
2728 // We decorate the public defintion with _Nonnull so that people recompiling
2729 // their code with get a warning and might fix their bug, but need to pass
2730 // NULL here to test that we remain compatible.
2731 pthread_mutex_t* null_value = nullptr;
2732 ASSERT_EQ(EINVAL, pthread_mutex_unlock(null_value));
Christopher Ferris60907c72015-06-09 18:46:15 -07002733#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002734 GTEST_SKIP() << "32-bit bionic-only test";
Christopher Ferris60907c72015-06-09 18:46:15 -07002735#endif
2736}
2737
2738TEST_F(pthread_DeathTest, pthread_mutex_lock_null_64) {
2739#if defined(__BIONIC__) && defined(__LP64__)
2740 pthread_mutex_t* null_value = nullptr;
2741 ASSERT_EXIT(pthread_mutex_lock(null_value), testing::KilledBySignal(SIGSEGV), "");
2742#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002743 GTEST_SKIP() << "64-bit bionic-only test";
Christopher Ferris60907c72015-06-09 18:46:15 -07002744#endif
2745}
2746
2747TEST_F(pthread_DeathTest, pthread_mutex_unlock_null_64) {
2748#if defined(__BIONIC__) && defined(__LP64__)
2749 pthread_mutex_t* null_value = nullptr;
2750 ASSERT_EXIT(pthread_mutex_unlock(null_value), testing::KilledBySignal(SIGSEGV), "");
2751#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002752 GTEST_SKIP() << "64-bit bionic-only test";
Christopher Ferris60907c72015-06-09 18:46:15 -07002753#endif
2754}
Yabin Cui33ac04a2015-09-22 11:16:15 -07002755
2756extern _Unwind_Reason_Code FrameCounter(_Unwind_Context* ctx, void* arg);
2757
2758static volatile bool signal_handler_on_altstack_done;
2759
Josh Gao61db9ac2017-03-15 19:42:05 -07002760__attribute__((__noinline__))
2761static void signal_handler_backtrace() {
2762 // Check if we have enough stack space for unwinding.
2763 int count = 0;
2764 _Unwind_Backtrace(FrameCounter, &count);
2765 ASSERT_GT(count, 0);
2766}
2767
2768__attribute__((__noinline__))
2769static void signal_handler_logging() {
2770 // Check if we have enough stack space for logging.
2771 std::string s(2048, '*');
2772 GTEST_LOG_(INFO) << s;
2773 signal_handler_on_altstack_done = true;
2774}
2775
2776__attribute__((__noinline__))
2777static void signal_handler_snprintf() {
2778 // Check if we have enough stack space for snprintf to a PATH_MAX buffer, plus some extra.
2779 char buf[PATH_MAX + 2048];
2780 ASSERT_GT(snprintf(buf, sizeof(buf), "/proc/%d/status", getpid()), 0);
2781}
2782
Yabin Cui33ac04a2015-09-22 11:16:15 -07002783static void SignalHandlerOnAltStack(int signo, siginfo_t*, void*) {
2784 ASSERT_EQ(SIGUSR1, signo);
Josh Gao61db9ac2017-03-15 19:42:05 -07002785 signal_handler_backtrace();
2786 signal_handler_logging();
2787 signal_handler_snprintf();
Yabin Cui33ac04a2015-09-22 11:16:15 -07002788}
2789
Josh Gao415daa82017-03-06 17:45:33 -08002790TEST(pthread, big_enough_signal_stack) {
Yabin Cui33ac04a2015-09-22 11:16:15 -07002791 signal_handler_on_altstack_done = false;
2792 ScopedSignalHandler handler(SIGUSR1, SignalHandlerOnAltStack, SA_SIGINFO | SA_ONSTACK);
2793 kill(getpid(), SIGUSR1);
2794 ASSERT_TRUE(signal_handler_on_altstack_done);
2795}
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002796
2797TEST(pthread, pthread_barrierattr_smoke) {
2798 pthread_barrierattr_t attr;
2799 ASSERT_EQ(0, pthread_barrierattr_init(&attr));
2800 int pshared;
2801 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
2802 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
2803 ASSERT_EQ(0, pthread_barrierattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
2804 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
2805 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
2806 ASSERT_EQ(0, pthread_barrierattr_destroy(&attr));
2807}
2808
Yabin Cui81d27972016-03-22 13:45:55 -07002809struct BarrierTestHelperData {
2810 size_t thread_count;
2811 pthread_barrier_t barrier;
2812 std::atomic<int> finished_mask;
2813 std::atomic<int> serial_thread_count;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002814 size_t iteration_count;
Yabin Cui81d27972016-03-22 13:45:55 -07002815 std::atomic<size_t> finished_iteration_count;
2816
2817 BarrierTestHelperData(size_t thread_count, size_t iteration_count)
2818 : thread_count(thread_count), finished_mask(0), serial_thread_count(0),
2819 iteration_count(iteration_count), finished_iteration_count(0) {
2820 }
2821};
2822
2823struct BarrierTestHelperArg {
2824 int id;
2825 BarrierTestHelperData* data;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002826};
2827
2828static void BarrierTestHelper(BarrierTestHelperArg* arg) {
Yabin Cui81d27972016-03-22 13:45:55 -07002829 for (size_t i = 0; i < arg->data->iteration_count; ++i) {
2830 int result = pthread_barrier_wait(&arg->data->barrier);
2831 if (result == PTHREAD_BARRIER_SERIAL_THREAD) {
2832 arg->data->serial_thread_count++;
2833 } else {
2834 ASSERT_EQ(0, result);
2835 }
Yabin Cuid5c04c52017-05-02 12:57:39 -07002836 int mask = arg->data->finished_mask.fetch_or(1 << arg->id);
Yabin Cuiab4cddc2017-05-02 16:18:13 -07002837 mask |= 1 << arg->id;
Yabin Cuid5c04c52017-05-02 12:57:39 -07002838 if (mask == ((1 << arg->data->thread_count) - 1)) {
Yabin Cui81d27972016-03-22 13:45:55 -07002839 ASSERT_EQ(1, arg->data->serial_thread_count);
2840 arg->data->finished_iteration_count++;
2841 arg->data->finished_mask = 0;
2842 arg->data->serial_thread_count = 0;
2843 }
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002844 }
2845}
2846
2847TEST(pthread, pthread_barrier_smoke) {
2848 const size_t BARRIER_ITERATION_COUNT = 10;
2849 const size_t BARRIER_THREAD_COUNT = 10;
Yabin Cui81d27972016-03-22 13:45:55 -07002850 BarrierTestHelperData data(BARRIER_THREAD_COUNT, BARRIER_ITERATION_COUNT);
2851 ASSERT_EQ(0, pthread_barrier_init(&data.barrier, nullptr, data.thread_count));
2852 std::vector<pthread_t> threads(data.thread_count);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002853 std::vector<BarrierTestHelperArg> args(threads.size());
2854 for (size_t i = 0; i < threads.size(); ++i) {
Yabin Cui81d27972016-03-22 13:45:55 -07002855 args[i].id = i;
2856 args[i].data = &data;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002857 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
2858 reinterpret_cast<void* (*)(void*)>(BarrierTestHelper), &args[i]));
2859 }
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002860 for (size_t i = 0; i < threads.size(); ++i) {
2861 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
2862 }
Yabin Cui81d27972016-03-22 13:45:55 -07002863 ASSERT_EQ(data.iteration_count, data.finished_iteration_count);
2864 ASSERT_EQ(0, pthread_barrier_destroy(&data.barrier));
2865}
2866
2867struct BarrierDestroyTestArg {
2868 std::atomic<int> tid;
2869 pthread_barrier_t* barrier;
2870};
2871
2872static void BarrierDestroyTestHelper(BarrierDestroyTestArg* arg) {
2873 arg->tid = gettid();
2874 ASSERT_EQ(0, pthread_barrier_wait(arg->barrier));
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002875}
2876
2877TEST(pthread, pthread_barrier_destroy) {
2878 pthread_barrier_t barrier;
2879 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, 2));
2880 pthread_t thread;
Yabin Cui81d27972016-03-22 13:45:55 -07002881 BarrierDestroyTestArg arg;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002882 arg.tid = 0;
2883 arg.barrier = &barrier;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002884 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui81d27972016-03-22 13:45:55 -07002885 reinterpret_cast<void* (*)(void*)>(BarrierDestroyTestHelper), &arg));
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002886 WaitUntilThreadSleep(arg.tid);
2887 ASSERT_EQ(EBUSY, pthread_barrier_destroy(&barrier));
2888 ASSERT_EQ(PTHREAD_BARRIER_SERIAL_THREAD, pthread_barrier_wait(&barrier));
2889 // Verify if the barrier can be destroyed directly after pthread_barrier_wait().
2890 ASSERT_EQ(0, pthread_barrier_destroy(&barrier));
2891 ASSERT_EQ(0, pthread_join(thread, nullptr));
2892#if defined(__BIONIC__)
2893 ASSERT_EQ(EINVAL, pthread_barrier_destroy(&barrier));
2894#endif
2895}
2896
2897struct BarrierOrderingTestHelperArg {
2898 pthread_barrier_t* barrier;
2899 size_t* array;
2900 size_t array_length;
2901 size_t id;
2902};
2903
2904void BarrierOrderingTestHelper(BarrierOrderingTestHelperArg* arg) {
2905 const size_t ITERATION_COUNT = 10000;
2906 for (size_t i = 1; i <= ITERATION_COUNT; ++i) {
2907 arg->array[arg->id] = i;
Yabin Cuic9a659c2015-11-05 15:36:08 -08002908 int result = pthread_barrier_wait(arg->barrier);
2909 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002910 for (size_t j = 0; j < arg->array_length; ++j) {
2911 ASSERT_EQ(i, arg->array[j]);
2912 }
Yabin Cuic9a659c2015-11-05 15:36:08 -08002913 result = pthread_barrier_wait(arg->barrier);
2914 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002915 }
2916}
2917
2918TEST(pthread, pthread_barrier_check_ordering) {
2919 const size_t THREAD_COUNT = 4;
2920 pthread_barrier_t barrier;
2921 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, THREAD_COUNT));
2922 size_t array[THREAD_COUNT];
2923 std::vector<pthread_t> threads(THREAD_COUNT);
2924 std::vector<BarrierOrderingTestHelperArg> args(THREAD_COUNT);
2925 for (size_t i = 0; i < THREAD_COUNT; ++i) {
2926 args[i].barrier = &barrier;
2927 args[i].array = array;
2928 args[i].array_length = THREAD_COUNT;
2929 args[i].id = i;
2930 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
2931 reinterpret_cast<void* (*)(void*)>(BarrierOrderingTestHelper),
2932 &args[i]));
2933 }
2934 for (size_t i = 0; i < THREAD_COUNT; ++i) {
2935 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
2936 }
2937}
Yabin Cuife3a83a2015-11-17 16:03:18 -08002938
Elliott Hughes463faad2018-07-06 14:34:49 -07002939TEST(pthread, pthread_barrier_init_zero_count) {
2940 pthread_barrier_t barrier;
2941 ASSERT_EQ(EINVAL, pthread_barrier_init(&barrier, nullptr, 0));
2942}
2943
Yabin Cuife3a83a2015-11-17 16:03:18 -08002944TEST(pthread, pthread_spinlock_smoke) {
2945 pthread_spinlock_t lock;
2946 ASSERT_EQ(0, pthread_spin_init(&lock, 0));
2947 ASSERT_EQ(0, pthread_spin_trylock(&lock));
2948 ASSERT_EQ(0, pthread_spin_unlock(&lock));
2949 ASSERT_EQ(0, pthread_spin_lock(&lock));
2950 ASSERT_EQ(EBUSY, pthread_spin_trylock(&lock));
2951 ASSERT_EQ(0, pthread_spin_unlock(&lock));
2952 ASSERT_EQ(0, pthread_spin_destroy(&lock));
2953}
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002954
Elliott Hughes8aecba72017-10-17 15:34:41 -07002955TEST(pthread, pthread_attr_getdetachstate__pthread_attr_setdetachstate) {
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002956 pthread_attr_t attr;
2957 ASSERT_EQ(0, pthread_attr_init(&attr));
2958
Elliott Hughes8aecba72017-10-17 15:34:41 -07002959 int state;
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002960 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002961 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2962 ASSERT_EQ(PTHREAD_CREATE_DETACHED, state);
2963
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002964 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002965 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2966 ASSERT_EQ(PTHREAD_CREATE_JOINABLE, state);
2967
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002968 ASSERT_EQ(EINVAL, pthread_attr_setdetachstate(&attr, 123));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002969 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2970 ASSERT_EQ(PTHREAD_CREATE_JOINABLE, state);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002971}
2972
2973TEST(pthread, pthread_create__mmap_failures) {
Evgeny Eltsinb4f7aaa2020-06-09 15:49:20 +02002974 // After thread is successfully created, native_bridge might need more memory to run it.
2975 SKIP_WITH_NATIVE_BRIDGE;
2976
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002977 pthread_attr_t attr;
2978 ASSERT_EQ(0, pthread_attr_init(&attr));
2979 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
2980
2981 const auto kPageSize = sysconf(_SC_PAGE_SIZE);
2982
Elliott Hughes57512982017-10-02 22:49:18 -07002983 // Use up all the VMAs. By default this is 64Ki (though some will already be in use).
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002984 std::vector<void*> pages;
Elliott Hughes57512982017-10-02 22:49:18 -07002985 pages.reserve(64 * 1024);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002986 int prot = PROT_NONE;
2987 while (true) {
2988 void* page = mmap(nullptr, kPageSize, prot, MAP_ANON|MAP_PRIVATE, -1, 0);
2989 if (page == MAP_FAILED) break;
2990 pages.push_back(page);
2991 prot = (prot == PROT_NONE) ? PROT_READ : PROT_NONE;
2992 }
2993
2994 // Try creating threads, freeing up a page each time we fail.
2995 size_t EAGAIN_count = 0;
2996 size_t i = 0;
2997 for (; i < pages.size(); ++i) {
2998 pthread_t t;
2999 int status = pthread_create(&t, &attr, IdFn, nullptr);
3000 if (status != EAGAIN) break;
3001 ++EAGAIN_count;
3002 ASSERT_EQ(0, munmap(pages[i], kPageSize));
3003 }
3004
Ryan Prichard45d13492019-01-03 02:51:30 -08003005 // Creating a thread uses at least three VMAs: the combined stack and TLS, and a guard on each
3006 // side. So we should have seen at least three failures.
3007 ASSERT_GE(EAGAIN_count, 3U);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07003008
3009 for (; i < pages.size(); ++i) {
3010 ASSERT_EQ(0, munmap(pages[i], kPageSize));
3011 }
3012}
Elliott Hughesdff08ce2017-10-16 09:58:45 -07003013
3014TEST(pthread, pthread_setschedparam) {
3015 sched_param p = { .sched_priority = INT_MIN };
3016 ASSERT_EQ(EINVAL, pthread_setschedparam(pthread_self(), INT_MIN, &p));
3017}
3018
3019TEST(pthread, pthread_setschedprio) {
3020 ASSERT_EQ(EINVAL, pthread_setschedprio(pthread_self(), INT_MIN));
3021}
Elliott Hughes8aecba72017-10-17 15:34:41 -07003022
3023TEST(pthread, pthread_attr_getinheritsched__pthread_attr_setinheritsched) {
3024 pthread_attr_t attr;
3025 ASSERT_EQ(0, pthread_attr_init(&attr));
3026
3027 int state;
3028 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
3029 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
3030 ASSERT_EQ(PTHREAD_INHERIT_SCHED, state);
3031
3032 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
3033 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
3034 ASSERT_EQ(PTHREAD_EXPLICIT_SCHED, state);
3035
3036 ASSERT_EQ(EINVAL, pthread_attr_setinheritsched(&attr, 123));
3037 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
3038 ASSERT_EQ(PTHREAD_EXPLICIT_SCHED, state);
3039}
3040
3041TEST(pthread, pthread_attr_setinheritsched__PTHREAD_INHERIT_SCHED__PTHREAD_EXPLICIT_SCHED) {
3042 pthread_attr_t attr;
3043 ASSERT_EQ(0, pthread_attr_init(&attr));
3044
3045 // If we set invalid scheduling attributes but choose to inherit, everything's fine...
3046 sched_param param = { .sched_priority = sched_get_priority_max(SCHED_FIFO) + 1 };
3047 ASSERT_EQ(0, pthread_attr_setschedparam(&attr, &param));
3048 ASSERT_EQ(0, pthread_attr_setschedpolicy(&attr, SCHED_FIFO));
3049 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
3050
3051 pthread_t t;
3052 ASSERT_EQ(0, pthread_create(&t, &attr, IdFn, nullptr));
3053 ASSERT_EQ(0, pthread_join(t, nullptr));
3054
Elliott Hughes7a660662017-10-30 09:26:06 -07003055#if defined(__LP64__)
3056 // If we ask to use them, though, we'll see a failure...
Elliott Hughes8aecba72017-10-17 15:34:41 -07003057 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
3058 ASSERT_EQ(EINVAL, pthread_create(&t, &attr, IdFn, nullptr));
Elliott Hughes7a660662017-10-30 09:26:06 -07003059#else
3060 // For backwards compatibility with broken apps, we just ignore failures
3061 // to set scheduler attributes on LP32.
3062#endif
Elliott Hughes8aecba72017-10-17 15:34:41 -07003063}
3064
3065TEST(pthread, pthread_attr_setinheritsched_PTHREAD_INHERIT_SCHED_takes_effect) {
3066 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
3067 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO, &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, 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}
3085
3086TEST(pthread, pthread_attr_setinheritsched_PTHREAD_EXPLICIT_SCHED_takes_effect) {
3087 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
3088 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO, &param);
Elliott Hughesbcaa4542019-03-08 15:20:23 -08003089 if (rc == EPERM) GTEST_SKIP() << "pthread_setschedparam failed with EPERM";
Elliott Hughes8aecba72017-10-17 15:34:41 -07003090 ASSERT_EQ(0, rc);
3091
3092 pthread_attr_t attr;
3093 ASSERT_EQ(0, pthread_attr_init(&attr));
3094 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
3095 ASSERT_EQ(0, pthread_attr_setschedpolicy(&attr, SCHED_OTHER));
3096
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003097 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07003098 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003099 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07003100 int actual_policy;
3101 sched_param actual_param;
3102 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
3103 ASSERT_EQ(SCHED_OTHER, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003104 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07003105 ASSERT_EQ(0, pthread_join(t, nullptr));
3106}
3107
3108TEST(pthread, pthread_attr_setinheritsched__takes_effect_despite_SCHED_RESET_ON_FORK) {
3109 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
3110 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param);
Elliott Hughesbcaa4542019-03-08 15:20:23 -08003111 if (rc == EPERM) GTEST_SKIP() << "pthread_setschedparam failed with EPERM";
Elliott Hughes8aecba72017-10-17 15:34:41 -07003112 ASSERT_EQ(0, rc);
3113
3114 pthread_attr_t attr;
3115 ASSERT_EQ(0, pthread_attr_init(&attr));
3116 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
3117
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003118 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07003119 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003120 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07003121 int actual_policy;
3122 sched_param actual_param;
3123 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
3124 ASSERT_EQ(SCHED_FIFO | SCHED_RESET_ON_FORK, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003125 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07003126 ASSERT_EQ(0, pthread_join(t, nullptr));
3127}
Peter Collingbourne5d3aa862020-09-11 15:05:17 -07003128
3129extern "C" bool android_run_on_all_threads(bool (*func)(void*), void* arg);
3130
3131TEST(pthread, run_on_all_threads) {
3132#if defined(__BIONIC__)
3133 pthread_t t;
3134 ASSERT_EQ(
3135 0, pthread_create(
3136 &t, nullptr,
3137 [](void*) -> void* {
3138 pthread_attr_t detached;
3139 if (pthread_attr_init(&detached) != 0 ||
3140 pthread_attr_setdetachstate(&detached, PTHREAD_CREATE_DETACHED) != 0) {
3141 return reinterpret_cast<void*>(errno);
3142 }
3143
3144 for (int i = 0; i != 1000; ++i) {
3145 pthread_t t1, t2;
3146 if (pthread_create(
3147 &t1, &detached, [](void*) -> void* { return nullptr; }, nullptr) != 0 ||
3148 pthread_create(
3149 &t2, nullptr, [](void*) -> void* { return nullptr; }, nullptr) != 0 ||
3150 pthread_join(t2, nullptr) != 0) {
3151 return reinterpret_cast<void*>(errno);
3152 }
3153 }
3154
3155 if (pthread_attr_destroy(&detached) != 0) {
3156 return reinterpret_cast<void*>(errno);
3157 }
3158 return nullptr;
3159 },
3160 nullptr));
3161
3162 for (int i = 0; i != 1000; ++i) {
3163 ASSERT_TRUE(android_run_on_all_threads([](void* arg) { return arg == nullptr; }, nullptr));
3164 }
3165
3166 void *retval;
3167 ASSERT_EQ(0, pthread_join(t, &retval));
3168 ASSERT_EQ(nullptr, retval);
3169#else
3170 GTEST_SKIP() << "bionic-only test";
3171#endif
3172}
Elliott Hughese117d6e2024-11-14 17:31:13 +00003173
3174TEST(pthread, pthread_getaffinity_np_failure) {
3175 // Trivial test of the errno-preserving/returning behavior.
3176#pragma clang diagnostic push
3177#pragma clang diagnostic ignored "-Wnonnull"
3178 errno = 0;
3179 ASSERT_EQ(EINVAL, pthread_getaffinity_np(pthread_self(), 0, nullptr));
3180 ASSERT_ERRNO(0);
3181#pragma clang diagnostic pop
3182}
3183
Elliott Hughesd354c422024-11-18 14:49:45 +00003184TEST(pthread, pthread_getaffinity) {
3185 cpu_set_t set;
3186 CPU_ZERO(&set);
3187 ASSERT_EQ(0, pthread_getaffinity_np(pthread_self(), sizeof(set), &set));
3188 ASSERT_GT(CPU_COUNT(&set), 0);
3189}
3190
Elliott Hughese117d6e2024-11-14 17:31:13 +00003191TEST(pthread, pthread_setaffinity_np_failure) {
3192 // Trivial test of the errno-preserving/returning behavior.
3193#pragma clang diagnostic push
3194#pragma clang diagnostic ignored "-Wnonnull"
3195 errno = 0;
3196 ASSERT_EQ(EINVAL, pthread_setaffinity_np(pthread_self(), 0, nullptr));
3197 ASSERT_ERRNO(0);
3198#pragma clang diagnostic pop
3199}
Elliott Hughesfab5e6f2024-11-18 21:37:20 +00003200
3201TEST(pthread, pthread_setaffinity) {
3202 cpu_set_t set;
3203 CPU_ZERO(&set);
3204 ASSERT_EQ(0, pthread_getaffinity_np(pthread_self(), sizeof(set), &set));
3205 // It's hard to make any more general claim than this,
3206 // but it ought to be safe to ask for the same affinity you already have.
3207 ASSERT_EQ(0, pthread_setaffinity_np(pthread_self(), sizeof(set), &set));
3208}