blob: 3686ffb3dfc2dae79583ccdf991585521eace5f7 [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>
Elliott Hughes70b24b12013-11-15 11:51:07 -080026#include <sys/mman.h>
Elliott Hughes4d098ca2016-04-11 12:43:05 -070027#include <sys/prctl.h>
George Burgess IV08fd0722019-01-15 19:00:11 -080028#include <sys/resource.h>
Elliott Hughes57b7a612014-08-25 17:26:50 -070029#include <sys/syscall.h>
Narayan Kamath51e6cb32014-03-03 15:38:51 +000030#include <time.h>
Elliott Hughes4d014e12012-09-07 16:47:54 -070031#include <unistd.h>
Yabin Cui33ac04a2015-09-22 11:16:15 -070032#include <unwind.h>
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070033
Yabin Cui08ee8d22015-02-11 17:04:36 -080034#include <atomic>
Josh Gaoddf757e2018-10-17 15:23:03 -070035#include <future>
Yabin Cuib5845722015-03-16 22:46:42 -070036#include <vector>
Yabin Cui08ee8d22015-02-11 17:04:36 -080037
Elliott Hughes5e62b342018-10-25 11:00:00 -070038#include <android-base/macros.h>
Yabin Cui6b9c85b2018-01-23 12:56:18 -080039#include <android-base/parseint.h>
Tom Cherryb8ab6182017-04-05 16:20:29 -070040#include <android-base/scopeguard.h>
Elliott Hughes141b9172021-04-09 17:13:09 -070041#include <android-base/silent_death_test.h>
Yabin Cui6b9c85b2018-01-23 12:56:18 -080042#include <android-base/strings.h>
Tom Cherryb8ab6182017-04-05 16:20:29 -070043
Yabin Cuic9a659c2015-11-05 15:36:08 -080044#include "private/bionic_constants.h"
Elliott Hughes71ba5892018-02-07 12:44:45 -080045#include "SignalUtils.h"
Elliott Hughes15dfd632015-09-22 16:40:14 -070046#include "utils.h"
47
Elliott Hughes141b9172021-04-09 17:13:09 -070048using pthread_DeathTest = SilentDeathTest;
Elliott Hughese657eb42021-02-18 17:11:56 -080049
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070050TEST(pthread, pthread_key_create) {
51 pthread_key_t key;
Yi Kong32bc0fc2018-08-02 17:31:13 -070052 ASSERT_EQ(0, pthread_key_create(&key, nullptr));
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070053 ASSERT_EQ(0, pthread_key_delete(key));
54 // Can't delete a key that's already been deleted.
55 ASSERT_EQ(EINVAL, pthread_key_delete(key));
56}
Elliott Hughes4d014e12012-09-07 16:47:54 -070057
Dan Albertc4bcc752014-09-30 11:48:24 -070058TEST(pthread, pthread_keys_max) {
Yabin Cui6c238f22014-12-11 20:50:41 -080059 // POSIX says PTHREAD_KEYS_MAX should be at least _POSIX_THREAD_KEYS_MAX.
60 ASSERT_GE(PTHREAD_KEYS_MAX, _POSIX_THREAD_KEYS_MAX);
Dan Albertc4bcc752014-09-30 11:48:24 -070061}
Elliott Hughes718a5b52014-01-28 17:02:03 -080062
Yabin Cui6c238f22014-12-11 20:50:41 -080063TEST(pthread, sysconf_SC_THREAD_KEYS_MAX_eq_PTHREAD_KEYS_MAX) {
Dan Albertc4bcc752014-09-30 11:48:24 -070064 int sysconf_max = sysconf(_SC_THREAD_KEYS_MAX);
Yabin Cui6c238f22014-12-11 20:50:41 -080065 ASSERT_EQ(sysconf_max, PTHREAD_KEYS_MAX);
Dan Albertc4bcc752014-09-30 11:48:24 -070066}
67
68TEST(pthread, pthread_key_many_distinct) {
Yabin Cui6c238f22014-12-11 20:50:41 -080069 // As gtest uses pthread keys, we can't allocate exactly PTHREAD_KEYS_MAX
70 // pthread keys, but We should be able to allocate at least this many keys.
71 int nkeys = PTHREAD_KEYS_MAX / 2;
Dan Albertc4bcc752014-09-30 11:48:24 -070072 std::vector<pthread_key_t> keys;
73
Tom Cherryb8ab6182017-04-05 16:20:29 -070074 auto scope_guard = android::base::make_scope_guard([&keys] {
Elliott Hughes0b2acdf2015-10-02 18:25:19 -070075 for (const auto& key : keys) {
Dan Albertc4bcc752014-09-30 11:48:24 -070076 EXPECT_EQ(0, pthread_key_delete(key));
77 }
78 });
79
80 for (int i = 0; i < nkeys; ++i) {
81 pthread_key_t key;
Elliott Hughes61706932015-03-31 10:56:58 -070082 // If this fails, it's likely that LIBC_PTHREAD_KEY_RESERVED_COUNT is wrong.
Yi Kong32bc0fc2018-08-02 17:31:13 -070083 ASSERT_EQ(0, pthread_key_create(&key, nullptr)) << i << " of " << nkeys;
Dan Albertc4bcc752014-09-30 11:48:24 -070084 keys.push_back(key);
85 ASSERT_EQ(0, pthread_setspecific(key, reinterpret_cast<void*>(i)));
86 }
87
88 for (int i = keys.size() - 1; i >= 0; --i) {
89 ASSERT_EQ(reinterpret_cast<void*>(i), pthread_getspecific(keys.back()));
90 pthread_key_t key = keys.back();
91 keys.pop_back();
92 ASSERT_EQ(0, pthread_key_delete(key));
93 }
94}
95
Yabin Cui6c238f22014-12-11 20:50:41 -080096TEST(pthread, pthread_key_not_exceed_PTHREAD_KEYS_MAX) {
Elliott Hughes44b53ad2013-02-11 20:18:47 +000097 std::vector<pthread_key_t> keys;
Dan Albertc4bcc752014-09-30 11:48:24 -070098 int rv = 0;
Yabin Cui6c238f22014-12-11 20:50:41 -080099
100 // Pthread keys are used by gtest, so PTHREAD_KEYS_MAX should
101 // be more than we are allowed to allocate now.
102 for (int i = 0; i < PTHREAD_KEYS_MAX; i++) {
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000103 pthread_key_t key;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700104 rv = pthread_key_create(&key, nullptr);
Dan Albertc4bcc752014-09-30 11:48:24 -0700105 if (rv == EAGAIN) {
106 break;
107 }
108 EXPECT_EQ(0, rv);
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000109 keys.push_back(key);
110 }
111
Dan Albertc4bcc752014-09-30 11:48:24 -0700112 // Don't leak keys.
Elliott Hughes0b2acdf2015-10-02 18:25:19 -0700113 for (const auto& key : keys) {
Dan Albertc4bcc752014-09-30 11:48:24 -0700114 EXPECT_EQ(0, pthread_key_delete(key));
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000115 }
Dan Albertc4bcc752014-09-30 11:48:24 -0700116 keys.clear();
117
118 // We should have eventually reached the maximum number of keys and received
119 // EAGAIN.
120 ASSERT_EQ(EAGAIN, rv);
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000121}
122
Elliott Hughesebb770f2014-06-25 13:46:46 -0700123TEST(pthread, pthread_key_delete) {
124 void* expected = reinterpret_cast<void*>(1234);
125 pthread_key_t key;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700126 ASSERT_EQ(0, pthread_key_create(&key, nullptr));
Elliott Hughesebb770f2014-06-25 13:46:46 -0700127 ASSERT_EQ(0, pthread_setspecific(key, expected));
128 ASSERT_EQ(expected, pthread_getspecific(key));
129 ASSERT_EQ(0, pthread_key_delete(key));
Yi Kong32bc0fc2018-08-02 17:31:13 -0700130 // After deletion, pthread_getspecific returns nullptr.
131 ASSERT_EQ(nullptr, pthread_getspecific(key));
Elliott Hughesebb770f2014-06-25 13:46:46 -0700132 // And you can't use pthread_setspecific with the deleted key.
133 ASSERT_EQ(EINVAL, pthread_setspecific(key, expected));
134}
135
Elliott Hughes40a52172014-07-30 14:48:10 -0700136TEST(pthread, pthread_key_fork) {
137 void* expected = reinterpret_cast<void*>(1234);
138 pthread_key_t key;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700139 ASSERT_EQ(0, pthread_key_create(&key, nullptr));
Elliott Hughes40a52172014-07-30 14:48:10 -0700140 ASSERT_EQ(0, pthread_setspecific(key, expected));
141 ASSERT_EQ(expected, pthread_getspecific(key));
142
143 pid_t pid = fork();
144 ASSERT_NE(-1, pid) << strerror(errno);
145
146 if (pid == 0) {
147 // The surviving thread inherits all the forking thread's TLS values...
148 ASSERT_EQ(expected, pthread_getspecific(key));
149 _exit(99);
150 }
151
Elliott Hughes33697a02016-01-26 13:04:57 -0800152 AssertChildExited(pid, 99);
Elliott Hughes40a52172014-07-30 14:48:10 -0700153
154 ASSERT_EQ(expected, pthread_getspecific(key));
Dan Albert1d53ae22014-09-02 15:24:26 -0700155 ASSERT_EQ(0, pthread_key_delete(key));
Elliott Hughes40a52172014-07-30 14:48:10 -0700156}
157
158static void* DirtyKeyFn(void* key) {
159 return pthread_getspecific(*reinterpret_cast<pthread_key_t*>(key));
160}
161
162TEST(pthread, pthread_key_dirty) {
163 pthread_key_t key;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700164 ASSERT_EQ(0, pthread_key_create(&key, nullptr));
Elliott Hughes40a52172014-07-30 14:48:10 -0700165
Yabin Cuia36158a2015-11-16 21:06:16 -0800166 size_t stack_size = 640 * 1024;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700167 void* stack = mmap(nullptr, stack_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
Elliott Hughes40a52172014-07-30 14:48:10 -0700168 ASSERT_NE(MAP_FAILED, stack);
169 memset(stack, 0xff, stack_size);
170
171 pthread_attr_t attr;
172 ASSERT_EQ(0, pthread_attr_init(&attr));
173 ASSERT_EQ(0, pthread_attr_setstack(&attr, stack, stack_size));
174
175 pthread_t t;
176 ASSERT_EQ(0, pthread_create(&t, &attr, DirtyKeyFn, &key));
177
178 void* result;
179 ASSERT_EQ(0, pthread_join(t, &result));
180 ASSERT_EQ(nullptr, result); // Not ~0!
181
182 ASSERT_EQ(0, munmap(stack, stack_size));
Dan Albert1d53ae22014-09-02 15:24:26 -0700183 ASSERT_EQ(0, pthread_key_delete(key));
Elliott Hughes40a52172014-07-30 14:48:10 -0700184}
185
Yabin Cui5ddbb3f2015-03-05 20:35:32 -0800186TEST(pthread, static_pthread_key_used_before_creation) {
187#if defined(__BIONIC__)
188 // See http://b/19625804. The bug is about a static/global pthread key being used before creation.
189 // So here tests if the static/global default value 0 can be detected as invalid key.
190 static pthread_key_t key;
191 ASSERT_EQ(nullptr, pthread_getspecific(key));
192 ASSERT_EQ(EINVAL, pthread_setspecific(key, nullptr));
193 ASSERT_EQ(EINVAL, pthread_key_delete(key));
194#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -0800195 GTEST_SKIP() << "bionic-only test";
Yabin Cui5ddbb3f2015-03-05 20:35:32 -0800196#endif
197}
198
Elliott Hughes4d014e12012-09-07 16:47:54 -0700199static void* IdFn(void* arg) {
200 return arg;
201}
202
Yabin Cui63481602014-12-01 17:41:04 -0800203class SpinFunctionHelper {
204 public:
205 SpinFunctionHelper() {
206 SpinFunctionHelper::spin_flag_ = true;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400207 }
Elliott Hughes0bd9d132017-11-02 13:11:13 -0700208
Yabin Cui63481602014-12-01 17:41:04 -0800209 ~SpinFunctionHelper() {
210 UnSpin();
211 }
Elliott Hughes0bd9d132017-11-02 13:11:13 -0700212
Yabin Cui63481602014-12-01 17:41:04 -0800213 auto GetFunction() -> void* (*)(void*) {
214 return SpinFunctionHelper::SpinFn;
215 }
216
217 void UnSpin() {
218 SpinFunctionHelper::spin_flag_ = false;
219 }
220
221 private:
222 static void* SpinFn(void*) {
223 while (spin_flag_) {}
Yi Kong32bc0fc2018-08-02 17:31:13 -0700224 return nullptr;
Yabin Cui63481602014-12-01 17:41:04 -0800225 }
Yabin Cuia36158a2015-11-16 21:06:16 -0800226 static std::atomic<bool> spin_flag_;
Yabin Cui63481602014-12-01 17:41:04 -0800227};
228
229// It doesn't matter if spin_flag_ is used in several tests,
230// because it is always set to false after each test. Each thread
231// loops on spin_flag_ can find it becomes false at some time.
Yabin Cuia36158a2015-11-16 21:06:16 -0800232std::atomic<bool> SpinFunctionHelper::spin_flag_;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400233
Elliott Hughes4d014e12012-09-07 16:47:54 -0700234static void* JoinFn(void* arg) {
Yi Kong32bc0fc2018-08-02 17:31:13 -0700235 return reinterpret_cast<void*>(pthread_join(reinterpret_cast<pthread_t>(arg), nullptr));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700236}
237
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400238static void AssertDetached(pthread_t t, bool is_detached) {
239 pthread_attr_t attr;
240 ASSERT_EQ(0, pthread_getattr_np(t, &attr));
241 int detach_state;
242 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &detach_state));
243 pthread_attr_destroy(&attr);
244 ASSERT_EQ(is_detached, (detach_state == PTHREAD_CREATE_DETACHED));
245}
246
Elliott Hughes7484c212017-02-02 02:41:38 +0000247static void MakeDeadThread(pthread_t& t) {
Yi Kong32bc0fc2018-08-02 17:31:13 -0700248 ASSERT_EQ(0, pthread_create(&t, nullptr, IdFn, nullptr));
249 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes7484c212017-02-02 02:41:38 +0000250}
251
Elliott Hughes4d014e12012-09-07 16:47:54 -0700252TEST(pthread, pthread_create) {
253 void* expected_result = reinterpret_cast<void*>(123);
254 // Can we create a thread?
255 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700256 ASSERT_EQ(0, pthread_create(&t, nullptr, IdFn, expected_result));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700257 // If we join, do we get the expected value back?
258 void* result;
259 ASSERT_EQ(0, pthread_join(t, &result));
260 ASSERT_EQ(expected_result, result);
261}
262
Elliott Hughes3e898472013-02-12 16:40:24 +0000263TEST(pthread, pthread_create_EAGAIN) {
264 pthread_attr_t attributes;
265 ASSERT_EQ(0, pthread_attr_init(&attributes));
266 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, static_cast<size_t>(-1) & ~(getpagesize() - 1)));
267
268 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700269 ASSERT_EQ(EAGAIN, pthread_create(&t, &attributes, IdFn, nullptr));
Elliott Hughes3e898472013-02-12 16:40:24 +0000270}
271
Elliott Hughes4d014e12012-09-07 16:47:54 -0700272TEST(pthread, pthread_no_join_after_detach) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700273 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800274
Elliott Hughes4d014e12012-09-07 16:47:54 -0700275 pthread_t t1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700276 ASSERT_EQ(0, pthread_create(&t1, nullptr, spin_helper.GetFunction(), nullptr));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700277
278 // After a pthread_detach...
279 ASSERT_EQ(0, pthread_detach(t1));
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400280 AssertDetached(t1, true);
Elliott Hughes4d014e12012-09-07 16:47:54 -0700281
282 // ...pthread_join should fail.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700283 ASSERT_EQ(EINVAL, pthread_join(t1, nullptr));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700284}
285
286TEST(pthread, pthread_no_op_detach_after_join) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700287 SpinFunctionHelper spin_helper;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400288
Elliott Hughes4d014e12012-09-07 16:47:54 -0700289 pthread_t t1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700290 ASSERT_EQ(0, pthread_create(&t1, nullptr, spin_helper.GetFunction(), nullptr));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700291
292 // If thread 2 is already waiting to join thread 1...
293 pthread_t t2;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700294 ASSERT_EQ(0, pthread_create(&t2, nullptr, JoinFn, reinterpret_cast<void*>(t1)));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700295
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400296 sleep(1); // (Give t2 a chance to call pthread_join.)
Elliott Hughes4d014e12012-09-07 16:47:54 -0700297
Yabin Cuibbb04322015-03-19 15:19:25 -0700298#if defined(__BIONIC__)
299 ASSERT_EQ(EINVAL, pthread_detach(t1));
300#else
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400301 ASSERT_EQ(0, pthread_detach(t1));
Yabin Cuibbb04322015-03-19 15:19:25 -0700302#endif
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400303 AssertDetached(t1, false);
304
Elliott Hughes725b2a92016-03-23 11:20:47 -0700305 spin_helper.UnSpin();
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400306
307 // ...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 -0700308 void* join_result;
309 ASSERT_EQ(0, pthread_join(t2, &join_result));
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700310 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700311}
Elliott Hughes14f19592012-10-29 10:19:44 -0700312
313TEST(pthread, pthread_join_self) {
Yi Kong32bc0fc2018-08-02 17:31:13 -0700314 ASSERT_EQ(EDEADLK, pthread_join(pthread_self(), nullptr));
Elliott Hughes14f19592012-10-29 10:19:44 -0700315}
Elliott Hughes4f251be2012-11-01 16:33:29 -0700316
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800317struct TestBug37410 {
318 pthread_t main_thread;
319 pthread_mutex_t mutex;
Elliott Hughes4f251be2012-11-01 16:33:29 -0700320
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800321 static void main() {
322 TestBug37410 data;
323 data.main_thread = pthread_self();
Yi Kong32bc0fc2018-08-02 17:31:13 -0700324 ASSERT_EQ(0, pthread_mutex_init(&data.mutex, nullptr));
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800325 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
326
327 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700328 ASSERT_EQ(0, pthread_create(&t, nullptr, TestBug37410::thread_fn, reinterpret_cast<void*>(&data)));
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800329
330 // Wait for the thread to be running...
331 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
332 ASSERT_EQ(0, pthread_mutex_unlock(&data.mutex));
333
334 // ...and exit.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700335 pthread_exit(nullptr);
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800336 }
337
338 private:
339 static void* thread_fn(void* arg) {
340 TestBug37410* data = reinterpret_cast<TestBug37410*>(arg);
341
Evgenii Stepanov352853a2019-02-05 17:37:37 -0800342 // Unlocking data->mutex will cause the main thread to exit, invalidating *data. Save the handle.
343 pthread_t main_thread = data->main_thread;
344
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800345 // Let the main thread know we're running.
346 pthread_mutex_unlock(&data->mutex);
347
348 // And wait for the main thread to exit.
Evgenii Stepanov352853a2019-02-05 17:37:37 -0800349 pthread_join(main_thread, nullptr);
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800350
Yi Kong32bc0fc2018-08-02 17:31:13 -0700351 return nullptr;
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800352 }
353};
Elliott Hughes4f251be2012-11-01 16:33:29 -0700354
Elliott Hughes7fd803c2013-02-14 16:33:52 -0800355// Even though this isn't really a death test, we have to say "DeathTest" here so gtest knows to
356// run this test (which exits normally) in its own process.
Yabin Cui9df70402014-11-05 18:01:01 -0800357TEST_F(pthread_DeathTest, pthread_bug_37410) {
Elliott Hughes4f251be2012-11-01 16:33:29 -0700358 // http://code.google.com/p/android/issues/detail?id=37410
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800359 ASSERT_EXIT(TestBug37410::main(), ::testing::ExitedWithCode(0), "");
Elliott Hughes4f251be2012-11-01 16:33:29 -0700360}
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800361
362static void* SignalHandlerFn(void* arg) {
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800363 sigset64_t wait_set;
364 sigfillset64(&wait_set);
365 return reinterpret_cast<void*>(sigwait64(&wait_set, reinterpret_cast<int*>(arg)));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800366}
367
368TEST(pthread, pthread_sigmask) {
Elliott Hughes19e62322013-10-15 11:23:57 -0700369 // Check that SIGUSR1 isn't blocked.
370 sigset_t original_set;
371 sigemptyset(&original_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700372 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, nullptr, &original_set));
Elliott Hughes19e62322013-10-15 11:23:57 -0700373 ASSERT_FALSE(sigismember(&original_set, SIGUSR1));
374
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800375 // Block SIGUSR1.
376 sigset_t set;
377 sigemptyset(&set);
378 sigaddset(&set, SIGUSR1);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700379 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, &set, nullptr));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800380
Elliott Hughes19e62322013-10-15 11:23:57 -0700381 // Check that SIGUSR1 is blocked.
382 sigset_t final_set;
383 sigemptyset(&final_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700384 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, nullptr, &final_set));
Elliott Hughes19e62322013-10-15 11:23:57 -0700385 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
386 // ...and that sigprocmask agrees with pthread_sigmask.
387 sigemptyset(&final_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700388 ASSERT_EQ(0, sigprocmask(SIG_BLOCK, nullptr, &final_set));
Elliott Hughes19e62322013-10-15 11:23:57 -0700389 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
390
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800391 // Spawn a thread that calls sigwait and tells us what it received.
392 pthread_t signal_thread;
393 int received_signal = -1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700394 ASSERT_EQ(0, pthread_create(&signal_thread, nullptr, SignalHandlerFn, &received_signal));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800395
396 // Send that thread SIGUSR1.
397 pthread_kill(signal_thread, SIGUSR1);
398
399 // See what it got.
400 void* join_result;
401 ASSERT_EQ(0, pthread_join(signal_thread, &join_result));
402 ASSERT_EQ(SIGUSR1, received_signal);
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700403 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
Elliott Hughes19e62322013-10-15 11:23:57 -0700404
405 // Restore the original signal mask.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700406 ASSERT_EQ(0, pthread_sigmask(SIG_SETMASK, &original_set, nullptr));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800407}
Elliott Hughes5e3fc432013-02-11 16:36:48 -0800408
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800409TEST(pthread, pthread_sigmask64_SIGTRMIN) {
410 // Check that SIGRTMIN isn't blocked.
411 sigset64_t original_set;
412 sigemptyset64(&original_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700413 ASSERT_EQ(0, pthread_sigmask64(SIG_BLOCK, nullptr, &original_set));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800414 ASSERT_FALSE(sigismember64(&original_set, SIGRTMIN));
415
416 // Block SIGRTMIN.
417 sigset64_t set;
418 sigemptyset64(&set);
419 sigaddset64(&set, SIGRTMIN);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700420 ASSERT_EQ(0, pthread_sigmask64(SIG_BLOCK, &set, nullptr));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800421
422 // Check that SIGRTMIN is blocked.
423 sigset64_t final_set;
424 sigemptyset64(&final_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700425 ASSERT_EQ(0, pthread_sigmask64(SIG_BLOCK, nullptr, &final_set));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800426 ASSERT_TRUE(sigismember64(&final_set, SIGRTMIN));
427 // ...and that sigprocmask64 agrees with pthread_sigmask64.
428 sigemptyset64(&final_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700429 ASSERT_EQ(0, sigprocmask64(SIG_BLOCK, nullptr, &final_set));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800430 ASSERT_TRUE(sigismember64(&final_set, SIGRTMIN));
431
432 // Spawn a thread that calls sigwait64 and tells us what it received.
433 pthread_t signal_thread;
434 int received_signal = -1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700435 ASSERT_EQ(0, pthread_create(&signal_thread, nullptr, SignalHandlerFn, &received_signal));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800436
437 // Send that thread SIGRTMIN.
438 pthread_kill(signal_thread, SIGRTMIN);
439
440 // See what it got.
441 void* join_result;
442 ASSERT_EQ(0, pthread_join(signal_thread, &join_result));
443 ASSERT_EQ(SIGRTMIN, received_signal);
444 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
445
446 // Restore the original signal mask.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700447 ASSERT_EQ(0, pthread_sigmask64(SIG_SETMASK, &original_set, nullptr));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800448}
449
Elliott Hughes725b2a92016-03-23 11:20:47 -0700450static void test_pthread_setname_np__pthread_getname_np(pthread_t t) {
451 ASSERT_EQ(0, pthread_setname_np(t, "short"));
452 char name[32];
453 ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name)));
454 ASSERT_STREQ("short", name);
455
Elliott Hughesd1aea302015-04-25 10:05:24 -0700456 // The limit is 15 characters --- the kernel's buffer is 16, but includes a NUL.
Elliott Hughes725b2a92016-03-23 11:20:47 -0700457 ASSERT_EQ(0, pthread_setname_np(t, "123456789012345"));
458 ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name)));
459 ASSERT_STREQ("123456789012345", name);
460
461 ASSERT_EQ(ERANGE, pthread_setname_np(t, "1234567890123456"));
462
463 // The passed-in buffer should be at least 16 bytes.
464 ASSERT_EQ(0, pthread_getname_np(t, name, 16));
465 ASSERT_EQ(ERANGE, pthread_getname_np(t, name, 15));
Elliott Hughes3e898472013-02-12 16:40:24 +0000466}
467
Elliott Hughes725b2a92016-03-23 11:20:47 -0700468TEST(pthread, pthread_setname_np__pthread_getname_np__self) {
469 test_pthread_setname_np__pthread_getname_np(pthread_self());
Elliott Hughes3e898472013-02-12 16:40:24 +0000470}
471
Elliott Hughes725b2a92016-03-23 11:20:47 -0700472TEST(pthread, pthread_setname_np__pthread_getname_np__other) {
473 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800474
Elliott Hughes725b2a92016-03-23 11:20:47 -0700475 pthread_t t;
Elliott Hughes4d098ca2016-04-11 12:43:05 -0700476 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
477 test_pthread_setname_np__pthread_getname_np(t);
478 spin_helper.UnSpin();
479 ASSERT_EQ(0, pthread_join(t, nullptr));
480}
481
482// http://b/28051133: a kernel misfeature means that you can't change the
483// name of another thread if you've set PR_SET_DUMPABLE to 0.
484TEST(pthread, pthread_setname_np__pthread_getname_np__other_PR_SET_DUMPABLE) {
485 ASSERT_EQ(0, prctl(PR_SET_DUMPABLE, 0)) << strerror(errno);
486
487 SpinFunctionHelper spin_helper;
488
489 pthread_t t;
490 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
Elliott Hughes725b2a92016-03-23 11:20:47 -0700491 test_pthread_setname_np__pthread_getname_np(t);
492 spin_helper.UnSpin();
493 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes3e898472013-02-12 16:40:24 +0000494}
495
Elliott Hughes11859d42017-02-13 17:59:29 -0800496TEST_F(pthread_DeathTest, pthread_setname_np__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000497 pthread_t dead_thread;
498 MakeDeadThread(dead_thread);
499
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800500 EXPECT_DEATH(pthread_setname_np(dead_thread, "short 3"),
501 "invalid pthread_t (.*) passed to pthread_setname_np");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800502}
503
504TEST_F(pthread_DeathTest, pthread_setname_np__null_thread) {
505 pthread_t null_thread = 0;
506 EXPECT_EQ(ENOENT, pthread_setname_np(null_thread, "short 3"));
Elliott Hughes11859d42017-02-13 17:59:29 -0800507}
508
509TEST_F(pthread_DeathTest, pthread_getname_np__no_such_thread) {
510 pthread_t dead_thread;
511 MakeDeadThread(dead_thread);
512
Elliott Hughesbcb15292017-02-07 21:05:30 +0000513 char name[64];
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800514 EXPECT_DEATH(pthread_getname_np(dead_thread, name, sizeof(name)),
515 "invalid pthread_t (.*) passed to pthread_getname_np");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800516}
517
518TEST_F(pthread_DeathTest, pthread_getname_np__null_thread) {
519 pthread_t null_thread = 0;
520
521 char name[64];
522 EXPECT_EQ(ENOENT, pthread_getname_np(null_thread, name, sizeof(name)));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000523}
524
Elliott Hughes9d23e042013-02-15 19:21:51 -0800525TEST(pthread, pthread_kill__0) {
526 // Signal 0 just tests that the thread exists, so it's safe to call on ourselves.
527 ASSERT_EQ(0, pthread_kill(pthread_self(), 0));
528}
529
530TEST(pthread, pthread_kill__invalid_signal) {
531 ASSERT_EQ(EINVAL, pthread_kill(pthread_self(), -1));
532}
533
Elliott Hughesfae89fc2013-02-21 11:22:23 -0800534static void pthread_kill__in_signal_handler_helper(int signal_number) {
535 static int count = 0;
536 ASSERT_EQ(SIGALRM, signal_number);
537 if (++count == 1) {
538 // Can we call pthread_kill from a signal handler?
539 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
540 }
541}
542
543TEST(pthread, pthread_kill__in_signal_handler) {
Elliott Hughes4b558f52014-03-04 15:58:02 -0800544 ScopedSignalHandler ssh(SIGALRM, pthread_kill__in_signal_handler_helper);
Elliott Hughesfae89fc2013-02-21 11:22:23 -0800545 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
546}
547
Josh Gaoddf757e2018-10-17 15:23:03 -0700548TEST(pthread, pthread_kill__exited_thread) {
549 static std::promise<pid_t> tid_promise;
550 pthread_t thread;
551 ASSERT_EQ(0, pthread_create(&thread, nullptr,
552 [](void*) -> void* {
553 tid_promise.set_value(gettid());
554 return nullptr;
555 },
556 nullptr));
557
558 pid_t tid = tid_promise.get_future().get();
559 while (TEMP_FAILURE_RETRY(syscall(__NR_tgkill, getpid(), tid, 0)) != -1) {
560 continue;
561 }
562 ASSERT_EQ(ESRCH, errno);
563
564 ASSERT_EQ(ESRCH, pthread_kill(thread, 0));
565}
566
Elliott Hughes11859d42017-02-13 17:59:29 -0800567TEST_F(pthread_DeathTest, pthread_detach__no_such_thread) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000568 pthread_t dead_thread;
569 MakeDeadThread(dead_thread);
570
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800571 EXPECT_DEATH(pthread_detach(dead_thread),
572 "invalid pthread_t (.*) passed to pthread_detach");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800573}
574
575TEST_F(pthread_DeathTest, pthread_detach__null_thread) {
576 pthread_t null_thread = 0;
577 EXPECT_EQ(ESRCH, pthread_detach(null_thread));
Elliott Hughes7484c212017-02-02 02:41:38 +0000578}
579
Jeff Hao9b06cc32013-08-15 14:51:16 -0700580TEST(pthread, pthread_getcpuclockid__clock_gettime) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700581 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800582
Jeff Hao9b06cc32013-08-15 14:51:16 -0700583 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700584 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
Jeff Hao9b06cc32013-08-15 14:51:16 -0700585
586 clockid_t c;
587 ASSERT_EQ(0, pthread_getcpuclockid(t, &c));
588 timespec ts;
589 ASSERT_EQ(0, clock_gettime(c, &ts));
Elliott Hughes725b2a92016-03-23 11:20:47 -0700590 spin_helper.UnSpin();
Yabin Cuia36158a2015-11-16 21:06:16 -0800591 ASSERT_EQ(0, pthread_join(t, nullptr));
Jeff Hao9b06cc32013-08-15 14:51:16 -0700592}
593
Elliott Hughes11859d42017-02-13 17:59:29 -0800594TEST_F(pthread_DeathTest, pthread_getcpuclockid__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000595 pthread_t dead_thread;
596 MakeDeadThread(dead_thread);
597
598 clockid_t c;
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800599 EXPECT_DEATH(pthread_getcpuclockid(dead_thread, &c),
600 "invalid pthread_t (.*) passed to pthread_getcpuclockid");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800601}
602
603TEST_F(pthread_DeathTest, pthread_getcpuclockid__null_thread) {
604 pthread_t null_thread = 0;
605 clockid_t c;
606 EXPECT_EQ(ESRCH, pthread_getcpuclockid(null_thread, &c));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000607}
608
Elliott Hughes11859d42017-02-13 17:59:29 -0800609TEST_F(pthread_DeathTest, pthread_getschedparam__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000610 pthread_t dead_thread;
611 MakeDeadThread(dead_thread);
612
613 int policy;
614 sched_param param;
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800615 EXPECT_DEATH(pthread_getschedparam(dead_thread, &policy, &param),
616 "invalid pthread_t (.*) passed to pthread_getschedparam");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800617}
618
619TEST_F(pthread_DeathTest, pthread_getschedparam__null_thread) {
620 pthread_t null_thread = 0;
621 int policy;
622 sched_param param;
623 EXPECT_EQ(ESRCH, pthread_getschedparam(null_thread, &policy, &param));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000624}
625
Elliott Hughes11859d42017-02-13 17:59:29 -0800626TEST_F(pthread_DeathTest, pthread_setschedparam__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000627 pthread_t dead_thread;
628 MakeDeadThread(dead_thread);
629
630 int policy = 0;
631 sched_param param;
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800632 EXPECT_DEATH(pthread_setschedparam(dead_thread, policy, &param),
633 "invalid pthread_t (.*) passed to pthread_setschedparam");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800634}
635
636TEST_F(pthread_DeathTest, pthread_setschedparam__null_thread) {
637 pthread_t null_thread = 0;
638 int policy = 0;
639 sched_param param;
640 EXPECT_EQ(ESRCH, pthread_setschedparam(null_thread, policy, &param));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000641}
642
Elliott Hughesdff08ce2017-10-16 09:58:45 -0700643TEST_F(pthread_DeathTest, pthread_setschedprio__no_such_thread) {
644 pthread_t dead_thread;
645 MakeDeadThread(dead_thread);
646
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800647 EXPECT_DEATH(pthread_setschedprio(dead_thread, 123),
648 "invalid pthread_t (.*) passed to pthread_setschedprio");
Elliott Hughesdff08ce2017-10-16 09:58:45 -0700649}
650
651TEST_F(pthread_DeathTest, pthread_setschedprio__null_thread) {
652 pthread_t null_thread = 0;
653 EXPECT_EQ(ESRCH, pthread_setschedprio(null_thread, 123));
654}
655
Elliott Hughes11859d42017-02-13 17:59:29 -0800656TEST_F(pthread_DeathTest, pthread_join__no_such_thread) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000657 pthread_t dead_thread;
658 MakeDeadThread(dead_thread);
659
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800660 EXPECT_DEATH(pthread_join(dead_thread, nullptr),
661 "invalid pthread_t (.*) passed to pthread_join");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800662}
663
664TEST_F(pthread_DeathTest, pthread_join__null_thread) {
665 pthread_t null_thread = 0;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700666 EXPECT_EQ(ESRCH, pthread_join(null_thread, nullptr));
Elliott Hughes7484c212017-02-02 02:41:38 +0000667}
668
Elliott Hughes11859d42017-02-13 17:59:29 -0800669TEST_F(pthread_DeathTest, pthread_kill__no_such_thread) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000670 pthread_t dead_thread;
671 MakeDeadThread(dead_thread);
672
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800673 EXPECT_DEATH(pthread_kill(dead_thread, 0),
674 "invalid pthread_t (.*) passed to pthread_kill");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800675}
676
677TEST_F(pthread_DeathTest, pthread_kill__null_thread) {
678 pthread_t null_thread = 0;
679 EXPECT_EQ(ESRCH, pthread_kill(null_thread, 0));
Elliott Hughes7484c212017-02-02 02:41:38 +0000680}
681
msg5550f020d12013-06-06 14:59:28 -0400682TEST(pthread, pthread_join__multijoin) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700683 SpinFunctionHelper spin_helper;
msg5550f020d12013-06-06 14:59:28 -0400684
685 pthread_t t1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700686 ASSERT_EQ(0, pthread_create(&t1, nullptr, spin_helper.GetFunction(), nullptr));
msg5550f020d12013-06-06 14:59:28 -0400687
688 pthread_t t2;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700689 ASSERT_EQ(0, pthread_create(&t2, nullptr, JoinFn, reinterpret_cast<void*>(t1)));
msg5550f020d12013-06-06 14:59:28 -0400690
691 sleep(1); // (Give t2 a chance to call pthread_join.)
692
693 // Multiple joins to the same thread should fail.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700694 ASSERT_EQ(EINVAL, pthread_join(t1, nullptr));
msg5550f020d12013-06-06 14:59:28 -0400695
Elliott Hughes725b2a92016-03-23 11:20:47 -0700696 spin_helper.UnSpin();
msg5550f020d12013-06-06 14:59:28 -0400697
698 // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes).
699 void* join_result;
700 ASSERT_EQ(0, pthread_join(t2, &join_result));
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700701 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
msg5550f020d12013-06-06 14:59:28 -0400702}
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700703
Elliott Hughes70b24b12013-11-15 11:51:07 -0800704TEST(pthread, pthread_join__race) {
705 // http://b/11693195 --- pthread_join could return before the thread had actually exited.
706 // If the joiner unmapped the thread's stack, that could lead to SIGSEGV in the thread.
707 for (size_t i = 0; i < 1024; ++i) {
Yabin Cuia36158a2015-11-16 21:06:16 -0800708 size_t stack_size = 640*1024;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700709 void* stack = mmap(nullptr, stack_size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
Elliott Hughes70b24b12013-11-15 11:51:07 -0800710
711 pthread_attr_t a;
712 pthread_attr_init(&a);
713 pthread_attr_setstack(&a, stack, stack_size);
714
715 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700716 ASSERT_EQ(0, pthread_create(&t, &a, IdFn, nullptr));
717 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes70b24b12013-11-15 11:51:07 -0800718 ASSERT_EQ(0, munmap(stack, stack_size));
719 }
720}
721
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700722static void* GetActualGuardSizeFn(void* arg) {
723 pthread_attr_t attributes;
724 pthread_getattr_np(pthread_self(), &attributes);
725 pthread_attr_getguardsize(&attributes, reinterpret_cast<size_t*>(arg));
Yi Kong32bc0fc2018-08-02 17:31:13 -0700726 return nullptr;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700727}
728
729static size_t GetActualGuardSize(const pthread_attr_t& attributes) {
730 size_t result;
731 pthread_t t;
732 pthread_create(&t, &attributes, GetActualGuardSizeFn, &result);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700733 pthread_join(t, nullptr);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700734 return result;
735}
736
737static void* GetActualStackSizeFn(void* arg) {
738 pthread_attr_t attributes;
739 pthread_getattr_np(pthread_self(), &attributes);
740 pthread_attr_getstacksize(&attributes, reinterpret_cast<size_t*>(arg));
Yi Kong32bc0fc2018-08-02 17:31:13 -0700741 return nullptr;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700742}
743
744static size_t GetActualStackSize(const pthread_attr_t& attributes) {
745 size_t result;
746 pthread_t t;
747 pthread_create(&t, &attributes, GetActualStackSizeFn, &result);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700748 pthread_join(t, nullptr);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700749 return result;
750}
751
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700752TEST(pthread, pthread_attr_setguardsize_tiny) {
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700753 pthread_attr_t attributes;
754 ASSERT_EQ(0, pthread_attr_init(&attributes));
755
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700756 // No such thing as too small: will be rounded up to one page by pthread_create.
757 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 128));
758 size_t guard_size;
759 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
760 ASSERT_EQ(128U, guard_size);
761 ASSERT_EQ(4096U, GetActualGuardSize(attributes));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700762}
763
764TEST(pthread, pthread_attr_setguardsize_reasonable) {
765 pthread_attr_t attributes;
766 ASSERT_EQ(0, pthread_attr_init(&attributes));
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700767
768 // Large enough and a multiple of the page size.
769 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700770 size_t guard_size;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700771 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
772 ASSERT_EQ(32*1024U, guard_size);
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700773 ASSERT_EQ(32*1024U, GetActualGuardSize(attributes));
774}
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700775
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700776TEST(pthread, pthread_attr_setguardsize_needs_rounding) {
777 pthread_attr_t attributes;
778 ASSERT_EQ(0, pthread_attr_init(&attributes));
779
780 // Large enough but not a multiple of the page size.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700781 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024 + 1));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700782 size_t guard_size;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700783 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
784 ASSERT_EQ(32*1024U + 1, guard_size);
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700785 ASSERT_EQ(36*1024U, GetActualGuardSize(attributes));
786}
787
788TEST(pthread, pthread_attr_setguardsize_enormous) {
789 pthread_attr_t attributes;
790 ASSERT_EQ(0, pthread_attr_init(&attributes));
791
792 // Larger than the stack itself. (Historically we mistakenly carved
793 // the guard out of the stack itself, rather than adding it after the
794 // end.)
795 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024*1024));
796 size_t guard_size;
797 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
798 ASSERT_EQ(32*1024*1024U, guard_size);
799 ASSERT_EQ(32*1024*1024U, GetActualGuardSize(attributes));
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700800}
801
802TEST(pthread, pthread_attr_setstacksize) {
803 pthread_attr_t attributes;
804 ASSERT_EQ(0, pthread_attr_init(&attributes));
805
806 // Get the default stack size.
807 size_t default_stack_size;
808 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &default_stack_size));
809
810 // Too small.
811 ASSERT_EQ(EINVAL, pthread_attr_setstacksize(&attributes, 128));
812 size_t stack_size;
813 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
814 ASSERT_EQ(default_stack_size, stack_size);
815 ASSERT_GE(GetActualStackSize(attributes), default_stack_size);
816
Yabin Cui917d3902015-01-08 12:32:42 -0800817 // Large enough and a multiple of the page size; may be rounded up by pthread_create.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700818 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024));
819 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
820 ASSERT_EQ(32*1024U, stack_size);
Yabin Cui917d3902015-01-08 12:32:42 -0800821 ASSERT_GE(GetActualStackSize(attributes), 32*1024U);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700822
Yabin Cui917d3902015-01-08 12:32:42 -0800823 // Large enough but not aligned; will be rounded up by pthread_create.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700824 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024 + 1));
825 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
826 ASSERT_EQ(32*1024U + 1, stack_size);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800827#if defined(__BIONIC__)
Yabin Cui917d3902015-01-08 12:32:42 -0800828 ASSERT_GT(GetActualStackSize(attributes), 32*1024U + 1);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800829#else // __BIONIC__
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700830 // glibc rounds down, in violation of POSIX. They document this in their BUGS section.
831 ASSERT_EQ(GetActualStackSize(attributes), 32*1024U);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800832#endif // __BIONIC__
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700833}
Elliott Hughesc3f11402013-10-30 14:40:09 -0700834
Yabin Cui76615da2015-03-17 14:22:09 -0700835TEST(pthread, pthread_rwlockattr_smoke) {
836 pthread_rwlockattr_t attr;
837 ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
838
839 int pshared_value_array[] = {PTHREAD_PROCESS_PRIVATE, PTHREAD_PROCESS_SHARED};
840 for (size_t i = 0; i < sizeof(pshared_value_array) / sizeof(pshared_value_array[0]); ++i) {
841 ASSERT_EQ(0, pthread_rwlockattr_setpshared(&attr, pshared_value_array[i]));
842 int pshared;
843 ASSERT_EQ(0, pthread_rwlockattr_getpshared(&attr, &pshared));
844 ASSERT_EQ(pshared_value_array[i], pshared);
845 }
846
Colin Cross7da20342021-07-28 11:18:11 -0700847#if !defined(MUSL)
848 // musl doesn't have pthread_rwlockattr_setkind_np
Yabin Cui76615da2015-03-17 14:22:09 -0700849 int kind_array[] = {PTHREAD_RWLOCK_PREFER_READER_NP,
850 PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP};
851 for (size_t i = 0; i < sizeof(kind_array) / sizeof(kind_array[0]); ++i) {
852 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_array[i]));
853 int kind;
854 ASSERT_EQ(0, pthread_rwlockattr_getkind_np(&attr, &kind));
855 ASSERT_EQ(kind_array[i], kind);
856 }
Colin Cross7da20342021-07-28 11:18:11 -0700857#endif
Yabin Cui76615da2015-03-17 14:22:09 -0700858
859 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
860}
861
862TEST(pthread, pthread_rwlock_init_same_as_PTHREAD_RWLOCK_INITIALIZER) {
863 pthread_rwlock_t lock1 = PTHREAD_RWLOCK_INITIALIZER;
864 pthread_rwlock_t lock2;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700865 ASSERT_EQ(0, pthread_rwlock_init(&lock2, nullptr));
Yabin Cui76615da2015-03-17 14:22:09 -0700866 ASSERT_EQ(0, memcmp(&lock1, &lock2, sizeof(lock1)));
867}
868
Elliott Hughesc3f11402013-10-30 14:40:09 -0700869TEST(pthread, pthread_rwlock_smoke) {
870 pthread_rwlock_t l;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700871 ASSERT_EQ(0, pthread_rwlock_init(&l, nullptr));
Elliott Hughesc3f11402013-10-30 14:40:09 -0700872
Calin Juravle76f352e2014-05-19 13:41:10 +0100873 // Single read lock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700874 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
875 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
876
Calin Juravle76f352e2014-05-19 13:41:10 +0100877 // Multiple read lock
878 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
879 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
880 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
881 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
882
883 // Write lock
Calin Juravle92687e42014-05-22 19:21:22 +0100884 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
885 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100886
887 // Try writer lock
888 ASSERT_EQ(0, pthread_rwlock_trywrlock(&l));
889 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
890 ASSERT_EQ(EBUSY, pthread_rwlock_tryrdlock(&l));
891 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
892
893 // Try reader lock
894 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
895 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
896 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
897 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
898 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
899
900 // Try writer lock after unlock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700901 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
902 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
903
Calin Juravle76f352e2014-05-19 13:41:10 +0100904 // EDEADLK in "read after write"
905 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
906 ASSERT_EQ(EDEADLK, pthread_rwlock_rdlock(&l));
907 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
908
909 // EDEADLK in "write after write"
910 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
911 ASSERT_EQ(EDEADLK, pthread_rwlock_wrlock(&l));
912 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100913
Elliott Hughesc3f11402013-10-30 14:40:09 -0700914 ASSERT_EQ(0, pthread_rwlock_destroy(&l));
915}
916
Yabin Cui08ee8d22015-02-11 17:04:36 -0800917struct RwlockWakeupHelperArg {
918 pthread_rwlock_t lock;
919 enum Progress {
920 LOCK_INITIALIZED,
921 LOCK_WAITING,
922 LOCK_RELEASED,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800923 LOCK_ACCESSED,
924 LOCK_TIMEDOUT,
Yabin Cui08ee8d22015-02-11 17:04:36 -0800925 };
926 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -0700927 std::atomic<pid_t> tid;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800928 std::function<int (pthread_rwlock_t*)> trylock_function;
929 std::function<int (pthread_rwlock_t*)> lock_function;
930 std::function<int (pthread_rwlock_t*, const timespec*)> timed_lock_function;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -0800931 clockid_t clock;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800932};
933
Yabin Cuic9a659c2015-11-05 15:36:08 -0800934static void pthread_rwlock_wakeup_helper(RwlockWakeupHelperArg* arg) {
Yabin Cuif7969852015-04-02 17:47:48 -0700935 arg->tid = gettid();
Yabin Cui08ee8d22015-02-11 17:04:36 -0800936 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
937 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
938
Yabin Cuic9a659c2015-11-05 15:36:08 -0800939 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
940 ASSERT_EQ(0, arg->lock_function(&arg->lock));
Yabin Cui08ee8d22015-02-11 17:04:36 -0800941 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_RELEASED, arg->progress);
942 ASSERT_EQ(0, pthread_rwlock_unlock(&arg->lock));
943
944 arg->progress = RwlockWakeupHelperArg::LOCK_ACCESSED;
945}
946
Yabin Cuic9a659c2015-11-05 15:36:08 -0800947static void test_pthread_rwlock_reader_wakeup_writer(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -0800948 RwlockWakeupHelperArg wakeup_arg;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700949 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -0800950 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
951 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -0700952 wakeup_arg.tid = 0;
Tom Cherry60ddedf2018-02-20 15:40:02 -0800953 wakeup_arg.trylock_function = &pthread_rwlock_trywrlock;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800954 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800955
956 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700957 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800958 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -0700959 WaitUntilThreadSleep(wakeup_arg.tid);
960 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
961
Yabin Cui08ee8d22015-02-11 17:04:36 -0800962 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
963 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
964
Yi Kong32bc0fc2018-08-02 17:31:13 -0700965 ASSERT_EQ(0, pthread_join(thread, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -0800966 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
967 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
968}
969
Yabin Cuic9a659c2015-11-05 15:36:08 -0800970TEST(pthread, pthread_rwlock_reader_wakeup_writer) {
971 test_pthread_rwlock_reader_wakeup_writer(pthread_rwlock_wrlock);
Yabin Cui08ee8d22015-02-11 17:04:36 -0800972}
973
Yabin Cuic9a659c2015-11-05 15:36:08 -0800974TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait) {
975 timespec ts;
976 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
977 ts.tv_sec += 1;
978 test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) {
979 return pthread_rwlock_timedwrlock(lock, &ts);
980 });
981}
982
Tom Cherryc6b5bcd2018-03-05 14:14:44 -0800983TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait_monotonic_np) {
984#if defined(__BIONIC__)
985 timespec ts;
986 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
987 ts.tv_sec += 1;
988 test_pthread_rwlock_reader_wakeup_writer(
989 [&](pthread_rwlock_t* lock) { return pthread_rwlock_timedwrlock_monotonic_np(lock, &ts); });
990#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -0800991 GTEST_SKIP() << "pthread_rwlock_timedwrlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -0800992#endif // __BIONIC__
993}
994
Tom Cherry69010802019-05-07 20:33:05 -0700995TEST(pthread, pthread_rwlock_reader_wakeup_writer_clockwait) {
996#if defined(__BIONIC__)
997 timespec ts;
998 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
999 ts.tv_sec += 1;
1000 test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) {
1001 return pthread_rwlock_clockwrlock(lock, CLOCK_MONOTONIC, &ts);
1002 });
1003
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_clockwrlock(lock, CLOCK_REALTIME, &ts);
1008 });
1009#else // __BIONIC__
1010 GTEST_SKIP() << "pthread_rwlock_clockwrlock not available";
1011#endif // __BIONIC__
1012}
1013
Yabin Cuic9a659c2015-11-05 15:36:08 -08001014static void test_pthread_rwlock_writer_wakeup_reader(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -08001015 RwlockWakeupHelperArg wakeup_arg;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001016 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -08001017 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
1018 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -07001019 wakeup_arg.tid = 0;
Tom Cherry60ddedf2018-02-20 15:40:02 -08001020 wakeup_arg.trylock_function = &pthread_rwlock_tryrdlock;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001021 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -08001022
1023 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001024 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cuic9a659c2015-11-05 15:36:08 -08001025 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -07001026 WaitUntilThreadSleep(wakeup_arg.tid);
1027 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
1028
Yabin Cui08ee8d22015-02-11 17:04:36 -08001029 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
1030 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
1031
Yi Kong32bc0fc2018-08-02 17:31:13 -07001032 ASSERT_EQ(0, pthread_join(thread, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -08001033 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
1034 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
1035}
1036
Yabin Cuic9a659c2015-11-05 15:36:08 -08001037TEST(pthread, pthread_rwlock_writer_wakeup_reader) {
1038 test_pthread_rwlock_writer_wakeup_reader(pthread_rwlock_rdlock);
1039}
1040
1041TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait) {
1042 timespec ts;
1043 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1044 ts.tv_sec += 1;
1045 test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) {
1046 return pthread_rwlock_timedrdlock(lock, &ts);
1047 });
1048}
1049
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001050TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait_monotonic_np) {
1051#if defined(__BIONIC__)
1052 timespec ts;
1053 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1054 ts.tv_sec += 1;
1055 test_pthread_rwlock_writer_wakeup_reader(
1056 [&](pthread_rwlock_t* lock) { return pthread_rwlock_timedrdlock_monotonic_np(lock, &ts); });
1057#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001058 GTEST_SKIP() << "pthread_rwlock_timedrdlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001059#endif // __BIONIC__
1060}
1061
Tom Cherry69010802019-05-07 20:33:05 -07001062TEST(pthread, pthread_rwlock_writer_wakeup_reader_clockwait) {
1063#if defined(__BIONIC__)
1064 timespec ts;
1065 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1066 ts.tv_sec += 1;
1067 test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) {
1068 return pthread_rwlock_clockrdlock(lock, CLOCK_MONOTONIC, &ts);
1069 });
1070
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_clockrdlock(lock, CLOCK_REALTIME, &ts);
1075 });
1076#else // __BIONIC__
1077 GTEST_SKIP() << "pthread_rwlock_clockrdlock not available";
1078#endif // __BIONIC__
1079}
1080
Yabin Cuic9a659c2015-11-05 15:36:08 -08001081static void pthread_rwlock_wakeup_timeout_helper(RwlockWakeupHelperArg* arg) {
1082 arg->tid = gettid();
1083 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
1084 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
1085
1086 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
1087
1088 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001089 ASSERT_EQ(0, clock_gettime(arg->clock, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001090 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
1091 ts.tv_nsec = -1;
1092 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
1093 ts.tv_nsec = NS_PER_S;
1094 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
1095 ts.tv_nsec = NS_PER_S - 1;
1096 ts.tv_sec = -1;
1097 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001098 ASSERT_EQ(0, clock_gettime(arg->clock, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001099 ts.tv_sec += 1;
1100 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
1101 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, arg->progress);
1102 arg->progress = RwlockWakeupHelperArg::LOCK_TIMEDOUT;
1103}
1104
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001105static void pthread_rwlock_timedrdlock_timeout_helper(
1106 clockid_t clock, int (*lock_function)(pthread_rwlock_t* __rwlock, const timespec* __timeout)) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001107 RwlockWakeupHelperArg wakeup_arg;
1108 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
1109 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
1110 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
1111 wakeup_arg.tid = 0;
Tom Cherry60ddedf2018-02-20 15:40:02 -08001112 wakeup_arg.trylock_function = &pthread_rwlock_tryrdlock;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001113 wakeup_arg.timed_lock_function = lock_function;
1114 wakeup_arg.clock = clock;
1115
1116 pthread_t thread;
1117 ASSERT_EQ(0, pthread_create(&thread, nullptr,
1118 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
1119 WaitUntilThreadSleep(wakeup_arg.tid);
1120 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
1121
1122 ASSERT_EQ(0, pthread_join(thread, nullptr));
1123 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
1124 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
1125 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
1126}
1127
1128TEST(pthread, pthread_rwlock_timedrdlock_timeout) {
1129 pthread_rwlock_timedrdlock_timeout_helper(CLOCK_REALTIME, pthread_rwlock_timedrdlock);
1130}
1131
1132TEST(pthread, pthread_rwlock_timedrdlock_monotonic_np_timeout) {
1133#if defined(__BIONIC__)
1134 pthread_rwlock_timedrdlock_timeout_helper(CLOCK_MONOTONIC,
1135 pthread_rwlock_timedrdlock_monotonic_np);
1136#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001137 GTEST_SKIP() << "pthread_rwlock_timedrdlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001138#endif // __BIONIC__
1139}
1140
Tom Cherry69010802019-05-07 20:33:05 -07001141TEST(pthread, pthread_rwlock_clockrdlock_monotonic_timeout) {
1142#if defined(__BIONIC__)
1143 pthread_rwlock_timedrdlock_timeout_helper(
1144 CLOCK_MONOTONIC, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) {
1145 return pthread_rwlock_clockrdlock(__rwlock, CLOCK_MONOTONIC, __timeout);
1146 });
1147#else // __BIONIC__
1148 GTEST_SKIP() << "pthread_rwlock_clockrdlock not available";
1149#endif // __BIONIC__
1150}
1151
1152TEST(pthread, pthread_rwlock_clockrdlock_realtime_timeout) {
1153#if defined(__BIONIC__)
1154 pthread_rwlock_timedrdlock_timeout_helper(
1155 CLOCK_REALTIME, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) {
1156 return pthread_rwlock_clockrdlock(__rwlock, CLOCK_REALTIME, __timeout);
1157 });
1158#else // __BIONIC__
1159 GTEST_SKIP() << "pthread_rwlock_clockrdlock not available";
1160#endif // __BIONIC__
1161}
1162
1163TEST(pthread, pthread_rwlock_clockrdlock_invalid) {
1164#if defined(__BIONIC__)
1165 pthread_rwlock_t lock = PTHREAD_RWLOCK_INITIALIZER;
1166 timespec ts;
1167 EXPECT_EQ(EINVAL, pthread_rwlock_clockrdlock(&lock, CLOCK_PROCESS_CPUTIME_ID, &ts));
1168#else // __BIONIC__
1169 GTEST_SKIP() << "pthread_rwlock_clockrdlock not available";
1170#endif // __BIONIC__
1171}
1172
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001173static void pthread_rwlock_timedwrlock_timeout_helper(
1174 clockid_t clock, int (*lock_function)(pthread_rwlock_t* __rwlock, const timespec* __timeout)) {
1175 RwlockWakeupHelperArg wakeup_arg;
1176 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
1177 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
1178 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
1179 wakeup_arg.tid = 0;
1180 wakeup_arg.trylock_function = &pthread_rwlock_trywrlock;
1181 wakeup_arg.timed_lock_function = lock_function;
1182 wakeup_arg.clock = clock;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001183
1184 pthread_t thread;
1185 ASSERT_EQ(0, pthread_create(&thread, nullptr,
1186 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
1187 WaitUntilThreadSleep(wakeup_arg.tid);
1188 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
1189
1190 ASSERT_EQ(0, pthread_join(thread, nullptr));
1191 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
1192 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
1193 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
1194}
1195
1196TEST(pthread, pthread_rwlock_timedwrlock_timeout) {
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001197 pthread_rwlock_timedwrlock_timeout_helper(CLOCK_REALTIME, pthread_rwlock_timedwrlock);
1198}
Yabin Cuic9a659c2015-11-05 15:36:08 -08001199
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001200TEST(pthread, pthread_rwlock_timedwrlock_monotonic_np_timeout) {
1201#if defined(__BIONIC__)
1202 pthread_rwlock_timedwrlock_timeout_helper(CLOCK_MONOTONIC,
1203 pthread_rwlock_timedwrlock_monotonic_np);
1204#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001205 GTEST_SKIP() << "pthread_rwlock_timedwrlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001206#endif // __BIONIC__
Yabin Cuic9a659c2015-11-05 15:36:08 -08001207}
1208
Tom Cherry69010802019-05-07 20:33:05 -07001209TEST(pthread, pthread_rwlock_clockwrlock_monotonic_timeout) {
1210#if defined(__BIONIC__)
1211 pthread_rwlock_timedwrlock_timeout_helper(
1212 CLOCK_MONOTONIC, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) {
1213 return pthread_rwlock_clockwrlock(__rwlock, CLOCK_MONOTONIC, __timeout);
1214 });
1215#else // __BIONIC__
1216 GTEST_SKIP() << "pthread_rwlock_clockwrlock not available";
1217#endif // __BIONIC__
1218}
1219
1220TEST(pthread, pthread_rwlock_clockwrlock_realtime_timeout) {
1221#if defined(__BIONIC__)
1222 pthread_rwlock_timedwrlock_timeout_helper(
1223 CLOCK_REALTIME, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) {
1224 return pthread_rwlock_clockwrlock(__rwlock, CLOCK_REALTIME, __timeout);
1225 });
1226#else // __BIONIC__
1227 GTEST_SKIP() << "pthread_rwlock_clockwrlock not available";
1228#endif // __BIONIC__
1229}
1230
1231TEST(pthread, pthread_rwlock_clockwrlock_invalid) {
1232#if defined(__BIONIC__)
1233 pthread_rwlock_t lock = PTHREAD_RWLOCK_INITIALIZER;
1234 timespec ts;
1235 EXPECT_EQ(EINVAL, pthread_rwlock_clockwrlock(&lock, CLOCK_PROCESS_CPUTIME_ID, &ts));
1236#else // __BIONIC__
1237 GTEST_SKIP() << "pthread_rwlock_clockrwlock not available";
1238#endif // __BIONIC__
1239}
1240
Colin Cross7da20342021-07-28 11:18:11 -07001241#if !defined(MUSL)
1242// musl doesn't have pthread_rwlockattr_setkind_np
Yabin Cui76615da2015-03-17 14:22:09 -07001243class RwlockKindTestHelper {
1244 private:
1245 struct ThreadArg {
1246 RwlockKindTestHelper* helper;
1247 std::atomic<pid_t>& tid;
1248
1249 ThreadArg(RwlockKindTestHelper* helper, std::atomic<pid_t>& tid)
1250 : helper(helper), tid(tid) { }
1251 };
1252
1253 public:
1254 pthread_rwlock_t lock;
1255
1256 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -07001257 explicit RwlockKindTestHelper(int kind_type) {
Yabin Cui76615da2015-03-17 14:22:09 -07001258 InitRwlock(kind_type);
1259 }
1260
1261 ~RwlockKindTestHelper() {
1262 DestroyRwlock();
1263 }
1264
1265 void CreateWriterThread(pthread_t& thread, std::atomic<pid_t>& tid) {
1266 tid = 0;
1267 ThreadArg* arg = new ThreadArg(this, tid);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001268 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui76615da2015-03-17 14:22:09 -07001269 reinterpret_cast<void* (*)(void*)>(WriterThreadFn), arg));
1270 }
1271
1272 void CreateReaderThread(pthread_t& thread, std::atomic<pid_t>& tid) {
1273 tid = 0;
1274 ThreadArg* arg = new ThreadArg(this, tid);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001275 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui76615da2015-03-17 14:22:09 -07001276 reinterpret_cast<void* (*)(void*)>(ReaderThreadFn), arg));
1277 }
1278
1279 private:
1280 void InitRwlock(int kind_type) {
1281 pthread_rwlockattr_t attr;
1282 ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
1283 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_type));
1284 ASSERT_EQ(0, pthread_rwlock_init(&lock, &attr));
1285 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
1286 }
1287
1288 void DestroyRwlock() {
1289 ASSERT_EQ(0, pthread_rwlock_destroy(&lock));
1290 }
1291
1292 static void WriterThreadFn(ThreadArg* arg) {
1293 arg->tid = gettid();
1294
1295 RwlockKindTestHelper* helper = arg->helper;
1296 ASSERT_EQ(0, pthread_rwlock_wrlock(&helper->lock));
1297 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
1298 delete arg;
1299 }
1300
1301 static void ReaderThreadFn(ThreadArg* arg) {
1302 arg->tid = gettid();
1303
1304 RwlockKindTestHelper* helper = arg->helper;
1305 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper->lock));
1306 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
1307 delete arg;
1308 }
1309};
Colin Cross7da20342021-07-28 11:18:11 -07001310#endif
Yabin Cui76615da2015-03-17 14:22:09 -07001311
1312TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_READER_NP) {
Colin Cross7da20342021-07-28 11:18:11 -07001313#if !defined(MUSL)
Yabin Cui76615da2015-03-17 14:22:09 -07001314 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_READER_NP);
1315 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
1316
1317 pthread_t writer_thread;
1318 std::atomic<pid_t> writer_tid;
1319 helper.CreateWriterThread(writer_thread, writer_tid);
1320 WaitUntilThreadSleep(writer_tid);
1321
1322 pthread_t reader_thread;
1323 std::atomic<pid_t> reader_tid;
1324 helper.CreateReaderThread(reader_thread, reader_tid);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001325 ASSERT_EQ(0, pthread_join(reader_thread, nullptr));
Yabin Cui76615da2015-03-17 14:22:09 -07001326
1327 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
Yi Kong32bc0fc2018-08-02 17:31:13 -07001328 ASSERT_EQ(0, pthread_join(writer_thread, nullptr));
Colin Cross7da20342021-07-28 11:18:11 -07001329#else
1330 GTEST_SKIP() << "musl doesn't have pthread_rwlockattr_setkind_np";
1331#endif
Yabin Cui76615da2015-03-17 14:22:09 -07001332}
1333
1334TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP) {
Colin Cross7da20342021-07-28 11:18:11 -07001335#if !defined(MUSL)
Yabin Cui76615da2015-03-17 14:22:09 -07001336 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
1337 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
1338
1339 pthread_t writer_thread;
1340 std::atomic<pid_t> writer_tid;
1341 helper.CreateWriterThread(writer_thread, writer_tid);
1342 WaitUntilThreadSleep(writer_tid);
1343
1344 pthread_t reader_thread;
1345 std::atomic<pid_t> reader_tid;
1346 helper.CreateReaderThread(reader_thread, reader_tid);
1347 WaitUntilThreadSleep(reader_tid);
1348
1349 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
Yi Kong32bc0fc2018-08-02 17:31:13 -07001350 ASSERT_EQ(0, pthread_join(writer_thread, nullptr));
1351 ASSERT_EQ(0, pthread_join(reader_thread, nullptr));
Colin Cross7da20342021-07-28 11:18:11 -07001352#else
1353 GTEST_SKIP() << "musl doesn't have pthread_rwlockattr_setkind_np";
1354#endif
Yabin Cui76615da2015-03-17 14:22:09 -07001355}
1356
Elliott Hughes1728b232014-05-14 10:02:03 -07001357static int g_once_fn_call_count = 0;
Elliott Hughesc3f11402013-10-30 14:40:09 -07001358static void OnceFn() {
Elliott Hughes1728b232014-05-14 10:02:03 -07001359 ++g_once_fn_call_count;
Elliott Hughesc3f11402013-10-30 14:40:09 -07001360}
1361
1362TEST(pthread, pthread_once_smoke) {
1363 pthread_once_t once_control = PTHREAD_ONCE_INIT;
1364 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
1365 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
Elliott Hughes1728b232014-05-14 10:02:03 -07001366 ASSERT_EQ(1, g_once_fn_call_count);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001367}
1368
Elliott Hughes3694ec62014-05-14 11:46:08 -07001369static std::string pthread_once_1934122_result = "";
1370
1371static void Routine2() {
1372 pthread_once_1934122_result += "2";
1373}
1374
1375static void Routine1() {
1376 pthread_once_t once_control_2 = PTHREAD_ONCE_INIT;
1377 pthread_once_1934122_result += "1";
1378 pthread_once(&once_control_2, &Routine2);
1379}
1380
1381TEST(pthread, pthread_once_1934122) {
1382 // Very old versions of Android couldn't call pthread_once from a
1383 // pthread_once init routine. http://b/1934122.
1384 pthread_once_t once_control_1 = PTHREAD_ONCE_INIT;
1385 ASSERT_EQ(0, pthread_once(&once_control_1, &Routine1));
1386 ASSERT_EQ("12", pthread_once_1934122_result);
1387}
1388
Elliott Hughes1728b232014-05-14 10:02:03 -07001389static int g_atfork_prepare_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001390static void AtForkPrepare1() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 1; }
1391static void AtForkPrepare2() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -07001392static int g_atfork_parent_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001393static void AtForkParent1() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 1; }
1394static void AtForkParent2() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -07001395static int g_atfork_child_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001396static void AtForkChild1() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 1; }
1397static void AtForkChild2() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 2; }
Elliott Hughesc3f11402013-10-30 14:40:09 -07001398
Dmitriy Ivanov00e37812014-11-20 16:53:47 -08001399TEST(pthread, pthread_atfork_smoke) {
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001400 ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1));
1401 ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2));
Elliott Hughesc3f11402013-10-30 14:40:09 -07001402
Elliott Hughes33697a02016-01-26 13:04:57 -08001403 pid_t pid = fork();
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001404 ASSERT_NE(-1, pid) << strerror(errno);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001405
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001406 // Child and parent calls are made in the order they were registered.
1407 if (pid == 0) {
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001408 ASSERT_EQ(12, g_atfork_child_calls);
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001409 _exit(0);
1410 }
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001411 ASSERT_EQ(12, g_atfork_parent_calls);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001412
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001413 // Prepare calls are made in the reverse order.
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001414 ASSERT_EQ(21, g_atfork_prepare_calls);
Elliott Hughes33697a02016-01-26 13:04:57 -08001415 AssertChildExited(pid, 0);
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001416}
1417
Elliott Hughesc3f11402013-10-30 14:40:09 -07001418TEST(pthread, pthread_attr_getscope) {
1419 pthread_attr_t attr;
1420 ASSERT_EQ(0, pthread_attr_init(&attr));
1421
1422 int scope;
1423 ASSERT_EQ(0, pthread_attr_getscope(&attr, &scope));
1424 ASSERT_EQ(PTHREAD_SCOPE_SYSTEM, scope);
1425}
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001426
1427TEST(pthread, pthread_condattr_init) {
1428 pthread_condattr_t attr;
1429 pthread_condattr_init(&attr);
1430
1431 clockid_t clock;
1432 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1433 ASSERT_EQ(CLOCK_REALTIME, clock);
1434
1435 int pshared;
1436 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1437 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
1438}
1439
1440TEST(pthread, pthread_condattr_setclock) {
1441 pthread_condattr_t attr;
1442 pthread_condattr_init(&attr);
1443
1444 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_REALTIME));
1445 clockid_t clock;
1446 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1447 ASSERT_EQ(CLOCK_REALTIME, clock);
1448
1449 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1450 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1451 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1452
1453 ASSERT_EQ(EINVAL, pthread_condattr_setclock(&attr, CLOCK_PROCESS_CPUTIME_ID));
1454}
1455
1456TEST(pthread, pthread_cond_broadcast__preserves_condattr_flags) {
Yabin Cui32651b82015-03-13 20:30:00 -07001457#if defined(__BIONIC__)
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001458 pthread_condattr_t attr;
1459 pthread_condattr_init(&attr);
1460
1461 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1462 ASSERT_EQ(0, pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
1463
1464 pthread_cond_t cond_var;
1465 ASSERT_EQ(0, pthread_cond_init(&cond_var, &attr));
1466
1467 ASSERT_EQ(0, pthread_cond_signal(&cond_var));
1468 ASSERT_EQ(0, pthread_cond_broadcast(&cond_var));
1469
Yabin Cui32651b82015-03-13 20:30:00 -07001470 attr = static_cast<pthread_condattr_t>(*reinterpret_cast<uint32_t*>(cond_var.__private));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001471 clockid_t clock;
1472 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1473 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1474 int pshared;
1475 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1476 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
Yabin Cui32651b82015-03-13 20:30:00 -07001477#else // !defined(__BIONIC__)
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001478 GTEST_SKIP() << "bionic-only test";
Yabin Cui32651b82015-03-13 20:30:00 -07001479#endif // !defined(__BIONIC__)
1480}
1481
1482class pthread_CondWakeupTest : public ::testing::Test {
1483 protected:
1484 pthread_mutex_t mutex;
1485 pthread_cond_t cond;
1486
1487 enum Progress {
1488 INITIALIZED,
1489 WAITING,
1490 SIGNALED,
1491 FINISHED,
1492 };
1493 std::atomic<Progress> progress;
1494 pthread_t thread;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001495 std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function;
Yabin Cui32651b82015-03-13 20:30:00 -07001496
1497 protected:
Yabin Cuic9a659c2015-11-05 15:36:08 -08001498 void SetUp() override {
1499 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1500 }
1501
1502 void InitCond(clockid_t clock=CLOCK_REALTIME) {
1503 pthread_condattr_t attr;
1504 ASSERT_EQ(0, pthread_condattr_init(&attr));
1505 ASSERT_EQ(0, pthread_condattr_setclock(&attr, clock));
1506 ASSERT_EQ(0, pthread_cond_init(&cond, &attr));
1507 ASSERT_EQ(0, pthread_condattr_destroy(&attr));
1508 }
1509
Tom Cherry69010802019-05-07 20:33:05 -07001510 void StartWaitingThread(
1511 std::function<int(pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function) {
Yabin Cui32651b82015-03-13 20:30:00 -07001512 progress = INITIALIZED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001513 this->wait_function = wait_function;
Tom Cherry69010802019-05-07 20:33:05 -07001514 ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(WaitThreadFn),
1515 this));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001516 while (progress != WAITING) {
Yabin Cui32651b82015-03-13 20:30:00 -07001517 usleep(5000);
1518 }
1519 usleep(5000);
1520 }
1521
Tom Cherry69010802019-05-07 20:33:05 -07001522 void RunTimedTest(
1523 clockid_t clock,
1524 std::function<int(pthread_cond_t* cond, pthread_mutex_t* mutex, const timespec* timeout)>
1525 wait_function) {
1526 timespec ts;
1527 ASSERT_EQ(0, clock_gettime(clock, &ts));
1528 ts.tv_sec += 1;
1529
1530 StartWaitingThread([&wait_function, &ts](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1531 return wait_function(cond, mutex, &ts);
1532 });
1533
1534 progress = SIGNALED;
1535 ASSERT_EQ(0, pthread_cond_signal(&cond));
1536 }
1537
1538 void RunTimedTest(clockid_t clock, std::function<int(pthread_cond_t* cond, pthread_mutex_t* mutex,
1539 clockid_t clock, const timespec* timeout)>
1540 wait_function) {
1541 RunTimedTest(clock, [clock, &wait_function](pthread_cond_t* cond, pthread_mutex_t* mutex,
1542 const timespec* timeout) {
1543 return wait_function(cond, mutex, clock, timeout);
1544 });
1545 }
1546
Yabin Cuic9a659c2015-11-05 15:36:08 -08001547 void TearDown() override {
1548 ASSERT_EQ(0, pthread_join(thread, nullptr));
1549 ASSERT_EQ(FINISHED, progress);
1550 ASSERT_EQ(0, pthread_cond_destroy(&cond));
1551 ASSERT_EQ(0, pthread_mutex_destroy(&mutex));
1552 }
1553
Yabin Cui32651b82015-03-13 20:30:00 -07001554 private:
1555 static void WaitThreadFn(pthread_CondWakeupTest* test) {
1556 ASSERT_EQ(0, pthread_mutex_lock(&test->mutex));
1557 test->progress = WAITING;
1558 while (test->progress == WAITING) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001559 ASSERT_EQ(0, test->wait_function(&test->cond, &test->mutex));
Yabin Cui32651b82015-03-13 20:30:00 -07001560 }
1561 ASSERT_EQ(SIGNALED, test->progress);
1562 test->progress = FINISHED;
1563 ASSERT_EQ(0, pthread_mutex_unlock(&test->mutex));
1564 }
1565};
1566
Yabin Cuic9a659c2015-11-05 15:36:08 -08001567TEST_F(pthread_CondWakeupTest, signal_wait) {
1568 InitCond();
1569 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1570 return pthread_cond_wait(cond, mutex);
1571 });
Yabin Cui32651b82015-03-13 20:30:00 -07001572 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001573 ASSERT_EQ(0, pthread_cond_signal(&cond));
Yabin Cui32651b82015-03-13 20:30:00 -07001574}
1575
Yabin Cuic9a659c2015-11-05 15:36:08 -08001576TEST_F(pthread_CondWakeupTest, broadcast_wait) {
1577 InitCond();
1578 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1579 return pthread_cond_wait(cond, mutex);
1580 });
Yabin Cui32651b82015-03-13 20:30:00 -07001581 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001582 ASSERT_EQ(0, pthread_cond_broadcast(&cond));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001583}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001584
Yabin Cuic9a659c2015-11-05 15:36:08 -08001585TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_REALTIME) {
1586 InitCond(CLOCK_REALTIME);
Tom Cherry69010802019-05-07 20:33:05 -07001587 RunTimedTest(CLOCK_REALTIME, pthread_cond_timedwait);
Yabin Cuic9a659c2015-11-05 15:36:08 -08001588}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001589
Yabin Cuic9a659c2015-11-05 15:36:08 -08001590TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC) {
1591 InitCond(CLOCK_MONOTONIC);
Tom Cherry69010802019-05-07 20:33:05 -07001592 RunTimedTest(CLOCK_MONOTONIC, pthread_cond_timedwait);
Yabin Cuic9a659c2015-11-05 15:36:08 -08001593}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001594
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001595TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC_np) {
1596#if defined(__BIONIC__)
1597 InitCond(CLOCK_REALTIME);
Tom Cherry69010802019-05-07 20:33:05 -07001598 RunTimedTest(CLOCK_MONOTONIC, pthread_cond_timedwait_monotonic_np);
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001599#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001600 GTEST_SKIP() << "pthread_cond_timedwait_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001601#endif // __BIONIC__
1602}
1603
Tom Cherry69010802019-05-07 20:33:05 -07001604TEST_F(pthread_CondWakeupTest, signal_clockwait_monotonic_monotonic) {
1605#if defined(__BIONIC__)
1606 InitCond(CLOCK_MONOTONIC);
1607 RunTimedTest(CLOCK_MONOTONIC, pthread_cond_clockwait);
1608#else // __BIONIC__
1609 GTEST_SKIP() << "pthread_cond_clockwait not available";
1610#endif // __BIONIC__
1611}
1612
1613TEST_F(pthread_CondWakeupTest, signal_clockwait_monotonic_realtime) {
1614#if defined(__BIONIC__)
1615 InitCond(CLOCK_MONOTONIC);
1616 RunTimedTest(CLOCK_REALTIME, pthread_cond_clockwait);
1617#else // __BIONIC__
1618 GTEST_SKIP() << "pthread_cond_clockwait not available";
1619#endif // __BIONIC__
1620}
1621
1622TEST_F(pthread_CondWakeupTest, signal_clockwait_realtime_monotonic) {
1623#if defined(__BIONIC__)
1624 InitCond(CLOCK_REALTIME);
1625 RunTimedTest(CLOCK_MONOTONIC, pthread_cond_clockwait);
1626#else // __BIONIC__
1627 GTEST_SKIP() << "pthread_cond_clockwait not available";
1628#endif // __BIONIC__
1629}
1630
1631TEST_F(pthread_CondWakeupTest, signal_clockwait_realtime_realtime) {
1632#if defined(__BIONIC__)
1633 InitCond(CLOCK_REALTIME);
1634 RunTimedTest(CLOCK_REALTIME, pthread_cond_clockwait);
1635#else // __BIONIC__
1636 GTEST_SKIP() << "pthread_cond_clockwait not available";
1637#endif // __BIONIC__
1638}
1639
Tom Cherry800c1a92019-07-17 10:45:18 -07001640static void pthread_cond_timedwait_timeout_helper(bool init_monotonic, clockid_t clock,
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001641 int (*wait_function)(pthread_cond_t* __cond,
1642 pthread_mutex_t* __mutex,
1643 const timespec* __timeout)) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001644 pthread_mutex_t mutex;
1645 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1646 pthread_cond_t cond;
Tom Cherry800c1a92019-07-17 10:45:18 -07001647
1648 if (init_monotonic) {
1649 pthread_condattr_t attr;
1650 pthread_condattr_init(&attr);
1651
1652 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1653 clockid_t clock;
1654 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1655 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1656
1657 ASSERT_EQ(0, pthread_cond_init(&cond, &attr));
1658 } else {
1659 ASSERT_EQ(0, pthread_cond_init(&cond, nullptr));
1660 }
Yabin Cuic9a659c2015-11-05 15:36:08 -08001661 ASSERT_EQ(0, pthread_mutex_lock(&mutex));
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001662
Yabin Cuic9a659c2015-11-05 15:36:08 -08001663 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001664 ASSERT_EQ(0, clock_gettime(clock, &ts));
1665 ASSERT_EQ(ETIMEDOUT, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001666 ts.tv_nsec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001667 ASSERT_EQ(EINVAL, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001668 ts.tv_nsec = NS_PER_S;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001669 ASSERT_EQ(EINVAL, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001670 ts.tv_nsec = NS_PER_S - 1;
1671 ts.tv_sec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001672 ASSERT_EQ(ETIMEDOUT, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001673 ASSERT_EQ(0, pthread_mutex_unlock(&mutex));
Elliott Hughes0e714a52014-03-03 16:42:47 -08001674}
Elliott Hughes57b7a612014-08-25 17:26:50 -07001675
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001676TEST(pthread, pthread_cond_timedwait_timeout) {
Tom Cherry800c1a92019-07-17 10:45:18 -07001677 pthread_cond_timedwait_timeout_helper(false, CLOCK_REALTIME, pthread_cond_timedwait);
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001678}
1679
1680TEST(pthread, pthread_cond_timedwait_monotonic_np_timeout) {
1681#if defined(__BIONIC__)
Tom Cherry800c1a92019-07-17 10:45:18 -07001682 pthread_cond_timedwait_timeout_helper(false, CLOCK_MONOTONIC, pthread_cond_timedwait_monotonic_np);
1683 pthread_cond_timedwait_timeout_helper(true, CLOCK_MONOTONIC, pthread_cond_timedwait_monotonic_np);
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001684#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001685 GTEST_SKIP() << "pthread_cond_timedwait_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001686#endif // __BIONIC__
1687}
1688
Tom Cherry69010802019-05-07 20:33:05 -07001689TEST(pthread, pthread_cond_clockwait_timeout) {
1690#if defined(__BIONIC__)
1691 pthread_cond_timedwait_timeout_helper(
Tom Cherry800c1a92019-07-17 10:45:18 -07001692 false, CLOCK_MONOTONIC,
Tom Cherry69010802019-05-07 20:33:05 -07001693 [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) {
1694 return pthread_cond_clockwait(__cond, __mutex, CLOCK_MONOTONIC, __timeout);
1695 });
1696 pthread_cond_timedwait_timeout_helper(
Tom Cherry800c1a92019-07-17 10:45:18 -07001697 true, CLOCK_MONOTONIC,
1698 [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) {
1699 return pthread_cond_clockwait(__cond, __mutex, CLOCK_MONOTONIC, __timeout);
1700 });
1701 pthread_cond_timedwait_timeout_helper(
1702 false, CLOCK_REALTIME,
1703 [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) {
1704 return pthread_cond_clockwait(__cond, __mutex, CLOCK_REALTIME, __timeout);
1705 });
1706 pthread_cond_timedwait_timeout_helper(
1707 true, CLOCK_REALTIME,
Tom Cherry69010802019-05-07 20:33:05 -07001708 [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) {
1709 return pthread_cond_clockwait(__cond, __mutex, CLOCK_REALTIME, __timeout);
1710 });
1711#else // __BIONIC__
1712 GTEST_SKIP() << "pthread_cond_clockwait not available";
1713#endif // __BIONIC__
1714}
1715
1716TEST(pthread, pthread_cond_clockwait_invalid) {
1717#if defined(__BIONIC__)
1718 pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
1719 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
1720 timespec ts;
1721 EXPECT_EQ(EINVAL, pthread_cond_clockwait(&cond, &mutex, CLOCK_PROCESS_CPUTIME_ID, &ts));
1722
1723#else // __BIONIC__
1724 GTEST_SKIP() << "pthread_cond_clockwait not available";
1725#endif // __BIONIC__
1726}
1727
Elliott Hughes57b7a612014-08-25 17:26:50 -07001728TEST(pthread, pthread_attr_getstack__main_thread) {
1729 // This test is only meaningful for the main thread, so make sure we're running on it!
1730 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1731
1732 // Get the main thread's attributes.
1733 pthread_attr_t attributes;
1734 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1735
1736 // Check that we correctly report that the main thread has no guard page.
1737 size_t guard_size;
1738 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
1739 ASSERT_EQ(0U, guard_size); // The main thread has no guard page.
1740
1741 // Get the stack base and the stack size (both ways).
1742 void* stack_base;
1743 size_t stack_size;
1744 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1745 size_t stack_size2;
1746 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1747
1748 // The two methods of asking for the stack size should agree.
1749 EXPECT_EQ(stack_size, stack_size2);
1750
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001751#if defined(__BIONIC__)
dimitry6dfa5b52018-01-30 13:24:28 +01001752 // Find stack in /proc/self/maps using a pointer to the stack.
1753 //
1754 // We do not use "[stack]" label because in native-bridge environment it is not
1755 // guaranteed to point to the right stack. A native bridge implementation may
1756 // keep separate stack for the guest code.
Yi Kong32bc0fc2018-08-02 17:31:13 -07001757 void* maps_stack_hi = nullptr;
Elliott Hughes15dfd632015-09-22 16:40:14 -07001758 std::vector<map_record> maps;
1759 ASSERT_TRUE(Maps::parse_maps(&maps));
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08001760 uintptr_t stack_address = reinterpret_cast<uintptr_t>(untag_address(&maps_stack_hi));
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07001761 for (const auto& map : maps) {
dimitry6dfa5b52018-01-30 13:24:28 +01001762 if (map.addr_start <= stack_address && map.addr_end > stack_address){
Elliott Hughes15dfd632015-09-22 16:40:14 -07001763 maps_stack_hi = reinterpret_cast<void*>(map.addr_end);
Elliott Hughes57b7a612014-08-25 17:26:50 -07001764 break;
1765 }
1766 }
Elliott Hughes57b7a612014-08-25 17:26:50 -07001767
dimitry6dfa5b52018-01-30 13:24:28 +01001768 // The high address of the /proc/self/maps stack region should equal stack_base + stack_size.
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001769 // Remember that the stack grows down (and is mapped in on demand), so the low address of the
1770 // region isn't very interesting.
1771 EXPECT_EQ(maps_stack_hi, reinterpret_cast<uint8_t*>(stack_base) + stack_size);
1772
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001773 // The stack size should correspond to RLIMIT_STACK.
Elliott Hughes57b7a612014-08-25 17:26:50 -07001774 rlimit rl;
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001775 ASSERT_EQ(0, getrlimit(RLIMIT_STACK, &rl));
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001776 uint64_t original_rlim_cur = rl.rlim_cur;
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001777 if (rl.rlim_cur == RLIM_INFINITY) {
1778 rl.rlim_cur = 8 * 1024 * 1024; // Bionic reports unlimited stacks as 8MiB.
1779 }
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001780 EXPECT_EQ(rl.rlim_cur, stack_size);
1781
Tom Cherryb8ab6182017-04-05 16:20:29 -07001782 auto guard = android::base::make_scope_guard([&rl, original_rlim_cur]() {
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001783 rl.rlim_cur = original_rlim_cur;
1784 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1785 });
1786
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001787 //
1788 // What if RLIMIT_STACK is smaller than the stack's current extent?
1789 //
Elliott Hughes57b7a612014-08-25 17:26:50 -07001790 rl.rlim_cur = rl.rlim_max = 1024; // 1KiB. We know the stack must be at least a page already.
1791 rl.rlim_max = RLIM_INFINITY;
1792 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1793
1794 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1795 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1796 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1797
1798 EXPECT_EQ(stack_size, stack_size2);
1799 ASSERT_EQ(1024U, stack_size);
1800
1801 //
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001802 // What if RLIMIT_STACK isn't a whole number of pages?
Elliott Hughes57b7a612014-08-25 17:26:50 -07001803 //
1804 rl.rlim_cur = rl.rlim_max = 6666; // Not a whole number of pages.
1805 rl.rlim_max = RLIM_INFINITY;
1806 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1807
1808 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1809 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1810 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1811
1812 EXPECT_EQ(stack_size, stack_size2);
1813 ASSERT_EQ(6666U, stack_size);
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001814#endif
Elliott Hughes57b7a612014-08-25 17:26:50 -07001815}
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001816
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001817struct GetStackSignalHandlerArg {
1818 volatile bool done;
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001819 void* signal_stack_base;
1820 size_t signal_stack_size;
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001821 void* main_stack_base;
1822 size_t main_stack_size;
1823};
1824
1825static GetStackSignalHandlerArg getstack_signal_handler_arg;
1826
1827static void getstack_signal_handler(int sig) {
1828 ASSERT_EQ(SIGUSR1, sig);
1829 // Use sleep() to make current thread be switched out by the kernel to provoke the error.
1830 sleep(1);
1831 pthread_attr_t attr;
1832 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1833 void* stack_base;
1834 size_t stack_size;
1835 ASSERT_EQ(0, pthread_attr_getstack(&attr, &stack_base, &stack_size));
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001836
1837 // Verify if the stack used by the signal handler is the alternate stack just registered.
1838 ASSERT_LE(getstack_signal_handler_arg.signal_stack_base, &attr);
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08001839 ASSERT_LT(static_cast<void*>(untag_address(&attr)),
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001840 static_cast<char*>(getstack_signal_handler_arg.signal_stack_base) +
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08001841 getstack_signal_handler_arg.signal_stack_size);
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001842
1843 // Verify if the main thread's stack got in the signal handler is correct.
1844 ASSERT_EQ(getstack_signal_handler_arg.main_stack_base, stack_base);
1845 ASSERT_LE(getstack_signal_handler_arg.main_stack_size, stack_size);
1846
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001847 getstack_signal_handler_arg.done = true;
1848}
1849
1850// The previous code obtained the main thread's stack by reading the entry in
1851// /proc/self/task/<pid>/maps that was labeled [stack]. Unfortunately, on x86/x86_64, the kernel
1852// relies on sp0 in task state segment(tss) to label the stack map with [stack]. If the kernel
1853// switches a process while the main thread is in an alternate stack, then the kernel will label
1854// the wrong map with [stack]. This test verifies that when the above situation happens, the main
1855// thread's stack is found correctly.
1856TEST(pthread, pthread_attr_getstack_in_signal_handler) {
Yabin Cui61e4d462016-03-07 17:44:58 -08001857 // This test is only meaningful for the main thread, so make sure we're running on it!
1858 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1859
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001860 const size_t sig_stack_size = 16 * 1024;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001861 void* sig_stack = mmap(nullptr, sig_stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS,
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001862 -1, 0);
1863 ASSERT_NE(MAP_FAILED, sig_stack);
1864 stack_t ss;
1865 ss.ss_sp = sig_stack;
1866 ss.ss_size = sig_stack_size;
1867 ss.ss_flags = 0;
1868 stack_t oss;
1869 ASSERT_EQ(0, sigaltstack(&ss, &oss));
1870
Yabin Cui61e4d462016-03-07 17:44:58 -08001871 pthread_attr_t attr;
1872 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1873 void* main_stack_base;
1874 size_t main_stack_size;
1875 ASSERT_EQ(0, pthread_attr_getstack(&attr, &main_stack_base, &main_stack_size));
1876
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001877 ScopedSignalHandler handler(SIGUSR1, getstack_signal_handler, SA_ONSTACK);
1878 getstack_signal_handler_arg.done = false;
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001879 getstack_signal_handler_arg.signal_stack_base = sig_stack;
1880 getstack_signal_handler_arg.signal_stack_size = sig_stack_size;
1881 getstack_signal_handler_arg.main_stack_base = main_stack_base;
1882 getstack_signal_handler_arg.main_stack_size = main_stack_size;
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001883 kill(getpid(), SIGUSR1);
1884 ASSERT_EQ(true, getstack_signal_handler_arg.done);
1885
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001886 ASSERT_EQ(0, sigaltstack(&oss, nullptr));
1887 ASSERT_EQ(0, munmap(sig_stack, sig_stack_size));
1888}
1889
Yabin Cui917d3902015-01-08 12:32:42 -08001890static void pthread_attr_getstack_18908062_helper(void*) {
1891 char local_variable;
1892 pthread_attr_t attributes;
1893 pthread_getattr_np(pthread_self(), &attributes);
1894 void* stack_base;
1895 size_t stack_size;
1896 pthread_attr_getstack(&attributes, &stack_base, &stack_size);
1897
1898 // Test whether &local_variable is in [stack_base, stack_base + stack_size).
1899 ASSERT_LE(reinterpret_cast<char*>(stack_base), &local_variable);
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08001900 ASSERT_LT(untag_address(&local_variable), reinterpret_cast<char*>(stack_base) + stack_size);
Yabin Cui917d3902015-01-08 12:32:42 -08001901}
1902
1903// Check whether something on stack is in the range of
1904// [stack_base, stack_base + stack_size). see b/18908062.
1905TEST(pthread, pthread_attr_getstack_18908062) {
1906 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001907 ASSERT_EQ(0, pthread_create(&t, nullptr,
Yabin Cui917d3902015-01-08 12:32:42 -08001908 reinterpret_cast<void* (*)(void*)>(pthread_attr_getstack_18908062_helper),
Yi Kong32bc0fc2018-08-02 17:31:13 -07001909 nullptr));
1910 ASSERT_EQ(0, pthread_join(t, nullptr));
Yabin Cui917d3902015-01-08 12:32:42 -08001911}
1912
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001913#if defined(__BIONIC__)
Elliott Hughesf2083612015-11-11 13:32:28 -08001914static pthread_mutex_t pthread_gettid_np_mutex = PTHREAD_MUTEX_INITIALIZER;
1915
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001916static void* pthread_gettid_np_helper(void* arg) {
1917 *reinterpret_cast<pid_t*>(arg) = gettid();
Elliott Hughesf2083612015-11-11 13:32:28 -08001918
1919 // Wait for our parent to call pthread_gettid_np on us before exiting.
1920 pthread_mutex_lock(&pthread_gettid_np_mutex);
1921 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001922 return nullptr;
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001923}
1924#endif
1925
1926TEST(pthread, pthread_gettid_np) {
1927#if defined(__BIONIC__)
1928 ASSERT_EQ(gettid(), pthread_gettid_np(pthread_self()));
1929
Elliott Hughesf2083612015-11-11 13:32:28 -08001930 // Ensure the other thread doesn't exit until after we've called
1931 // pthread_gettid_np on it.
1932 pthread_mutex_lock(&pthread_gettid_np_mutex);
1933
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001934 pid_t t_gettid_result;
1935 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001936 pthread_create(&t, nullptr, pthread_gettid_np_helper, &t_gettid_result);
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001937
1938 pid_t t_pthread_gettid_np_result = pthread_gettid_np(t);
1939
Elliott Hughesf2083612015-11-11 13:32:28 -08001940 // Release the other thread and wait for it to exit.
1941 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001942 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001943
1944 ASSERT_EQ(t_gettid_result, t_pthread_gettid_np_result);
1945#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001946 GTEST_SKIP() << "pthread_gettid_np not available";
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001947#endif
1948}
Elliott Hughes34c987a2014-09-22 16:01:26 -07001949
1950static size_t cleanup_counter = 0;
1951
Derek Xue41996952014-09-25 11:05:32 +01001952static void AbortCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001953 abort();
1954}
1955
Derek Xue41996952014-09-25 11:05:32 +01001956static void CountCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001957 ++cleanup_counter;
1958}
1959
Derek Xue41996952014-09-25 11:05:32 +01001960static void PthreadCleanupTester() {
Yi Kong32bc0fc2018-08-02 17:31:13 -07001961 pthread_cleanup_push(CountCleanupRoutine, nullptr);
1962 pthread_cleanup_push(CountCleanupRoutine, nullptr);
1963 pthread_cleanup_push(AbortCleanupRoutine, nullptr);
Elliott Hughes34c987a2014-09-22 16:01:26 -07001964
1965 pthread_cleanup_pop(0); // Pop the abort without executing it.
1966 pthread_cleanup_pop(1); // Pop one count while executing it.
1967 ASSERT_EQ(1U, cleanup_counter);
1968 // Exit while the other count is still on the cleanup stack.
Yi Kong32bc0fc2018-08-02 17:31:13 -07001969 pthread_exit(nullptr);
Elliott Hughes34c987a2014-09-22 16:01:26 -07001970
1971 // Calls to pthread_cleanup_pop/pthread_cleanup_push must always be balanced.
1972 pthread_cleanup_pop(0);
1973}
1974
Derek Xue41996952014-09-25 11:05:32 +01001975static void* PthreadCleanupStartRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001976 PthreadCleanupTester();
Yi Kong32bc0fc2018-08-02 17:31:13 -07001977 return nullptr;
Elliott Hughes34c987a2014-09-22 16:01:26 -07001978}
1979
1980TEST(pthread, pthread_cleanup_push__pthread_cleanup_pop) {
1981 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001982 ASSERT_EQ(0, pthread_create(&t, nullptr, PthreadCleanupStartRoutine, nullptr));
1983 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes34c987a2014-09-22 16:01:26 -07001984 ASSERT_EQ(2U, cleanup_counter);
1985}
Derek Xue41996952014-09-25 11:05:32 +01001986
1987TEST(pthread, PTHREAD_MUTEX_DEFAULT_is_PTHREAD_MUTEX_NORMAL) {
1988 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_DEFAULT);
1989}
1990
1991TEST(pthread, pthread_mutexattr_gettype) {
1992 pthread_mutexattr_t attr;
1993 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1994
1995 int attr_type;
1996
1997 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL));
1998 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1999 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, attr_type);
2000
2001 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK));
2002 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
2003 ASSERT_EQ(PTHREAD_MUTEX_ERRORCHECK, attr_type);
2004
2005 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE));
2006 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
2007 ASSERT_EQ(PTHREAD_MUTEX_RECURSIVE, attr_type);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002008
2009 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
2010}
2011
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002012TEST(pthread, pthread_mutexattr_protocol) {
2013 pthread_mutexattr_t attr;
2014 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
2015
2016 int protocol;
2017 ASSERT_EQ(0, pthread_mutexattr_getprotocol(&attr, &protocol));
2018 ASSERT_EQ(PTHREAD_PRIO_NONE, protocol);
2019 for (size_t repeat = 0; repeat < 2; ++repeat) {
2020 for (int set_protocol : {PTHREAD_PRIO_NONE, PTHREAD_PRIO_INHERIT}) {
2021 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, set_protocol));
2022 ASSERT_EQ(0, pthread_mutexattr_getprotocol(&attr, &protocol));
2023 ASSERT_EQ(protocol, set_protocol);
2024 }
2025 }
2026}
2027
Yabin Cui17393b02015-03-21 15:08:25 -07002028struct PthreadMutex {
2029 pthread_mutex_t lock;
2030
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002031 explicit PthreadMutex(int mutex_type, int protocol = PTHREAD_PRIO_NONE) {
2032 init(mutex_type, protocol);
Yabin Cui17393b02015-03-21 15:08:25 -07002033 }
2034
2035 ~PthreadMutex() {
2036 destroy();
2037 }
2038
2039 private:
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002040 void init(int mutex_type, int protocol) {
Yabin Cui17393b02015-03-21 15:08:25 -07002041 pthread_mutexattr_t attr;
2042 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
2043 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, mutex_type));
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002044 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, protocol));
Yabin Cui17393b02015-03-21 15:08:25 -07002045 ASSERT_EQ(0, pthread_mutex_init(&lock, &attr));
2046 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
2047 }
2048
2049 void destroy() {
2050 ASSERT_EQ(0, pthread_mutex_destroy(&lock));
2051 }
2052
2053 DISALLOW_COPY_AND_ASSIGN(PthreadMutex);
2054};
Derek Xue41996952014-09-25 11:05:32 +01002055
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002056static int UnlockFromAnotherThread(pthread_mutex_t* mutex) {
2057 pthread_t thread;
2058 pthread_create(&thread, nullptr, [](void* mutex_voidp) -> void* {
2059 pthread_mutex_t* mutex = static_cast<pthread_mutex_t*>(mutex_voidp);
2060 intptr_t result = pthread_mutex_unlock(mutex);
2061 return reinterpret_cast<void*>(result);
2062 }, mutex);
2063 void* result;
2064 EXPECT_EQ(0, pthread_join(thread, &result));
2065 return reinterpret_cast<intptr_t>(result);
2066};
2067
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002068static void TestPthreadMutexLockNormal(int protocol) {
2069 PthreadMutex m(PTHREAD_MUTEX_NORMAL, protocol);
Derek Xue41996952014-09-25 11:05:32 +01002070
Yabin Cui17393b02015-03-21 15:08:25 -07002071 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002072 if (protocol == PTHREAD_PRIO_INHERIT) {
2073 ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock));
2074 }
Yabin Cui17393b02015-03-21 15:08:25 -07002075 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08002076 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
2077 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
2078 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01002079}
2080
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002081static void TestPthreadMutexLockErrorCheck(int protocol) {
2082 PthreadMutex m(PTHREAD_MUTEX_ERRORCHECK, protocol);
Derek Xue41996952014-09-25 11:05:32 +01002083
Yabin Cui17393b02015-03-21 15:08:25 -07002084 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002085 ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07002086 ASSERT_EQ(EDEADLK, pthread_mutex_lock(&m.lock));
2087 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2088 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002089 if (protocol == PTHREAD_PRIO_NONE) {
2090 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
2091 } else {
2092 ASSERT_EQ(EDEADLK, pthread_mutex_trylock(&m.lock));
2093 }
Yabin Cui17393b02015-03-21 15:08:25 -07002094 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2095 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01002096}
2097
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002098static void TestPthreadMutexLockRecursive(int protocol) {
2099 PthreadMutex m(PTHREAD_MUTEX_RECURSIVE, protocol);
Derek Xue41996952014-09-25 11:05:32 +01002100
Yabin Cui17393b02015-03-21 15:08:25 -07002101 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002102 ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07002103 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002104 ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07002105 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2106 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2107 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08002108 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
2109 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07002110 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2111 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
2112}
2113
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002114TEST(pthread, pthread_mutex_lock_NORMAL) {
2115 TestPthreadMutexLockNormal(PTHREAD_PRIO_NONE);
2116}
2117
2118TEST(pthread, pthread_mutex_lock_ERRORCHECK) {
2119 TestPthreadMutexLockErrorCheck(PTHREAD_PRIO_NONE);
2120}
2121
2122TEST(pthread, pthread_mutex_lock_RECURSIVE) {
2123 TestPthreadMutexLockRecursive(PTHREAD_PRIO_NONE);
2124}
2125
2126TEST(pthread, pthread_mutex_lock_pi) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002127 TestPthreadMutexLockNormal(PTHREAD_PRIO_INHERIT);
2128 TestPthreadMutexLockErrorCheck(PTHREAD_PRIO_INHERIT);
2129 TestPthreadMutexLockRecursive(PTHREAD_PRIO_INHERIT);
2130}
2131
Yabin Cui5a00ba72018-01-26 17:32:31 -08002132TEST(pthread, pthread_mutex_pi_count_limit) {
2133#if defined(__BIONIC__) && !defined(__LP64__)
2134 // Bionic only supports 65536 pi mutexes in 32-bit programs.
2135 pthread_mutexattr_t attr;
2136 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
2137 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT));
2138 std::vector<pthread_mutex_t> mutexes(65536);
2139 // Test if we can use 65536 pi mutexes at the same time.
2140 // Run 2 times to check if freed pi mutexes can be recycled.
2141 for (int repeat = 0; repeat < 2; ++repeat) {
2142 for (auto& m : mutexes) {
2143 ASSERT_EQ(0, pthread_mutex_init(&m, &attr));
2144 }
2145 pthread_mutex_t m;
2146 ASSERT_EQ(ENOMEM, pthread_mutex_init(&m, &attr));
2147 for (auto& m : mutexes) {
2148 ASSERT_EQ(0, pthread_mutex_lock(&m));
2149 }
2150 for (auto& m : mutexes) {
2151 ASSERT_EQ(0, pthread_mutex_unlock(&m));
2152 }
2153 for (auto& m : mutexes) {
2154 ASSERT_EQ(0, pthread_mutex_destroy(&m));
2155 }
2156 }
2157 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
2158#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002159 GTEST_SKIP() << "pi mutex count not limited to 64Ki";
Yabin Cui5a00ba72018-01-26 17:32:31 -08002160#endif
2161}
2162
Yabin Cui17393b02015-03-21 15:08:25 -07002163TEST(pthread, pthread_mutex_init_same_as_static_initializers) {
2164 pthread_mutex_t lock_normal = PTHREAD_MUTEX_INITIALIZER;
2165 PthreadMutex m1(PTHREAD_MUTEX_NORMAL);
2166 ASSERT_EQ(0, memcmp(&lock_normal, &m1.lock, sizeof(pthread_mutex_t)));
2167 pthread_mutex_destroy(&lock_normal);
2168
Colin Cross7da20342021-07-28 11:18:11 -07002169#if !defined(MUSL)
2170 // musl doesn't support PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP or
2171 // PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP.
Yabin Cui17393b02015-03-21 15:08:25 -07002172 pthread_mutex_t lock_errorcheck = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
2173 PthreadMutex m2(PTHREAD_MUTEX_ERRORCHECK);
2174 ASSERT_EQ(0, memcmp(&lock_errorcheck, &m2.lock, sizeof(pthread_mutex_t)));
2175 pthread_mutex_destroy(&lock_errorcheck);
2176
2177 pthread_mutex_t lock_recursive = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
2178 PthreadMutex m3(PTHREAD_MUTEX_RECURSIVE);
2179 ASSERT_EQ(0, memcmp(&lock_recursive, &m3.lock, sizeof(pthread_mutex_t)));
2180 ASSERT_EQ(0, pthread_mutex_destroy(&lock_recursive));
Colin Cross7da20342021-07-28 11:18:11 -07002181#endif
Derek Xue41996952014-09-25 11:05:32 +01002182}
Yabin Cui5a00ba72018-01-26 17:32:31 -08002183
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002184class MutexWakeupHelper {
2185 private:
Yabin Cui17393b02015-03-21 15:08:25 -07002186 PthreadMutex m;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002187 enum Progress {
2188 LOCK_INITIALIZED,
2189 LOCK_WAITING,
2190 LOCK_RELEASED,
2191 LOCK_ACCESSED
2192 };
2193 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -07002194 std::atomic<pid_t> tid;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002195
2196 static void thread_fn(MutexWakeupHelper* helper) {
Yabin Cuif7969852015-04-02 17:47:48 -07002197 helper->tid = gettid();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002198 ASSERT_EQ(LOCK_INITIALIZED, helper->progress);
2199 helper->progress = LOCK_WAITING;
2200
Yabin Cui17393b02015-03-21 15:08:25 -07002201 ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002202 ASSERT_EQ(LOCK_RELEASED, helper->progress);
Yabin Cui17393b02015-03-21 15:08:25 -07002203 ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002204
2205 helper->progress = LOCK_ACCESSED;
2206 }
2207
2208 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -07002209 explicit MutexWakeupHelper(int mutex_type) : m(mutex_type) {
Yabin Cui17393b02015-03-21 15:08:25 -07002210 }
2211
2212 void test() {
2213 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002214 progress = LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -07002215 tid = 0;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002216
2217 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002218 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002219 reinterpret_cast<void* (*)(void*)>(MutexWakeupHelper::thread_fn), this));
2220
Yabin Cuif7969852015-04-02 17:47:48 -07002221 WaitUntilThreadSleep(tid);
2222 ASSERT_EQ(LOCK_WAITING, progress);
2223
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002224 progress = LOCK_RELEASED;
Yabin Cui17393b02015-03-21 15:08:25 -07002225 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002226
Yi Kong32bc0fc2018-08-02 17:31:13 -07002227 ASSERT_EQ(0, pthread_join(thread, nullptr));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002228 ASSERT_EQ(LOCK_ACCESSED, progress);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002229 }
2230};
2231
2232TEST(pthread, pthread_mutex_NORMAL_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07002233 MutexWakeupHelper helper(PTHREAD_MUTEX_NORMAL);
2234 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002235}
2236
2237TEST(pthread, pthread_mutex_ERRORCHECK_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07002238 MutexWakeupHelper helper(PTHREAD_MUTEX_ERRORCHECK);
2239 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002240}
2241
2242TEST(pthread, pthread_mutex_RECURSIVE_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07002243 MutexWakeupHelper helper(PTHREAD_MUTEX_RECURSIVE);
2244 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002245}
2246
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002247static int GetThreadPriority(pid_t tid) {
2248 // sched_getparam() returns the static priority of a thread, which can't reflect a thread's
2249 // priority after priority inheritance. So read /proc/<pid>/stat to get the dynamic priority.
2250 std::string filename = android::base::StringPrintf("/proc/%d/stat", tid);
2251 std::string content;
2252 int result = INT_MAX;
2253 if (!android::base::ReadFileToString(filename, &content)) {
2254 return result;
2255 }
2256 std::vector<std::string> strs = android::base::Split(content, " ");
2257 if (strs.size() < 18) {
2258 return result;
2259 }
2260 if (!android::base::ParseInt(strs[17], &result)) {
2261 return INT_MAX;
2262 }
2263 return result;
2264}
2265
2266class PIMutexWakeupHelper {
2267private:
2268 PthreadMutex m;
2269 int protocol;
2270 enum Progress {
2271 LOCK_INITIALIZED,
2272 LOCK_CHILD_READY,
2273 LOCK_WAITING,
2274 LOCK_RELEASED,
2275 };
2276 std::atomic<Progress> progress;
2277 std::atomic<pid_t> main_tid;
2278 std::atomic<pid_t> child_tid;
2279 PthreadMutex start_thread_m;
2280
2281 static void thread_fn(PIMutexWakeupHelper* helper) {
2282 helper->child_tid = gettid();
2283 ASSERT_EQ(LOCK_INITIALIZED, helper->progress);
2284 ASSERT_EQ(0, setpriority(PRIO_PROCESS, gettid(), 1));
2285 ASSERT_EQ(21, GetThreadPriority(gettid()));
2286 ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock));
2287 helper->progress = LOCK_CHILD_READY;
2288 ASSERT_EQ(0, pthread_mutex_lock(&helper->start_thread_m.lock));
2289
2290 ASSERT_EQ(0, pthread_mutex_unlock(&helper->start_thread_m.lock));
2291 WaitUntilThreadSleep(helper->main_tid);
2292 ASSERT_EQ(LOCK_WAITING, helper->progress);
2293
2294 if (helper->protocol == PTHREAD_PRIO_INHERIT) {
2295 ASSERT_EQ(20, GetThreadPriority(gettid()));
2296 } else {
2297 ASSERT_EQ(21, GetThreadPriority(gettid()));
2298 }
2299 helper->progress = LOCK_RELEASED;
2300 ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock));
2301 }
2302
2303public:
2304 explicit PIMutexWakeupHelper(int mutex_type, int protocol)
2305 : m(mutex_type, protocol), protocol(protocol), start_thread_m(PTHREAD_MUTEX_NORMAL) {
2306 }
2307
2308 void test() {
2309 ASSERT_EQ(0, pthread_mutex_lock(&start_thread_m.lock));
2310 main_tid = gettid();
2311 ASSERT_EQ(20, GetThreadPriority(main_tid));
2312 progress = LOCK_INITIALIZED;
2313 child_tid = 0;
2314
2315 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002316 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002317 reinterpret_cast<void* (*)(void*)>(PIMutexWakeupHelper::thread_fn), this));
2318
2319 WaitUntilThreadSleep(child_tid);
2320 ASSERT_EQ(LOCK_CHILD_READY, progress);
2321 ASSERT_EQ(0, pthread_mutex_unlock(&start_thread_m.lock));
2322 progress = LOCK_WAITING;
2323 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
2324
2325 ASSERT_EQ(LOCK_RELEASED, progress);
2326 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2327 ASSERT_EQ(0, pthread_join(thread, nullptr));
2328 }
2329};
2330
2331TEST(pthread, pthread_mutex_pi_wakeup) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002332 for (int type : {PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_RECURSIVE, PTHREAD_MUTEX_ERRORCHECK}) {
2333 for (int protocol : {PTHREAD_PRIO_INHERIT}) {
2334 PIMutexWakeupHelper helper(type, protocol);
2335 helper.test();
2336 }
2337 }
2338}
2339
Yabin Cui140f3672015-02-03 10:32:00 -08002340TEST(pthread, pthread_mutex_owner_tid_limit) {
Yabin Cuie69c2452015-02-13 16:21:25 -08002341#if defined(__BIONIC__) && !defined(__LP64__)
Yabin Cui140f3672015-02-03 10:32:00 -08002342 FILE* fp = fopen("/proc/sys/kernel/pid_max", "r");
Yi Kong32bc0fc2018-08-02 17:31:13 -07002343 ASSERT_TRUE(fp != nullptr);
Yabin Cui140f3672015-02-03 10:32:00 -08002344 long pid_max;
2345 ASSERT_EQ(1, fscanf(fp, "%ld", &pid_max));
2346 fclose(fp);
Yabin Cuie69c2452015-02-13 16:21:25 -08002347 // Bionic's pthread_mutex implementation on 32-bit devices uses 16 bits to represent owner tid.
Yabin Cui140f3672015-02-03 10:32:00 -08002348 ASSERT_LE(pid_max, 65536);
Yabin Cuie69c2452015-02-13 16:21:25 -08002349#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002350 GTEST_SKIP() << "pthread_mutex supports 32-bit tid";
Yabin Cuie69c2452015-02-13 16:21:25 -08002351#endif
Yabin Cui140f3672015-02-03 10:32:00 -08002352}
Yabin Cuib5845722015-03-16 22:46:42 -07002353
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002354static void pthread_mutex_timedlock_helper(clockid_t clock,
2355 int (*lock_function)(pthread_mutex_t* __mutex,
2356 const timespec* __timeout)) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08002357 pthread_mutex_t m;
2358 ASSERT_EQ(0, pthread_mutex_init(&m, nullptr));
2359
2360 // If the mutex is already locked, pthread_mutex_timedlock should time out.
2361 ASSERT_EQ(0, pthread_mutex_lock(&m));
2362
2363 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002364 ASSERT_EQ(0, clock_gettime(clock, &ts));
2365 ASSERT_EQ(ETIMEDOUT, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002366 ts.tv_nsec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002367 ASSERT_EQ(EINVAL, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002368 ts.tv_nsec = NS_PER_S;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002369 ASSERT_EQ(EINVAL, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002370 ts.tv_nsec = NS_PER_S - 1;
2371 ts.tv_sec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002372 ASSERT_EQ(ETIMEDOUT, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002373
2374 // If the mutex is unlocked, pthread_mutex_timedlock should succeed.
2375 ASSERT_EQ(0, pthread_mutex_unlock(&m));
2376
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002377 ASSERT_EQ(0, clock_gettime(clock, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002378 ts.tv_sec += 1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002379 ASSERT_EQ(0, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002380
2381 ASSERT_EQ(0, pthread_mutex_unlock(&m));
2382 ASSERT_EQ(0, pthread_mutex_destroy(&m));
2383}
2384
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002385TEST(pthread, pthread_mutex_timedlock) {
2386 pthread_mutex_timedlock_helper(CLOCK_REALTIME, pthread_mutex_timedlock);
2387}
2388
2389TEST(pthread, pthread_mutex_timedlock_monotonic_np) {
2390#if defined(__BIONIC__)
2391 pthread_mutex_timedlock_helper(CLOCK_MONOTONIC, pthread_mutex_timedlock_monotonic_np);
2392#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002393 GTEST_SKIP() << "pthread_mutex_timedlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002394#endif // __BIONIC__
2395}
2396
Tom Cherry69010802019-05-07 20:33:05 -07002397TEST(pthread, pthread_mutex_clocklock) {
2398#if defined(__BIONIC__)
2399 pthread_mutex_timedlock_helper(
2400 CLOCK_MONOTONIC, [](pthread_mutex_t* __mutex, const timespec* __timeout) {
2401 return pthread_mutex_clocklock(__mutex, CLOCK_MONOTONIC, __timeout);
2402 });
2403 pthread_mutex_timedlock_helper(
2404 CLOCK_REALTIME, [](pthread_mutex_t* __mutex, const timespec* __timeout) {
2405 return pthread_mutex_clocklock(__mutex, CLOCK_REALTIME, __timeout);
2406 });
2407#else // __BIONIC__
2408 GTEST_SKIP() << "pthread_mutex_clocklock not available";
2409#endif // __BIONIC__
2410}
2411
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002412static void pthread_mutex_timedlock_pi_helper(clockid_t clock,
2413 int (*lock_function)(pthread_mutex_t* __mutex,
2414 const timespec* __timeout)) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002415 PthreadMutex m(PTHREAD_MUTEX_NORMAL, PTHREAD_PRIO_INHERIT);
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002416
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002417 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002418 clock_gettime(clock, &ts);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002419 ts.tv_sec += 1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002420 ASSERT_EQ(0, lock_function(&m.lock, &ts));
2421
2422 struct ThreadArgs {
2423 clockid_t clock;
2424 int (*lock_function)(pthread_mutex_t* __mutex, const timespec* __timeout);
2425 PthreadMutex& m;
2426 };
2427
2428 ThreadArgs thread_args = {
2429 .clock = clock,
2430 .lock_function = lock_function,
2431 .m = m,
2432 };
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002433
2434 auto ThreadFn = [](void* arg) -> void* {
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002435 auto args = static_cast<ThreadArgs*>(arg);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002436 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002437 clock_gettime(args->clock, &ts);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002438 ts.tv_sec += 1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002439 intptr_t result = args->lock_function(&args->m.lock, &ts);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002440 return reinterpret_cast<void*>(result);
2441 };
2442
2443 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002444 ASSERT_EQ(0, pthread_create(&thread, nullptr, ThreadFn, &thread_args));
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002445 void* result;
2446 ASSERT_EQ(0, pthread_join(thread, &result));
2447 ASSERT_EQ(ETIMEDOUT, reinterpret_cast<intptr_t>(result));
2448 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2449}
2450
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002451TEST(pthread, pthread_mutex_timedlock_pi) {
2452 pthread_mutex_timedlock_pi_helper(CLOCK_REALTIME, pthread_mutex_timedlock);
2453}
2454
2455TEST(pthread, pthread_mutex_timedlock_monotonic_np_pi) {
2456#if defined(__BIONIC__)
2457 pthread_mutex_timedlock_pi_helper(CLOCK_MONOTONIC, pthread_mutex_timedlock_monotonic_np);
2458#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002459 GTEST_SKIP() << "pthread_mutex_timedlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002460#endif // __BIONIC__
2461}
2462
Tom Cherry69010802019-05-07 20:33:05 -07002463TEST(pthread, pthread_mutex_clocklock_pi) {
2464#if defined(__BIONIC__)
2465 pthread_mutex_timedlock_pi_helper(
2466 CLOCK_MONOTONIC, [](pthread_mutex_t* __mutex, const timespec* __timeout) {
2467 return pthread_mutex_clocklock(__mutex, CLOCK_MONOTONIC, __timeout);
2468 });
2469 pthread_mutex_timedlock_pi_helper(
2470 CLOCK_REALTIME, [](pthread_mutex_t* __mutex, const timespec* __timeout) {
2471 return pthread_mutex_clocklock(__mutex, CLOCK_REALTIME, __timeout);
2472 });
2473#else // __BIONIC__
2474 GTEST_SKIP() << "pthread_mutex_clocklock not available";
2475#endif // __BIONIC__
2476}
2477
2478TEST(pthread, pthread_mutex_clocklock_invalid) {
2479#if defined(__BIONIC__)
2480 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
2481 timespec ts;
2482 EXPECT_EQ(EINVAL, pthread_mutex_clocklock(&mutex, CLOCK_PROCESS_CPUTIME_ID, &ts));
2483#else // __BIONIC__
2484 GTEST_SKIP() << "pthread_mutex_clocklock not available";
2485#endif // __BIONIC__
2486}
2487
Elliott Hughese657eb42021-02-18 17:11:56 -08002488TEST_F(pthread_DeathTest, pthread_mutex_using_destroyed_mutex) {
Yabin Cui9651fdf2018-03-14 12:02:21 -07002489#if defined(__BIONIC__)
2490 pthread_mutex_t m;
2491 ASSERT_EQ(0, pthread_mutex_init(&m, nullptr));
2492 ASSERT_EQ(0, pthread_mutex_destroy(&m));
2493 ASSERT_EXIT(pthread_mutex_lock(&m), ::testing::KilledBySignal(SIGABRT),
2494 "pthread_mutex_lock called on a destroyed mutex");
2495 ASSERT_EXIT(pthread_mutex_unlock(&m), ::testing::KilledBySignal(SIGABRT),
2496 "pthread_mutex_unlock called on a destroyed mutex");
2497 ASSERT_EXIT(pthread_mutex_trylock(&m), ::testing::KilledBySignal(SIGABRT),
2498 "pthread_mutex_trylock called on a destroyed mutex");
2499 timespec ts;
2500 ASSERT_EXIT(pthread_mutex_timedlock(&m, &ts), ::testing::KilledBySignal(SIGABRT),
2501 "pthread_mutex_timedlock called on a destroyed mutex");
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002502 ASSERT_EXIT(pthread_mutex_timedlock_monotonic_np(&m, &ts), ::testing::KilledBySignal(SIGABRT),
2503 "pthread_mutex_timedlock_monotonic_np called on a destroyed mutex");
Tom Cherry69010802019-05-07 20:33:05 -07002504 ASSERT_EXIT(pthread_mutex_clocklock(&m, CLOCK_MONOTONIC, &ts), ::testing::KilledBySignal(SIGABRT),
2505 "pthread_mutex_clocklock called on a destroyed mutex");
2506 ASSERT_EXIT(pthread_mutex_clocklock(&m, CLOCK_REALTIME, &ts), ::testing::KilledBySignal(SIGABRT),
2507 "pthread_mutex_clocklock called on a destroyed mutex");
2508 ASSERT_EXIT(pthread_mutex_clocklock(&m, CLOCK_PROCESS_CPUTIME_ID, &ts),
2509 ::testing::KilledBySignal(SIGABRT),
2510 "pthread_mutex_clocklock called on a destroyed mutex");
Yabin Cui9651fdf2018-03-14 12:02:21 -07002511 ASSERT_EXIT(pthread_mutex_destroy(&m), ::testing::KilledBySignal(SIGABRT),
2512 "pthread_mutex_destroy called on a destroyed mutex");
2513#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002514 GTEST_SKIP() << "bionic-only test";
Yabin Cui9651fdf2018-03-14 12:02:21 -07002515#endif
2516}
2517
Yabin Cuib5845722015-03-16 22:46:42 -07002518class StrictAlignmentAllocator {
2519 public:
2520 void* allocate(size_t size, size_t alignment) {
2521 char* p = new char[size + alignment * 2];
2522 allocated_array.push_back(p);
2523 while (!is_strict_aligned(p, alignment)) {
2524 ++p;
2525 }
2526 return p;
2527 }
2528
2529 ~StrictAlignmentAllocator() {
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07002530 for (const auto& p : allocated_array) {
2531 delete[] p;
Yabin Cuib5845722015-03-16 22:46:42 -07002532 }
2533 }
2534
2535 private:
2536 bool is_strict_aligned(char* p, size_t alignment) {
2537 return (reinterpret_cast<uintptr_t>(p) % (alignment * 2)) == alignment;
2538 }
2539
2540 std::vector<char*> allocated_array;
2541};
2542
2543TEST(pthread, pthread_types_allow_four_bytes_alignment) {
2544#if defined(__BIONIC__)
2545 // For binary compatibility with old version, we need to allow 4-byte aligned data for pthread types.
2546 StrictAlignmentAllocator allocator;
2547 pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(
2548 allocator.allocate(sizeof(pthread_mutex_t), 4));
Yi Kong32bc0fc2018-08-02 17:31:13 -07002549 ASSERT_EQ(0, pthread_mutex_init(mutex, nullptr));
Yabin Cuib5845722015-03-16 22:46:42 -07002550 ASSERT_EQ(0, pthread_mutex_lock(mutex));
2551 ASSERT_EQ(0, pthread_mutex_unlock(mutex));
2552 ASSERT_EQ(0, pthread_mutex_destroy(mutex));
2553
2554 pthread_cond_t* cond = reinterpret_cast<pthread_cond_t*>(
2555 allocator.allocate(sizeof(pthread_cond_t), 4));
Yi Kong32bc0fc2018-08-02 17:31:13 -07002556 ASSERT_EQ(0, pthread_cond_init(cond, nullptr));
Yabin Cuib5845722015-03-16 22:46:42 -07002557 ASSERT_EQ(0, pthread_cond_signal(cond));
2558 ASSERT_EQ(0, pthread_cond_broadcast(cond));
2559 ASSERT_EQ(0, pthread_cond_destroy(cond));
2560
2561 pthread_rwlock_t* rwlock = reinterpret_cast<pthread_rwlock_t*>(
2562 allocator.allocate(sizeof(pthread_rwlock_t), 4));
Yi Kong32bc0fc2018-08-02 17:31:13 -07002563 ASSERT_EQ(0, pthread_rwlock_init(rwlock, nullptr));
Yabin Cuib5845722015-03-16 22:46:42 -07002564 ASSERT_EQ(0, pthread_rwlock_rdlock(rwlock));
2565 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
2566 ASSERT_EQ(0, pthread_rwlock_wrlock(rwlock));
2567 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
2568 ASSERT_EQ(0, pthread_rwlock_destroy(rwlock));
2569
2570#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002571 GTEST_SKIP() << "bionic-only test";
Yabin Cuib5845722015-03-16 22:46:42 -07002572#endif
2573}
Christopher Ferris60907c72015-06-09 18:46:15 -07002574
2575TEST(pthread, pthread_mutex_lock_null_32) {
2576#if defined(__BIONIC__) && !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -07002577 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return
2578 // EINVAL in that case: http://b/19995172.
2579 //
2580 // We decorate the public defintion with _Nonnull so that people recompiling
2581 // their code with get a warning and might fix their bug, but need to pass
2582 // NULL here to test that we remain compatible.
2583 pthread_mutex_t* null_value = nullptr;
2584 ASSERT_EQ(EINVAL, pthread_mutex_lock(null_value));
Christopher Ferris60907c72015-06-09 18:46:15 -07002585#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002586 GTEST_SKIP() << "32-bit bionic-only test";
Christopher Ferris60907c72015-06-09 18:46:15 -07002587#endif
2588}
2589
2590TEST(pthread, pthread_mutex_unlock_null_32) {
2591#if defined(__BIONIC__) && !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -07002592 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return
2593 // EINVAL in that case: http://b/19995172.
2594 //
2595 // We decorate the public defintion with _Nonnull so that people recompiling
2596 // their code with get a warning and might fix their bug, but need to pass
2597 // NULL here to test that we remain compatible.
2598 pthread_mutex_t* null_value = nullptr;
2599 ASSERT_EQ(EINVAL, pthread_mutex_unlock(null_value));
Christopher Ferris60907c72015-06-09 18:46:15 -07002600#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002601 GTEST_SKIP() << "32-bit bionic-only test";
Christopher Ferris60907c72015-06-09 18:46:15 -07002602#endif
2603}
2604
2605TEST_F(pthread_DeathTest, pthread_mutex_lock_null_64) {
2606#if defined(__BIONIC__) && defined(__LP64__)
2607 pthread_mutex_t* null_value = nullptr;
2608 ASSERT_EXIT(pthread_mutex_lock(null_value), testing::KilledBySignal(SIGSEGV), "");
2609#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002610 GTEST_SKIP() << "64-bit bionic-only test";
Christopher Ferris60907c72015-06-09 18:46:15 -07002611#endif
2612}
2613
2614TEST_F(pthread_DeathTest, pthread_mutex_unlock_null_64) {
2615#if defined(__BIONIC__) && defined(__LP64__)
2616 pthread_mutex_t* null_value = nullptr;
2617 ASSERT_EXIT(pthread_mutex_unlock(null_value), testing::KilledBySignal(SIGSEGV), "");
2618#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002619 GTEST_SKIP() << "64-bit bionic-only test";
Christopher Ferris60907c72015-06-09 18:46:15 -07002620#endif
2621}
Yabin Cui33ac04a2015-09-22 11:16:15 -07002622
2623extern _Unwind_Reason_Code FrameCounter(_Unwind_Context* ctx, void* arg);
2624
2625static volatile bool signal_handler_on_altstack_done;
2626
Josh Gao61db9ac2017-03-15 19:42:05 -07002627__attribute__((__noinline__))
2628static void signal_handler_backtrace() {
2629 // Check if we have enough stack space for unwinding.
2630 int count = 0;
2631 _Unwind_Backtrace(FrameCounter, &count);
2632 ASSERT_GT(count, 0);
2633}
2634
2635__attribute__((__noinline__))
2636static void signal_handler_logging() {
2637 // Check if we have enough stack space for logging.
2638 std::string s(2048, '*');
2639 GTEST_LOG_(INFO) << s;
2640 signal_handler_on_altstack_done = true;
2641}
2642
2643__attribute__((__noinline__))
2644static void signal_handler_snprintf() {
2645 // Check if we have enough stack space for snprintf to a PATH_MAX buffer, plus some extra.
2646 char buf[PATH_MAX + 2048];
2647 ASSERT_GT(snprintf(buf, sizeof(buf), "/proc/%d/status", getpid()), 0);
2648}
2649
Yabin Cui33ac04a2015-09-22 11:16:15 -07002650static void SignalHandlerOnAltStack(int signo, siginfo_t*, void*) {
2651 ASSERT_EQ(SIGUSR1, signo);
Josh Gao61db9ac2017-03-15 19:42:05 -07002652 signal_handler_backtrace();
2653 signal_handler_logging();
2654 signal_handler_snprintf();
Yabin Cui33ac04a2015-09-22 11:16:15 -07002655}
2656
Josh Gao415daa82017-03-06 17:45:33 -08002657TEST(pthread, big_enough_signal_stack) {
Yabin Cui33ac04a2015-09-22 11:16:15 -07002658 signal_handler_on_altstack_done = false;
2659 ScopedSignalHandler handler(SIGUSR1, SignalHandlerOnAltStack, SA_SIGINFO | SA_ONSTACK);
2660 kill(getpid(), SIGUSR1);
2661 ASSERT_TRUE(signal_handler_on_altstack_done);
2662}
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002663
2664TEST(pthread, pthread_barrierattr_smoke) {
2665 pthread_barrierattr_t attr;
2666 ASSERT_EQ(0, pthread_barrierattr_init(&attr));
2667 int pshared;
2668 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
2669 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
2670 ASSERT_EQ(0, pthread_barrierattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
2671 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
2672 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
2673 ASSERT_EQ(0, pthread_barrierattr_destroy(&attr));
2674}
2675
Yabin Cui81d27972016-03-22 13:45:55 -07002676struct BarrierTestHelperData {
2677 size_t thread_count;
2678 pthread_barrier_t barrier;
2679 std::atomic<int> finished_mask;
2680 std::atomic<int> serial_thread_count;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002681 size_t iteration_count;
Yabin Cui81d27972016-03-22 13:45:55 -07002682 std::atomic<size_t> finished_iteration_count;
2683
2684 BarrierTestHelperData(size_t thread_count, size_t iteration_count)
2685 : thread_count(thread_count), finished_mask(0), serial_thread_count(0),
2686 iteration_count(iteration_count), finished_iteration_count(0) {
2687 }
2688};
2689
2690struct BarrierTestHelperArg {
2691 int id;
2692 BarrierTestHelperData* data;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002693};
2694
2695static void BarrierTestHelper(BarrierTestHelperArg* arg) {
Yabin Cui81d27972016-03-22 13:45:55 -07002696 for (size_t i = 0; i < arg->data->iteration_count; ++i) {
2697 int result = pthread_barrier_wait(&arg->data->barrier);
2698 if (result == PTHREAD_BARRIER_SERIAL_THREAD) {
2699 arg->data->serial_thread_count++;
2700 } else {
2701 ASSERT_EQ(0, result);
2702 }
Yabin Cuid5c04c52017-05-02 12:57:39 -07002703 int mask = arg->data->finished_mask.fetch_or(1 << arg->id);
Yabin Cuiab4cddc2017-05-02 16:18:13 -07002704 mask |= 1 << arg->id;
Yabin Cuid5c04c52017-05-02 12:57:39 -07002705 if (mask == ((1 << arg->data->thread_count) - 1)) {
Yabin Cui81d27972016-03-22 13:45:55 -07002706 ASSERT_EQ(1, arg->data->serial_thread_count);
2707 arg->data->finished_iteration_count++;
2708 arg->data->finished_mask = 0;
2709 arg->data->serial_thread_count = 0;
2710 }
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002711 }
2712}
2713
2714TEST(pthread, pthread_barrier_smoke) {
2715 const size_t BARRIER_ITERATION_COUNT = 10;
2716 const size_t BARRIER_THREAD_COUNT = 10;
Yabin Cui81d27972016-03-22 13:45:55 -07002717 BarrierTestHelperData data(BARRIER_THREAD_COUNT, BARRIER_ITERATION_COUNT);
2718 ASSERT_EQ(0, pthread_barrier_init(&data.barrier, nullptr, data.thread_count));
2719 std::vector<pthread_t> threads(data.thread_count);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002720 std::vector<BarrierTestHelperArg> args(threads.size());
2721 for (size_t i = 0; i < threads.size(); ++i) {
Yabin Cui81d27972016-03-22 13:45:55 -07002722 args[i].id = i;
2723 args[i].data = &data;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002724 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
2725 reinterpret_cast<void* (*)(void*)>(BarrierTestHelper), &args[i]));
2726 }
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002727 for (size_t i = 0; i < threads.size(); ++i) {
2728 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
2729 }
Yabin Cui81d27972016-03-22 13:45:55 -07002730 ASSERT_EQ(data.iteration_count, data.finished_iteration_count);
2731 ASSERT_EQ(0, pthread_barrier_destroy(&data.barrier));
2732}
2733
2734struct BarrierDestroyTestArg {
2735 std::atomic<int> tid;
2736 pthread_barrier_t* barrier;
2737};
2738
2739static void BarrierDestroyTestHelper(BarrierDestroyTestArg* arg) {
2740 arg->tid = gettid();
2741 ASSERT_EQ(0, pthread_barrier_wait(arg->barrier));
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002742}
2743
2744TEST(pthread, pthread_barrier_destroy) {
2745 pthread_barrier_t barrier;
2746 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, 2));
2747 pthread_t thread;
Yabin Cui81d27972016-03-22 13:45:55 -07002748 BarrierDestroyTestArg arg;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002749 arg.tid = 0;
2750 arg.barrier = &barrier;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002751 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui81d27972016-03-22 13:45:55 -07002752 reinterpret_cast<void* (*)(void*)>(BarrierDestroyTestHelper), &arg));
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002753 WaitUntilThreadSleep(arg.tid);
2754 ASSERT_EQ(EBUSY, pthread_barrier_destroy(&barrier));
2755 ASSERT_EQ(PTHREAD_BARRIER_SERIAL_THREAD, pthread_barrier_wait(&barrier));
2756 // Verify if the barrier can be destroyed directly after pthread_barrier_wait().
2757 ASSERT_EQ(0, pthread_barrier_destroy(&barrier));
2758 ASSERT_EQ(0, pthread_join(thread, nullptr));
2759#if defined(__BIONIC__)
2760 ASSERT_EQ(EINVAL, pthread_barrier_destroy(&barrier));
2761#endif
2762}
2763
2764struct BarrierOrderingTestHelperArg {
2765 pthread_barrier_t* barrier;
2766 size_t* array;
2767 size_t array_length;
2768 size_t id;
2769};
2770
2771void BarrierOrderingTestHelper(BarrierOrderingTestHelperArg* arg) {
2772 const size_t ITERATION_COUNT = 10000;
2773 for (size_t i = 1; i <= ITERATION_COUNT; ++i) {
2774 arg->array[arg->id] = i;
Yabin Cuic9a659c2015-11-05 15:36:08 -08002775 int result = pthread_barrier_wait(arg->barrier);
2776 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002777 for (size_t j = 0; j < arg->array_length; ++j) {
2778 ASSERT_EQ(i, arg->array[j]);
2779 }
Yabin Cuic9a659c2015-11-05 15:36:08 -08002780 result = pthread_barrier_wait(arg->barrier);
2781 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002782 }
2783}
2784
2785TEST(pthread, pthread_barrier_check_ordering) {
2786 const size_t THREAD_COUNT = 4;
2787 pthread_barrier_t barrier;
2788 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, THREAD_COUNT));
2789 size_t array[THREAD_COUNT];
2790 std::vector<pthread_t> threads(THREAD_COUNT);
2791 std::vector<BarrierOrderingTestHelperArg> args(THREAD_COUNT);
2792 for (size_t i = 0; i < THREAD_COUNT; ++i) {
2793 args[i].barrier = &barrier;
2794 args[i].array = array;
2795 args[i].array_length = THREAD_COUNT;
2796 args[i].id = i;
2797 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
2798 reinterpret_cast<void* (*)(void*)>(BarrierOrderingTestHelper),
2799 &args[i]));
2800 }
2801 for (size_t i = 0; i < THREAD_COUNT; ++i) {
2802 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
2803 }
2804}
Yabin Cuife3a83a2015-11-17 16:03:18 -08002805
Elliott Hughes463faad2018-07-06 14:34:49 -07002806TEST(pthread, pthread_barrier_init_zero_count) {
2807 pthread_barrier_t barrier;
2808 ASSERT_EQ(EINVAL, pthread_barrier_init(&barrier, nullptr, 0));
2809}
2810
Yabin Cuife3a83a2015-11-17 16:03:18 -08002811TEST(pthread, pthread_spinlock_smoke) {
2812 pthread_spinlock_t lock;
2813 ASSERT_EQ(0, pthread_spin_init(&lock, 0));
2814 ASSERT_EQ(0, pthread_spin_trylock(&lock));
2815 ASSERT_EQ(0, pthread_spin_unlock(&lock));
2816 ASSERT_EQ(0, pthread_spin_lock(&lock));
2817 ASSERT_EQ(EBUSY, pthread_spin_trylock(&lock));
2818 ASSERT_EQ(0, pthread_spin_unlock(&lock));
2819 ASSERT_EQ(0, pthread_spin_destroy(&lock));
2820}
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002821
Elliott Hughes8aecba72017-10-17 15:34:41 -07002822TEST(pthread, pthread_attr_getdetachstate__pthread_attr_setdetachstate) {
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002823 pthread_attr_t attr;
2824 ASSERT_EQ(0, pthread_attr_init(&attr));
2825
Elliott Hughes8aecba72017-10-17 15:34:41 -07002826 int state;
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002827 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002828 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2829 ASSERT_EQ(PTHREAD_CREATE_DETACHED, state);
2830
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002831 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002832 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2833 ASSERT_EQ(PTHREAD_CREATE_JOINABLE, state);
2834
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002835 ASSERT_EQ(EINVAL, pthread_attr_setdetachstate(&attr, 123));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002836 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2837 ASSERT_EQ(PTHREAD_CREATE_JOINABLE, state);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002838}
2839
2840TEST(pthread, pthread_create__mmap_failures) {
Evgeny Eltsinb4f7aaa2020-06-09 15:49:20 +02002841 // After thread is successfully created, native_bridge might need more memory to run it.
2842 SKIP_WITH_NATIVE_BRIDGE;
2843
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002844 pthread_attr_t attr;
2845 ASSERT_EQ(0, pthread_attr_init(&attr));
2846 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
2847
2848 const auto kPageSize = sysconf(_SC_PAGE_SIZE);
2849
Elliott Hughes57512982017-10-02 22:49:18 -07002850 // Use up all the VMAs. By default this is 64Ki (though some will already be in use).
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002851 std::vector<void*> pages;
Elliott Hughes57512982017-10-02 22:49:18 -07002852 pages.reserve(64 * 1024);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002853 int prot = PROT_NONE;
2854 while (true) {
2855 void* page = mmap(nullptr, kPageSize, prot, MAP_ANON|MAP_PRIVATE, -1, 0);
2856 if (page == MAP_FAILED) break;
2857 pages.push_back(page);
2858 prot = (prot == PROT_NONE) ? PROT_READ : PROT_NONE;
2859 }
2860
2861 // Try creating threads, freeing up a page each time we fail.
2862 size_t EAGAIN_count = 0;
2863 size_t i = 0;
2864 for (; i < pages.size(); ++i) {
2865 pthread_t t;
2866 int status = pthread_create(&t, &attr, IdFn, nullptr);
2867 if (status != EAGAIN) break;
2868 ++EAGAIN_count;
2869 ASSERT_EQ(0, munmap(pages[i], kPageSize));
2870 }
2871
Ryan Prichard45d13492019-01-03 02:51:30 -08002872 // Creating a thread uses at least three VMAs: the combined stack and TLS, and a guard on each
2873 // side. So we should have seen at least three failures.
2874 ASSERT_GE(EAGAIN_count, 3U);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002875
2876 for (; i < pages.size(); ++i) {
2877 ASSERT_EQ(0, munmap(pages[i], kPageSize));
2878 }
2879}
Elliott Hughesdff08ce2017-10-16 09:58:45 -07002880
2881TEST(pthread, pthread_setschedparam) {
2882 sched_param p = { .sched_priority = INT_MIN };
2883 ASSERT_EQ(EINVAL, pthread_setschedparam(pthread_self(), INT_MIN, &p));
2884}
2885
2886TEST(pthread, pthread_setschedprio) {
2887 ASSERT_EQ(EINVAL, pthread_setschedprio(pthread_self(), INT_MIN));
2888}
Elliott Hughes8aecba72017-10-17 15:34:41 -07002889
2890TEST(pthread, pthread_attr_getinheritsched__pthread_attr_setinheritsched) {
2891 pthread_attr_t attr;
2892 ASSERT_EQ(0, pthread_attr_init(&attr));
2893
2894 int state;
2895 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2896 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
2897 ASSERT_EQ(PTHREAD_INHERIT_SCHED, state);
2898
2899 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
2900 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
2901 ASSERT_EQ(PTHREAD_EXPLICIT_SCHED, state);
2902
2903 ASSERT_EQ(EINVAL, pthread_attr_setinheritsched(&attr, 123));
2904 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
2905 ASSERT_EQ(PTHREAD_EXPLICIT_SCHED, state);
2906}
2907
2908TEST(pthread, pthread_attr_setinheritsched__PTHREAD_INHERIT_SCHED__PTHREAD_EXPLICIT_SCHED) {
2909 pthread_attr_t attr;
2910 ASSERT_EQ(0, pthread_attr_init(&attr));
2911
2912 // If we set invalid scheduling attributes but choose to inherit, everything's fine...
2913 sched_param param = { .sched_priority = sched_get_priority_max(SCHED_FIFO) + 1 };
2914 ASSERT_EQ(0, pthread_attr_setschedparam(&attr, &param));
2915 ASSERT_EQ(0, pthread_attr_setschedpolicy(&attr, SCHED_FIFO));
2916 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2917
2918 pthread_t t;
2919 ASSERT_EQ(0, pthread_create(&t, &attr, IdFn, nullptr));
2920 ASSERT_EQ(0, pthread_join(t, nullptr));
2921
Elliott Hughes7a660662017-10-30 09:26:06 -07002922#if defined(__LP64__)
2923 // If we ask to use them, though, we'll see a failure...
Elliott Hughes8aecba72017-10-17 15:34:41 -07002924 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
2925 ASSERT_EQ(EINVAL, pthread_create(&t, &attr, IdFn, nullptr));
Elliott Hughes7a660662017-10-30 09:26:06 -07002926#else
2927 // For backwards compatibility with broken apps, we just ignore failures
2928 // to set scheduler attributes on LP32.
2929#endif
Elliott Hughes8aecba72017-10-17 15:34:41 -07002930}
2931
2932TEST(pthread, pthread_attr_setinheritsched_PTHREAD_INHERIT_SCHED_takes_effect) {
2933 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
2934 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO, &param);
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002935 if (rc == EPERM) GTEST_SKIP() << "pthread_setschedparam failed with EPERM";
Elliott Hughes8aecba72017-10-17 15:34:41 -07002936 ASSERT_EQ(0, rc);
2937
2938 pthread_attr_t attr;
2939 ASSERT_EQ(0, pthread_attr_init(&attr));
2940 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2941
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002942 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07002943 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002944 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002945 int actual_policy;
2946 sched_param actual_param;
2947 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
2948 ASSERT_EQ(SCHED_FIFO, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002949 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07002950 ASSERT_EQ(0, pthread_join(t, nullptr));
2951}
2952
2953TEST(pthread, pthread_attr_setinheritsched_PTHREAD_EXPLICIT_SCHED_takes_effect) {
2954 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
2955 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO, &param);
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002956 if (rc == EPERM) GTEST_SKIP() << "pthread_setschedparam failed with EPERM";
Elliott Hughes8aecba72017-10-17 15:34:41 -07002957 ASSERT_EQ(0, rc);
2958
2959 pthread_attr_t attr;
2960 ASSERT_EQ(0, pthread_attr_init(&attr));
2961 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
2962 ASSERT_EQ(0, pthread_attr_setschedpolicy(&attr, SCHED_OTHER));
2963
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002964 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07002965 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002966 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002967 int actual_policy;
2968 sched_param actual_param;
2969 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
2970 ASSERT_EQ(SCHED_OTHER, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002971 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07002972 ASSERT_EQ(0, pthread_join(t, nullptr));
2973}
2974
2975TEST(pthread, pthread_attr_setinheritsched__takes_effect_despite_SCHED_RESET_ON_FORK) {
2976 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
2977 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param);
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002978 if (rc == EPERM) GTEST_SKIP() << "pthread_setschedparam failed with EPERM";
Elliott Hughes8aecba72017-10-17 15:34:41 -07002979 ASSERT_EQ(0, rc);
2980
2981 pthread_attr_t attr;
2982 ASSERT_EQ(0, pthread_attr_init(&attr));
2983 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2984
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002985 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07002986 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002987 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002988 int actual_policy;
2989 sched_param actual_param;
2990 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
2991 ASSERT_EQ(SCHED_FIFO | SCHED_RESET_ON_FORK, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002992 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07002993 ASSERT_EQ(0, pthread_join(t, nullptr));
2994}
Peter Collingbourne5d3aa862020-09-11 15:05:17 -07002995
2996extern "C" bool android_run_on_all_threads(bool (*func)(void*), void* arg);
2997
2998TEST(pthread, run_on_all_threads) {
2999#if defined(__BIONIC__)
3000 pthread_t t;
3001 ASSERT_EQ(
3002 0, pthread_create(
3003 &t, nullptr,
3004 [](void*) -> void* {
3005 pthread_attr_t detached;
3006 if (pthread_attr_init(&detached) != 0 ||
3007 pthread_attr_setdetachstate(&detached, PTHREAD_CREATE_DETACHED) != 0) {
3008 return reinterpret_cast<void*>(errno);
3009 }
3010
3011 for (int i = 0; i != 1000; ++i) {
3012 pthread_t t1, t2;
3013 if (pthread_create(
3014 &t1, &detached, [](void*) -> void* { return nullptr; }, nullptr) != 0 ||
3015 pthread_create(
3016 &t2, nullptr, [](void*) -> void* { return nullptr; }, nullptr) != 0 ||
3017 pthread_join(t2, nullptr) != 0) {
3018 return reinterpret_cast<void*>(errno);
3019 }
3020 }
3021
3022 if (pthread_attr_destroy(&detached) != 0) {
3023 return reinterpret_cast<void*>(errno);
3024 }
3025 return nullptr;
3026 },
3027 nullptr));
3028
3029 for (int i = 0; i != 1000; ++i) {
3030 ASSERT_TRUE(android_run_on_all_threads([](void* arg) { return arg == nullptr; }, nullptr));
3031 }
3032
3033 void *retval;
3034 ASSERT_EQ(0, pthread_join(t, &retval));
3035 ASSERT_EQ(nullptr, retval);
3036#else
3037 GTEST_SKIP() << "bionic-only test";
3038#endif
3039}