blob: 1421365f811e95fd1ab4841560725cc41d8c7f04 [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
Dan Albertc4bcc752014-09-30 11:48:24 -070062TEST(pthread, pthread_keys_max) {
Yabin Cui6c238f22014-12-11 20:50:41 -080063 // POSIX says PTHREAD_KEYS_MAX should be at least _POSIX_THREAD_KEYS_MAX.
64 ASSERT_GE(PTHREAD_KEYS_MAX, _POSIX_THREAD_KEYS_MAX);
Dan Albertc4bcc752014-09-30 11:48:24 -070065}
Elliott Hughes718a5b52014-01-28 17:02:03 -080066
Yabin Cui6c238f22014-12-11 20:50:41 -080067TEST(pthread, sysconf_SC_THREAD_KEYS_MAX_eq_PTHREAD_KEYS_MAX) {
Dan Albertc4bcc752014-09-30 11:48:24 -070068 int sysconf_max = sysconf(_SC_THREAD_KEYS_MAX);
Yabin Cui6c238f22014-12-11 20:50:41 -080069 ASSERT_EQ(sysconf_max, PTHREAD_KEYS_MAX);
Dan Albertc4bcc752014-09-30 11:48:24 -070070}
71
72TEST(pthread, pthread_key_many_distinct) {
Yabin Cui6c238f22014-12-11 20:50:41 -080073 // As gtest uses pthread keys, we can't allocate exactly PTHREAD_KEYS_MAX
74 // pthread keys, but We should be able to allocate at least this many keys.
75 int nkeys = PTHREAD_KEYS_MAX / 2;
Dan Albertc4bcc752014-09-30 11:48:24 -070076 std::vector<pthread_key_t> keys;
77
Tom Cherryb8ab6182017-04-05 16:20:29 -070078 auto scope_guard = android::base::make_scope_guard([&keys] {
Elliott Hughes0b2acdf2015-10-02 18:25:19 -070079 for (const auto& key : keys) {
Dan Albertc4bcc752014-09-30 11:48:24 -070080 EXPECT_EQ(0, pthread_key_delete(key));
81 }
82 });
83
84 for (int i = 0; i < nkeys; ++i) {
85 pthread_key_t key;
Elliott Hughes61706932015-03-31 10:56:58 -070086 // If this fails, it's likely that LIBC_PTHREAD_KEY_RESERVED_COUNT is wrong.
Yi Kong32bc0fc2018-08-02 17:31:13 -070087 ASSERT_EQ(0, pthread_key_create(&key, nullptr)) << i << " of " << nkeys;
Dan Albertc4bcc752014-09-30 11:48:24 -070088 keys.push_back(key);
89 ASSERT_EQ(0, pthread_setspecific(key, reinterpret_cast<void*>(i)));
90 }
91
92 for (int i = keys.size() - 1; i >= 0; --i) {
93 ASSERT_EQ(reinterpret_cast<void*>(i), pthread_getspecific(keys.back()));
94 pthread_key_t key = keys.back();
95 keys.pop_back();
96 ASSERT_EQ(0, pthread_key_delete(key));
97 }
98}
99
Yabin Cui6c238f22014-12-11 20:50:41 -0800100TEST(pthread, pthread_key_not_exceed_PTHREAD_KEYS_MAX) {
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000101 std::vector<pthread_key_t> keys;
Dan Albertc4bcc752014-09-30 11:48:24 -0700102 int rv = 0;
Yabin Cui6c238f22014-12-11 20:50:41 -0800103
104 // Pthread keys are used by gtest, so PTHREAD_KEYS_MAX should
105 // be more than we are allowed to allocate now.
106 for (int i = 0; i < PTHREAD_KEYS_MAX; i++) {
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000107 pthread_key_t key;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700108 rv = pthread_key_create(&key, nullptr);
Dan Albertc4bcc752014-09-30 11:48:24 -0700109 if (rv == EAGAIN) {
110 break;
111 }
112 EXPECT_EQ(0, rv);
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000113 keys.push_back(key);
114 }
115
Dan Albertc4bcc752014-09-30 11:48:24 -0700116 // Don't leak keys.
Elliott Hughes0b2acdf2015-10-02 18:25:19 -0700117 for (const auto& key : keys) {
Dan Albertc4bcc752014-09-30 11:48:24 -0700118 EXPECT_EQ(0, pthread_key_delete(key));
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000119 }
Dan Albertc4bcc752014-09-30 11:48:24 -0700120 keys.clear();
121
122 // We should have eventually reached the maximum number of keys and received
123 // EAGAIN.
124 ASSERT_EQ(EAGAIN, rv);
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000125}
126
Elliott Hughesebb770f2014-06-25 13:46:46 -0700127TEST(pthread, pthread_key_delete) {
128 void* expected = reinterpret_cast<void*>(1234);
129 pthread_key_t key;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700130 ASSERT_EQ(0, pthread_key_create(&key, nullptr));
Elliott Hughesebb770f2014-06-25 13:46:46 -0700131 ASSERT_EQ(0, pthread_setspecific(key, expected));
132 ASSERT_EQ(expected, pthread_getspecific(key));
133 ASSERT_EQ(0, pthread_key_delete(key));
Yi Kong32bc0fc2018-08-02 17:31:13 -0700134 // After deletion, pthread_getspecific returns nullptr.
135 ASSERT_EQ(nullptr, pthread_getspecific(key));
Elliott Hughesebb770f2014-06-25 13:46:46 -0700136 // And you can't use pthread_setspecific with the deleted key.
137 ASSERT_EQ(EINVAL, pthread_setspecific(key, expected));
138}
139
Elliott Hughes40a52172014-07-30 14:48:10 -0700140TEST(pthread, pthread_key_fork) {
141 void* expected = reinterpret_cast<void*>(1234);
142 pthread_key_t key;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700143 ASSERT_EQ(0, pthread_key_create(&key, nullptr));
Elliott Hughes40a52172014-07-30 14:48:10 -0700144 ASSERT_EQ(0, pthread_setspecific(key, expected));
145 ASSERT_EQ(expected, pthread_getspecific(key));
146
147 pid_t pid = fork();
148 ASSERT_NE(-1, pid) << strerror(errno);
149
150 if (pid == 0) {
151 // The surviving thread inherits all the forking thread's TLS values...
152 ASSERT_EQ(expected, pthread_getspecific(key));
153 _exit(99);
154 }
155
Elliott Hughes33697a02016-01-26 13:04:57 -0800156 AssertChildExited(pid, 99);
Elliott Hughes40a52172014-07-30 14:48:10 -0700157
158 ASSERT_EQ(expected, pthread_getspecific(key));
Dan Albert1d53ae22014-09-02 15:24:26 -0700159 ASSERT_EQ(0, pthread_key_delete(key));
Elliott Hughes40a52172014-07-30 14:48:10 -0700160}
161
162static void* DirtyKeyFn(void* key) {
163 return pthread_getspecific(*reinterpret_cast<pthread_key_t*>(key));
164}
165
166TEST(pthread, pthread_key_dirty) {
167 pthread_key_t key;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700168 ASSERT_EQ(0, pthread_key_create(&key, nullptr));
Elliott Hughes40a52172014-07-30 14:48:10 -0700169
Yabin Cuia36158a2015-11-16 21:06:16 -0800170 size_t stack_size = 640 * 1024;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700171 void* stack = mmap(nullptr, stack_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
Elliott Hughes40a52172014-07-30 14:48:10 -0700172 ASSERT_NE(MAP_FAILED, stack);
173 memset(stack, 0xff, stack_size);
174
175 pthread_attr_t attr;
176 ASSERT_EQ(0, pthread_attr_init(&attr));
177 ASSERT_EQ(0, pthread_attr_setstack(&attr, stack, stack_size));
178
179 pthread_t t;
180 ASSERT_EQ(0, pthread_create(&t, &attr, DirtyKeyFn, &key));
181
182 void* result;
183 ASSERT_EQ(0, pthread_join(t, &result));
184 ASSERT_EQ(nullptr, result); // Not ~0!
185
186 ASSERT_EQ(0, munmap(stack, stack_size));
Dan Albert1d53ae22014-09-02 15:24:26 -0700187 ASSERT_EQ(0, pthread_key_delete(key));
Elliott Hughes40a52172014-07-30 14:48:10 -0700188}
189
Florian Mayerf9666202023-02-28 14:26:06 -0800190static void* FnWithStackFrame(void*) {
191 int x;
192 *const_cast<volatile int*>(&x) = 1;
193 return nullptr;
194}
195
196TEST(pthread, pthread_heap_allocated_stack) {
197 SKIP_WITH_HWASAN; // TODO(b/148982147): Re-enable when fixed.
198
199 size_t stack_size = 640 * 1024;
Elliott Hughes18e335b2023-04-21 11:18:40 -0700200 std::unique_ptr<char[]> stack(new (std::align_val_t(getpagesize())) char[stack_size]);
201 memset(stack.get(), '\xff', stack_size);
Florian Mayerf9666202023-02-28 14:26:06 -0800202
203 pthread_attr_t attr;
204 ASSERT_EQ(0, pthread_attr_init(&attr));
Elliott Hughes18e335b2023-04-21 11:18:40 -0700205 ASSERT_EQ(0, pthread_attr_setstack(&attr, stack.get(), stack_size));
Florian Mayerf9666202023-02-28 14:26:06 -0800206
207 pthread_t t;
208 ASSERT_EQ(0, pthread_create(&t, &attr, FnWithStackFrame, nullptr));
209
210 void* result;
211 ASSERT_EQ(0, pthread_join(t, &result));
212}
213
Yabin Cui5ddbb3f2015-03-05 20:35:32 -0800214TEST(pthread, static_pthread_key_used_before_creation) {
215#if defined(__BIONIC__)
216 // See http://b/19625804. The bug is about a static/global pthread key being used before creation.
217 // So here tests if the static/global default value 0 can be detected as invalid key.
218 static pthread_key_t key;
219 ASSERT_EQ(nullptr, pthread_getspecific(key));
220 ASSERT_EQ(EINVAL, pthread_setspecific(key, nullptr));
221 ASSERT_EQ(EINVAL, pthread_key_delete(key));
222#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -0800223 GTEST_SKIP() << "bionic-only test";
Yabin Cui5ddbb3f2015-03-05 20:35:32 -0800224#endif
225}
226
Elliott Hughes4d014e12012-09-07 16:47:54 -0700227static void* IdFn(void* arg) {
228 return arg;
229}
230
Yabin Cui63481602014-12-01 17:41:04 -0800231class SpinFunctionHelper {
232 public:
233 SpinFunctionHelper() {
234 SpinFunctionHelper::spin_flag_ = true;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400235 }
Elliott Hughes0bd9d132017-11-02 13:11:13 -0700236
Yabin Cui63481602014-12-01 17:41:04 -0800237 ~SpinFunctionHelper() {
238 UnSpin();
239 }
Elliott Hughes0bd9d132017-11-02 13:11:13 -0700240
Yabin Cui63481602014-12-01 17:41:04 -0800241 auto GetFunction() -> void* (*)(void*) {
242 return SpinFunctionHelper::SpinFn;
243 }
244
245 void UnSpin() {
246 SpinFunctionHelper::spin_flag_ = false;
247 }
248
249 private:
250 static void* SpinFn(void*) {
251 while (spin_flag_) {}
Yi Kong32bc0fc2018-08-02 17:31:13 -0700252 return nullptr;
Yabin Cui63481602014-12-01 17:41:04 -0800253 }
Yabin Cuia36158a2015-11-16 21:06:16 -0800254 static std::atomic<bool> spin_flag_;
Yabin Cui63481602014-12-01 17:41:04 -0800255};
256
257// It doesn't matter if spin_flag_ is used in several tests,
258// because it is always set to false after each test. Each thread
259// loops on spin_flag_ can find it becomes false at some time.
Yabin Cuia36158a2015-11-16 21:06:16 -0800260std::atomic<bool> SpinFunctionHelper::spin_flag_;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400261
Elliott Hughes4d014e12012-09-07 16:47:54 -0700262static void* JoinFn(void* arg) {
Yi Kong32bc0fc2018-08-02 17:31:13 -0700263 return reinterpret_cast<void*>(pthread_join(reinterpret_cast<pthread_t>(arg), nullptr));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700264}
265
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400266static void AssertDetached(pthread_t t, bool is_detached) {
267 pthread_attr_t attr;
268 ASSERT_EQ(0, pthread_getattr_np(t, &attr));
269 int detach_state;
270 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &detach_state));
271 pthread_attr_destroy(&attr);
272 ASSERT_EQ(is_detached, (detach_state == PTHREAD_CREATE_DETACHED));
273}
274
Elliott Hughes7484c212017-02-02 02:41:38 +0000275static void MakeDeadThread(pthread_t& t) {
Yi Kong32bc0fc2018-08-02 17:31:13 -0700276 ASSERT_EQ(0, pthread_create(&t, nullptr, IdFn, nullptr));
277 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes7484c212017-02-02 02:41:38 +0000278}
279
Elliott Hughes4d014e12012-09-07 16:47:54 -0700280TEST(pthread, pthread_create) {
281 void* expected_result = reinterpret_cast<void*>(123);
282 // Can we create a thread?
283 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700284 ASSERT_EQ(0, pthread_create(&t, nullptr, IdFn, expected_result));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700285 // If we join, do we get the expected value back?
286 void* result;
287 ASSERT_EQ(0, pthread_join(t, &result));
288 ASSERT_EQ(expected_result, result);
289}
290
Elliott Hughes3e898472013-02-12 16:40:24 +0000291TEST(pthread, pthread_create_EAGAIN) {
292 pthread_attr_t attributes;
293 ASSERT_EQ(0, pthread_attr_init(&attributes));
294 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, static_cast<size_t>(-1) & ~(getpagesize() - 1)));
295
296 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700297 ASSERT_EQ(EAGAIN, pthread_create(&t, &attributes, IdFn, nullptr));
Elliott Hughes3e898472013-02-12 16:40:24 +0000298}
299
Elliott Hughes4d014e12012-09-07 16:47:54 -0700300TEST(pthread, pthread_no_join_after_detach) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700301 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800302
Elliott Hughes4d014e12012-09-07 16:47:54 -0700303 pthread_t t1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700304 ASSERT_EQ(0, pthread_create(&t1, nullptr, spin_helper.GetFunction(), nullptr));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700305
306 // After a pthread_detach...
307 ASSERT_EQ(0, pthread_detach(t1));
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400308 AssertDetached(t1, true);
Elliott Hughes4d014e12012-09-07 16:47:54 -0700309
310 // ...pthread_join should fail.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700311 ASSERT_EQ(EINVAL, pthread_join(t1, nullptr));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700312}
313
314TEST(pthread, pthread_no_op_detach_after_join) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700315 SpinFunctionHelper spin_helper;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400316
Elliott Hughes4d014e12012-09-07 16:47:54 -0700317 pthread_t t1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700318 ASSERT_EQ(0, pthread_create(&t1, nullptr, spin_helper.GetFunction(), nullptr));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700319
320 // If thread 2 is already waiting to join thread 1...
321 pthread_t t2;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700322 ASSERT_EQ(0, pthread_create(&t2, nullptr, JoinFn, reinterpret_cast<void*>(t1)));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700323
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400324 sleep(1); // (Give t2 a chance to call pthread_join.)
Elliott Hughes4d014e12012-09-07 16:47:54 -0700325
Yabin Cuibbb04322015-03-19 15:19:25 -0700326#if defined(__BIONIC__)
327 ASSERT_EQ(EINVAL, pthread_detach(t1));
328#else
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400329 ASSERT_EQ(0, pthread_detach(t1));
Yabin Cuibbb04322015-03-19 15:19:25 -0700330#endif
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400331 AssertDetached(t1, false);
332
Elliott Hughes725b2a92016-03-23 11:20:47 -0700333 spin_helper.UnSpin();
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400334
335 // ...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 -0700336 void* join_result;
337 ASSERT_EQ(0, pthread_join(t2, &join_result));
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700338 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700339}
Elliott Hughes14f19592012-10-29 10:19:44 -0700340
341TEST(pthread, pthread_join_self) {
Yi Kong32bc0fc2018-08-02 17:31:13 -0700342 ASSERT_EQ(EDEADLK, pthread_join(pthread_self(), nullptr));
Elliott Hughes14f19592012-10-29 10:19:44 -0700343}
Elliott Hughes4f251be2012-11-01 16:33:29 -0700344
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800345struct TestBug37410 {
346 pthread_t main_thread;
347 pthread_mutex_t mutex;
Elliott Hughes4f251be2012-11-01 16:33:29 -0700348
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800349 static void main() {
350 TestBug37410 data;
351 data.main_thread = pthread_self();
Yi Kong32bc0fc2018-08-02 17:31:13 -0700352 ASSERT_EQ(0, pthread_mutex_init(&data.mutex, nullptr));
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800353 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
354
355 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700356 ASSERT_EQ(0, pthread_create(&t, nullptr, TestBug37410::thread_fn, reinterpret_cast<void*>(&data)));
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800357
358 // Wait for the thread to be running...
359 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
360 ASSERT_EQ(0, pthread_mutex_unlock(&data.mutex));
361
362 // ...and exit.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700363 pthread_exit(nullptr);
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800364 }
365
366 private:
367 static void* thread_fn(void* arg) {
368 TestBug37410* data = reinterpret_cast<TestBug37410*>(arg);
369
Evgenii Stepanov352853a2019-02-05 17:37:37 -0800370 // Unlocking data->mutex will cause the main thread to exit, invalidating *data. Save the handle.
371 pthread_t main_thread = data->main_thread;
372
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800373 // Let the main thread know we're running.
374 pthread_mutex_unlock(&data->mutex);
375
376 // And wait for the main thread to exit.
Evgenii Stepanov352853a2019-02-05 17:37:37 -0800377 pthread_join(main_thread, nullptr);
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800378
Yi Kong32bc0fc2018-08-02 17:31:13 -0700379 return nullptr;
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800380 }
381};
Elliott Hughes4f251be2012-11-01 16:33:29 -0700382
Elliott Hughes7fd803c2013-02-14 16:33:52 -0800383// Even though this isn't really a death test, we have to say "DeathTest" here so gtest knows to
384// run this test (which exits normally) in its own process.
Yabin Cui9df70402014-11-05 18:01:01 -0800385TEST_F(pthread_DeathTest, pthread_bug_37410) {
Elliott Hughes4f251be2012-11-01 16:33:29 -0700386 // http://code.google.com/p/android/issues/detail?id=37410
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800387 ASSERT_EXIT(TestBug37410::main(), ::testing::ExitedWithCode(0), "");
Elliott Hughes4f251be2012-11-01 16:33:29 -0700388}
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800389
390static void* SignalHandlerFn(void* arg) {
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800391 sigset64_t wait_set;
392 sigfillset64(&wait_set);
393 return reinterpret_cast<void*>(sigwait64(&wait_set, reinterpret_cast<int*>(arg)));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800394}
395
396TEST(pthread, pthread_sigmask) {
Elliott Hughes19e62322013-10-15 11:23:57 -0700397 // Check that SIGUSR1 isn't blocked.
398 sigset_t original_set;
399 sigemptyset(&original_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700400 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, nullptr, &original_set));
Elliott Hughes19e62322013-10-15 11:23:57 -0700401 ASSERT_FALSE(sigismember(&original_set, SIGUSR1));
402
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800403 // Block SIGUSR1.
404 sigset_t set;
405 sigemptyset(&set);
406 sigaddset(&set, SIGUSR1);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700407 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, &set, nullptr));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800408
Elliott Hughes19e62322013-10-15 11:23:57 -0700409 // Check that SIGUSR1 is blocked.
410 sigset_t final_set;
411 sigemptyset(&final_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700412 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, nullptr, &final_set));
Elliott Hughes19e62322013-10-15 11:23:57 -0700413 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
414 // ...and that sigprocmask agrees with pthread_sigmask.
415 sigemptyset(&final_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700416 ASSERT_EQ(0, sigprocmask(SIG_BLOCK, nullptr, &final_set));
Elliott Hughes19e62322013-10-15 11:23:57 -0700417 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
418
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800419 // Spawn a thread that calls sigwait and tells us what it received.
420 pthread_t signal_thread;
421 int received_signal = -1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700422 ASSERT_EQ(0, pthread_create(&signal_thread, nullptr, SignalHandlerFn, &received_signal));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800423
424 // Send that thread SIGUSR1.
425 pthread_kill(signal_thread, SIGUSR1);
426
427 // See what it got.
428 void* join_result;
429 ASSERT_EQ(0, pthread_join(signal_thread, &join_result));
430 ASSERT_EQ(SIGUSR1, received_signal);
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700431 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
Elliott Hughes19e62322013-10-15 11:23:57 -0700432
433 // Restore the original signal mask.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700434 ASSERT_EQ(0, pthread_sigmask(SIG_SETMASK, &original_set, nullptr));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800435}
Elliott Hughes5e3fc432013-02-11 16:36:48 -0800436
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800437TEST(pthread, pthread_sigmask64_SIGTRMIN) {
438 // Check that SIGRTMIN isn't blocked.
439 sigset64_t original_set;
440 sigemptyset64(&original_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700441 ASSERT_EQ(0, pthread_sigmask64(SIG_BLOCK, nullptr, &original_set));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800442 ASSERT_FALSE(sigismember64(&original_set, SIGRTMIN));
443
444 // Block SIGRTMIN.
445 sigset64_t set;
446 sigemptyset64(&set);
447 sigaddset64(&set, SIGRTMIN);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700448 ASSERT_EQ(0, pthread_sigmask64(SIG_BLOCK, &set, nullptr));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800449
450 // Check that SIGRTMIN is blocked.
451 sigset64_t final_set;
452 sigemptyset64(&final_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700453 ASSERT_EQ(0, pthread_sigmask64(SIG_BLOCK, nullptr, &final_set));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800454 ASSERT_TRUE(sigismember64(&final_set, SIGRTMIN));
455 // ...and that sigprocmask64 agrees with pthread_sigmask64.
456 sigemptyset64(&final_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700457 ASSERT_EQ(0, sigprocmask64(SIG_BLOCK, nullptr, &final_set));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800458 ASSERT_TRUE(sigismember64(&final_set, SIGRTMIN));
459
460 // Spawn a thread that calls sigwait64 and tells us what it received.
461 pthread_t signal_thread;
462 int received_signal = -1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700463 ASSERT_EQ(0, pthread_create(&signal_thread, nullptr, SignalHandlerFn, &received_signal));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800464
465 // Send that thread SIGRTMIN.
466 pthread_kill(signal_thread, SIGRTMIN);
467
468 // See what it got.
469 void* join_result;
470 ASSERT_EQ(0, pthread_join(signal_thread, &join_result));
471 ASSERT_EQ(SIGRTMIN, received_signal);
472 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
473
474 // Restore the original signal mask.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700475 ASSERT_EQ(0, pthread_sigmask64(SIG_SETMASK, &original_set, nullptr));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800476}
477
Elliott Hughes725b2a92016-03-23 11:20:47 -0700478static void test_pthread_setname_np__pthread_getname_np(pthread_t t) {
479 ASSERT_EQ(0, pthread_setname_np(t, "short"));
480 char name[32];
481 ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name)));
482 ASSERT_STREQ("short", name);
483
Elliott Hughesd1aea302015-04-25 10:05:24 -0700484 // The limit is 15 characters --- the kernel's buffer is 16, but includes a NUL.
Elliott Hughes725b2a92016-03-23 11:20:47 -0700485 ASSERT_EQ(0, pthread_setname_np(t, "123456789012345"));
486 ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name)));
487 ASSERT_STREQ("123456789012345", name);
488
489 ASSERT_EQ(ERANGE, pthread_setname_np(t, "1234567890123456"));
490
491 // The passed-in buffer should be at least 16 bytes.
492 ASSERT_EQ(0, pthread_getname_np(t, name, 16));
493 ASSERT_EQ(ERANGE, pthread_getname_np(t, name, 15));
Elliott Hughes3e898472013-02-12 16:40:24 +0000494}
495
Elliott Hughes725b2a92016-03-23 11:20:47 -0700496TEST(pthread, pthread_setname_np__pthread_getname_np__self) {
497 test_pthread_setname_np__pthread_getname_np(pthread_self());
Elliott Hughes3e898472013-02-12 16:40:24 +0000498}
499
Elliott Hughes725b2a92016-03-23 11:20:47 -0700500TEST(pthread, pthread_setname_np__pthread_getname_np__other) {
501 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800502
Elliott Hughes725b2a92016-03-23 11:20:47 -0700503 pthread_t t;
Elliott Hughes4d098ca2016-04-11 12:43:05 -0700504 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
505 test_pthread_setname_np__pthread_getname_np(t);
506 spin_helper.UnSpin();
507 ASSERT_EQ(0, pthread_join(t, nullptr));
508}
509
510// http://b/28051133: a kernel misfeature means that you can't change the
511// name of another thread if you've set PR_SET_DUMPABLE to 0.
512TEST(pthread, pthread_setname_np__pthread_getname_np__other_PR_SET_DUMPABLE) {
513 ASSERT_EQ(0, prctl(PR_SET_DUMPABLE, 0)) << strerror(errno);
514
515 SpinFunctionHelper spin_helper;
516
517 pthread_t t;
518 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
Elliott Hughes725b2a92016-03-23 11:20:47 -0700519 test_pthread_setname_np__pthread_getname_np(t);
520 spin_helper.UnSpin();
521 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes3e898472013-02-12 16:40:24 +0000522}
523
Elliott Hughes11859d42017-02-13 17:59:29 -0800524TEST_F(pthread_DeathTest, pthread_setname_np__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000525 pthread_t dead_thread;
526 MakeDeadThread(dead_thread);
527
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800528 EXPECT_DEATH(pthread_setname_np(dead_thread, "short 3"),
529 "invalid pthread_t (.*) passed to pthread_setname_np");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800530}
531
532TEST_F(pthread_DeathTest, pthread_setname_np__null_thread) {
533 pthread_t null_thread = 0;
534 EXPECT_EQ(ENOENT, pthread_setname_np(null_thread, "short 3"));
Elliott Hughes11859d42017-02-13 17:59:29 -0800535}
536
537TEST_F(pthread_DeathTest, pthread_getname_np__no_such_thread) {
538 pthread_t dead_thread;
539 MakeDeadThread(dead_thread);
540
Elliott Hughesbcb15292017-02-07 21:05:30 +0000541 char name[64];
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800542 EXPECT_DEATH(pthread_getname_np(dead_thread, name, sizeof(name)),
543 "invalid pthread_t (.*) passed to pthread_getname_np");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800544}
545
546TEST_F(pthread_DeathTest, pthread_getname_np__null_thread) {
547 pthread_t null_thread = 0;
548
549 char name[64];
550 EXPECT_EQ(ENOENT, pthread_getname_np(null_thread, name, sizeof(name)));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000551}
552
Elliott Hughes9d23e042013-02-15 19:21:51 -0800553TEST(pthread, pthread_kill__0) {
554 // Signal 0 just tests that the thread exists, so it's safe to call on ourselves.
555 ASSERT_EQ(0, pthread_kill(pthread_self(), 0));
556}
557
558TEST(pthread, pthread_kill__invalid_signal) {
559 ASSERT_EQ(EINVAL, pthread_kill(pthread_self(), -1));
560}
561
Elliott Hughesfae89fc2013-02-21 11:22:23 -0800562static void pthread_kill__in_signal_handler_helper(int signal_number) {
563 static int count = 0;
564 ASSERT_EQ(SIGALRM, signal_number);
565 if (++count == 1) {
566 // Can we call pthread_kill from a signal handler?
567 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
568 }
569}
570
571TEST(pthread, pthread_kill__in_signal_handler) {
Elliott Hughes4b558f52014-03-04 15:58:02 -0800572 ScopedSignalHandler ssh(SIGALRM, pthread_kill__in_signal_handler_helper);
Elliott Hughesfae89fc2013-02-21 11:22:23 -0800573 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
574}
575
Josh Gaoddf757e2018-10-17 15:23:03 -0700576TEST(pthread, pthread_kill__exited_thread) {
577 static std::promise<pid_t> tid_promise;
578 pthread_t thread;
579 ASSERT_EQ(0, pthread_create(&thread, nullptr,
580 [](void*) -> void* {
581 tid_promise.set_value(gettid());
582 return nullptr;
583 },
584 nullptr));
585
586 pid_t tid = tid_promise.get_future().get();
587 while (TEMP_FAILURE_RETRY(syscall(__NR_tgkill, getpid(), tid, 0)) != -1) {
588 continue;
589 }
Elliott Hughes95646e62023-09-21 14:11:19 -0700590 ASSERT_ERRNO(ESRCH);
Josh Gaoddf757e2018-10-17 15:23:03 -0700591
592 ASSERT_EQ(ESRCH, pthread_kill(thread, 0));
593}
594
Elliott Hughes11859d42017-02-13 17:59:29 -0800595TEST_F(pthread_DeathTest, pthread_detach__no_such_thread) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000596 pthread_t dead_thread;
597 MakeDeadThread(dead_thread);
598
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800599 EXPECT_DEATH(pthread_detach(dead_thread),
600 "invalid pthread_t (.*) passed to pthread_detach");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800601}
602
603TEST_F(pthread_DeathTest, pthread_detach__null_thread) {
604 pthread_t null_thread = 0;
605 EXPECT_EQ(ESRCH, pthread_detach(null_thread));
Elliott Hughes7484c212017-02-02 02:41:38 +0000606}
607
Jeff Hao9b06cc32013-08-15 14:51:16 -0700608TEST(pthread, pthread_getcpuclockid__clock_gettime) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700609 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800610
Jeff Hao9b06cc32013-08-15 14:51:16 -0700611 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700612 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
Jeff Hao9b06cc32013-08-15 14:51:16 -0700613
614 clockid_t c;
615 ASSERT_EQ(0, pthread_getcpuclockid(t, &c));
616 timespec ts;
617 ASSERT_EQ(0, clock_gettime(c, &ts));
Elliott Hughes725b2a92016-03-23 11:20:47 -0700618 spin_helper.UnSpin();
Yabin Cuia36158a2015-11-16 21:06:16 -0800619 ASSERT_EQ(0, pthread_join(t, nullptr));
Jeff Hao9b06cc32013-08-15 14:51:16 -0700620}
621
Elliott Hughes11859d42017-02-13 17:59:29 -0800622TEST_F(pthread_DeathTest, pthread_getcpuclockid__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000623 pthread_t dead_thread;
624 MakeDeadThread(dead_thread);
625
626 clockid_t c;
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800627 EXPECT_DEATH(pthread_getcpuclockid(dead_thread, &c),
628 "invalid pthread_t (.*) passed to pthread_getcpuclockid");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800629}
630
631TEST_F(pthread_DeathTest, pthread_getcpuclockid__null_thread) {
632 pthread_t null_thread = 0;
633 clockid_t c;
634 EXPECT_EQ(ESRCH, pthread_getcpuclockid(null_thread, &c));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000635}
636
Elliott Hughes11859d42017-02-13 17:59:29 -0800637TEST_F(pthread_DeathTest, pthread_getschedparam__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000638 pthread_t dead_thread;
639 MakeDeadThread(dead_thread);
640
641 int policy;
642 sched_param param;
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800643 EXPECT_DEATH(pthread_getschedparam(dead_thread, &policy, &param),
644 "invalid pthread_t (.*) passed to pthread_getschedparam");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800645}
646
647TEST_F(pthread_DeathTest, pthread_getschedparam__null_thread) {
648 pthread_t null_thread = 0;
649 int policy;
650 sched_param param;
651 EXPECT_EQ(ESRCH, pthread_getschedparam(null_thread, &policy, &param));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000652}
653
Elliott Hughes11859d42017-02-13 17:59:29 -0800654TEST_F(pthread_DeathTest, pthread_setschedparam__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000655 pthread_t dead_thread;
656 MakeDeadThread(dead_thread);
657
658 int policy = 0;
659 sched_param param;
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800660 EXPECT_DEATH(pthread_setschedparam(dead_thread, policy, &param),
661 "invalid pthread_t (.*) passed to pthread_setschedparam");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800662}
663
664TEST_F(pthread_DeathTest, pthread_setschedparam__null_thread) {
665 pthread_t null_thread = 0;
666 int policy = 0;
667 sched_param param;
668 EXPECT_EQ(ESRCH, pthread_setschedparam(null_thread, policy, &param));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000669}
670
Elliott Hughesdff08ce2017-10-16 09:58:45 -0700671TEST_F(pthread_DeathTest, pthread_setschedprio__no_such_thread) {
672 pthread_t dead_thread;
673 MakeDeadThread(dead_thread);
674
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800675 EXPECT_DEATH(pthread_setschedprio(dead_thread, 123),
676 "invalid pthread_t (.*) passed to pthread_setschedprio");
Elliott Hughesdff08ce2017-10-16 09:58:45 -0700677}
678
679TEST_F(pthread_DeathTest, pthread_setschedprio__null_thread) {
680 pthread_t null_thread = 0;
681 EXPECT_EQ(ESRCH, pthread_setschedprio(null_thread, 123));
682}
683
Elliott Hughes11859d42017-02-13 17:59:29 -0800684TEST_F(pthread_DeathTest, pthread_join__no_such_thread) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000685 pthread_t dead_thread;
686 MakeDeadThread(dead_thread);
687
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800688 EXPECT_DEATH(pthread_join(dead_thread, nullptr),
689 "invalid pthread_t (.*) passed to pthread_join");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800690}
691
692TEST_F(pthread_DeathTest, pthread_join__null_thread) {
693 pthread_t null_thread = 0;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700694 EXPECT_EQ(ESRCH, pthread_join(null_thread, nullptr));
Elliott Hughes7484c212017-02-02 02:41:38 +0000695}
696
Elliott Hughes11859d42017-02-13 17:59:29 -0800697TEST_F(pthread_DeathTest, pthread_kill__no_such_thread) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000698 pthread_t dead_thread;
699 MakeDeadThread(dead_thread);
700
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800701 EXPECT_DEATH(pthread_kill(dead_thread, 0),
702 "invalid pthread_t (.*) passed to pthread_kill");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800703}
704
705TEST_F(pthread_DeathTest, pthread_kill__null_thread) {
706 pthread_t null_thread = 0;
707 EXPECT_EQ(ESRCH, pthread_kill(null_thread, 0));
Elliott Hughes7484c212017-02-02 02:41:38 +0000708}
709
msg5550f020d12013-06-06 14:59:28 -0400710TEST(pthread, pthread_join__multijoin) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700711 SpinFunctionHelper spin_helper;
msg5550f020d12013-06-06 14:59:28 -0400712
713 pthread_t t1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700714 ASSERT_EQ(0, pthread_create(&t1, nullptr, spin_helper.GetFunction(), nullptr));
msg5550f020d12013-06-06 14:59:28 -0400715
716 pthread_t t2;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700717 ASSERT_EQ(0, pthread_create(&t2, nullptr, JoinFn, reinterpret_cast<void*>(t1)));
msg5550f020d12013-06-06 14:59:28 -0400718
719 sleep(1); // (Give t2 a chance to call pthread_join.)
720
721 // Multiple joins to the same thread should fail.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700722 ASSERT_EQ(EINVAL, pthread_join(t1, nullptr));
msg5550f020d12013-06-06 14:59:28 -0400723
Elliott Hughes725b2a92016-03-23 11:20:47 -0700724 spin_helper.UnSpin();
msg5550f020d12013-06-06 14:59:28 -0400725
726 // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes).
727 void* join_result;
728 ASSERT_EQ(0, pthread_join(t2, &join_result));
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700729 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
msg5550f020d12013-06-06 14:59:28 -0400730}
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700731
Elliott Hughes70b24b12013-11-15 11:51:07 -0800732TEST(pthread, pthread_join__race) {
733 // http://b/11693195 --- pthread_join could return before the thread had actually exited.
734 // If the joiner unmapped the thread's stack, that could lead to SIGSEGV in the thread.
735 for (size_t i = 0; i < 1024; ++i) {
Yabin Cuia36158a2015-11-16 21:06:16 -0800736 size_t stack_size = 640*1024;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700737 void* stack = mmap(nullptr, stack_size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
Elliott Hughes70b24b12013-11-15 11:51:07 -0800738
739 pthread_attr_t a;
740 pthread_attr_init(&a);
741 pthread_attr_setstack(&a, stack, stack_size);
742
743 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700744 ASSERT_EQ(0, pthread_create(&t, &a, IdFn, nullptr));
745 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes70b24b12013-11-15 11:51:07 -0800746 ASSERT_EQ(0, munmap(stack, stack_size));
747 }
748}
749
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700750static void* GetActualGuardSizeFn(void* arg) {
751 pthread_attr_t attributes;
752 pthread_getattr_np(pthread_self(), &attributes);
753 pthread_attr_getguardsize(&attributes, reinterpret_cast<size_t*>(arg));
Yi Kong32bc0fc2018-08-02 17:31:13 -0700754 return nullptr;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700755}
756
757static size_t GetActualGuardSize(const pthread_attr_t& attributes) {
758 size_t result;
759 pthread_t t;
760 pthread_create(&t, &attributes, GetActualGuardSizeFn, &result);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700761 pthread_join(t, nullptr);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700762 return result;
763}
764
765static void* GetActualStackSizeFn(void* arg) {
766 pthread_attr_t attributes;
767 pthread_getattr_np(pthread_self(), &attributes);
768 pthread_attr_getstacksize(&attributes, reinterpret_cast<size_t*>(arg));
Yi Kong32bc0fc2018-08-02 17:31:13 -0700769 return nullptr;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700770}
771
772static size_t GetActualStackSize(const pthread_attr_t& attributes) {
773 size_t result;
774 pthread_t t;
775 pthread_create(&t, &attributes, GetActualStackSizeFn, &result);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700776 pthread_join(t, nullptr);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700777 return result;
778}
779
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700780TEST(pthread, pthread_attr_setguardsize_tiny) {
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700781 pthread_attr_t attributes;
782 ASSERT_EQ(0, pthread_attr_init(&attributes));
783
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700784 // No such thing as too small: will be rounded up to one page by pthread_create.
785 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 128));
786 size_t guard_size;
787 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
788 ASSERT_EQ(128U, guard_size);
Juan Yescas65af9a82023-12-07 11:35:21 -0800789 ASSERT_EQ(static_cast<unsigned long>(getpagesize()), GetActualGuardSize(attributes));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700790}
791
792TEST(pthread, pthread_attr_setguardsize_reasonable) {
793 pthread_attr_t attributes;
794 ASSERT_EQ(0, pthread_attr_init(&attributes));
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700795
796 // Large enough and a multiple of the page size.
797 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700798 size_t guard_size;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700799 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
800 ASSERT_EQ(32*1024U, guard_size);
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700801 ASSERT_EQ(32*1024U, GetActualGuardSize(attributes));
802}
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700803
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700804TEST(pthread, pthread_attr_setguardsize_needs_rounding) {
805 pthread_attr_t attributes;
806 ASSERT_EQ(0, pthread_attr_init(&attributes));
807
808 // Large enough but not a multiple of the page size.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700809 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024 + 1));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700810 size_t guard_size;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700811 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
812 ASSERT_EQ(32*1024U + 1, guard_size);
Juan Yescas65af9a82023-12-07 11:35:21 -0800813 ASSERT_EQ(roundup(32 * 1024U + 1, getpagesize()), GetActualGuardSize(attributes));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700814}
815
816TEST(pthread, pthread_attr_setguardsize_enormous) {
817 pthread_attr_t attributes;
818 ASSERT_EQ(0, pthread_attr_init(&attributes));
819
820 // Larger than the stack itself. (Historically we mistakenly carved
821 // the guard out of the stack itself, rather than adding it after the
822 // end.)
823 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024*1024));
824 size_t guard_size;
825 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
826 ASSERT_EQ(32*1024*1024U, guard_size);
827 ASSERT_EQ(32*1024*1024U, GetActualGuardSize(attributes));
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700828}
829
830TEST(pthread, pthread_attr_setstacksize) {
831 pthread_attr_t attributes;
832 ASSERT_EQ(0, pthread_attr_init(&attributes));
833
834 // Get the default stack size.
835 size_t default_stack_size;
836 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &default_stack_size));
837
838 // Too small.
839 ASSERT_EQ(EINVAL, pthread_attr_setstacksize(&attributes, 128));
840 size_t stack_size;
841 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
842 ASSERT_EQ(default_stack_size, stack_size);
843 ASSERT_GE(GetActualStackSize(attributes), default_stack_size);
844
Yabin Cui917d3902015-01-08 12:32:42 -0800845 // Large enough and a multiple of the page size; may be rounded up by pthread_create.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700846 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024));
847 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
848 ASSERT_EQ(32*1024U, stack_size);
Yabin Cui917d3902015-01-08 12:32:42 -0800849 ASSERT_GE(GetActualStackSize(attributes), 32*1024U);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700850
Yabin Cui917d3902015-01-08 12:32:42 -0800851 // Large enough but not aligned; will be rounded up by pthread_create.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700852 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024 + 1));
853 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
854 ASSERT_EQ(32*1024U + 1, stack_size);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800855#if defined(__BIONIC__)
Yabin Cui917d3902015-01-08 12:32:42 -0800856 ASSERT_GT(GetActualStackSize(attributes), 32*1024U + 1);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800857#else // __BIONIC__
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700858 // glibc rounds down, in violation of POSIX. They document this in their BUGS section.
859 ASSERT_EQ(GetActualStackSize(attributes), 32*1024U);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800860#endif // __BIONIC__
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700861}
Elliott Hughesc3f11402013-10-30 14:40:09 -0700862
Yabin Cui76615da2015-03-17 14:22:09 -0700863TEST(pthread, pthread_rwlockattr_smoke) {
864 pthread_rwlockattr_t attr;
865 ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
866
867 int pshared_value_array[] = {PTHREAD_PROCESS_PRIVATE, PTHREAD_PROCESS_SHARED};
868 for (size_t i = 0; i < sizeof(pshared_value_array) / sizeof(pshared_value_array[0]); ++i) {
869 ASSERT_EQ(0, pthread_rwlockattr_setpshared(&attr, pshared_value_array[i]));
870 int pshared;
871 ASSERT_EQ(0, pthread_rwlockattr_getpshared(&attr, &pshared));
872 ASSERT_EQ(pshared_value_array[i], pshared);
873 }
874
Colin Cross4c5595c2021-08-16 15:51:59 -0700875#if !defined(ANDROID_HOST_MUSL)
Colin Cross7da20342021-07-28 11:18:11 -0700876 // musl doesn't have pthread_rwlockattr_setkind_np
Yabin Cui76615da2015-03-17 14:22:09 -0700877 int kind_array[] = {PTHREAD_RWLOCK_PREFER_READER_NP,
878 PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP};
879 for (size_t i = 0; i < sizeof(kind_array) / sizeof(kind_array[0]); ++i) {
880 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_array[i]));
881 int kind;
882 ASSERT_EQ(0, pthread_rwlockattr_getkind_np(&attr, &kind));
883 ASSERT_EQ(kind_array[i], kind);
884 }
Colin Cross7da20342021-07-28 11:18:11 -0700885#endif
Yabin Cui76615da2015-03-17 14:22:09 -0700886
887 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
888}
889
890TEST(pthread, pthread_rwlock_init_same_as_PTHREAD_RWLOCK_INITIALIZER) {
891 pthread_rwlock_t lock1 = PTHREAD_RWLOCK_INITIALIZER;
892 pthread_rwlock_t lock2;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700893 ASSERT_EQ(0, pthread_rwlock_init(&lock2, nullptr));
Yabin Cui76615da2015-03-17 14:22:09 -0700894 ASSERT_EQ(0, memcmp(&lock1, &lock2, sizeof(lock1)));
895}
896
Elliott Hughesc3f11402013-10-30 14:40:09 -0700897TEST(pthread, pthread_rwlock_smoke) {
898 pthread_rwlock_t l;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700899 ASSERT_EQ(0, pthread_rwlock_init(&l, nullptr));
Elliott Hughesc3f11402013-10-30 14:40:09 -0700900
Calin Juravle76f352e2014-05-19 13:41:10 +0100901 // Single read lock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700902 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
903 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
904
Calin Juravle76f352e2014-05-19 13:41:10 +0100905 // Multiple read lock
906 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
907 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
908 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
909 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
910
911 // Write lock
Calin Juravle92687e42014-05-22 19:21:22 +0100912 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
913 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100914
915 // Try writer lock
916 ASSERT_EQ(0, pthread_rwlock_trywrlock(&l));
917 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
918 ASSERT_EQ(EBUSY, pthread_rwlock_tryrdlock(&l));
919 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
920
921 // Try reader lock
922 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
923 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
924 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
925 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
926 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
927
928 // Try writer lock after unlock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700929 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
930 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
931
Calin Juravle76f352e2014-05-19 13:41:10 +0100932 // EDEADLK in "read after write"
933 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
934 ASSERT_EQ(EDEADLK, pthread_rwlock_rdlock(&l));
935 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
936
937 // EDEADLK in "write after write"
938 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
939 ASSERT_EQ(EDEADLK, pthread_rwlock_wrlock(&l));
940 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100941
Elliott Hughesc3f11402013-10-30 14:40:09 -0700942 ASSERT_EQ(0, pthread_rwlock_destroy(&l));
943}
944
Yabin Cui08ee8d22015-02-11 17:04:36 -0800945struct RwlockWakeupHelperArg {
946 pthread_rwlock_t lock;
947 enum Progress {
948 LOCK_INITIALIZED,
949 LOCK_WAITING,
950 LOCK_RELEASED,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800951 LOCK_ACCESSED,
952 LOCK_TIMEDOUT,
Yabin Cui08ee8d22015-02-11 17:04:36 -0800953 };
954 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -0700955 std::atomic<pid_t> tid;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800956 std::function<int (pthread_rwlock_t*)> trylock_function;
957 std::function<int (pthread_rwlock_t*)> lock_function;
958 std::function<int (pthread_rwlock_t*, const timespec*)> timed_lock_function;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -0800959 clockid_t clock;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800960};
961
Yabin Cuic9a659c2015-11-05 15:36:08 -0800962static void pthread_rwlock_wakeup_helper(RwlockWakeupHelperArg* arg) {
Yabin Cuif7969852015-04-02 17:47:48 -0700963 arg->tid = gettid();
Yabin Cui08ee8d22015-02-11 17:04:36 -0800964 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
965 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
966
Yabin Cuic9a659c2015-11-05 15:36:08 -0800967 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
968 ASSERT_EQ(0, arg->lock_function(&arg->lock));
Yabin Cui08ee8d22015-02-11 17:04:36 -0800969 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_RELEASED, arg->progress);
970 ASSERT_EQ(0, pthread_rwlock_unlock(&arg->lock));
971
972 arg->progress = RwlockWakeupHelperArg::LOCK_ACCESSED;
973}
974
Yabin Cuic9a659c2015-11-05 15:36:08 -0800975static void test_pthread_rwlock_reader_wakeup_writer(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -0800976 RwlockWakeupHelperArg wakeup_arg;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700977 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -0800978 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
979 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -0700980 wakeup_arg.tid = 0;
Tom Cherry60ddedf2018-02-20 15:40:02 -0800981 wakeup_arg.trylock_function = &pthread_rwlock_trywrlock;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800982 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800983
984 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700985 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800986 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -0700987 WaitUntilThreadSleep(wakeup_arg.tid);
988 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
989
Yabin Cui08ee8d22015-02-11 17:04:36 -0800990 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
991 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
992
Yi Kong32bc0fc2018-08-02 17:31:13 -0700993 ASSERT_EQ(0, pthread_join(thread, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -0800994 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
995 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
996}
997
Yabin Cuic9a659c2015-11-05 15:36:08 -0800998TEST(pthread, pthread_rwlock_reader_wakeup_writer) {
999 test_pthread_rwlock_reader_wakeup_writer(pthread_rwlock_wrlock);
Yabin Cui08ee8d22015-02-11 17:04:36 -08001000}
1001
Yabin Cuic9a659c2015-11-05 15:36:08 -08001002TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait) {
1003 timespec ts;
1004 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1005 ts.tv_sec += 1;
1006 test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) {
1007 return pthread_rwlock_timedwrlock(lock, &ts);
1008 });
1009}
1010
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001011TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait_monotonic_np) {
1012#if defined(__BIONIC__)
1013 timespec ts;
1014 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1015 ts.tv_sec += 1;
1016 test_pthread_rwlock_reader_wakeup_writer(
1017 [&](pthread_rwlock_t* lock) { return pthread_rwlock_timedwrlock_monotonic_np(lock, &ts); });
1018#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001019 GTEST_SKIP() << "pthread_rwlock_timedwrlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001020#endif // __BIONIC__
1021}
1022
Tom Cherry69010802019-05-07 20:33:05 -07001023TEST(pthread, pthread_rwlock_reader_wakeup_writer_clockwait) {
1024#if defined(__BIONIC__)
1025 timespec ts;
1026 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1027 ts.tv_sec += 1;
1028 test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) {
1029 return pthread_rwlock_clockwrlock(lock, CLOCK_MONOTONIC, &ts);
1030 });
1031
1032 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1033 ts.tv_sec += 1;
1034 test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) {
1035 return pthread_rwlock_clockwrlock(lock, CLOCK_REALTIME, &ts);
1036 });
1037#else // __BIONIC__
1038 GTEST_SKIP() << "pthread_rwlock_clockwrlock not available";
1039#endif // __BIONIC__
1040}
1041
Yabin Cuic9a659c2015-11-05 15:36:08 -08001042static void test_pthread_rwlock_writer_wakeup_reader(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -08001043 RwlockWakeupHelperArg wakeup_arg;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001044 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -08001045 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
1046 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -07001047 wakeup_arg.tid = 0;
Tom Cherry60ddedf2018-02-20 15:40:02 -08001048 wakeup_arg.trylock_function = &pthread_rwlock_tryrdlock;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001049 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -08001050
1051 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001052 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cuic9a659c2015-11-05 15:36:08 -08001053 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -07001054 WaitUntilThreadSleep(wakeup_arg.tid);
1055 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
1056
Yabin Cui08ee8d22015-02-11 17:04:36 -08001057 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
1058 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
1059
Yi Kong32bc0fc2018-08-02 17:31:13 -07001060 ASSERT_EQ(0, pthread_join(thread, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -08001061 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
1062 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
1063}
1064
Yabin Cuic9a659c2015-11-05 15:36:08 -08001065TEST(pthread, pthread_rwlock_writer_wakeup_reader) {
1066 test_pthread_rwlock_writer_wakeup_reader(pthread_rwlock_rdlock);
1067}
1068
1069TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait) {
1070 timespec ts;
1071 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1072 ts.tv_sec += 1;
1073 test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) {
1074 return pthread_rwlock_timedrdlock(lock, &ts);
1075 });
1076}
1077
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001078TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait_monotonic_np) {
1079#if defined(__BIONIC__)
1080 timespec ts;
1081 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1082 ts.tv_sec += 1;
1083 test_pthread_rwlock_writer_wakeup_reader(
1084 [&](pthread_rwlock_t* lock) { return pthread_rwlock_timedrdlock_monotonic_np(lock, &ts); });
1085#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001086 GTEST_SKIP() << "pthread_rwlock_timedrdlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001087#endif // __BIONIC__
1088}
1089
Tom Cherry69010802019-05-07 20:33:05 -07001090TEST(pthread, pthread_rwlock_writer_wakeup_reader_clockwait) {
1091#if defined(__BIONIC__)
1092 timespec ts;
1093 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1094 ts.tv_sec += 1;
1095 test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) {
1096 return pthread_rwlock_clockrdlock(lock, CLOCK_MONOTONIC, &ts);
1097 });
1098
1099 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1100 ts.tv_sec += 1;
1101 test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) {
1102 return pthread_rwlock_clockrdlock(lock, CLOCK_REALTIME, &ts);
1103 });
1104#else // __BIONIC__
1105 GTEST_SKIP() << "pthread_rwlock_clockrdlock not available";
1106#endif // __BIONIC__
1107}
1108
Yabin Cuic9a659c2015-11-05 15:36:08 -08001109static void pthread_rwlock_wakeup_timeout_helper(RwlockWakeupHelperArg* arg) {
1110 arg->tid = gettid();
1111 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
1112 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
1113
1114 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
1115
1116 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001117 ASSERT_EQ(0, clock_gettime(arg->clock, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001118 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
1119 ts.tv_nsec = -1;
1120 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
1121 ts.tv_nsec = NS_PER_S;
1122 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
1123 ts.tv_nsec = NS_PER_S - 1;
1124 ts.tv_sec = -1;
1125 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001126 ASSERT_EQ(0, clock_gettime(arg->clock, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001127 ts.tv_sec += 1;
1128 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
1129 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, arg->progress);
1130 arg->progress = RwlockWakeupHelperArg::LOCK_TIMEDOUT;
1131}
1132
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001133static void pthread_rwlock_timedrdlock_timeout_helper(
1134 clockid_t clock, int (*lock_function)(pthread_rwlock_t* __rwlock, const timespec* __timeout)) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001135 RwlockWakeupHelperArg wakeup_arg;
1136 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
1137 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
1138 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
1139 wakeup_arg.tid = 0;
Tom Cherry60ddedf2018-02-20 15:40:02 -08001140 wakeup_arg.trylock_function = &pthread_rwlock_tryrdlock;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001141 wakeup_arg.timed_lock_function = lock_function;
1142 wakeup_arg.clock = clock;
1143
1144 pthread_t thread;
1145 ASSERT_EQ(0, pthread_create(&thread, nullptr,
1146 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
1147 WaitUntilThreadSleep(wakeup_arg.tid);
1148 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
1149
1150 ASSERT_EQ(0, pthread_join(thread, nullptr));
1151 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
1152 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
1153 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
1154}
1155
1156TEST(pthread, pthread_rwlock_timedrdlock_timeout) {
1157 pthread_rwlock_timedrdlock_timeout_helper(CLOCK_REALTIME, pthread_rwlock_timedrdlock);
1158}
1159
1160TEST(pthread, pthread_rwlock_timedrdlock_monotonic_np_timeout) {
1161#if defined(__BIONIC__)
1162 pthread_rwlock_timedrdlock_timeout_helper(CLOCK_MONOTONIC,
1163 pthread_rwlock_timedrdlock_monotonic_np);
1164#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001165 GTEST_SKIP() << "pthread_rwlock_timedrdlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001166#endif // __BIONIC__
1167}
1168
Tom Cherry69010802019-05-07 20:33:05 -07001169TEST(pthread, pthread_rwlock_clockrdlock_monotonic_timeout) {
1170#if defined(__BIONIC__)
1171 pthread_rwlock_timedrdlock_timeout_helper(
1172 CLOCK_MONOTONIC, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) {
1173 return pthread_rwlock_clockrdlock(__rwlock, CLOCK_MONOTONIC, __timeout);
1174 });
1175#else // __BIONIC__
1176 GTEST_SKIP() << "pthread_rwlock_clockrdlock not available";
1177#endif // __BIONIC__
1178}
1179
1180TEST(pthread, pthread_rwlock_clockrdlock_realtime_timeout) {
1181#if defined(__BIONIC__)
1182 pthread_rwlock_timedrdlock_timeout_helper(
1183 CLOCK_REALTIME, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) {
1184 return pthread_rwlock_clockrdlock(__rwlock, CLOCK_REALTIME, __timeout);
1185 });
1186#else // __BIONIC__
1187 GTEST_SKIP() << "pthread_rwlock_clockrdlock not available";
1188#endif // __BIONIC__
1189}
1190
1191TEST(pthread, pthread_rwlock_clockrdlock_invalid) {
1192#if defined(__BIONIC__)
1193 pthread_rwlock_t lock = PTHREAD_RWLOCK_INITIALIZER;
1194 timespec ts;
1195 EXPECT_EQ(EINVAL, pthread_rwlock_clockrdlock(&lock, CLOCK_PROCESS_CPUTIME_ID, &ts));
1196#else // __BIONIC__
1197 GTEST_SKIP() << "pthread_rwlock_clockrdlock not available";
1198#endif // __BIONIC__
1199}
1200
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001201static void pthread_rwlock_timedwrlock_timeout_helper(
1202 clockid_t clock, int (*lock_function)(pthread_rwlock_t* __rwlock, const timespec* __timeout)) {
1203 RwlockWakeupHelperArg wakeup_arg;
1204 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
1205 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
1206 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
1207 wakeup_arg.tid = 0;
1208 wakeup_arg.trylock_function = &pthread_rwlock_trywrlock;
1209 wakeup_arg.timed_lock_function = lock_function;
1210 wakeup_arg.clock = clock;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001211
1212 pthread_t thread;
1213 ASSERT_EQ(0, pthread_create(&thread, nullptr,
1214 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
1215 WaitUntilThreadSleep(wakeup_arg.tid);
1216 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
1217
1218 ASSERT_EQ(0, pthread_join(thread, nullptr));
1219 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
1220 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
1221 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
1222}
1223
1224TEST(pthread, pthread_rwlock_timedwrlock_timeout) {
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001225 pthread_rwlock_timedwrlock_timeout_helper(CLOCK_REALTIME, pthread_rwlock_timedwrlock);
1226}
Yabin Cuic9a659c2015-11-05 15:36:08 -08001227
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001228TEST(pthread, pthread_rwlock_timedwrlock_monotonic_np_timeout) {
1229#if defined(__BIONIC__)
1230 pthread_rwlock_timedwrlock_timeout_helper(CLOCK_MONOTONIC,
1231 pthread_rwlock_timedwrlock_monotonic_np);
1232#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001233 GTEST_SKIP() << "pthread_rwlock_timedwrlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001234#endif // __BIONIC__
Yabin Cuic9a659c2015-11-05 15:36:08 -08001235}
1236
Tom Cherry69010802019-05-07 20:33:05 -07001237TEST(pthread, pthread_rwlock_clockwrlock_monotonic_timeout) {
1238#if defined(__BIONIC__)
1239 pthread_rwlock_timedwrlock_timeout_helper(
1240 CLOCK_MONOTONIC, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) {
1241 return pthread_rwlock_clockwrlock(__rwlock, CLOCK_MONOTONIC, __timeout);
1242 });
1243#else // __BIONIC__
1244 GTEST_SKIP() << "pthread_rwlock_clockwrlock not available";
1245#endif // __BIONIC__
1246}
1247
1248TEST(pthread, pthread_rwlock_clockwrlock_realtime_timeout) {
1249#if defined(__BIONIC__)
1250 pthread_rwlock_timedwrlock_timeout_helper(
1251 CLOCK_REALTIME, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) {
1252 return pthread_rwlock_clockwrlock(__rwlock, CLOCK_REALTIME, __timeout);
1253 });
1254#else // __BIONIC__
1255 GTEST_SKIP() << "pthread_rwlock_clockwrlock not available";
1256#endif // __BIONIC__
1257}
1258
1259TEST(pthread, pthread_rwlock_clockwrlock_invalid) {
1260#if defined(__BIONIC__)
1261 pthread_rwlock_t lock = PTHREAD_RWLOCK_INITIALIZER;
1262 timespec ts;
1263 EXPECT_EQ(EINVAL, pthread_rwlock_clockwrlock(&lock, CLOCK_PROCESS_CPUTIME_ID, &ts));
1264#else // __BIONIC__
1265 GTEST_SKIP() << "pthread_rwlock_clockrwlock not available";
1266#endif // __BIONIC__
1267}
1268
Colin Cross4c5595c2021-08-16 15:51:59 -07001269#if !defined(ANDROID_HOST_MUSL)
Colin Cross7da20342021-07-28 11:18:11 -07001270// musl doesn't have pthread_rwlockattr_setkind_np
Yabin Cui76615da2015-03-17 14:22:09 -07001271class RwlockKindTestHelper {
1272 private:
1273 struct ThreadArg {
1274 RwlockKindTestHelper* helper;
1275 std::atomic<pid_t>& tid;
1276
1277 ThreadArg(RwlockKindTestHelper* helper, std::atomic<pid_t>& tid)
1278 : helper(helper), tid(tid) { }
1279 };
1280
1281 public:
1282 pthread_rwlock_t lock;
1283
1284 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -07001285 explicit RwlockKindTestHelper(int kind_type) {
Yabin Cui76615da2015-03-17 14:22:09 -07001286 InitRwlock(kind_type);
1287 }
1288
1289 ~RwlockKindTestHelper() {
1290 DestroyRwlock();
1291 }
1292
1293 void CreateWriterThread(pthread_t& thread, std::atomic<pid_t>& tid) {
1294 tid = 0;
1295 ThreadArg* arg = new ThreadArg(this, tid);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001296 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui76615da2015-03-17 14:22:09 -07001297 reinterpret_cast<void* (*)(void*)>(WriterThreadFn), arg));
1298 }
1299
1300 void CreateReaderThread(pthread_t& thread, std::atomic<pid_t>& tid) {
1301 tid = 0;
1302 ThreadArg* arg = new ThreadArg(this, tid);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001303 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui76615da2015-03-17 14:22:09 -07001304 reinterpret_cast<void* (*)(void*)>(ReaderThreadFn), arg));
1305 }
1306
1307 private:
1308 void InitRwlock(int kind_type) {
1309 pthread_rwlockattr_t attr;
1310 ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
1311 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_type));
1312 ASSERT_EQ(0, pthread_rwlock_init(&lock, &attr));
1313 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
1314 }
1315
1316 void DestroyRwlock() {
1317 ASSERT_EQ(0, pthread_rwlock_destroy(&lock));
1318 }
1319
1320 static void WriterThreadFn(ThreadArg* arg) {
1321 arg->tid = gettid();
1322
1323 RwlockKindTestHelper* helper = arg->helper;
1324 ASSERT_EQ(0, pthread_rwlock_wrlock(&helper->lock));
1325 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
1326 delete arg;
1327 }
1328
1329 static void ReaderThreadFn(ThreadArg* arg) {
1330 arg->tid = gettid();
1331
1332 RwlockKindTestHelper* helper = arg->helper;
1333 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper->lock));
1334 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
1335 delete arg;
1336 }
1337};
Colin Cross7da20342021-07-28 11:18:11 -07001338#endif
Yabin Cui76615da2015-03-17 14:22:09 -07001339
1340TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_READER_NP) {
Colin Cross4c5595c2021-08-16 15:51:59 -07001341#if !defined(ANDROID_HOST_MUSL)
Yabin Cui76615da2015-03-17 14:22:09 -07001342 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_READER_NP);
1343 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
1344
1345 pthread_t writer_thread;
1346 std::atomic<pid_t> writer_tid;
1347 helper.CreateWriterThread(writer_thread, writer_tid);
1348 WaitUntilThreadSleep(writer_tid);
1349
1350 pthread_t reader_thread;
1351 std::atomic<pid_t> reader_tid;
1352 helper.CreateReaderThread(reader_thread, reader_tid);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001353 ASSERT_EQ(0, pthread_join(reader_thread, nullptr));
Yabin Cui76615da2015-03-17 14:22:09 -07001354
1355 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
Yi Kong32bc0fc2018-08-02 17:31:13 -07001356 ASSERT_EQ(0, pthread_join(writer_thread, nullptr));
Colin Cross7da20342021-07-28 11:18:11 -07001357#else
1358 GTEST_SKIP() << "musl doesn't have pthread_rwlockattr_setkind_np";
1359#endif
Yabin Cui76615da2015-03-17 14:22:09 -07001360}
1361
1362TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP) {
Colin Cross4c5595c2021-08-16 15:51:59 -07001363#if !defined(ANDROID_HOST_MUSL)
Yabin Cui76615da2015-03-17 14:22:09 -07001364 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
1365 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
1366
1367 pthread_t writer_thread;
1368 std::atomic<pid_t> writer_tid;
1369 helper.CreateWriterThread(writer_thread, writer_tid);
1370 WaitUntilThreadSleep(writer_tid);
1371
1372 pthread_t reader_thread;
1373 std::atomic<pid_t> reader_tid;
1374 helper.CreateReaderThread(reader_thread, reader_tid);
1375 WaitUntilThreadSleep(reader_tid);
1376
1377 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
Yi Kong32bc0fc2018-08-02 17:31:13 -07001378 ASSERT_EQ(0, pthread_join(writer_thread, nullptr));
1379 ASSERT_EQ(0, pthread_join(reader_thread, nullptr));
Colin Cross7da20342021-07-28 11:18:11 -07001380#else
1381 GTEST_SKIP() << "musl doesn't have pthread_rwlockattr_setkind_np";
1382#endif
Yabin Cui76615da2015-03-17 14:22:09 -07001383}
1384
Elliott Hughes1728b232014-05-14 10:02:03 -07001385static int g_once_fn_call_count = 0;
Elliott Hughesc3f11402013-10-30 14:40:09 -07001386static void OnceFn() {
Elliott Hughes1728b232014-05-14 10:02:03 -07001387 ++g_once_fn_call_count;
Elliott Hughesc3f11402013-10-30 14:40:09 -07001388}
1389
1390TEST(pthread, pthread_once_smoke) {
1391 pthread_once_t once_control = PTHREAD_ONCE_INIT;
1392 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
1393 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
Elliott Hughes1728b232014-05-14 10:02:03 -07001394 ASSERT_EQ(1, g_once_fn_call_count);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001395}
1396
Elliott Hughes3694ec62014-05-14 11:46:08 -07001397static std::string pthread_once_1934122_result = "";
1398
1399static void Routine2() {
1400 pthread_once_1934122_result += "2";
1401}
1402
1403static void Routine1() {
1404 pthread_once_t once_control_2 = PTHREAD_ONCE_INIT;
1405 pthread_once_1934122_result += "1";
1406 pthread_once(&once_control_2, &Routine2);
1407}
1408
1409TEST(pthread, pthread_once_1934122) {
1410 // Very old versions of Android couldn't call pthread_once from a
1411 // pthread_once init routine. http://b/1934122.
1412 pthread_once_t once_control_1 = PTHREAD_ONCE_INIT;
1413 ASSERT_EQ(0, pthread_once(&once_control_1, &Routine1));
1414 ASSERT_EQ("12", pthread_once_1934122_result);
1415}
1416
Elliott Hughes1728b232014-05-14 10:02:03 -07001417static int g_atfork_prepare_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001418static void AtForkPrepare1() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 1; }
1419static void AtForkPrepare2() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -07001420static int g_atfork_parent_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001421static void AtForkParent1() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 1; }
1422static void AtForkParent2() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -07001423static int g_atfork_child_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001424static void AtForkChild1() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 1; }
1425static void AtForkChild2() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 2; }
Elliott Hughesc3f11402013-10-30 14:40:09 -07001426
Elliott Hughes2411fff2024-02-24 23:55:58 +00001427TEST(pthread, pthread_atfork_smoke_fork) {
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001428 ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1));
1429 ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2));
Elliott Hughesc3f11402013-10-30 14:40:09 -07001430
Elliott Hughes2411fff2024-02-24 23:55:58 +00001431 g_atfork_prepare_calls = g_atfork_parent_calls = g_atfork_child_calls = 0;
Elliott Hughes33697a02016-01-26 13:04:57 -08001432 pid_t pid = fork();
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001433 ASSERT_NE(-1, pid) << strerror(errno);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001434
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001435 // Child and parent calls are made in the order they were registered.
1436 if (pid == 0) {
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001437 ASSERT_EQ(12, g_atfork_child_calls);
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001438 _exit(0);
1439 }
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001440 ASSERT_EQ(12, g_atfork_parent_calls);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001441
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001442 // Prepare calls are made in the reverse order.
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001443 ASSERT_EQ(21, g_atfork_prepare_calls);
Elliott Hughes33697a02016-01-26 13:04:57 -08001444 AssertChildExited(pid, 0);
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001445}
1446
Elliott Hughes2411fff2024-02-24 23:55:58 +00001447TEST(pthread, pthread_atfork_smoke_vfork) {
1448 ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1));
1449 ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2));
1450
1451 g_atfork_prepare_calls = g_atfork_parent_calls = g_atfork_child_calls = 0;
1452 pid_t pid = vfork();
1453 ASSERT_NE(-1, pid) << strerror(errno);
1454
1455 // atfork handlers are not called.
1456 if (pid == 0) {
1457 ASSERT_EQ(0, g_atfork_child_calls);
1458 _exit(0);
1459 }
1460 ASSERT_EQ(0, g_atfork_parent_calls);
1461 ASSERT_EQ(0, g_atfork_prepare_calls);
1462 AssertChildExited(pid, 0);
1463}
1464
1465TEST(pthread, pthread_atfork_smoke__Fork) {
1466#if defined(__BIONIC__)
1467 ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1));
1468 ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2));
1469
1470 g_atfork_prepare_calls = g_atfork_parent_calls = g_atfork_child_calls = 0;
1471 pid_t pid = _Fork();
1472 ASSERT_NE(-1, pid) << strerror(errno);
1473
1474 // atfork handlers are not called.
1475 if (pid == 0) {
1476 ASSERT_EQ(0, g_atfork_child_calls);
1477 _exit(0);
1478 }
1479 ASSERT_EQ(0, g_atfork_parent_calls);
1480 ASSERT_EQ(0, g_atfork_prepare_calls);
1481 AssertChildExited(pid, 0);
1482#endif
1483}
1484
Elliott Hughesc3f11402013-10-30 14:40:09 -07001485TEST(pthread, pthread_attr_getscope) {
1486 pthread_attr_t attr;
1487 ASSERT_EQ(0, pthread_attr_init(&attr));
1488
1489 int scope;
1490 ASSERT_EQ(0, pthread_attr_getscope(&attr, &scope));
1491 ASSERT_EQ(PTHREAD_SCOPE_SYSTEM, scope);
1492}
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001493
1494TEST(pthread, pthread_condattr_init) {
1495 pthread_condattr_t attr;
1496 pthread_condattr_init(&attr);
1497
1498 clockid_t clock;
1499 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1500 ASSERT_EQ(CLOCK_REALTIME, clock);
1501
1502 int pshared;
1503 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1504 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
1505}
1506
1507TEST(pthread, pthread_condattr_setclock) {
1508 pthread_condattr_t attr;
1509 pthread_condattr_init(&attr);
1510
1511 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_REALTIME));
1512 clockid_t clock;
1513 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1514 ASSERT_EQ(CLOCK_REALTIME, clock);
1515
1516 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1517 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1518 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1519
1520 ASSERT_EQ(EINVAL, pthread_condattr_setclock(&attr, CLOCK_PROCESS_CPUTIME_ID));
1521}
1522
1523TEST(pthread, pthread_cond_broadcast__preserves_condattr_flags) {
Yabin Cui32651b82015-03-13 20:30:00 -07001524#if defined(__BIONIC__)
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001525 pthread_condattr_t attr;
1526 pthread_condattr_init(&attr);
1527
1528 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1529 ASSERT_EQ(0, pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
1530
1531 pthread_cond_t cond_var;
1532 ASSERT_EQ(0, pthread_cond_init(&cond_var, &attr));
1533
1534 ASSERT_EQ(0, pthread_cond_signal(&cond_var));
1535 ASSERT_EQ(0, pthread_cond_broadcast(&cond_var));
1536
Yabin Cui32651b82015-03-13 20:30:00 -07001537 attr = static_cast<pthread_condattr_t>(*reinterpret_cast<uint32_t*>(cond_var.__private));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001538 clockid_t clock;
1539 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1540 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1541 int pshared;
1542 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1543 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
Yabin Cui32651b82015-03-13 20:30:00 -07001544#else // !defined(__BIONIC__)
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001545 GTEST_SKIP() << "bionic-only test";
Yabin Cui32651b82015-03-13 20:30:00 -07001546#endif // !defined(__BIONIC__)
1547}
1548
1549class pthread_CondWakeupTest : public ::testing::Test {
1550 protected:
1551 pthread_mutex_t mutex;
1552 pthread_cond_t cond;
1553
1554 enum Progress {
1555 INITIALIZED,
1556 WAITING,
1557 SIGNALED,
1558 FINISHED,
1559 };
1560 std::atomic<Progress> progress;
1561 pthread_t thread;
Peter Collingbournec5b81842021-12-02 12:38:46 -08001562 timespec ts;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001563 std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function;
Yabin Cui32651b82015-03-13 20:30:00 -07001564
1565 protected:
Yabin Cuic9a659c2015-11-05 15:36:08 -08001566 void SetUp() override {
1567 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1568 }
1569
1570 void InitCond(clockid_t clock=CLOCK_REALTIME) {
1571 pthread_condattr_t attr;
1572 ASSERT_EQ(0, pthread_condattr_init(&attr));
1573 ASSERT_EQ(0, pthread_condattr_setclock(&attr, clock));
1574 ASSERT_EQ(0, pthread_cond_init(&cond, &attr));
1575 ASSERT_EQ(0, pthread_condattr_destroy(&attr));
1576 }
1577
Tom Cherry69010802019-05-07 20:33:05 -07001578 void StartWaitingThread(
1579 std::function<int(pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function) {
Yabin Cui32651b82015-03-13 20:30:00 -07001580 progress = INITIALIZED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001581 this->wait_function = wait_function;
Tom Cherry69010802019-05-07 20:33:05 -07001582 ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(WaitThreadFn),
1583 this));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001584 while (progress != WAITING) {
Yabin Cui32651b82015-03-13 20:30:00 -07001585 usleep(5000);
1586 }
1587 usleep(5000);
1588 }
1589
Tom Cherry69010802019-05-07 20:33:05 -07001590 void RunTimedTest(
1591 clockid_t clock,
1592 std::function<int(pthread_cond_t* cond, pthread_mutex_t* mutex, const timespec* timeout)>
1593 wait_function) {
Tom Cherry69010802019-05-07 20:33:05 -07001594 ASSERT_EQ(0, clock_gettime(clock, &ts));
1595 ts.tv_sec += 1;
1596
Peter Collingbournec5b81842021-12-02 12:38:46 -08001597 StartWaitingThread([&wait_function, this](pthread_cond_t* cond, pthread_mutex_t* mutex) {
Tom Cherry69010802019-05-07 20:33:05 -07001598 return wait_function(cond, mutex, &ts);
1599 });
1600
1601 progress = SIGNALED;
1602 ASSERT_EQ(0, pthread_cond_signal(&cond));
1603 }
1604
1605 void RunTimedTest(clockid_t clock, std::function<int(pthread_cond_t* cond, pthread_mutex_t* mutex,
1606 clockid_t clock, const timespec* timeout)>
1607 wait_function) {
1608 RunTimedTest(clock, [clock, &wait_function](pthread_cond_t* cond, pthread_mutex_t* mutex,
1609 const timespec* timeout) {
1610 return wait_function(cond, mutex, clock, timeout);
1611 });
1612 }
1613
Yabin Cuic9a659c2015-11-05 15:36:08 -08001614 void TearDown() override {
1615 ASSERT_EQ(0, pthread_join(thread, nullptr));
1616 ASSERT_EQ(FINISHED, progress);
1617 ASSERT_EQ(0, pthread_cond_destroy(&cond));
1618 ASSERT_EQ(0, pthread_mutex_destroy(&mutex));
1619 }
1620
Yabin Cui32651b82015-03-13 20:30:00 -07001621 private:
1622 static void WaitThreadFn(pthread_CondWakeupTest* test) {
1623 ASSERT_EQ(0, pthread_mutex_lock(&test->mutex));
1624 test->progress = WAITING;
1625 while (test->progress == WAITING) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001626 ASSERT_EQ(0, test->wait_function(&test->cond, &test->mutex));
Yabin Cui32651b82015-03-13 20:30:00 -07001627 }
1628 ASSERT_EQ(SIGNALED, test->progress);
1629 test->progress = FINISHED;
1630 ASSERT_EQ(0, pthread_mutex_unlock(&test->mutex));
1631 }
1632};
1633
Yabin Cuic9a659c2015-11-05 15:36:08 -08001634TEST_F(pthread_CondWakeupTest, signal_wait) {
1635 InitCond();
1636 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1637 return pthread_cond_wait(cond, mutex);
1638 });
Yabin Cui32651b82015-03-13 20:30:00 -07001639 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001640 ASSERT_EQ(0, pthread_cond_signal(&cond));
Yabin Cui32651b82015-03-13 20:30:00 -07001641}
1642
Yabin Cuic9a659c2015-11-05 15:36:08 -08001643TEST_F(pthread_CondWakeupTest, broadcast_wait) {
1644 InitCond();
1645 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1646 return pthread_cond_wait(cond, mutex);
1647 });
Yabin Cui32651b82015-03-13 20:30:00 -07001648 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001649 ASSERT_EQ(0, pthread_cond_broadcast(&cond));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001650}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001651
Yabin Cuic9a659c2015-11-05 15:36:08 -08001652TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_REALTIME) {
1653 InitCond(CLOCK_REALTIME);
Tom Cherry69010802019-05-07 20:33:05 -07001654 RunTimedTest(CLOCK_REALTIME, pthread_cond_timedwait);
Yabin Cuic9a659c2015-11-05 15:36:08 -08001655}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001656
Yabin Cuic9a659c2015-11-05 15:36:08 -08001657TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC) {
1658 InitCond(CLOCK_MONOTONIC);
Tom Cherry69010802019-05-07 20:33:05 -07001659 RunTimedTest(CLOCK_MONOTONIC, pthread_cond_timedwait);
Yabin Cuic9a659c2015-11-05 15:36:08 -08001660}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001661
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001662TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC_np) {
1663#if defined(__BIONIC__)
1664 InitCond(CLOCK_REALTIME);
Tom Cherry69010802019-05-07 20:33:05 -07001665 RunTimedTest(CLOCK_MONOTONIC, pthread_cond_timedwait_monotonic_np);
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001666#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001667 GTEST_SKIP() << "pthread_cond_timedwait_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001668#endif // __BIONIC__
1669}
1670
Tom Cherry69010802019-05-07 20:33:05 -07001671TEST_F(pthread_CondWakeupTest, signal_clockwait_monotonic_monotonic) {
1672#if defined(__BIONIC__)
1673 InitCond(CLOCK_MONOTONIC);
1674 RunTimedTest(CLOCK_MONOTONIC, pthread_cond_clockwait);
1675#else // __BIONIC__
1676 GTEST_SKIP() << "pthread_cond_clockwait not available";
1677#endif // __BIONIC__
1678}
1679
1680TEST_F(pthread_CondWakeupTest, signal_clockwait_monotonic_realtime) {
1681#if defined(__BIONIC__)
1682 InitCond(CLOCK_MONOTONIC);
1683 RunTimedTest(CLOCK_REALTIME, pthread_cond_clockwait);
1684#else // __BIONIC__
1685 GTEST_SKIP() << "pthread_cond_clockwait not available";
1686#endif // __BIONIC__
1687}
1688
1689TEST_F(pthread_CondWakeupTest, signal_clockwait_realtime_monotonic) {
1690#if defined(__BIONIC__)
1691 InitCond(CLOCK_REALTIME);
1692 RunTimedTest(CLOCK_MONOTONIC, pthread_cond_clockwait);
1693#else // __BIONIC__
1694 GTEST_SKIP() << "pthread_cond_clockwait not available";
1695#endif // __BIONIC__
1696}
1697
1698TEST_F(pthread_CondWakeupTest, signal_clockwait_realtime_realtime) {
1699#if defined(__BIONIC__)
1700 InitCond(CLOCK_REALTIME);
1701 RunTimedTest(CLOCK_REALTIME, pthread_cond_clockwait);
1702#else // __BIONIC__
1703 GTEST_SKIP() << "pthread_cond_clockwait not available";
1704#endif // __BIONIC__
1705}
1706
Tom Cherry800c1a92019-07-17 10:45:18 -07001707static void pthread_cond_timedwait_timeout_helper(bool init_monotonic, clockid_t clock,
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001708 int (*wait_function)(pthread_cond_t* __cond,
1709 pthread_mutex_t* __mutex,
1710 const timespec* __timeout)) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001711 pthread_mutex_t mutex;
1712 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1713 pthread_cond_t cond;
Tom Cherry800c1a92019-07-17 10:45:18 -07001714
1715 if (init_monotonic) {
1716 pthread_condattr_t attr;
1717 pthread_condattr_init(&attr);
1718
1719 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1720 clockid_t clock;
1721 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1722 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1723
1724 ASSERT_EQ(0, pthread_cond_init(&cond, &attr));
1725 } else {
1726 ASSERT_EQ(0, pthread_cond_init(&cond, nullptr));
1727 }
Yabin Cuic9a659c2015-11-05 15:36:08 -08001728 ASSERT_EQ(0, pthread_mutex_lock(&mutex));
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001729
Yabin Cuic9a659c2015-11-05 15:36:08 -08001730 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001731 ASSERT_EQ(0, clock_gettime(clock, &ts));
1732 ASSERT_EQ(ETIMEDOUT, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001733 ts.tv_nsec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001734 ASSERT_EQ(EINVAL, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001735 ts.tv_nsec = NS_PER_S;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001736 ASSERT_EQ(EINVAL, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001737 ts.tv_nsec = NS_PER_S - 1;
1738 ts.tv_sec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001739 ASSERT_EQ(ETIMEDOUT, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001740 ASSERT_EQ(0, pthread_mutex_unlock(&mutex));
Elliott Hughes0e714a52014-03-03 16:42:47 -08001741}
Elliott Hughes57b7a612014-08-25 17:26:50 -07001742
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001743TEST(pthread, pthread_cond_timedwait_timeout) {
Tom Cherry800c1a92019-07-17 10:45:18 -07001744 pthread_cond_timedwait_timeout_helper(false, CLOCK_REALTIME, pthread_cond_timedwait);
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001745}
1746
1747TEST(pthread, pthread_cond_timedwait_monotonic_np_timeout) {
1748#if defined(__BIONIC__)
Tom Cherry800c1a92019-07-17 10:45:18 -07001749 pthread_cond_timedwait_timeout_helper(false, CLOCK_MONOTONIC, pthread_cond_timedwait_monotonic_np);
1750 pthread_cond_timedwait_timeout_helper(true, CLOCK_MONOTONIC, pthread_cond_timedwait_monotonic_np);
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001751#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001752 GTEST_SKIP() << "pthread_cond_timedwait_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001753#endif // __BIONIC__
1754}
1755
Tom Cherry69010802019-05-07 20:33:05 -07001756TEST(pthread, pthread_cond_clockwait_timeout) {
1757#if defined(__BIONIC__)
1758 pthread_cond_timedwait_timeout_helper(
Tom Cherry800c1a92019-07-17 10:45:18 -07001759 false, CLOCK_MONOTONIC,
Tom Cherry69010802019-05-07 20:33:05 -07001760 [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) {
1761 return pthread_cond_clockwait(__cond, __mutex, CLOCK_MONOTONIC, __timeout);
1762 });
1763 pthread_cond_timedwait_timeout_helper(
Tom Cherry800c1a92019-07-17 10:45:18 -07001764 true, CLOCK_MONOTONIC,
1765 [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) {
1766 return pthread_cond_clockwait(__cond, __mutex, CLOCK_MONOTONIC, __timeout);
1767 });
1768 pthread_cond_timedwait_timeout_helper(
1769 false, CLOCK_REALTIME,
1770 [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) {
1771 return pthread_cond_clockwait(__cond, __mutex, CLOCK_REALTIME, __timeout);
1772 });
1773 pthread_cond_timedwait_timeout_helper(
1774 true, CLOCK_REALTIME,
Tom Cherry69010802019-05-07 20:33:05 -07001775 [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) {
1776 return pthread_cond_clockwait(__cond, __mutex, CLOCK_REALTIME, __timeout);
1777 });
1778#else // __BIONIC__
1779 GTEST_SKIP() << "pthread_cond_clockwait not available";
1780#endif // __BIONIC__
1781}
1782
1783TEST(pthread, pthread_cond_clockwait_invalid) {
1784#if defined(__BIONIC__)
1785 pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
1786 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
1787 timespec ts;
1788 EXPECT_EQ(EINVAL, pthread_cond_clockwait(&cond, &mutex, CLOCK_PROCESS_CPUTIME_ID, &ts));
1789
1790#else // __BIONIC__
1791 GTEST_SKIP() << "pthread_cond_clockwait not available";
1792#endif // __BIONIC__
1793}
1794
Elliott Hughes57b7a612014-08-25 17:26:50 -07001795TEST(pthread, pthread_attr_getstack__main_thread) {
1796 // This test is only meaningful for the main thread, so make sure we're running on it!
1797 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1798
1799 // Get the main thread's attributes.
1800 pthread_attr_t attributes;
1801 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1802
1803 // Check that we correctly report that the main thread has no guard page.
1804 size_t guard_size;
1805 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
1806 ASSERT_EQ(0U, guard_size); // The main thread has no guard page.
1807
1808 // Get the stack base and the stack size (both ways).
1809 void* stack_base;
1810 size_t stack_size;
1811 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1812 size_t stack_size2;
1813 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1814
1815 // The two methods of asking for the stack size should agree.
1816 EXPECT_EQ(stack_size, stack_size2);
1817
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001818#if defined(__BIONIC__)
dimitry6dfa5b52018-01-30 13:24:28 +01001819 // Find stack in /proc/self/maps using a pointer to the stack.
1820 //
1821 // We do not use "[stack]" label because in native-bridge environment it is not
1822 // guaranteed to point to the right stack. A native bridge implementation may
1823 // keep separate stack for the guest code.
Yi Kong32bc0fc2018-08-02 17:31:13 -07001824 void* maps_stack_hi = nullptr;
Elliott Hughes15dfd632015-09-22 16:40:14 -07001825 std::vector<map_record> maps;
1826 ASSERT_TRUE(Maps::parse_maps(&maps));
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08001827 uintptr_t stack_address = reinterpret_cast<uintptr_t>(untag_address(&maps_stack_hi));
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07001828 for (const auto& map : maps) {
dimitry6dfa5b52018-01-30 13:24:28 +01001829 if (map.addr_start <= stack_address && map.addr_end > stack_address){
Elliott Hughes15dfd632015-09-22 16:40:14 -07001830 maps_stack_hi = reinterpret_cast<void*>(map.addr_end);
Elliott Hughes57b7a612014-08-25 17:26:50 -07001831 break;
1832 }
1833 }
Elliott Hughes57b7a612014-08-25 17:26:50 -07001834
dimitry6dfa5b52018-01-30 13:24:28 +01001835 // The high address of the /proc/self/maps stack region should equal stack_base + stack_size.
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001836 // Remember that the stack grows down (and is mapped in on demand), so the low address of the
1837 // region isn't very interesting.
1838 EXPECT_EQ(maps_stack_hi, reinterpret_cast<uint8_t*>(stack_base) + stack_size);
1839
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001840 // The stack size should correspond to RLIMIT_STACK.
Elliott Hughes57b7a612014-08-25 17:26:50 -07001841 rlimit rl;
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001842 ASSERT_EQ(0, getrlimit(RLIMIT_STACK, &rl));
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001843 uint64_t original_rlim_cur = rl.rlim_cur;
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001844 if (rl.rlim_cur == RLIM_INFINITY) {
1845 rl.rlim_cur = 8 * 1024 * 1024; // Bionic reports unlimited stacks as 8MiB.
1846 }
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001847 EXPECT_EQ(rl.rlim_cur, stack_size);
1848
Tom Cherryb8ab6182017-04-05 16:20:29 -07001849 auto guard = android::base::make_scope_guard([&rl, original_rlim_cur]() {
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001850 rl.rlim_cur = original_rlim_cur;
1851 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1852 });
1853
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001854 //
1855 // What if RLIMIT_STACK is smaller than the stack's current extent?
1856 //
Elliott Hughes57b7a612014-08-25 17:26:50 -07001857 rl.rlim_cur = rl.rlim_max = 1024; // 1KiB. We know the stack must be at least a page already.
1858 rl.rlim_max = RLIM_INFINITY;
1859 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1860
1861 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1862 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1863 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1864
1865 EXPECT_EQ(stack_size, stack_size2);
1866 ASSERT_EQ(1024U, stack_size);
1867
1868 //
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001869 // What if RLIMIT_STACK isn't a whole number of pages?
Elliott Hughes57b7a612014-08-25 17:26:50 -07001870 //
1871 rl.rlim_cur = rl.rlim_max = 6666; // Not a whole number of pages.
1872 rl.rlim_max = RLIM_INFINITY;
1873 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1874
1875 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1876 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1877 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1878
1879 EXPECT_EQ(stack_size, stack_size2);
1880 ASSERT_EQ(6666U, stack_size);
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001881#endif
Elliott Hughes57b7a612014-08-25 17:26:50 -07001882}
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001883
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001884struct GetStackSignalHandlerArg {
1885 volatile bool done;
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001886 void* signal_stack_base;
1887 size_t signal_stack_size;
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001888 void* main_stack_base;
1889 size_t main_stack_size;
1890};
1891
1892static GetStackSignalHandlerArg getstack_signal_handler_arg;
1893
1894static void getstack_signal_handler(int sig) {
1895 ASSERT_EQ(SIGUSR1, sig);
1896 // Use sleep() to make current thread be switched out by the kernel to provoke the error.
1897 sleep(1);
1898 pthread_attr_t attr;
1899 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1900 void* stack_base;
1901 size_t stack_size;
1902 ASSERT_EQ(0, pthread_attr_getstack(&attr, &stack_base, &stack_size));
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001903
1904 // Verify if the stack used by the signal handler is the alternate stack just registered.
1905 ASSERT_LE(getstack_signal_handler_arg.signal_stack_base, &attr);
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08001906 ASSERT_LT(static_cast<void*>(untag_address(&attr)),
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001907 static_cast<char*>(getstack_signal_handler_arg.signal_stack_base) +
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08001908 getstack_signal_handler_arg.signal_stack_size);
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001909
1910 // Verify if the main thread's stack got in the signal handler is correct.
1911 ASSERT_EQ(getstack_signal_handler_arg.main_stack_base, stack_base);
1912 ASSERT_LE(getstack_signal_handler_arg.main_stack_size, stack_size);
1913
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001914 getstack_signal_handler_arg.done = true;
1915}
1916
1917// The previous code obtained the main thread's stack by reading the entry in
1918// /proc/self/task/<pid>/maps that was labeled [stack]. Unfortunately, on x86/x86_64, the kernel
1919// relies on sp0 in task state segment(tss) to label the stack map with [stack]. If the kernel
1920// switches a process while the main thread is in an alternate stack, then the kernel will label
1921// the wrong map with [stack]. This test verifies that when the above situation happens, the main
1922// thread's stack is found correctly.
1923TEST(pthread, pthread_attr_getstack_in_signal_handler) {
Yabin Cui61e4d462016-03-07 17:44:58 -08001924 // This test is only meaningful for the main thread, so make sure we're running on it!
1925 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1926
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001927 const size_t sig_stack_size = 16 * 1024;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001928 void* sig_stack = mmap(nullptr, sig_stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS,
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001929 -1, 0);
1930 ASSERT_NE(MAP_FAILED, sig_stack);
1931 stack_t ss;
1932 ss.ss_sp = sig_stack;
1933 ss.ss_size = sig_stack_size;
1934 ss.ss_flags = 0;
1935 stack_t oss;
1936 ASSERT_EQ(0, sigaltstack(&ss, &oss));
1937
Yabin Cui61e4d462016-03-07 17:44:58 -08001938 pthread_attr_t attr;
1939 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1940 void* main_stack_base;
1941 size_t main_stack_size;
1942 ASSERT_EQ(0, pthread_attr_getstack(&attr, &main_stack_base, &main_stack_size));
1943
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001944 ScopedSignalHandler handler(SIGUSR1, getstack_signal_handler, SA_ONSTACK);
1945 getstack_signal_handler_arg.done = false;
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001946 getstack_signal_handler_arg.signal_stack_base = sig_stack;
1947 getstack_signal_handler_arg.signal_stack_size = sig_stack_size;
1948 getstack_signal_handler_arg.main_stack_base = main_stack_base;
1949 getstack_signal_handler_arg.main_stack_size = main_stack_size;
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001950 kill(getpid(), SIGUSR1);
1951 ASSERT_EQ(true, getstack_signal_handler_arg.done);
1952
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001953 ASSERT_EQ(0, sigaltstack(&oss, nullptr));
1954 ASSERT_EQ(0, munmap(sig_stack, sig_stack_size));
1955}
1956
Yabin Cui917d3902015-01-08 12:32:42 -08001957static void pthread_attr_getstack_18908062_helper(void*) {
1958 char local_variable;
1959 pthread_attr_t attributes;
1960 pthread_getattr_np(pthread_self(), &attributes);
1961 void* stack_base;
1962 size_t stack_size;
1963 pthread_attr_getstack(&attributes, &stack_base, &stack_size);
1964
1965 // Test whether &local_variable is in [stack_base, stack_base + stack_size).
1966 ASSERT_LE(reinterpret_cast<char*>(stack_base), &local_variable);
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08001967 ASSERT_LT(untag_address(&local_variable), reinterpret_cast<char*>(stack_base) + stack_size);
Yabin Cui917d3902015-01-08 12:32:42 -08001968}
1969
1970// Check whether something on stack is in the range of
1971// [stack_base, stack_base + stack_size). see b/18908062.
1972TEST(pthread, pthread_attr_getstack_18908062) {
1973 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001974 ASSERT_EQ(0, pthread_create(&t, nullptr,
Yabin Cui917d3902015-01-08 12:32:42 -08001975 reinterpret_cast<void* (*)(void*)>(pthread_attr_getstack_18908062_helper),
Yi Kong32bc0fc2018-08-02 17:31:13 -07001976 nullptr));
1977 ASSERT_EQ(0, pthread_join(t, nullptr));
Yabin Cui917d3902015-01-08 12:32:42 -08001978}
1979
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001980#if defined(__BIONIC__)
Elliott Hughesf2083612015-11-11 13:32:28 -08001981static pthread_mutex_t pthread_gettid_np_mutex = PTHREAD_MUTEX_INITIALIZER;
1982
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001983static void* pthread_gettid_np_helper(void* arg) {
1984 *reinterpret_cast<pid_t*>(arg) = gettid();
Elliott Hughesf2083612015-11-11 13:32:28 -08001985
1986 // Wait for our parent to call pthread_gettid_np on us before exiting.
1987 pthread_mutex_lock(&pthread_gettid_np_mutex);
1988 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001989 return nullptr;
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001990}
1991#endif
1992
1993TEST(pthread, pthread_gettid_np) {
1994#if defined(__BIONIC__)
1995 ASSERT_EQ(gettid(), pthread_gettid_np(pthread_self()));
1996
Elliott Hughesf2083612015-11-11 13:32:28 -08001997 // Ensure the other thread doesn't exit until after we've called
1998 // pthread_gettid_np on it.
1999 pthread_mutex_lock(&pthread_gettid_np_mutex);
2000
Elliott Hughes8fb639c2014-09-12 14:43:07 -07002001 pid_t t_gettid_result;
2002 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002003 pthread_create(&t, nullptr, pthread_gettid_np_helper, &t_gettid_result);
Elliott Hughes8fb639c2014-09-12 14:43:07 -07002004
2005 pid_t t_pthread_gettid_np_result = pthread_gettid_np(t);
2006
Elliott Hughesf2083612015-11-11 13:32:28 -08002007 // Release the other thread and wait for it to exit.
2008 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Yi Kong32bc0fc2018-08-02 17:31:13 -07002009 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes8fb639c2014-09-12 14:43:07 -07002010
2011 ASSERT_EQ(t_gettid_result, t_pthread_gettid_np_result);
2012#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002013 GTEST_SKIP() << "pthread_gettid_np not available";
Elliott Hughes8fb639c2014-09-12 14:43:07 -07002014#endif
2015}
Elliott Hughes34c987a2014-09-22 16:01:26 -07002016
2017static size_t cleanup_counter = 0;
2018
Derek Xue41996952014-09-25 11:05:32 +01002019static void AbortCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07002020 abort();
2021}
2022
Derek Xue41996952014-09-25 11:05:32 +01002023static void CountCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07002024 ++cleanup_counter;
2025}
2026
Derek Xue41996952014-09-25 11:05:32 +01002027static void PthreadCleanupTester() {
Yi Kong32bc0fc2018-08-02 17:31:13 -07002028 pthread_cleanup_push(CountCleanupRoutine, nullptr);
2029 pthread_cleanup_push(CountCleanupRoutine, nullptr);
2030 pthread_cleanup_push(AbortCleanupRoutine, nullptr);
Elliott Hughes34c987a2014-09-22 16:01:26 -07002031
2032 pthread_cleanup_pop(0); // Pop the abort without executing it.
2033 pthread_cleanup_pop(1); // Pop one count while executing it.
2034 ASSERT_EQ(1U, cleanup_counter);
2035 // Exit while the other count is still on the cleanup stack.
Yi Kong32bc0fc2018-08-02 17:31:13 -07002036 pthread_exit(nullptr);
Elliott Hughes34c987a2014-09-22 16:01:26 -07002037
2038 // Calls to pthread_cleanup_pop/pthread_cleanup_push must always be balanced.
2039 pthread_cleanup_pop(0);
2040}
2041
Derek Xue41996952014-09-25 11:05:32 +01002042static void* PthreadCleanupStartRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07002043 PthreadCleanupTester();
Yi Kong32bc0fc2018-08-02 17:31:13 -07002044 return nullptr;
Elliott Hughes34c987a2014-09-22 16:01:26 -07002045}
2046
2047TEST(pthread, pthread_cleanup_push__pthread_cleanup_pop) {
2048 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002049 ASSERT_EQ(0, pthread_create(&t, nullptr, PthreadCleanupStartRoutine, nullptr));
2050 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes34c987a2014-09-22 16:01:26 -07002051 ASSERT_EQ(2U, cleanup_counter);
2052}
Derek Xue41996952014-09-25 11:05:32 +01002053
2054TEST(pthread, PTHREAD_MUTEX_DEFAULT_is_PTHREAD_MUTEX_NORMAL) {
2055 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_DEFAULT);
2056}
2057
2058TEST(pthread, pthread_mutexattr_gettype) {
2059 pthread_mutexattr_t attr;
2060 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
2061
2062 int attr_type;
2063
2064 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL));
2065 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
2066 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, attr_type);
2067
2068 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK));
2069 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
2070 ASSERT_EQ(PTHREAD_MUTEX_ERRORCHECK, attr_type);
2071
2072 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE));
2073 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
2074 ASSERT_EQ(PTHREAD_MUTEX_RECURSIVE, attr_type);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002075
2076 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
2077}
2078
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002079TEST(pthread, pthread_mutexattr_protocol) {
2080 pthread_mutexattr_t attr;
2081 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
2082
2083 int protocol;
2084 ASSERT_EQ(0, pthread_mutexattr_getprotocol(&attr, &protocol));
2085 ASSERT_EQ(PTHREAD_PRIO_NONE, protocol);
2086 for (size_t repeat = 0; repeat < 2; ++repeat) {
2087 for (int set_protocol : {PTHREAD_PRIO_NONE, PTHREAD_PRIO_INHERIT}) {
2088 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, set_protocol));
2089 ASSERT_EQ(0, pthread_mutexattr_getprotocol(&attr, &protocol));
2090 ASSERT_EQ(protocol, set_protocol);
2091 }
2092 }
2093}
2094
Yabin Cui17393b02015-03-21 15:08:25 -07002095struct PthreadMutex {
2096 pthread_mutex_t lock;
2097
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002098 explicit PthreadMutex(int mutex_type, int protocol = PTHREAD_PRIO_NONE) {
2099 init(mutex_type, protocol);
Yabin Cui17393b02015-03-21 15:08:25 -07002100 }
2101
2102 ~PthreadMutex() {
2103 destroy();
2104 }
2105
2106 private:
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002107 void init(int mutex_type, int protocol) {
Yabin Cui17393b02015-03-21 15:08:25 -07002108 pthread_mutexattr_t attr;
2109 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
2110 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, mutex_type));
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002111 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, protocol));
Yabin Cui17393b02015-03-21 15:08:25 -07002112 ASSERT_EQ(0, pthread_mutex_init(&lock, &attr));
2113 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
2114 }
2115
2116 void destroy() {
2117 ASSERT_EQ(0, pthread_mutex_destroy(&lock));
2118 }
2119
2120 DISALLOW_COPY_AND_ASSIGN(PthreadMutex);
2121};
Derek Xue41996952014-09-25 11:05:32 +01002122
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002123static int UnlockFromAnotherThread(pthread_mutex_t* mutex) {
2124 pthread_t thread;
2125 pthread_create(&thread, nullptr, [](void* mutex_voidp) -> void* {
2126 pthread_mutex_t* mutex = static_cast<pthread_mutex_t*>(mutex_voidp);
2127 intptr_t result = pthread_mutex_unlock(mutex);
2128 return reinterpret_cast<void*>(result);
2129 }, mutex);
2130 void* result;
2131 EXPECT_EQ(0, pthread_join(thread, &result));
2132 return reinterpret_cast<intptr_t>(result);
2133};
2134
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002135static void TestPthreadMutexLockNormal(int protocol) {
2136 PthreadMutex m(PTHREAD_MUTEX_NORMAL, protocol);
Derek Xue41996952014-09-25 11:05:32 +01002137
Yabin Cui17393b02015-03-21 15:08:25 -07002138 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002139 if (protocol == PTHREAD_PRIO_INHERIT) {
2140 ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock));
2141 }
Yabin Cui17393b02015-03-21 15:08:25 -07002142 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08002143 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
2144 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
2145 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01002146}
2147
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002148static void TestPthreadMutexLockErrorCheck(int protocol) {
2149 PthreadMutex m(PTHREAD_MUTEX_ERRORCHECK, protocol);
Derek Xue41996952014-09-25 11:05:32 +01002150
Yabin Cui17393b02015-03-21 15:08:25 -07002151 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002152 ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07002153 ASSERT_EQ(EDEADLK, pthread_mutex_lock(&m.lock));
2154 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2155 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002156 if (protocol == PTHREAD_PRIO_NONE) {
2157 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
2158 } else {
2159 ASSERT_EQ(EDEADLK, pthread_mutex_trylock(&m.lock));
2160 }
Yabin Cui17393b02015-03-21 15:08:25 -07002161 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2162 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01002163}
2164
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002165static void TestPthreadMutexLockRecursive(int protocol) {
2166 PthreadMutex m(PTHREAD_MUTEX_RECURSIVE, protocol);
Derek Xue41996952014-09-25 11:05:32 +01002167
Yabin Cui17393b02015-03-21 15:08:25 -07002168 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002169 ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07002170 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002171 ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07002172 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2173 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2174 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08002175 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
2176 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07002177 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2178 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
2179}
2180
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002181TEST(pthread, pthread_mutex_lock_NORMAL) {
2182 TestPthreadMutexLockNormal(PTHREAD_PRIO_NONE);
2183}
2184
2185TEST(pthread, pthread_mutex_lock_ERRORCHECK) {
2186 TestPthreadMutexLockErrorCheck(PTHREAD_PRIO_NONE);
2187}
2188
2189TEST(pthread, pthread_mutex_lock_RECURSIVE) {
2190 TestPthreadMutexLockRecursive(PTHREAD_PRIO_NONE);
2191}
2192
2193TEST(pthread, pthread_mutex_lock_pi) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002194 TestPthreadMutexLockNormal(PTHREAD_PRIO_INHERIT);
2195 TestPthreadMutexLockErrorCheck(PTHREAD_PRIO_INHERIT);
2196 TestPthreadMutexLockRecursive(PTHREAD_PRIO_INHERIT);
2197}
2198
Yabin Cui5a00ba72018-01-26 17:32:31 -08002199TEST(pthread, pthread_mutex_pi_count_limit) {
2200#if defined(__BIONIC__) && !defined(__LP64__)
2201 // Bionic only supports 65536 pi mutexes in 32-bit programs.
2202 pthread_mutexattr_t attr;
2203 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
2204 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT));
2205 std::vector<pthread_mutex_t> mutexes(65536);
2206 // Test if we can use 65536 pi mutexes at the same time.
2207 // Run 2 times to check if freed pi mutexes can be recycled.
2208 for (int repeat = 0; repeat < 2; ++repeat) {
2209 for (auto& m : mutexes) {
2210 ASSERT_EQ(0, pthread_mutex_init(&m, &attr));
2211 }
2212 pthread_mutex_t m;
2213 ASSERT_EQ(ENOMEM, pthread_mutex_init(&m, &attr));
2214 for (auto& m : mutexes) {
2215 ASSERT_EQ(0, pthread_mutex_lock(&m));
2216 }
2217 for (auto& m : mutexes) {
2218 ASSERT_EQ(0, pthread_mutex_unlock(&m));
2219 }
2220 for (auto& m : mutexes) {
2221 ASSERT_EQ(0, pthread_mutex_destroy(&m));
2222 }
2223 }
2224 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
2225#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002226 GTEST_SKIP() << "pi mutex count not limited to 64Ki";
Yabin Cui5a00ba72018-01-26 17:32:31 -08002227#endif
2228}
2229
Yabin Cui17393b02015-03-21 15:08:25 -07002230TEST(pthread, pthread_mutex_init_same_as_static_initializers) {
2231 pthread_mutex_t lock_normal = PTHREAD_MUTEX_INITIALIZER;
2232 PthreadMutex m1(PTHREAD_MUTEX_NORMAL);
2233 ASSERT_EQ(0, memcmp(&lock_normal, &m1.lock, sizeof(pthread_mutex_t)));
2234 pthread_mutex_destroy(&lock_normal);
2235
Colin Cross4c5595c2021-08-16 15:51:59 -07002236#if !defined(ANDROID_HOST_MUSL)
Colin Cross7da20342021-07-28 11:18:11 -07002237 // musl doesn't support PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP or
2238 // PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP.
Yabin Cui17393b02015-03-21 15:08:25 -07002239 pthread_mutex_t lock_errorcheck = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
2240 PthreadMutex m2(PTHREAD_MUTEX_ERRORCHECK);
2241 ASSERT_EQ(0, memcmp(&lock_errorcheck, &m2.lock, sizeof(pthread_mutex_t)));
2242 pthread_mutex_destroy(&lock_errorcheck);
2243
2244 pthread_mutex_t lock_recursive = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
2245 PthreadMutex m3(PTHREAD_MUTEX_RECURSIVE);
2246 ASSERT_EQ(0, memcmp(&lock_recursive, &m3.lock, sizeof(pthread_mutex_t)));
2247 ASSERT_EQ(0, pthread_mutex_destroy(&lock_recursive));
Colin Cross7da20342021-07-28 11:18:11 -07002248#endif
Derek Xue41996952014-09-25 11:05:32 +01002249}
Yabin Cui5a00ba72018-01-26 17:32:31 -08002250
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002251class MutexWakeupHelper {
2252 private:
Yabin Cui17393b02015-03-21 15:08:25 -07002253 PthreadMutex m;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002254 enum Progress {
2255 LOCK_INITIALIZED,
2256 LOCK_WAITING,
2257 LOCK_RELEASED,
2258 LOCK_ACCESSED
2259 };
2260 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -07002261 std::atomic<pid_t> tid;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002262
2263 static void thread_fn(MutexWakeupHelper* helper) {
Yabin Cuif7969852015-04-02 17:47:48 -07002264 helper->tid = gettid();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002265 ASSERT_EQ(LOCK_INITIALIZED, helper->progress);
2266 helper->progress = LOCK_WAITING;
2267
Yabin Cui17393b02015-03-21 15:08:25 -07002268 ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002269 ASSERT_EQ(LOCK_RELEASED, helper->progress);
Yabin Cui17393b02015-03-21 15:08:25 -07002270 ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002271
2272 helper->progress = LOCK_ACCESSED;
2273 }
2274
2275 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -07002276 explicit MutexWakeupHelper(int mutex_type) : m(mutex_type) {
Yabin Cui17393b02015-03-21 15:08:25 -07002277 }
2278
2279 void test() {
2280 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002281 progress = LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -07002282 tid = 0;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002283
2284 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002285 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002286 reinterpret_cast<void* (*)(void*)>(MutexWakeupHelper::thread_fn), this));
2287
Yabin Cuif7969852015-04-02 17:47:48 -07002288 WaitUntilThreadSleep(tid);
2289 ASSERT_EQ(LOCK_WAITING, progress);
2290
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002291 progress = LOCK_RELEASED;
Yabin Cui17393b02015-03-21 15:08:25 -07002292 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002293
Yi Kong32bc0fc2018-08-02 17:31:13 -07002294 ASSERT_EQ(0, pthread_join(thread, nullptr));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002295 ASSERT_EQ(LOCK_ACCESSED, progress);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002296 }
2297};
2298
2299TEST(pthread, pthread_mutex_NORMAL_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07002300 MutexWakeupHelper helper(PTHREAD_MUTEX_NORMAL);
2301 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002302}
2303
2304TEST(pthread, pthread_mutex_ERRORCHECK_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07002305 MutexWakeupHelper helper(PTHREAD_MUTEX_ERRORCHECK);
2306 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002307}
2308
2309TEST(pthread, pthread_mutex_RECURSIVE_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07002310 MutexWakeupHelper helper(PTHREAD_MUTEX_RECURSIVE);
2311 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002312}
2313
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002314static int GetThreadPriority(pid_t tid) {
2315 // sched_getparam() returns the static priority of a thread, which can't reflect a thread's
2316 // priority after priority inheritance. So read /proc/<pid>/stat to get the dynamic priority.
2317 std::string filename = android::base::StringPrintf("/proc/%d/stat", tid);
2318 std::string content;
2319 int result = INT_MAX;
2320 if (!android::base::ReadFileToString(filename, &content)) {
2321 return result;
2322 }
2323 std::vector<std::string> strs = android::base::Split(content, " ");
2324 if (strs.size() < 18) {
2325 return result;
2326 }
2327 if (!android::base::ParseInt(strs[17], &result)) {
2328 return INT_MAX;
2329 }
2330 return result;
2331}
2332
2333class PIMutexWakeupHelper {
2334private:
2335 PthreadMutex m;
2336 int protocol;
2337 enum Progress {
2338 LOCK_INITIALIZED,
2339 LOCK_CHILD_READY,
2340 LOCK_WAITING,
2341 LOCK_RELEASED,
2342 };
2343 std::atomic<Progress> progress;
2344 std::atomic<pid_t> main_tid;
2345 std::atomic<pid_t> child_tid;
2346 PthreadMutex start_thread_m;
2347
2348 static void thread_fn(PIMutexWakeupHelper* helper) {
2349 helper->child_tid = gettid();
2350 ASSERT_EQ(LOCK_INITIALIZED, helper->progress);
2351 ASSERT_EQ(0, setpriority(PRIO_PROCESS, gettid(), 1));
2352 ASSERT_EQ(21, GetThreadPriority(gettid()));
2353 ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock));
2354 helper->progress = LOCK_CHILD_READY;
2355 ASSERT_EQ(0, pthread_mutex_lock(&helper->start_thread_m.lock));
2356
2357 ASSERT_EQ(0, pthread_mutex_unlock(&helper->start_thread_m.lock));
2358 WaitUntilThreadSleep(helper->main_tid);
2359 ASSERT_EQ(LOCK_WAITING, helper->progress);
2360
2361 if (helper->protocol == PTHREAD_PRIO_INHERIT) {
2362 ASSERT_EQ(20, GetThreadPriority(gettid()));
2363 } else {
2364 ASSERT_EQ(21, GetThreadPriority(gettid()));
2365 }
2366 helper->progress = LOCK_RELEASED;
2367 ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock));
2368 }
2369
2370public:
2371 explicit PIMutexWakeupHelper(int mutex_type, int protocol)
2372 : m(mutex_type, protocol), protocol(protocol), start_thread_m(PTHREAD_MUTEX_NORMAL) {
2373 }
2374
2375 void test() {
2376 ASSERT_EQ(0, pthread_mutex_lock(&start_thread_m.lock));
2377 main_tid = gettid();
2378 ASSERT_EQ(20, GetThreadPriority(main_tid));
2379 progress = LOCK_INITIALIZED;
2380 child_tid = 0;
2381
2382 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002383 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002384 reinterpret_cast<void* (*)(void*)>(PIMutexWakeupHelper::thread_fn), this));
2385
2386 WaitUntilThreadSleep(child_tid);
2387 ASSERT_EQ(LOCK_CHILD_READY, progress);
2388 ASSERT_EQ(0, pthread_mutex_unlock(&start_thread_m.lock));
2389 progress = LOCK_WAITING;
2390 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
2391
2392 ASSERT_EQ(LOCK_RELEASED, progress);
2393 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2394 ASSERT_EQ(0, pthread_join(thread, nullptr));
2395 }
2396};
2397
2398TEST(pthread, pthread_mutex_pi_wakeup) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002399 for (int type : {PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_RECURSIVE, PTHREAD_MUTEX_ERRORCHECK}) {
2400 for (int protocol : {PTHREAD_PRIO_INHERIT}) {
2401 PIMutexWakeupHelper helper(type, protocol);
2402 helper.test();
2403 }
2404 }
2405}
2406
Yabin Cui140f3672015-02-03 10:32:00 -08002407TEST(pthread, pthread_mutex_owner_tid_limit) {
Yabin Cuie69c2452015-02-13 16:21:25 -08002408#if defined(__BIONIC__) && !defined(__LP64__)
Yabin Cui140f3672015-02-03 10:32:00 -08002409 FILE* fp = fopen("/proc/sys/kernel/pid_max", "r");
Yi Kong32bc0fc2018-08-02 17:31:13 -07002410 ASSERT_TRUE(fp != nullptr);
Yabin Cui140f3672015-02-03 10:32:00 -08002411 long pid_max;
2412 ASSERT_EQ(1, fscanf(fp, "%ld", &pid_max));
2413 fclose(fp);
Yabin Cuie69c2452015-02-13 16:21:25 -08002414 // Bionic's pthread_mutex implementation on 32-bit devices uses 16 bits to represent owner tid.
Yabin Cui140f3672015-02-03 10:32:00 -08002415 ASSERT_LE(pid_max, 65536);
Yabin Cuie69c2452015-02-13 16:21:25 -08002416#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002417 GTEST_SKIP() << "pthread_mutex supports 32-bit tid";
Yabin Cuie69c2452015-02-13 16:21:25 -08002418#endif
Yabin Cui140f3672015-02-03 10:32:00 -08002419}
Yabin Cuib5845722015-03-16 22:46:42 -07002420
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002421static void pthread_mutex_timedlock_helper(clockid_t clock,
2422 int (*lock_function)(pthread_mutex_t* __mutex,
2423 const timespec* __timeout)) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08002424 pthread_mutex_t m;
2425 ASSERT_EQ(0, pthread_mutex_init(&m, nullptr));
2426
2427 // If the mutex is already locked, pthread_mutex_timedlock should time out.
2428 ASSERT_EQ(0, pthread_mutex_lock(&m));
2429
2430 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002431 ASSERT_EQ(0, clock_gettime(clock, &ts));
2432 ASSERT_EQ(ETIMEDOUT, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002433 ts.tv_nsec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002434 ASSERT_EQ(EINVAL, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002435 ts.tv_nsec = NS_PER_S;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002436 ASSERT_EQ(EINVAL, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002437 ts.tv_nsec = NS_PER_S - 1;
2438 ts.tv_sec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002439 ASSERT_EQ(ETIMEDOUT, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002440
Elliott Hugheseabc47b2024-11-08 22:05:00 +00002441 // Check we wait long enough for the lock before timing out...
2442
2443 // What time is it before we start?
Andy Hung5e19b182023-12-11 19:28:02 -08002444 ASSERT_EQ(0, clock_gettime(clock, &ts));
Elliott Hugheseabc47b2024-11-08 22:05:00 +00002445 const int64_t start_ns = to_ns(ts);
2446 // Add a second to get deadline, and wait until we time out.
Andy Hung5e19b182023-12-11 19:28:02 -08002447 ts.tv_sec += 1;
Andy Hung5e19b182023-12-11 19:28:02 -08002448 ASSERT_EQ(ETIMEDOUT, lock_function(&m, &ts));
2449
Elliott Hugheseabc47b2024-11-08 22:05:00 +00002450 // What time is it now we've timed out?
2451 timespec ts2;
2452 clock_gettime(clock, &ts2);
2453 const int64_t end_ns = to_ns(ts2);
2454
Andy Hung5e19b182023-12-11 19:28:02 -08002455 // The timedlock must have waited at least 1 second before returning.
Elliott Hugheseabc47b2024-11-08 22:05:00 +00002456 ASSERT_GE(end_ns - start_ns, NS_PER_S);
Andy Hung5e19b182023-12-11 19:28:02 -08002457
Yabin Cuic9a659c2015-11-05 15:36:08 -08002458 // If the mutex is unlocked, pthread_mutex_timedlock should succeed.
2459 ASSERT_EQ(0, pthread_mutex_unlock(&m));
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002460 ASSERT_EQ(0, clock_gettime(clock, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002461 ts.tv_sec += 1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002462 ASSERT_EQ(0, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002463
2464 ASSERT_EQ(0, pthread_mutex_unlock(&m));
2465 ASSERT_EQ(0, pthread_mutex_destroy(&m));
2466}
2467
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002468TEST(pthread, pthread_mutex_timedlock) {
2469 pthread_mutex_timedlock_helper(CLOCK_REALTIME, pthread_mutex_timedlock);
2470}
2471
2472TEST(pthread, pthread_mutex_timedlock_monotonic_np) {
2473#if defined(__BIONIC__)
2474 pthread_mutex_timedlock_helper(CLOCK_MONOTONIC, pthread_mutex_timedlock_monotonic_np);
2475#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002476 GTEST_SKIP() << "pthread_mutex_timedlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002477#endif // __BIONIC__
2478}
2479
Elliott Hugheseabc47b2024-11-08 22:05:00 +00002480TEST(pthread, pthread_mutex_clocklock_MONOTONIC) {
Tom Cherry69010802019-05-07 20:33:05 -07002481#if defined(__BIONIC__)
2482 pthread_mutex_timedlock_helper(
2483 CLOCK_MONOTONIC, [](pthread_mutex_t* __mutex, const timespec* __timeout) {
2484 return pthread_mutex_clocklock(__mutex, CLOCK_MONOTONIC, __timeout);
2485 });
Elliott Hugheseabc47b2024-11-08 22:05:00 +00002486#else // __BIONIC__
2487 GTEST_SKIP() << "pthread_mutex_clocklock not available";
2488#endif // __BIONIC__
2489}
2490
2491TEST(pthread, pthread_mutex_clocklock_REALTIME) {
2492#if defined(__BIONIC__)
Tom Cherry69010802019-05-07 20:33:05 -07002493 pthread_mutex_timedlock_helper(
2494 CLOCK_REALTIME, [](pthread_mutex_t* __mutex, const timespec* __timeout) {
2495 return pthread_mutex_clocklock(__mutex, CLOCK_REALTIME, __timeout);
2496 });
2497#else // __BIONIC__
2498 GTEST_SKIP() << "pthread_mutex_clocklock not available";
2499#endif // __BIONIC__
2500}
2501
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002502static void pthread_mutex_timedlock_pi_helper(clockid_t clock,
2503 int (*lock_function)(pthread_mutex_t* __mutex,
2504 const timespec* __timeout)) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002505 PthreadMutex m(PTHREAD_MUTEX_NORMAL, PTHREAD_PRIO_INHERIT);
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002506
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002507 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002508 clock_gettime(clock, &ts);
Andy Hung5e19b182023-12-11 19:28:02 -08002509 const int64_t start_ns = ts.tv_sec * NS_PER_S + ts.tv_nsec;
2510
2511 // add a second to get deadline.
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002512 ts.tv_sec += 1;
Andy Hung5e19b182023-12-11 19:28:02 -08002513
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002514 ASSERT_EQ(0, lock_function(&m.lock, &ts));
2515
2516 struct ThreadArgs {
2517 clockid_t clock;
2518 int (*lock_function)(pthread_mutex_t* __mutex, const timespec* __timeout);
2519 PthreadMutex& m;
2520 };
2521
2522 ThreadArgs thread_args = {
2523 .clock = clock,
2524 .lock_function = lock_function,
2525 .m = m,
2526 };
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002527
2528 auto ThreadFn = [](void* arg) -> void* {
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002529 auto args = static_cast<ThreadArgs*>(arg);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002530 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002531 clock_gettime(args->clock, &ts);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002532 ts.tv_sec += 1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002533 intptr_t result = args->lock_function(&args->m.lock, &ts);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002534 return reinterpret_cast<void*>(result);
2535 };
2536
2537 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002538 ASSERT_EQ(0, pthread_create(&thread, nullptr, ThreadFn, &thread_args));
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002539 void* result;
2540 ASSERT_EQ(0, pthread_join(thread, &result));
2541 ASSERT_EQ(ETIMEDOUT, reinterpret_cast<intptr_t>(result));
Andy Hung5e19b182023-12-11 19:28:02 -08002542
2543 // The timedlock must have waited at least 1 second before returning.
2544 clock_gettime(clock, &ts);
2545 const int64_t end_ns = ts.tv_sec * NS_PER_S + ts.tv_nsec;
2546 ASSERT_GT(end_ns - start_ns, NS_PER_S);
2547
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002548 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2549}
2550
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002551TEST(pthread, pthread_mutex_timedlock_pi) {
2552 pthread_mutex_timedlock_pi_helper(CLOCK_REALTIME, pthread_mutex_timedlock);
2553}
2554
2555TEST(pthread, pthread_mutex_timedlock_monotonic_np_pi) {
2556#if defined(__BIONIC__)
2557 pthread_mutex_timedlock_pi_helper(CLOCK_MONOTONIC, pthread_mutex_timedlock_monotonic_np);
2558#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002559 GTEST_SKIP() << "pthread_mutex_timedlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002560#endif // __BIONIC__
2561}
2562
Tom Cherry69010802019-05-07 20:33:05 -07002563TEST(pthread, pthread_mutex_clocklock_pi) {
2564#if defined(__BIONIC__)
2565 pthread_mutex_timedlock_pi_helper(
2566 CLOCK_MONOTONIC, [](pthread_mutex_t* __mutex, const timespec* __timeout) {
2567 return pthread_mutex_clocklock(__mutex, CLOCK_MONOTONIC, __timeout);
2568 });
2569 pthread_mutex_timedlock_pi_helper(
2570 CLOCK_REALTIME, [](pthread_mutex_t* __mutex, const timespec* __timeout) {
2571 return pthread_mutex_clocklock(__mutex, CLOCK_REALTIME, __timeout);
2572 });
2573#else // __BIONIC__
2574 GTEST_SKIP() << "pthread_mutex_clocklock not available";
2575#endif // __BIONIC__
2576}
2577
2578TEST(pthread, pthread_mutex_clocklock_invalid) {
2579#if defined(__BIONIC__)
2580 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
2581 timespec ts;
2582 EXPECT_EQ(EINVAL, pthread_mutex_clocklock(&mutex, CLOCK_PROCESS_CPUTIME_ID, &ts));
2583#else // __BIONIC__
2584 GTEST_SKIP() << "pthread_mutex_clocklock not available";
2585#endif // __BIONIC__
2586}
2587
Elliott Hughese657eb42021-02-18 17:11:56 -08002588TEST_F(pthread_DeathTest, pthread_mutex_using_destroyed_mutex) {
Yabin Cui9651fdf2018-03-14 12:02:21 -07002589#if defined(__BIONIC__)
2590 pthread_mutex_t m;
2591 ASSERT_EQ(0, pthread_mutex_init(&m, nullptr));
2592 ASSERT_EQ(0, pthread_mutex_destroy(&m));
2593 ASSERT_EXIT(pthread_mutex_lock(&m), ::testing::KilledBySignal(SIGABRT),
2594 "pthread_mutex_lock called on a destroyed mutex");
2595 ASSERT_EXIT(pthread_mutex_unlock(&m), ::testing::KilledBySignal(SIGABRT),
2596 "pthread_mutex_unlock called on a destroyed mutex");
2597 ASSERT_EXIT(pthread_mutex_trylock(&m), ::testing::KilledBySignal(SIGABRT),
2598 "pthread_mutex_trylock called on a destroyed mutex");
2599 timespec ts;
2600 ASSERT_EXIT(pthread_mutex_timedlock(&m, &ts), ::testing::KilledBySignal(SIGABRT),
2601 "pthread_mutex_timedlock called on a destroyed mutex");
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002602 ASSERT_EXIT(pthread_mutex_timedlock_monotonic_np(&m, &ts), ::testing::KilledBySignal(SIGABRT),
2603 "pthread_mutex_timedlock_monotonic_np called on a destroyed mutex");
Tom Cherry69010802019-05-07 20:33:05 -07002604 ASSERT_EXIT(pthread_mutex_clocklock(&m, CLOCK_MONOTONIC, &ts), ::testing::KilledBySignal(SIGABRT),
2605 "pthread_mutex_clocklock called on a destroyed mutex");
2606 ASSERT_EXIT(pthread_mutex_clocklock(&m, CLOCK_REALTIME, &ts), ::testing::KilledBySignal(SIGABRT),
2607 "pthread_mutex_clocklock called on a destroyed mutex");
2608 ASSERT_EXIT(pthread_mutex_clocklock(&m, CLOCK_PROCESS_CPUTIME_ID, &ts),
2609 ::testing::KilledBySignal(SIGABRT),
2610 "pthread_mutex_clocklock called on a destroyed mutex");
Yabin Cui9651fdf2018-03-14 12:02:21 -07002611 ASSERT_EXIT(pthread_mutex_destroy(&m), ::testing::KilledBySignal(SIGABRT),
2612 "pthread_mutex_destroy called on a destroyed mutex");
2613#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002614 GTEST_SKIP() << "bionic-only test";
Yabin Cui9651fdf2018-03-14 12:02:21 -07002615#endif
2616}
2617
Yabin Cuib5845722015-03-16 22:46:42 -07002618class StrictAlignmentAllocator {
2619 public:
2620 void* allocate(size_t size, size_t alignment) {
2621 char* p = new char[size + alignment * 2];
2622 allocated_array.push_back(p);
2623 while (!is_strict_aligned(p, alignment)) {
2624 ++p;
2625 }
2626 return p;
2627 }
2628
2629 ~StrictAlignmentAllocator() {
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07002630 for (const auto& p : allocated_array) {
2631 delete[] p;
Yabin Cuib5845722015-03-16 22:46:42 -07002632 }
2633 }
2634
2635 private:
2636 bool is_strict_aligned(char* p, size_t alignment) {
2637 return (reinterpret_cast<uintptr_t>(p) % (alignment * 2)) == alignment;
2638 }
2639
2640 std::vector<char*> allocated_array;
2641};
2642
2643TEST(pthread, pthread_types_allow_four_bytes_alignment) {
2644#if defined(__BIONIC__)
2645 // For binary compatibility with old version, we need to allow 4-byte aligned data for pthread types.
2646 StrictAlignmentAllocator allocator;
2647 pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(
2648 allocator.allocate(sizeof(pthread_mutex_t), 4));
Yi Kong32bc0fc2018-08-02 17:31:13 -07002649 ASSERT_EQ(0, pthread_mutex_init(mutex, nullptr));
Yabin Cuib5845722015-03-16 22:46:42 -07002650 ASSERT_EQ(0, pthread_mutex_lock(mutex));
2651 ASSERT_EQ(0, pthread_mutex_unlock(mutex));
2652 ASSERT_EQ(0, pthread_mutex_destroy(mutex));
2653
2654 pthread_cond_t* cond = reinterpret_cast<pthread_cond_t*>(
2655 allocator.allocate(sizeof(pthread_cond_t), 4));
Yi Kong32bc0fc2018-08-02 17:31:13 -07002656 ASSERT_EQ(0, pthread_cond_init(cond, nullptr));
Yabin Cuib5845722015-03-16 22:46:42 -07002657 ASSERT_EQ(0, pthread_cond_signal(cond));
2658 ASSERT_EQ(0, pthread_cond_broadcast(cond));
2659 ASSERT_EQ(0, pthread_cond_destroy(cond));
2660
2661 pthread_rwlock_t* rwlock = reinterpret_cast<pthread_rwlock_t*>(
2662 allocator.allocate(sizeof(pthread_rwlock_t), 4));
Yi Kong32bc0fc2018-08-02 17:31:13 -07002663 ASSERT_EQ(0, pthread_rwlock_init(rwlock, nullptr));
Yabin Cuib5845722015-03-16 22:46:42 -07002664 ASSERT_EQ(0, pthread_rwlock_rdlock(rwlock));
2665 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
2666 ASSERT_EQ(0, pthread_rwlock_wrlock(rwlock));
2667 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
2668 ASSERT_EQ(0, pthread_rwlock_destroy(rwlock));
2669
2670#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002671 GTEST_SKIP() << "bionic-only test";
Yabin Cuib5845722015-03-16 22:46:42 -07002672#endif
2673}
Christopher Ferris60907c72015-06-09 18:46:15 -07002674
2675TEST(pthread, pthread_mutex_lock_null_32) {
2676#if defined(__BIONIC__) && !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -07002677 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return
2678 // EINVAL in that case: http://b/19995172.
2679 //
2680 // We decorate the public defintion with _Nonnull so that people recompiling
2681 // their code with get a warning and might fix their bug, but need to pass
2682 // NULL here to test that we remain compatible.
2683 pthread_mutex_t* null_value = nullptr;
2684 ASSERT_EQ(EINVAL, pthread_mutex_lock(null_value));
Christopher Ferris60907c72015-06-09 18:46:15 -07002685#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002686 GTEST_SKIP() << "32-bit bionic-only test";
Christopher Ferris60907c72015-06-09 18:46:15 -07002687#endif
2688}
2689
2690TEST(pthread, pthread_mutex_unlock_null_32) {
2691#if defined(__BIONIC__) && !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -07002692 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return
2693 // EINVAL in that case: http://b/19995172.
2694 //
2695 // We decorate the public defintion with _Nonnull so that people recompiling
2696 // their code with get a warning and might fix their bug, but need to pass
2697 // NULL here to test that we remain compatible.
2698 pthread_mutex_t* null_value = nullptr;
2699 ASSERT_EQ(EINVAL, pthread_mutex_unlock(null_value));
Christopher Ferris60907c72015-06-09 18:46:15 -07002700#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002701 GTEST_SKIP() << "32-bit bionic-only test";
Christopher Ferris60907c72015-06-09 18:46:15 -07002702#endif
2703}
2704
2705TEST_F(pthread_DeathTest, pthread_mutex_lock_null_64) {
2706#if defined(__BIONIC__) && defined(__LP64__)
2707 pthread_mutex_t* null_value = nullptr;
2708 ASSERT_EXIT(pthread_mutex_lock(null_value), testing::KilledBySignal(SIGSEGV), "");
2709#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002710 GTEST_SKIP() << "64-bit bionic-only test";
Christopher Ferris60907c72015-06-09 18:46:15 -07002711#endif
2712}
2713
2714TEST_F(pthread_DeathTest, pthread_mutex_unlock_null_64) {
2715#if defined(__BIONIC__) && defined(__LP64__)
2716 pthread_mutex_t* null_value = nullptr;
2717 ASSERT_EXIT(pthread_mutex_unlock(null_value), testing::KilledBySignal(SIGSEGV), "");
2718#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002719 GTEST_SKIP() << "64-bit bionic-only test";
Christopher Ferris60907c72015-06-09 18:46:15 -07002720#endif
2721}
Yabin Cui33ac04a2015-09-22 11:16:15 -07002722
2723extern _Unwind_Reason_Code FrameCounter(_Unwind_Context* ctx, void* arg);
2724
2725static volatile bool signal_handler_on_altstack_done;
2726
Josh Gao61db9ac2017-03-15 19:42:05 -07002727__attribute__((__noinline__))
2728static void signal_handler_backtrace() {
2729 // Check if we have enough stack space for unwinding.
2730 int count = 0;
2731 _Unwind_Backtrace(FrameCounter, &count);
2732 ASSERT_GT(count, 0);
2733}
2734
2735__attribute__((__noinline__))
2736static void signal_handler_logging() {
2737 // Check if we have enough stack space for logging.
2738 std::string s(2048, '*');
2739 GTEST_LOG_(INFO) << s;
2740 signal_handler_on_altstack_done = true;
2741}
2742
2743__attribute__((__noinline__))
2744static void signal_handler_snprintf() {
2745 // Check if we have enough stack space for snprintf to a PATH_MAX buffer, plus some extra.
2746 char buf[PATH_MAX + 2048];
2747 ASSERT_GT(snprintf(buf, sizeof(buf), "/proc/%d/status", getpid()), 0);
2748}
2749
Yabin Cui33ac04a2015-09-22 11:16:15 -07002750static void SignalHandlerOnAltStack(int signo, siginfo_t*, void*) {
2751 ASSERT_EQ(SIGUSR1, signo);
Josh Gao61db9ac2017-03-15 19:42:05 -07002752 signal_handler_backtrace();
2753 signal_handler_logging();
2754 signal_handler_snprintf();
Yabin Cui33ac04a2015-09-22 11:16:15 -07002755}
2756
Josh Gao415daa82017-03-06 17:45:33 -08002757TEST(pthread, big_enough_signal_stack) {
Yabin Cui33ac04a2015-09-22 11:16:15 -07002758 signal_handler_on_altstack_done = false;
2759 ScopedSignalHandler handler(SIGUSR1, SignalHandlerOnAltStack, SA_SIGINFO | SA_ONSTACK);
2760 kill(getpid(), SIGUSR1);
2761 ASSERT_TRUE(signal_handler_on_altstack_done);
2762}
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002763
2764TEST(pthread, pthread_barrierattr_smoke) {
2765 pthread_barrierattr_t attr;
2766 ASSERT_EQ(0, pthread_barrierattr_init(&attr));
2767 int pshared;
2768 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
2769 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
2770 ASSERT_EQ(0, pthread_barrierattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
2771 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
2772 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
2773 ASSERT_EQ(0, pthread_barrierattr_destroy(&attr));
2774}
2775
Yabin Cui81d27972016-03-22 13:45:55 -07002776struct BarrierTestHelperData {
2777 size_t thread_count;
2778 pthread_barrier_t barrier;
2779 std::atomic<int> finished_mask;
2780 std::atomic<int> serial_thread_count;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002781 size_t iteration_count;
Yabin Cui81d27972016-03-22 13:45:55 -07002782 std::atomic<size_t> finished_iteration_count;
2783
2784 BarrierTestHelperData(size_t thread_count, size_t iteration_count)
2785 : thread_count(thread_count), finished_mask(0), serial_thread_count(0),
2786 iteration_count(iteration_count), finished_iteration_count(0) {
2787 }
2788};
2789
2790struct BarrierTestHelperArg {
2791 int id;
2792 BarrierTestHelperData* data;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002793};
2794
2795static void BarrierTestHelper(BarrierTestHelperArg* arg) {
Yabin Cui81d27972016-03-22 13:45:55 -07002796 for (size_t i = 0; i < arg->data->iteration_count; ++i) {
2797 int result = pthread_barrier_wait(&arg->data->barrier);
2798 if (result == PTHREAD_BARRIER_SERIAL_THREAD) {
2799 arg->data->serial_thread_count++;
2800 } else {
2801 ASSERT_EQ(0, result);
2802 }
Yabin Cuid5c04c52017-05-02 12:57:39 -07002803 int mask = arg->data->finished_mask.fetch_or(1 << arg->id);
Yabin Cuiab4cddc2017-05-02 16:18:13 -07002804 mask |= 1 << arg->id;
Yabin Cuid5c04c52017-05-02 12:57:39 -07002805 if (mask == ((1 << arg->data->thread_count) - 1)) {
Yabin Cui81d27972016-03-22 13:45:55 -07002806 ASSERT_EQ(1, arg->data->serial_thread_count);
2807 arg->data->finished_iteration_count++;
2808 arg->data->finished_mask = 0;
2809 arg->data->serial_thread_count = 0;
2810 }
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002811 }
2812}
2813
2814TEST(pthread, pthread_barrier_smoke) {
2815 const size_t BARRIER_ITERATION_COUNT = 10;
2816 const size_t BARRIER_THREAD_COUNT = 10;
Yabin Cui81d27972016-03-22 13:45:55 -07002817 BarrierTestHelperData data(BARRIER_THREAD_COUNT, BARRIER_ITERATION_COUNT);
2818 ASSERT_EQ(0, pthread_barrier_init(&data.barrier, nullptr, data.thread_count));
2819 std::vector<pthread_t> threads(data.thread_count);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002820 std::vector<BarrierTestHelperArg> args(threads.size());
2821 for (size_t i = 0; i < threads.size(); ++i) {
Yabin Cui81d27972016-03-22 13:45:55 -07002822 args[i].id = i;
2823 args[i].data = &data;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002824 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
2825 reinterpret_cast<void* (*)(void*)>(BarrierTestHelper), &args[i]));
2826 }
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002827 for (size_t i = 0; i < threads.size(); ++i) {
2828 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
2829 }
Yabin Cui81d27972016-03-22 13:45:55 -07002830 ASSERT_EQ(data.iteration_count, data.finished_iteration_count);
2831 ASSERT_EQ(0, pthread_barrier_destroy(&data.barrier));
2832}
2833
2834struct BarrierDestroyTestArg {
2835 std::atomic<int> tid;
2836 pthread_barrier_t* barrier;
2837};
2838
2839static void BarrierDestroyTestHelper(BarrierDestroyTestArg* arg) {
2840 arg->tid = gettid();
2841 ASSERT_EQ(0, pthread_barrier_wait(arg->barrier));
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002842}
2843
2844TEST(pthread, pthread_barrier_destroy) {
2845 pthread_barrier_t barrier;
2846 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, 2));
2847 pthread_t thread;
Yabin Cui81d27972016-03-22 13:45:55 -07002848 BarrierDestroyTestArg arg;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002849 arg.tid = 0;
2850 arg.barrier = &barrier;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002851 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui81d27972016-03-22 13:45:55 -07002852 reinterpret_cast<void* (*)(void*)>(BarrierDestroyTestHelper), &arg));
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002853 WaitUntilThreadSleep(arg.tid);
2854 ASSERT_EQ(EBUSY, pthread_barrier_destroy(&barrier));
2855 ASSERT_EQ(PTHREAD_BARRIER_SERIAL_THREAD, pthread_barrier_wait(&barrier));
2856 // Verify if the barrier can be destroyed directly after pthread_barrier_wait().
2857 ASSERT_EQ(0, pthread_barrier_destroy(&barrier));
2858 ASSERT_EQ(0, pthread_join(thread, nullptr));
2859#if defined(__BIONIC__)
2860 ASSERT_EQ(EINVAL, pthread_barrier_destroy(&barrier));
2861#endif
2862}
2863
2864struct BarrierOrderingTestHelperArg {
2865 pthread_barrier_t* barrier;
2866 size_t* array;
2867 size_t array_length;
2868 size_t id;
2869};
2870
2871void BarrierOrderingTestHelper(BarrierOrderingTestHelperArg* arg) {
2872 const size_t ITERATION_COUNT = 10000;
2873 for (size_t i = 1; i <= ITERATION_COUNT; ++i) {
2874 arg->array[arg->id] = i;
Yabin Cuic9a659c2015-11-05 15:36:08 -08002875 int result = pthread_barrier_wait(arg->barrier);
2876 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002877 for (size_t j = 0; j < arg->array_length; ++j) {
2878 ASSERT_EQ(i, arg->array[j]);
2879 }
Yabin Cuic9a659c2015-11-05 15:36:08 -08002880 result = pthread_barrier_wait(arg->barrier);
2881 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002882 }
2883}
2884
2885TEST(pthread, pthread_barrier_check_ordering) {
2886 const size_t THREAD_COUNT = 4;
2887 pthread_barrier_t barrier;
2888 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, THREAD_COUNT));
2889 size_t array[THREAD_COUNT];
2890 std::vector<pthread_t> threads(THREAD_COUNT);
2891 std::vector<BarrierOrderingTestHelperArg> args(THREAD_COUNT);
2892 for (size_t i = 0; i < THREAD_COUNT; ++i) {
2893 args[i].barrier = &barrier;
2894 args[i].array = array;
2895 args[i].array_length = THREAD_COUNT;
2896 args[i].id = i;
2897 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
2898 reinterpret_cast<void* (*)(void*)>(BarrierOrderingTestHelper),
2899 &args[i]));
2900 }
2901 for (size_t i = 0; i < THREAD_COUNT; ++i) {
2902 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
2903 }
2904}
Yabin Cuife3a83a2015-11-17 16:03:18 -08002905
Elliott Hughes463faad2018-07-06 14:34:49 -07002906TEST(pthread, pthread_barrier_init_zero_count) {
2907 pthread_barrier_t barrier;
2908 ASSERT_EQ(EINVAL, pthread_barrier_init(&barrier, nullptr, 0));
2909}
2910
Yabin Cuife3a83a2015-11-17 16:03:18 -08002911TEST(pthread, pthread_spinlock_smoke) {
2912 pthread_spinlock_t lock;
2913 ASSERT_EQ(0, pthread_spin_init(&lock, 0));
2914 ASSERT_EQ(0, pthread_spin_trylock(&lock));
2915 ASSERT_EQ(0, pthread_spin_unlock(&lock));
2916 ASSERT_EQ(0, pthread_spin_lock(&lock));
2917 ASSERT_EQ(EBUSY, pthread_spin_trylock(&lock));
2918 ASSERT_EQ(0, pthread_spin_unlock(&lock));
2919 ASSERT_EQ(0, pthread_spin_destroy(&lock));
2920}
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002921
Elliott Hughes8aecba72017-10-17 15:34:41 -07002922TEST(pthread, pthread_attr_getdetachstate__pthread_attr_setdetachstate) {
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002923 pthread_attr_t attr;
2924 ASSERT_EQ(0, pthread_attr_init(&attr));
2925
Elliott Hughes8aecba72017-10-17 15:34:41 -07002926 int state;
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002927 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002928 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2929 ASSERT_EQ(PTHREAD_CREATE_DETACHED, state);
2930
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002931 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002932 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2933 ASSERT_EQ(PTHREAD_CREATE_JOINABLE, state);
2934
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002935 ASSERT_EQ(EINVAL, pthread_attr_setdetachstate(&attr, 123));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002936 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2937 ASSERT_EQ(PTHREAD_CREATE_JOINABLE, state);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002938}
2939
2940TEST(pthread, pthread_create__mmap_failures) {
Evgeny Eltsinb4f7aaa2020-06-09 15:49:20 +02002941 // After thread is successfully created, native_bridge might need more memory to run it.
2942 SKIP_WITH_NATIVE_BRIDGE;
2943
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002944 pthread_attr_t attr;
2945 ASSERT_EQ(0, pthread_attr_init(&attr));
2946 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
2947
2948 const auto kPageSize = sysconf(_SC_PAGE_SIZE);
2949
Elliott Hughes57512982017-10-02 22:49:18 -07002950 // Use up all the VMAs. By default this is 64Ki (though some will already be in use).
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002951 std::vector<void*> pages;
Elliott Hughes57512982017-10-02 22:49:18 -07002952 pages.reserve(64 * 1024);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002953 int prot = PROT_NONE;
2954 while (true) {
2955 void* page = mmap(nullptr, kPageSize, prot, MAP_ANON|MAP_PRIVATE, -1, 0);
2956 if (page == MAP_FAILED) break;
2957 pages.push_back(page);
2958 prot = (prot == PROT_NONE) ? PROT_READ : PROT_NONE;
2959 }
2960
2961 // Try creating threads, freeing up a page each time we fail.
2962 size_t EAGAIN_count = 0;
2963 size_t i = 0;
2964 for (; i < pages.size(); ++i) {
2965 pthread_t t;
2966 int status = pthread_create(&t, &attr, IdFn, nullptr);
2967 if (status != EAGAIN) break;
2968 ++EAGAIN_count;
2969 ASSERT_EQ(0, munmap(pages[i], kPageSize));
2970 }
2971
Ryan Prichard45d13492019-01-03 02:51:30 -08002972 // Creating a thread uses at least three VMAs: the combined stack and TLS, and a guard on each
2973 // side. So we should have seen at least three failures.
2974 ASSERT_GE(EAGAIN_count, 3U);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002975
2976 for (; i < pages.size(); ++i) {
2977 ASSERT_EQ(0, munmap(pages[i], kPageSize));
2978 }
2979}
Elliott Hughesdff08ce2017-10-16 09:58:45 -07002980
2981TEST(pthread, pthread_setschedparam) {
2982 sched_param p = { .sched_priority = INT_MIN };
2983 ASSERT_EQ(EINVAL, pthread_setschedparam(pthread_self(), INT_MIN, &p));
2984}
2985
2986TEST(pthread, pthread_setschedprio) {
2987 ASSERT_EQ(EINVAL, pthread_setschedprio(pthread_self(), INT_MIN));
2988}
Elliott Hughes8aecba72017-10-17 15:34:41 -07002989
2990TEST(pthread, pthread_attr_getinheritsched__pthread_attr_setinheritsched) {
2991 pthread_attr_t attr;
2992 ASSERT_EQ(0, pthread_attr_init(&attr));
2993
2994 int state;
2995 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2996 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
2997 ASSERT_EQ(PTHREAD_INHERIT_SCHED, state);
2998
2999 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
3000 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
3001 ASSERT_EQ(PTHREAD_EXPLICIT_SCHED, state);
3002
3003 ASSERT_EQ(EINVAL, pthread_attr_setinheritsched(&attr, 123));
3004 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
3005 ASSERT_EQ(PTHREAD_EXPLICIT_SCHED, state);
3006}
3007
3008TEST(pthread, pthread_attr_setinheritsched__PTHREAD_INHERIT_SCHED__PTHREAD_EXPLICIT_SCHED) {
3009 pthread_attr_t attr;
3010 ASSERT_EQ(0, pthread_attr_init(&attr));
3011
3012 // If we set invalid scheduling attributes but choose to inherit, everything's fine...
3013 sched_param param = { .sched_priority = sched_get_priority_max(SCHED_FIFO) + 1 };
3014 ASSERT_EQ(0, pthread_attr_setschedparam(&attr, &param));
3015 ASSERT_EQ(0, pthread_attr_setschedpolicy(&attr, SCHED_FIFO));
3016 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
3017
3018 pthread_t t;
3019 ASSERT_EQ(0, pthread_create(&t, &attr, IdFn, nullptr));
3020 ASSERT_EQ(0, pthread_join(t, nullptr));
3021
Elliott Hughes7a660662017-10-30 09:26:06 -07003022#if defined(__LP64__)
3023 // If we ask to use them, though, we'll see a failure...
Elliott Hughes8aecba72017-10-17 15:34:41 -07003024 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
3025 ASSERT_EQ(EINVAL, pthread_create(&t, &attr, IdFn, nullptr));
Elliott Hughes7a660662017-10-30 09:26:06 -07003026#else
3027 // For backwards compatibility with broken apps, we just ignore failures
3028 // to set scheduler attributes on LP32.
3029#endif
Elliott Hughes8aecba72017-10-17 15:34:41 -07003030}
3031
3032TEST(pthread, pthread_attr_setinheritsched_PTHREAD_INHERIT_SCHED_takes_effect) {
3033 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
3034 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO, &param);
Elliott Hughesbcaa4542019-03-08 15:20:23 -08003035 if (rc == EPERM) GTEST_SKIP() << "pthread_setschedparam failed with EPERM";
Elliott Hughes8aecba72017-10-17 15:34:41 -07003036 ASSERT_EQ(0, rc);
3037
3038 pthread_attr_t attr;
3039 ASSERT_EQ(0, pthread_attr_init(&attr));
3040 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
3041
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003042 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07003043 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003044 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07003045 int actual_policy;
3046 sched_param actual_param;
3047 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
3048 ASSERT_EQ(SCHED_FIFO, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003049 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07003050 ASSERT_EQ(0, pthread_join(t, nullptr));
3051}
3052
3053TEST(pthread, pthread_attr_setinheritsched_PTHREAD_EXPLICIT_SCHED_takes_effect) {
3054 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
3055 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO, &param);
Elliott Hughesbcaa4542019-03-08 15:20:23 -08003056 if (rc == EPERM) GTEST_SKIP() << "pthread_setschedparam failed with EPERM";
Elliott Hughes8aecba72017-10-17 15:34:41 -07003057 ASSERT_EQ(0, rc);
3058
3059 pthread_attr_t attr;
3060 ASSERT_EQ(0, pthread_attr_init(&attr));
3061 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
3062 ASSERT_EQ(0, pthread_attr_setschedpolicy(&attr, SCHED_OTHER));
3063
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003064 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07003065 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003066 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07003067 int actual_policy;
3068 sched_param actual_param;
3069 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
3070 ASSERT_EQ(SCHED_OTHER, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003071 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07003072 ASSERT_EQ(0, pthread_join(t, nullptr));
3073}
3074
3075TEST(pthread, pthread_attr_setinheritsched__takes_effect_despite_SCHED_RESET_ON_FORK) {
3076 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
3077 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param);
Elliott Hughesbcaa4542019-03-08 15:20:23 -08003078 if (rc == EPERM) GTEST_SKIP() << "pthread_setschedparam failed with EPERM";
Elliott Hughes8aecba72017-10-17 15:34:41 -07003079 ASSERT_EQ(0, rc);
3080
3081 pthread_attr_t attr;
3082 ASSERT_EQ(0, pthread_attr_init(&attr));
3083 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
3084
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003085 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07003086 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003087 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07003088 int actual_policy;
3089 sched_param actual_param;
3090 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
3091 ASSERT_EQ(SCHED_FIFO | SCHED_RESET_ON_FORK, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07003092 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07003093 ASSERT_EQ(0, pthread_join(t, nullptr));
3094}
Peter Collingbourne5d3aa862020-09-11 15:05:17 -07003095
3096extern "C" bool android_run_on_all_threads(bool (*func)(void*), void* arg);
3097
3098TEST(pthread, run_on_all_threads) {
3099#if defined(__BIONIC__)
3100 pthread_t t;
3101 ASSERT_EQ(
3102 0, pthread_create(
3103 &t, nullptr,
3104 [](void*) -> void* {
3105 pthread_attr_t detached;
3106 if (pthread_attr_init(&detached) != 0 ||
3107 pthread_attr_setdetachstate(&detached, PTHREAD_CREATE_DETACHED) != 0) {
3108 return reinterpret_cast<void*>(errno);
3109 }
3110
3111 for (int i = 0; i != 1000; ++i) {
3112 pthread_t t1, t2;
3113 if (pthread_create(
3114 &t1, &detached, [](void*) -> void* { return nullptr; }, nullptr) != 0 ||
3115 pthread_create(
3116 &t2, nullptr, [](void*) -> void* { return nullptr; }, nullptr) != 0 ||
3117 pthread_join(t2, nullptr) != 0) {
3118 return reinterpret_cast<void*>(errno);
3119 }
3120 }
3121
3122 if (pthread_attr_destroy(&detached) != 0) {
3123 return reinterpret_cast<void*>(errno);
3124 }
3125 return nullptr;
3126 },
3127 nullptr));
3128
3129 for (int i = 0; i != 1000; ++i) {
3130 ASSERT_TRUE(android_run_on_all_threads([](void* arg) { return arg == nullptr; }, nullptr));
3131 }
3132
3133 void *retval;
3134 ASSERT_EQ(0, pthread_join(t, &retval));
3135 ASSERT_EQ(nullptr, retval);
3136#else
3137 GTEST_SKIP() << "bionic-only test";
3138#endif
3139}
Elliott Hughese117d6e2024-11-14 17:31:13 +00003140
3141TEST(pthread, pthread_getaffinity_np_failure) {
3142 // Trivial test of the errno-preserving/returning behavior.
3143#pragma clang diagnostic push
3144#pragma clang diagnostic ignored "-Wnonnull"
3145 errno = 0;
3146 ASSERT_EQ(EINVAL, pthread_getaffinity_np(pthread_self(), 0, nullptr));
3147 ASSERT_ERRNO(0);
3148#pragma clang diagnostic pop
3149}
3150
3151TEST(pthread, pthread_setaffinity_np_failure) {
3152 // Trivial test of the errno-preserving/returning behavior.
3153#pragma clang diagnostic push
3154#pragma clang diagnostic ignored "-Wnonnull"
3155 errno = 0;
3156 ASSERT_EQ(EINVAL, pthread_setaffinity_np(pthread_self(), 0, nullptr));
3157 ASSERT_ERRNO(0);
3158#pragma clang diagnostic pop
3159}