blob: 1a00460bc973876f44572786544f572a32f203f7 [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
847 int kind_array[] = {PTHREAD_RWLOCK_PREFER_READER_NP,
848 PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP};
849 for (size_t i = 0; i < sizeof(kind_array) / sizeof(kind_array[0]); ++i) {
850 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_array[i]));
851 int kind;
852 ASSERT_EQ(0, pthread_rwlockattr_getkind_np(&attr, &kind));
853 ASSERT_EQ(kind_array[i], kind);
854 }
855
856 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
857}
858
859TEST(pthread, pthread_rwlock_init_same_as_PTHREAD_RWLOCK_INITIALIZER) {
860 pthread_rwlock_t lock1 = PTHREAD_RWLOCK_INITIALIZER;
861 pthread_rwlock_t lock2;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700862 ASSERT_EQ(0, pthread_rwlock_init(&lock2, nullptr));
Yabin Cui76615da2015-03-17 14:22:09 -0700863 ASSERT_EQ(0, memcmp(&lock1, &lock2, sizeof(lock1)));
864}
865
Elliott Hughesc3f11402013-10-30 14:40:09 -0700866TEST(pthread, pthread_rwlock_smoke) {
867 pthread_rwlock_t l;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700868 ASSERT_EQ(0, pthread_rwlock_init(&l, nullptr));
Elliott Hughesc3f11402013-10-30 14:40:09 -0700869
Calin Juravle76f352e2014-05-19 13:41:10 +0100870 // Single read lock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700871 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
872 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
873
Calin Juravle76f352e2014-05-19 13:41:10 +0100874 // Multiple read lock
875 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
876 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
877 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
878 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
879
880 // Write lock
Calin Juravle92687e42014-05-22 19:21:22 +0100881 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
882 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100883
884 // Try writer lock
885 ASSERT_EQ(0, pthread_rwlock_trywrlock(&l));
886 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
887 ASSERT_EQ(EBUSY, pthread_rwlock_tryrdlock(&l));
888 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
889
890 // Try reader lock
891 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
892 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
893 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
894 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
895 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
896
897 // Try writer lock after unlock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700898 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
899 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
900
Calin Juravle76f352e2014-05-19 13:41:10 +0100901 // EDEADLK in "read after write"
902 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
903 ASSERT_EQ(EDEADLK, pthread_rwlock_rdlock(&l));
904 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
905
906 // EDEADLK in "write after write"
907 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
908 ASSERT_EQ(EDEADLK, pthread_rwlock_wrlock(&l));
909 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100910
Elliott Hughesc3f11402013-10-30 14:40:09 -0700911 ASSERT_EQ(0, pthread_rwlock_destroy(&l));
912}
913
Yabin Cui08ee8d22015-02-11 17:04:36 -0800914struct RwlockWakeupHelperArg {
915 pthread_rwlock_t lock;
916 enum Progress {
917 LOCK_INITIALIZED,
918 LOCK_WAITING,
919 LOCK_RELEASED,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800920 LOCK_ACCESSED,
921 LOCK_TIMEDOUT,
Yabin Cui08ee8d22015-02-11 17:04:36 -0800922 };
923 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -0700924 std::atomic<pid_t> tid;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800925 std::function<int (pthread_rwlock_t*)> trylock_function;
926 std::function<int (pthread_rwlock_t*)> lock_function;
927 std::function<int (pthread_rwlock_t*, const timespec*)> timed_lock_function;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -0800928 clockid_t clock;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800929};
930
Yabin Cuic9a659c2015-11-05 15:36:08 -0800931static void pthread_rwlock_wakeup_helper(RwlockWakeupHelperArg* arg) {
Yabin Cuif7969852015-04-02 17:47:48 -0700932 arg->tid = gettid();
Yabin Cui08ee8d22015-02-11 17:04:36 -0800933 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
934 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
935
Yabin Cuic9a659c2015-11-05 15:36:08 -0800936 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
937 ASSERT_EQ(0, arg->lock_function(&arg->lock));
Yabin Cui08ee8d22015-02-11 17:04:36 -0800938 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_RELEASED, arg->progress);
939 ASSERT_EQ(0, pthread_rwlock_unlock(&arg->lock));
940
941 arg->progress = RwlockWakeupHelperArg::LOCK_ACCESSED;
942}
943
Yabin Cuic9a659c2015-11-05 15:36:08 -0800944static void test_pthread_rwlock_reader_wakeup_writer(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -0800945 RwlockWakeupHelperArg wakeup_arg;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700946 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -0800947 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
948 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -0700949 wakeup_arg.tid = 0;
Tom Cherry60ddedf2018-02-20 15:40:02 -0800950 wakeup_arg.trylock_function = &pthread_rwlock_trywrlock;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800951 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800952
953 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700954 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800955 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -0700956 WaitUntilThreadSleep(wakeup_arg.tid);
957 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
958
Yabin Cui08ee8d22015-02-11 17:04:36 -0800959 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
960 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
961
Yi Kong32bc0fc2018-08-02 17:31:13 -0700962 ASSERT_EQ(0, pthread_join(thread, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -0800963 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
964 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
965}
966
Yabin Cuic9a659c2015-11-05 15:36:08 -0800967TEST(pthread, pthread_rwlock_reader_wakeup_writer) {
968 test_pthread_rwlock_reader_wakeup_writer(pthread_rwlock_wrlock);
Yabin Cui08ee8d22015-02-11 17:04:36 -0800969}
970
Yabin Cuic9a659c2015-11-05 15:36:08 -0800971TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait) {
972 timespec ts;
973 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
974 ts.tv_sec += 1;
975 test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) {
976 return pthread_rwlock_timedwrlock(lock, &ts);
977 });
978}
979
Tom Cherryc6b5bcd2018-03-05 14:14:44 -0800980TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait_monotonic_np) {
981#if defined(__BIONIC__)
982 timespec ts;
983 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
984 ts.tv_sec += 1;
985 test_pthread_rwlock_reader_wakeup_writer(
986 [&](pthread_rwlock_t* lock) { return pthread_rwlock_timedwrlock_monotonic_np(lock, &ts); });
987#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -0800988 GTEST_SKIP() << "pthread_rwlock_timedwrlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -0800989#endif // __BIONIC__
990}
991
Tom Cherry69010802019-05-07 20:33:05 -0700992TEST(pthread, pthread_rwlock_reader_wakeup_writer_clockwait) {
993#if defined(__BIONIC__)
994 timespec ts;
995 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
996 ts.tv_sec += 1;
997 test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) {
998 return pthread_rwlock_clockwrlock(lock, CLOCK_MONOTONIC, &ts);
999 });
1000
1001 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1002 ts.tv_sec += 1;
1003 test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) {
1004 return pthread_rwlock_clockwrlock(lock, CLOCK_REALTIME, &ts);
1005 });
1006#else // __BIONIC__
1007 GTEST_SKIP() << "pthread_rwlock_clockwrlock not available";
1008#endif // __BIONIC__
1009}
1010
Yabin Cuic9a659c2015-11-05 15:36:08 -08001011static void test_pthread_rwlock_writer_wakeup_reader(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -08001012 RwlockWakeupHelperArg wakeup_arg;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001013 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -08001014 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
1015 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -07001016 wakeup_arg.tid = 0;
Tom Cherry60ddedf2018-02-20 15:40:02 -08001017 wakeup_arg.trylock_function = &pthread_rwlock_tryrdlock;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001018 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -08001019
1020 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001021 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cuic9a659c2015-11-05 15:36:08 -08001022 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -07001023 WaitUntilThreadSleep(wakeup_arg.tid);
1024 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
1025
Yabin Cui08ee8d22015-02-11 17:04:36 -08001026 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
1027 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
1028
Yi Kong32bc0fc2018-08-02 17:31:13 -07001029 ASSERT_EQ(0, pthread_join(thread, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -08001030 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
1031 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
1032}
1033
Yabin Cuic9a659c2015-11-05 15:36:08 -08001034TEST(pthread, pthread_rwlock_writer_wakeup_reader) {
1035 test_pthread_rwlock_writer_wakeup_reader(pthread_rwlock_rdlock);
1036}
1037
1038TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait) {
1039 timespec ts;
1040 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1041 ts.tv_sec += 1;
1042 test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) {
1043 return pthread_rwlock_timedrdlock(lock, &ts);
1044 });
1045}
1046
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001047TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait_monotonic_np) {
1048#if defined(__BIONIC__)
1049 timespec ts;
1050 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1051 ts.tv_sec += 1;
1052 test_pthread_rwlock_writer_wakeup_reader(
1053 [&](pthread_rwlock_t* lock) { return pthread_rwlock_timedrdlock_monotonic_np(lock, &ts); });
1054#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001055 GTEST_SKIP() << "pthread_rwlock_timedrdlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001056#endif // __BIONIC__
1057}
1058
Tom Cherry69010802019-05-07 20:33:05 -07001059TEST(pthread, pthread_rwlock_writer_wakeup_reader_clockwait) {
1060#if defined(__BIONIC__)
1061 timespec ts;
1062 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1063 ts.tv_sec += 1;
1064 test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) {
1065 return pthread_rwlock_clockrdlock(lock, CLOCK_MONOTONIC, &ts);
1066 });
1067
1068 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1069 ts.tv_sec += 1;
1070 test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) {
1071 return pthread_rwlock_clockrdlock(lock, CLOCK_REALTIME, &ts);
1072 });
1073#else // __BIONIC__
1074 GTEST_SKIP() << "pthread_rwlock_clockrdlock not available";
1075#endif // __BIONIC__
1076}
1077
Yabin Cuic9a659c2015-11-05 15:36:08 -08001078static void pthread_rwlock_wakeup_timeout_helper(RwlockWakeupHelperArg* arg) {
1079 arg->tid = gettid();
1080 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
1081 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
1082
1083 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
1084
1085 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001086 ASSERT_EQ(0, clock_gettime(arg->clock, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001087 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
1088 ts.tv_nsec = -1;
1089 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
1090 ts.tv_nsec = NS_PER_S;
1091 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
1092 ts.tv_nsec = NS_PER_S - 1;
1093 ts.tv_sec = -1;
1094 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001095 ASSERT_EQ(0, clock_gettime(arg->clock, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001096 ts.tv_sec += 1;
1097 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
1098 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, arg->progress);
1099 arg->progress = RwlockWakeupHelperArg::LOCK_TIMEDOUT;
1100}
1101
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001102static void pthread_rwlock_timedrdlock_timeout_helper(
1103 clockid_t clock, int (*lock_function)(pthread_rwlock_t* __rwlock, const timespec* __timeout)) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001104 RwlockWakeupHelperArg wakeup_arg;
1105 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
1106 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
1107 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
1108 wakeup_arg.tid = 0;
Tom Cherry60ddedf2018-02-20 15:40:02 -08001109 wakeup_arg.trylock_function = &pthread_rwlock_tryrdlock;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001110 wakeup_arg.timed_lock_function = lock_function;
1111 wakeup_arg.clock = clock;
1112
1113 pthread_t thread;
1114 ASSERT_EQ(0, pthread_create(&thread, nullptr,
1115 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
1116 WaitUntilThreadSleep(wakeup_arg.tid);
1117 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
1118
1119 ASSERT_EQ(0, pthread_join(thread, nullptr));
1120 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
1121 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
1122 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
1123}
1124
1125TEST(pthread, pthread_rwlock_timedrdlock_timeout) {
1126 pthread_rwlock_timedrdlock_timeout_helper(CLOCK_REALTIME, pthread_rwlock_timedrdlock);
1127}
1128
1129TEST(pthread, pthread_rwlock_timedrdlock_monotonic_np_timeout) {
1130#if defined(__BIONIC__)
1131 pthread_rwlock_timedrdlock_timeout_helper(CLOCK_MONOTONIC,
1132 pthread_rwlock_timedrdlock_monotonic_np);
1133#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001134 GTEST_SKIP() << "pthread_rwlock_timedrdlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001135#endif // __BIONIC__
1136}
1137
Tom Cherry69010802019-05-07 20:33:05 -07001138TEST(pthread, pthread_rwlock_clockrdlock_monotonic_timeout) {
1139#if defined(__BIONIC__)
1140 pthread_rwlock_timedrdlock_timeout_helper(
1141 CLOCK_MONOTONIC, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) {
1142 return pthread_rwlock_clockrdlock(__rwlock, CLOCK_MONOTONIC, __timeout);
1143 });
1144#else // __BIONIC__
1145 GTEST_SKIP() << "pthread_rwlock_clockrdlock not available";
1146#endif // __BIONIC__
1147}
1148
1149TEST(pthread, pthread_rwlock_clockrdlock_realtime_timeout) {
1150#if defined(__BIONIC__)
1151 pthread_rwlock_timedrdlock_timeout_helper(
1152 CLOCK_REALTIME, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) {
1153 return pthread_rwlock_clockrdlock(__rwlock, CLOCK_REALTIME, __timeout);
1154 });
1155#else // __BIONIC__
1156 GTEST_SKIP() << "pthread_rwlock_clockrdlock not available";
1157#endif // __BIONIC__
1158}
1159
1160TEST(pthread, pthread_rwlock_clockrdlock_invalid) {
1161#if defined(__BIONIC__)
1162 pthread_rwlock_t lock = PTHREAD_RWLOCK_INITIALIZER;
1163 timespec ts;
1164 EXPECT_EQ(EINVAL, pthread_rwlock_clockrdlock(&lock, CLOCK_PROCESS_CPUTIME_ID, &ts));
1165#else // __BIONIC__
1166 GTEST_SKIP() << "pthread_rwlock_clockrdlock not available";
1167#endif // __BIONIC__
1168}
1169
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001170static void pthread_rwlock_timedwrlock_timeout_helper(
1171 clockid_t clock, int (*lock_function)(pthread_rwlock_t* __rwlock, const timespec* __timeout)) {
1172 RwlockWakeupHelperArg wakeup_arg;
1173 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
1174 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
1175 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
1176 wakeup_arg.tid = 0;
1177 wakeup_arg.trylock_function = &pthread_rwlock_trywrlock;
1178 wakeup_arg.timed_lock_function = lock_function;
1179 wakeup_arg.clock = clock;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001180
1181 pthread_t thread;
1182 ASSERT_EQ(0, pthread_create(&thread, nullptr,
1183 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
1184 WaitUntilThreadSleep(wakeup_arg.tid);
1185 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
1186
1187 ASSERT_EQ(0, pthread_join(thread, nullptr));
1188 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
1189 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
1190 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
1191}
1192
1193TEST(pthread, pthread_rwlock_timedwrlock_timeout) {
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001194 pthread_rwlock_timedwrlock_timeout_helper(CLOCK_REALTIME, pthread_rwlock_timedwrlock);
1195}
Yabin Cuic9a659c2015-11-05 15:36:08 -08001196
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001197TEST(pthread, pthread_rwlock_timedwrlock_monotonic_np_timeout) {
1198#if defined(__BIONIC__)
1199 pthread_rwlock_timedwrlock_timeout_helper(CLOCK_MONOTONIC,
1200 pthread_rwlock_timedwrlock_monotonic_np);
1201#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001202 GTEST_SKIP() << "pthread_rwlock_timedwrlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001203#endif // __BIONIC__
Yabin Cuic9a659c2015-11-05 15:36:08 -08001204}
1205
Tom Cherry69010802019-05-07 20:33:05 -07001206TEST(pthread, pthread_rwlock_clockwrlock_monotonic_timeout) {
1207#if defined(__BIONIC__)
1208 pthread_rwlock_timedwrlock_timeout_helper(
1209 CLOCK_MONOTONIC, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) {
1210 return pthread_rwlock_clockwrlock(__rwlock, CLOCK_MONOTONIC, __timeout);
1211 });
1212#else // __BIONIC__
1213 GTEST_SKIP() << "pthread_rwlock_clockwrlock not available";
1214#endif // __BIONIC__
1215}
1216
1217TEST(pthread, pthread_rwlock_clockwrlock_realtime_timeout) {
1218#if defined(__BIONIC__)
1219 pthread_rwlock_timedwrlock_timeout_helper(
1220 CLOCK_REALTIME, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) {
1221 return pthread_rwlock_clockwrlock(__rwlock, CLOCK_REALTIME, __timeout);
1222 });
1223#else // __BIONIC__
1224 GTEST_SKIP() << "pthread_rwlock_clockwrlock not available";
1225#endif // __BIONIC__
1226}
1227
1228TEST(pthread, pthread_rwlock_clockwrlock_invalid) {
1229#if defined(__BIONIC__)
1230 pthread_rwlock_t lock = PTHREAD_RWLOCK_INITIALIZER;
1231 timespec ts;
1232 EXPECT_EQ(EINVAL, pthread_rwlock_clockwrlock(&lock, CLOCK_PROCESS_CPUTIME_ID, &ts));
1233#else // __BIONIC__
1234 GTEST_SKIP() << "pthread_rwlock_clockrwlock not available";
1235#endif // __BIONIC__
1236}
1237
Yabin Cui76615da2015-03-17 14:22:09 -07001238class RwlockKindTestHelper {
1239 private:
1240 struct ThreadArg {
1241 RwlockKindTestHelper* helper;
1242 std::atomic<pid_t>& tid;
1243
1244 ThreadArg(RwlockKindTestHelper* helper, std::atomic<pid_t>& tid)
1245 : helper(helper), tid(tid) { }
1246 };
1247
1248 public:
1249 pthread_rwlock_t lock;
1250
1251 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -07001252 explicit RwlockKindTestHelper(int kind_type) {
Yabin Cui76615da2015-03-17 14:22:09 -07001253 InitRwlock(kind_type);
1254 }
1255
1256 ~RwlockKindTestHelper() {
1257 DestroyRwlock();
1258 }
1259
1260 void CreateWriterThread(pthread_t& thread, std::atomic<pid_t>& tid) {
1261 tid = 0;
1262 ThreadArg* arg = new ThreadArg(this, tid);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001263 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui76615da2015-03-17 14:22:09 -07001264 reinterpret_cast<void* (*)(void*)>(WriterThreadFn), arg));
1265 }
1266
1267 void CreateReaderThread(pthread_t& thread, std::atomic<pid_t>& tid) {
1268 tid = 0;
1269 ThreadArg* arg = new ThreadArg(this, tid);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001270 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui76615da2015-03-17 14:22:09 -07001271 reinterpret_cast<void* (*)(void*)>(ReaderThreadFn), arg));
1272 }
1273
1274 private:
1275 void InitRwlock(int kind_type) {
1276 pthread_rwlockattr_t attr;
1277 ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
1278 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_type));
1279 ASSERT_EQ(0, pthread_rwlock_init(&lock, &attr));
1280 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
1281 }
1282
1283 void DestroyRwlock() {
1284 ASSERT_EQ(0, pthread_rwlock_destroy(&lock));
1285 }
1286
1287 static void WriterThreadFn(ThreadArg* arg) {
1288 arg->tid = gettid();
1289
1290 RwlockKindTestHelper* helper = arg->helper;
1291 ASSERT_EQ(0, pthread_rwlock_wrlock(&helper->lock));
1292 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
1293 delete arg;
1294 }
1295
1296 static void ReaderThreadFn(ThreadArg* arg) {
1297 arg->tid = gettid();
1298
1299 RwlockKindTestHelper* helper = arg->helper;
1300 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper->lock));
1301 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
1302 delete arg;
1303 }
1304};
1305
1306TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_READER_NP) {
1307 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_READER_NP);
1308 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
1309
1310 pthread_t writer_thread;
1311 std::atomic<pid_t> writer_tid;
1312 helper.CreateWriterThread(writer_thread, writer_tid);
1313 WaitUntilThreadSleep(writer_tid);
1314
1315 pthread_t reader_thread;
1316 std::atomic<pid_t> reader_tid;
1317 helper.CreateReaderThread(reader_thread, reader_tid);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001318 ASSERT_EQ(0, pthread_join(reader_thread, nullptr));
Yabin Cui76615da2015-03-17 14:22:09 -07001319
1320 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
Yi Kong32bc0fc2018-08-02 17:31:13 -07001321 ASSERT_EQ(0, pthread_join(writer_thread, nullptr));
Yabin Cui76615da2015-03-17 14:22:09 -07001322}
1323
1324TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP) {
1325 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
1326 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
1327
1328 pthread_t writer_thread;
1329 std::atomic<pid_t> writer_tid;
1330 helper.CreateWriterThread(writer_thread, writer_tid);
1331 WaitUntilThreadSleep(writer_tid);
1332
1333 pthread_t reader_thread;
1334 std::atomic<pid_t> reader_tid;
1335 helper.CreateReaderThread(reader_thread, reader_tid);
1336 WaitUntilThreadSleep(reader_tid);
1337
1338 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
Yi Kong32bc0fc2018-08-02 17:31:13 -07001339 ASSERT_EQ(0, pthread_join(writer_thread, nullptr));
1340 ASSERT_EQ(0, pthread_join(reader_thread, nullptr));
Yabin Cui76615da2015-03-17 14:22:09 -07001341}
1342
Elliott Hughes1728b232014-05-14 10:02:03 -07001343static int g_once_fn_call_count = 0;
Elliott Hughesc3f11402013-10-30 14:40:09 -07001344static void OnceFn() {
Elliott Hughes1728b232014-05-14 10:02:03 -07001345 ++g_once_fn_call_count;
Elliott Hughesc3f11402013-10-30 14:40:09 -07001346}
1347
1348TEST(pthread, pthread_once_smoke) {
1349 pthread_once_t once_control = PTHREAD_ONCE_INIT;
1350 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
1351 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
Elliott Hughes1728b232014-05-14 10:02:03 -07001352 ASSERT_EQ(1, g_once_fn_call_count);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001353}
1354
Elliott Hughes3694ec62014-05-14 11:46:08 -07001355static std::string pthread_once_1934122_result = "";
1356
1357static void Routine2() {
1358 pthread_once_1934122_result += "2";
1359}
1360
1361static void Routine1() {
1362 pthread_once_t once_control_2 = PTHREAD_ONCE_INIT;
1363 pthread_once_1934122_result += "1";
1364 pthread_once(&once_control_2, &Routine2);
1365}
1366
1367TEST(pthread, pthread_once_1934122) {
1368 // Very old versions of Android couldn't call pthread_once from a
1369 // pthread_once init routine. http://b/1934122.
1370 pthread_once_t once_control_1 = PTHREAD_ONCE_INIT;
1371 ASSERT_EQ(0, pthread_once(&once_control_1, &Routine1));
1372 ASSERT_EQ("12", pthread_once_1934122_result);
1373}
1374
Elliott Hughes1728b232014-05-14 10:02:03 -07001375static int g_atfork_prepare_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001376static void AtForkPrepare1() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 1; }
1377static void AtForkPrepare2() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -07001378static int g_atfork_parent_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001379static void AtForkParent1() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 1; }
1380static void AtForkParent2() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -07001381static int g_atfork_child_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001382static void AtForkChild1() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 1; }
1383static void AtForkChild2() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 2; }
Elliott Hughesc3f11402013-10-30 14:40:09 -07001384
Dmitriy Ivanov00e37812014-11-20 16:53:47 -08001385TEST(pthread, pthread_atfork_smoke) {
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001386 ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1));
1387 ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2));
Elliott Hughesc3f11402013-10-30 14:40:09 -07001388
Elliott Hughes33697a02016-01-26 13:04:57 -08001389 pid_t pid = fork();
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001390 ASSERT_NE(-1, pid) << strerror(errno);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001391
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001392 // Child and parent calls are made in the order they were registered.
1393 if (pid == 0) {
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001394 ASSERT_EQ(12, g_atfork_child_calls);
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001395 _exit(0);
1396 }
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001397 ASSERT_EQ(12, g_atfork_parent_calls);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001398
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001399 // Prepare calls are made in the reverse order.
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001400 ASSERT_EQ(21, g_atfork_prepare_calls);
Elliott Hughes33697a02016-01-26 13:04:57 -08001401 AssertChildExited(pid, 0);
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001402}
1403
Elliott Hughesc3f11402013-10-30 14:40:09 -07001404TEST(pthread, pthread_attr_getscope) {
1405 pthread_attr_t attr;
1406 ASSERT_EQ(0, pthread_attr_init(&attr));
1407
1408 int scope;
1409 ASSERT_EQ(0, pthread_attr_getscope(&attr, &scope));
1410 ASSERT_EQ(PTHREAD_SCOPE_SYSTEM, scope);
1411}
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001412
1413TEST(pthread, pthread_condattr_init) {
1414 pthread_condattr_t attr;
1415 pthread_condattr_init(&attr);
1416
1417 clockid_t clock;
1418 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1419 ASSERT_EQ(CLOCK_REALTIME, clock);
1420
1421 int pshared;
1422 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1423 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
1424}
1425
1426TEST(pthread, pthread_condattr_setclock) {
1427 pthread_condattr_t attr;
1428 pthread_condattr_init(&attr);
1429
1430 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_REALTIME));
1431 clockid_t clock;
1432 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1433 ASSERT_EQ(CLOCK_REALTIME, clock);
1434
1435 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1436 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1437 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1438
1439 ASSERT_EQ(EINVAL, pthread_condattr_setclock(&attr, CLOCK_PROCESS_CPUTIME_ID));
1440}
1441
1442TEST(pthread, pthread_cond_broadcast__preserves_condattr_flags) {
Yabin Cui32651b82015-03-13 20:30:00 -07001443#if defined(__BIONIC__)
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001444 pthread_condattr_t attr;
1445 pthread_condattr_init(&attr);
1446
1447 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1448 ASSERT_EQ(0, pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
1449
1450 pthread_cond_t cond_var;
1451 ASSERT_EQ(0, pthread_cond_init(&cond_var, &attr));
1452
1453 ASSERT_EQ(0, pthread_cond_signal(&cond_var));
1454 ASSERT_EQ(0, pthread_cond_broadcast(&cond_var));
1455
Yabin Cui32651b82015-03-13 20:30:00 -07001456 attr = static_cast<pthread_condattr_t>(*reinterpret_cast<uint32_t*>(cond_var.__private));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001457 clockid_t clock;
1458 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1459 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1460 int pshared;
1461 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1462 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
Yabin Cui32651b82015-03-13 20:30:00 -07001463#else // !defined(__BIONIC__)
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001464 GTEST_SKIP() << "bionic-only test";
Yabin Cui32651b82015-03-13 20:30:00 -07001465#endif // !defined(__BIONIC__)
1466}
1467
1468class pthread_CondWakeupTest : public ::testing::Test {
1469 protected:
1470 pthread_mutex_t mutex;
1471 pthread_cond_t cond;
1472
1473 enum Progress {
1474 INITIALIZED,
1475 WAITING,
1476 SIGNALED,
1477 FINISHED,
1478 };
1479 std::atomic<Progress> progress;
1480 pthread_t thread;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001481 std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function;
Yabin Cui32651b82015-03-13 20:30:00 -07001482
1483 protected:
Yabin Cuic9a659c2015-11-05 15:36:08 -08001484 void SetUp() override {
1485 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1486 }
1487
1488 void InitCond(clockid_t clock=CLOCK_REALTIME) {
1489 pthread_condattr_t attr;
1490 ASSERT_EQ(0, pthread_condattr_init(&attr));
1491 ASSERT_EQ(0, pthread_condattr_setclock(&attr, clock));
1492 ASSERT_EQ(0, pthread_cond_init(&cond, &attr));
1493 ASSERT_EQ(0, pthread_condattr_destroy(&attr));
1494 }
1495
Tom Cherry69010802019-05-07 20:33:05 -07001496 void StartWaitingThread(
1497 std::function<int(pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function) {
Yabin Cui32651b82015-03-13 20:30:00 -07001498 progress = INITIALIZED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001499 this->wait_function = wait_function;
Tom Cherry69010802019-05-07 20:33:05 -07001500 ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(WaitThreadFn),
1501 this));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001502 while (progress != WAITING) {
Yabin Cui32651b82015-03-13 20:30:00 -07001503 usleep(5000);
1504 }
1505 usleep(5000);
1506 }
1507
Tom Cherry69010802019-05-07 20:33:05 -07001508 void RunTimedTest(
1509 clockid_t clock,
1510 std::function<int(pthread_cond_t* cond, pthread_mutex_t* mutex, const timespec* timeout)>
1511 wait_function) {
1512 timespec ts;
1513 ASSERT_EQ(0, clock_gettime(clock, &ts));
1514 ts.tv_sec += 1;
1515
1516 StartWaitingThread([&wait_function, &ts](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1517 return wait_function(cond, mutex, &ts);
1518 });
1519
1520 progress = SIGNALED;
1521 ASSERT_EQ(0, pthread_cond_signal(&cond));
1522 }
1523
1524 void RunTimedTest(clockid_t clock, std::function<int(pthread_cond_t* cond, pthread_mutex_t* mutex,
1525 clockid_t clock, const timespec* timeout)>
1526 wait_function) {
1527 RunTimedTest(clock, [clock, &wait_function](pthread_cond_t* cond, pthread_mutex_t* mutex,
1528 const timespec* timeout) {
1529 return wait_function(cond, mutex, clock, timeout);
1530 });
1531 }
1532
Yabin Cuic9a659c2015-11-05 15:36:08 -08001533 void TearDown() override {
1534 ASSERT_EQ(0, pthread_join(thread, nullptr));
1535 ASSERT_EQ(FINISHED, progress);
1536 ASSERT_EQ(0, pthread_cond_destroy(&cond));
1537 ASSERT_EQ(0, pthread_mutex_destroy(&mutex));
1538 }
1539
Yabin Cui32651b82015-03-13 20:30:00 -07001540 private:
1541 static void WaitThreadFn(pthread_CondWakeupTest* test) {
1542 ASSERT_EQ(0, pthread_mutex_lock(&test->mutex));
1543 test->progress = WAITING;
1544 while (test->progress == WAITING) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001545 ASSERT_EQ(0, test->wait_function(&test->cond, &test->mutex));
Yabin Cui32651b82015-03-13 20:30:00 -07001546 }
1547 ASSERT_EQ(SIGNALED, test->progress);
1548 test->progress = FINISHED;
1549 ASSERT_EQ(0, pthread_mutex_unlock(&test->mutex));
1550 }
1551};
1552
Yabin Cuic9a659c2015-11-05 15:36:08 -08001553TEST_F(pthread_CondWakeupTest, signal_wait) {
1554 InitCond();
1555 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1556 return pthread_cond_wait(cond, mutex);
1557 });
Yabin Cui32651b82015-03-13 20:30:00 -07001558 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001559 ASSERT_EQ(0, pthread_cond_signal(&cond));
Yabin Cui32651b82015-03-13 20:30:00 -07001560}
1561
Yabin Cuic9a659c2015-11-05 15:36:08 -08001562TEST_F(pthread_CondWakeupTest, broadcast_wait) {
1563 InitCond();
1564 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1565 return pthread_cond_wait(cond, mutex);
1566 });
Yabin Cui32651b82015-03-13 20:30:00 -07001567 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001568 ASSERT_EQ(0, pthread_cond_broadcast(&cond));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001569}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001570
Yabin Cuic9a659c2015-11-05 15:36:08 -08001571TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_REALTIME) {
1572 InitCond(CLOCK_REALTIME);
Tom Cherry69010802019-05-07 20:33:05 -07001573 RunTimedTest(CLOCK_REALTIME, pthread_cond_timedwait);
Yabin Cuic9a659c2015-11-05 15:36:08 -08001574}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001575
Yabin Cuic9a659c2015-11-05 15:36:08 -08001576TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC) {
1577 InitCond(CLOCK_MONOTONIC);
Tom Cherry69010802019-05-07 20:33:05 -07001578 RunTimedTest(CLOCK_MONOTONIC, pthread_cond_timedwait);
Yabin Cuic9a659c2015-11-05 15:36:08 -08001579}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001580
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001581TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC_np) {
1582#if defined(__BIONIC__)
1583 InitCond(CLOCK_REALTIME);
Tom Cherry69010802019-05-07 20:33:05 -07001584 RunTimedTest(CLOCK_MONOTONIC, pthread_cond_timedwait_monotonic_np);
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001585#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001586 GTEST_SKIP() << "pthread_cond_timedwait_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001587#endif // __BIONIC__
1588}
1589
Tom Cherry69010802019-05-07 20:33:05 -07001590TEST_F(pthread_CondWakeupTest, signal_clockwait_monotonic_monotonic) {
1591#if defined(__BIONIC__)
1592 InitCond(CLOCK_MONOTONIC);
1593 RunTimedTest(CLOCK_MONOTONIC, pthread_cond_clockwait);
1594#else // __BIONIC__
1595 GTEST_SKIP() << "pthread_cond_clockwait not available";
1596#endif // __BIONIC__
1597}
1598
1599TEST_F(pthread_CondWakeupTest, signal_clockwait_monotonic_realtime) {
1600#if defined(__BIONIC__)
1601 InitCond(CLOCK_MONOTONIC);
1602 RunTimedTest(CLOCK_REALTIME, pthread_cond_clockwait);
1603#else // __BIONIC__
1604 GTEST_SKIP() << "pthread_cond_clockwait not available";
1605#endif // __BIONIC__
1606}
1607
1608TEST_F(pthread_CondWakeupTest, signal_clockwait_realtime_monotonic) {
1609#if defined(__BIONIC__)
1610 InitCond(CLOCK_REALTIME);
1611 RunTimedTest(CLOCK_MONOTONIC, pthread_cond_clockwait);
1612#else // __BIONIC__
1613 GTEST_SKIP() << "pthread_cond_clockwait not available";
1614#endif // __BIONIC__
1615}
1616
1617TEST_F(pthread_CondWakeupTest, signal_clockwait_realtime_realtime) {
1618#if defined(__BIONIC__)
1619 InitCond(CLOCK_REALTIME);
1620 RunTimedTest(CLOCK_REALTIME, pthread_cond_clockwait);
1621#else // __BIONIC__
1622 GTEST_SKIP() << "pthread_cond_clockwait not available";
1623#endif // __BIONIC__
1624}
1625
Tom Cherry800c1a92019-07-17 10:45:18 -07001626static void pthread_cond_timedwait_timeout_helper(bool init_monotonic, clockid_t clock,
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001627 int (*wait_function)(pthread_cond_t* __cond,
1628 pthread_mutex_t* __mutex,
1629 const timespec* __timeout)) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001630 pthread_mutex_t mutex;
1631 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1632 pthread_cond_t cond;
Tom Cherry800c1a92019-07-17 10:45:18 -07001633
1634 if (init_monotonic) {
1635 pthread_condattr_t attr;
1636 pthread_condattr_init(&attr);
1637
1638 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1639 clockid_t clock;
1640 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1641 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1642
1643 ASSERT_EQ(0, pthread_cond_init(&cond, &attr));
1644 } else {
1645 ASSERT_EQ(0, pthread_cond_init(&cond, nullptr));
1646 }
Yabin Cuic9a659c2015-11-05 15:36:08 -08001647 ASSERT_EQ(0, pthread_mutex_lock(&mutex));
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001648
Yabin Cuic9a659c2015-11-05 15:36:08 -08001649 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001650 ASSERT_EQ(0, clock_gettime(clock, &ts));
1651 ASSERT_EQ(ETIMEDOUT, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001652 ts.tv_nsec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001653 ASSERT_EQ(EINVAL, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001654 ts.tv_nsec = NS_PER_S;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001655 ASSERT_EQ(EINVAL, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001656 ts.tv_nsec = NS_PER_S - 1;
1657 ts.tv_sec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001658 ASSERT_EQ(ETIMEDOUT, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001659 ASSERT_EQ(0, pthread_mutex_unlock(&mutex));
Elliott Hughes0e714a52014-03-03 16:42:47 -08001660}
Elliott Hughes57b7a612014-08-25 17:26:50 -07001661
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001662TEST(pthread, pthread_cond_timedwait_timeout) {
Tom Cherry800c1a92019-07-17 10:45:18 -07001663 pthread_cond_timedwait_timeout_helper(false, CLOCK_REALTIME, pthread_cond_timedwait);
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001664}
1665
1666TEST(pthread, pthread_cond_timedwait_monotonic_np_timeout) {
1667#if defined(__BIONIC__)
Tom Cherry800c1a92019-07-17 10:45:18 -07001668 pthread_cond_timedwait_timeout_helper(false, CLOCK_MONOTONIC, pthread_cond_timedwait_monotonic_np);
1669 pthread_cond_timedwait_timeout_helper(true, CLOCK_MONOTONIC, pthread_cond_timedwait_monotonic_np);
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001670#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001671 GTEST_SKIP() << "pthread_cond_timedwait_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001672#endif // __BIONIC__
1673}
1674
Tom Cherry69010802019-05-07 20:33:05 -07001675TEST(pthread, pthread_cond_clockwait_timeout) {
1676#if defined(__BIONIC__)
1677 pthread_cond_timedwait_timeout_helper(
Tom Cherry800c1a92019-07-17 10:45:18 -07001678 false, CLOCK_MONOTONIC,
Tom Cherry69010802019-05-07 20:33:05 -07001679 [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) {
1680 return pthread_cond_clockwait(__cond, __mutex, CLOCK_MONOTONIC, __timeout);
1681 });
1682 pthread_cond_timedwait_timeout_helper(
Tom Cherry800c1a92019-07-17 10:45:18 -07001683 true, CLOCK_MONOTONIC,
1684 [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) {
1685 return pthread_cond_clockwait(__cond, __mutex, CLOCK_MONOTONIC, __timeout);
1686 });
1687 pthread_cond_timedwait_timeout_helper(
1688 false, CLOCK_REALTIME,
1689 [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) {
1690 return pthread_cond_clockwait(__cond, __mutex, CLOCK_REALTIME, __timeout);
1691 });
1692 pthread_cond_timedwait_timeout_helper(
1693 true, CLOCK_REALTIME,
Tom Cherry69010802019-05-07 20:33:05 -07001694 [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) {
1695 return pthread_cond_clockwait(__cond, __mutex, CLOCK_REALTIME, __timeout);
1696 });
1697#else // __BIONIC__
1698 GTEST_SKIP() << "pthread_cond_clockwait not available";
1699#endif // __BIONIC__
1700}
1701
1702TEST(pthread, pthread_cond_clockwait_invalid) {
1703#if defined(__BIONIC__)
1704 pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
1705 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
1706 timespec ts;
1707 EXPECT_EQ(EINVAL, pthread_cond_clockwait(&cond, &mutex, CLOCK_PROCESS_CPUTIME_ID, &ts));
1708
1709#else // __BIONIC__
1710 GTEST_SKIP() << "pthread_cond_clockwait not available";
1711#endif // __BIONIC__
1712}
1713
Elliott Hughes57b7a612014-08-25 17:26:50 -07001714TEST(pthread, pthread_attr_getstack__main_thread) {
1715 // This test is only meaningful for the main thread, so make sure we're running on it!
1716 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1717
1718 // Get the main thread's attributes.
1719 pthread_attr_t attributes;
1720 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1721
1722 // Check that we correctly report that the main thread has no guard page.
1723 size_t guard_size;
1724 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
1725 ASSERT_EQ(0U, guard_size); // The main thread has no guard page.
1726
1727 // Get the stack base and the stack size (both ways).
1728 void* stack_base;
1729 size_t stack_size;
1730 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1731 size_t stack_size2;
1732 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1733
1734 // The two methods of asking for the stack size should agree.
1735 EXPECT_EQ(stack_size, stack_size2);
1736
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001737#if defined(__BIONIC__)
dimitry6dfa5b52018-01-30 13:24:28 +01001738 // Find stack in /proc/self/maps using a pointer to the stack.
1739 //
1740 // We do not use "[stack]" label because in native-bridge environment it is not
1741 // guaranteed to point to the right stack. A native bridge implementation may
1742 // keep separate stack for the guest code.
Yi Kong32bc0fc2018-08-02 17:31:13 -07001743 void* maps_stack_hi = nullptr;
Elliott Hughes15dfd632015-09-22 16:40:14 -07001744 std::vector<map_record> maps;
1745 ASSERT_TRUE(Maps::parse_maps(&maps));
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08001746 uintptr_t stack_address = reinterpret_cast<uintptr_t>(untag_address(&maps_stack_hi));
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07001747 for (const auto& map : maps) {
dimitry6dfa5b52018-01-30 13:24:28 +01001748 if (map.addr_start <= stack_address && map.addr_end > stack_address){
Elliott Hughes15dfd632015-09-22 16:40:14 -07001749 maps_stack_hi = reinterpret_cast<void*>(map.addr_end);
Elliott Hughes57b7a612014-08-25 17:26:50 -07001750 break;
1751 }
1752 }
Elliott Hughes57b7a612014-08-25 17:26:50 -07001753
dimitry6dfa5b52018-01-30 13:24:28 +01001754 // The high address of the /proc/self/maps stack region should equal stack_base + stack_size.
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001755 // Remember that the stack grows down (and is mapped in on demand), so the low address of the
1756 // region isn't very interesting.
1757 EXPECT_EQ(maps_stack_hi, reinterpret_cast<uint8_t*>(stack_base) + stack_size);
1758
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001759 // The stack size should correspond to RLIMIT_STACK.
Elliott Hughes57b7a612014-08-25 17:26:50 -07001760 rlimit rl;
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001761 ASSERT_EQ(0, getrlimit(RLIMIT_STACK, &rl));
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001762 uint64_t original_rlim_cur = rl.rlim_cur;
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001763 if (rl.rlim_cur == RLIM_INFINITY) {
1764 rl.rlim_cur = 8 * 1024 * 1024; // Bionic reports unlimited stacks as 8MiB.
1765 }
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001766 EXPECT_EQ(rl.rlim_cur, stack_size);
1767
Tom Cherryb8ab6182017-04-05 16:20:29 -07001768 auto guard = android::base::make_scope_guard([&rl, original_rlim_cur]() {
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001769 rl.rlim_cur = original_rlim_cur;
1770 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1771 });
1772
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001773 //
1774 // What if RLIMIT_STACK is smaller than the stack's current extent?
1775 //
Elliott Hughes57b7a612014-08-25 17:26:50 -07001776 rl.rlim_cur = rl.rlim_max = 1024; // 1KiB. We know the stack must be at least a page already.
1777 rl.rlim_max = RLIM_INFINITY;
1778 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1779
1780 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1781 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1782 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1783
1784 EXPECT_EQ(stack_size, stack_size2);
1785 ASSERT_EQ(1024U, stack_size);
1786
1787 //
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001788 // What if RLIMIT_STACK isn't a whole number of pages?
Elliott Hughes57b7a612014-08-25 17:26:50 -07001789 //
1790 rl.rlim_cur = rl.rlim_max = 6666; // Not a whole number of pages.
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(6666U, stack_size);
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001800#endif
Elliott Hughes57b7a612014-08-25 17:26:50 -07001801}
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001802
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001803struct GetStackSignalHandlerArg {
1804 volatile bool done;
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001805 void* signal_stack_base;
1806 size_t signal_stack_size;
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001807 void* main_stack_base;
1808 size_t main_stack_size;
1809};
1810
1811static GetStackSignalHandlerArg getstack_signal_handler_arg;
1812
1813static void getstack_signal_handler(int sig) {
1814 ASSERT_EQ(SIGUSR1, sig);
1815 // Use sleep() to make current thread be switched out by the kernel to provoke the error.
1816 sleep(1);
1817 pthread_attr_t attr;
1818 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1819 void* stack_base;
1820 size_t stack_size;
1821 ASSERT_EQ(0, pthread_attr_getstack(&attr, &stack_base, &stack_size));
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001822
1823 // Verify if the stack used by the signal handler is the alternate stack just registered.
1824 ASSERT_LE(getstack_signal_handler_arg.signal_stack_base, &attr);
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08001825 ASSERT_LT(static_cast<void*>(untag_address(&attr)),
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001826 static_cast<char*>(getstack_signal_handler_arg.signal_stack_base) +
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08001827 getstack_signal_handler_arg.signal_stack_size);
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001828
1829 // Verify if the main thread's stack got in the signal handler is correct.
1830 ASSERT_EQ(getstack_signal_handler_arg.main_stack_base, stack_base);
1831 ASSERT_LE(getstack_signal_handler_arg.main_stack_size, stack_size);
1832
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001833 getstack_signal_handler_arg.done = true;
1834}
1835
1836// The previous code obtained the main thread's stack by reading the entry in
1837// /proc/self/task/<pid>/maps that was labeled [stack]. Unfortunately, on x86/x86_64, the kernel
1838// relies on sp0 in task state segment(tss) to label the stack map with [stack]. If the kernel
1839// switches a process while the main thread is in an alternate stack, then the kernel will label
1840// the wrong map with [stack]. This test verifies that when the above situation happens, the main
1841// thread's stack is found correctly.
1842TEST(pthread, pthread_attr_getstack_in_signal_handler) {
Yabin Cui61e4d462016-03-07 17:44:58 -08001843 // This test is only meaningful for the main thread, so make sure we're running on it!
1844 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1845
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001846 const size_t sig_stack_size = 16 * 1024;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001847 void* sig_stack = mmap(nullptr, sig_stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS,
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001848 -1, 0);
1849 ASSERT_NE(MAP_FAILED, sig_stack);
1850 stack_t ss;
1851 ss.ss_sp = sig_stack;
1852 ss.ss_size = sig_stack_size;
1853 ss.ss_flags = 0;
1854 stack_t oss;
1855 ASSERT_EQ(0, sigaltstack(&ss, &oss));
1856
Yabin Cui61e4d462016-03-07 17:44:58 -08001857 pthread_attr_t attr;
1858 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1859 void* main_stack_base;
1860 size_t main_stack_size;
1861 ASSERT_EQ(0, pthread_attr_getstack(&attr, &main_stack_base, &main_stack_size));
1862
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001863 ScopedSignalHandler handler(SIGUSR1, getstack_signal_handler, SA_ONSTACK);
1864 getstack_signal_handler_arg.done = false;
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001865 getstack_signal_handler_arg.signal_stack_base = sig_stack;
1866 getstack_signal_handler_arg.signal_stack_size = sig_stack_size;
1867 getstack_signal_handler_arg.main_stack_base = main_stack_base;
1868 getstack_signal_handler_arg.main_stack_size = main_stack_size;
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001869 kill(getpid(), SIGUSR1);
1870 ASSERT_EQ(true, getstack_signal_handler_arg.done);
1871
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001872 ASSERT_EQ(0, sigaltstack(&oss, nullptr));
1873 ASSERT_EQ(0, munmap(sig_stack, sig_stack_size));
1874}
1875
Yabin Cui917d3902015-01-08 12:32:42 -08001876static void pthread_attr_getstack_18908062_helper(void*) {
1877 char local_variable;
1878 pthread_attr_t attributes;
1879 pthread_getattr_np(pthread_self(), &attributes);
1880 void* stack_base;
1881 size_t stack_size;
1882 pthread_attr_getstack(&attributes, &stack_base, &stack_size);
1883
1884 // Test whether &local_variable is in [stack_base, stack_base + stack_size).
1885 ASSERT_LE(reinterpret_cast<char*>(stack_base), &local_variable);
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08001886 ASSERT_LT(untag_address(&local_variable), reinterpret_cast<char*>(stack_base) + stack_size);
Yabin Cui917d3902015-01-08 12:32:42 -08001887}
1888
1889// Check whether something on stack is in the range of
1890// [stack_base, stack_base + stack_size). see b/18908062.
1891TEST(pthread, pthread_attr_getstack_18908062) {
1892 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001893 ASSERT_EQ(0, pthread_create(&t, nullptr,
Yabin Cui917d3902015-01-08 12:32:42 -08001894 reinterpret_cast<void* (*)(void*)>(pthread_attr_getstack_18908062_helper),
Yi Kong32bc0fc2018-08-02 17:31:13 -07001895 nullptr));
1896 ASSERT_EQ(0, pthread_join(t, nullptr));
Yabin Cui917d3902015-01-08 12:32:42 -08001897}
1898
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001899#if defined(__BIONIC__)
Elliott Hughesf2083612015-11-11 13:32:28 -08001900static pthread_mutex_t pthread_gettid_np_mutex = PTHREAD_MUTEX_INITIALIZER;
1901
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001902static void* pthread_gettid_np_helper(void* arg) {
1903 *reinterpret_cast<pid_t*>(arg) = gettid();
Elliott Hughesf2083612015-11-11 13:32:28 -08001904
1905 // Wait for our parent to call pthread_gettid_np on us before exiting.
1906 pthread_mutex_lock(&pthread_gettid_np_mutex);
1907 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001908 return nullptr;
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001909}
1910#endif
1911
1912TEST(pthread, pthread_gettid_np) {
1913#if defined(__BIONIC__)
1914 ASSERT_EQ(gettid(), pthread_gettid_np(pthread_self()));
1915
Elliott Hughesf2083612015-11-11 13:32:28 -08001916 // Ensure the other thread doesn't exit until after we've called
1917 // pthread_gettid_np on it.
1918 pthread_mutex_lock(&pthread_gettid_np_mutex);
1919
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001920 pid_t t_gettid_result;
1921 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001922 pthread_create(&t, nullptr, pthread_gettid_np_helper, &t_gettid_result);
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001923
1924 pid_t t_pthread_gettid_np_result = pthread_gettid_np(t);
1925
Elliott Hughesf2083612015-11-11 13:32:28 -08001926 // Release the other thread and wait for it to exit.
1927 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001928 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001929
1930 ASSERT_EQ(t_gettid_result, t_pthread_gettid_np_result);
1931#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08001932 GTEST_SKIP() << "pthread_gettid_np not available";
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001933#endif
1934}
Elliott Hughes34c987a2014-09-22 16:01:26 -07001935
1936static size_t cleanup_counter = 0;
1937
Derek Xue41996952014-09-25 11:05:32 +01001938static void AbortCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001939 abort();
1940}
1941
Derek Xue41996952014-09-25 11:05:32 +01001942static void CountCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001943 ++cleanup_counter;
1944}
1945
Derek Xue41996952014-09-25 11:05:32 +01001946static void PthreadCleanupTester() {
Yi Kong32bc0fc2018-08-02 17:31:13 -07001947 pthread_cleanup_push(CountCleanupRoutine, nullptr);
1948 pthread_cleanup_push(CountCleanupRoutine, nullptr);
1949 pthread_cleanup_push(AbortCleanupRoutine, nullptr);
Elliott Hughes34c987a2014-09-22 16:01:26 -07001950
1951 pthread_cleanup_pop(0); // Pop the abort without executing it.
1952 pthread_cleanup_pop(1); // Pop one count while executing it.
1953 ASSERT_EQ(1U, cleanup_counter);
1954 // Exit while the other count is still on the cleanup stack.
Yi Kong32bc0fc2018-08-02 17:31:13 -07001955 pthread_exit(nullptr);
Elliott Hughes34c987a2014-09-22 16:01:26 -07001956
1957 // Calls to pthread_cleanup_pop/pthread_cleanup_push must always be balanced.
1958 pthread_cleanup_pop(0);
1959}
1960
Derek Xue41996952014-09-25 11:05:32 +01001961static void* PthreadCleanupStartRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001962 PthreadCleanupTester();
Yi Kong32bc0fc2018-08-02 17:31:13 -07001963 return nullptr;
Elliott Hughes34c987a2014-09-22 16:01:26 -07001964}
1965
1966TEST(pthread, pthread_cleanup_push__pthread_cleanup_pop) {
1967 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001968 ASSERT_EQ(0, pthread_create(&t, nullptr, PthreadCleanupStartRoutine, nullptr));
1969 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes34c987a2014-09-22 16:01:26 -07001970 ASSERT_EQ(2U, cleanup_counter);
1971}
Derek Xue41996952014-09-25 11:05:32 +01001972
1973TEST(pthread, PTHREAD_MUTEX_DEFAULT_is_PTHREAD_MUTEX_NORMAL) {
1974 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_DEFAULT);
1975}
1976
1977TEST(pthread, pthread_mutexattr_gettype) {
1978 pthread_mutexattr_t attr;
1979 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1980
1981 int attr_type;
1982
1983 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL));
1984 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1985 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, attr_type);
1986
1987 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK));
1988 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1989 ASSERT_EQ(PTHREAD_MUTEX_ERRORCHECK, attr_type);
1990
1991 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE));
1992 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1993 ASSERT_EQ(PTHREAD_MUTEX_RECURSIVE, attr_type);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001994
1995 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
1996}
1997
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001998TEST(pthread, pthread_mutexattr_protocol) {
1999 pthread_mutexattr_t attr;
2000 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
2001
2002 int protocol;
2003 ASSERT_EQ(0, pthread_mutexattr_getprotocol(&attr, &protocol));
2004 ASSERT_EQ(PTHREAD_PRIO_NONE, protocol);
2005 for (size_t repeat = 0; repeat < 2; ++repeat) {
2006 for (int set_protocol : {PTHREAD_PRIO_NONE, PTHREAD_PRIO_INHERIT}) {
2007 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, set_protocol));
2008 ASSERT_EQ(0, pthread_mutexattr_getprotocol(&attr, &protocol));
2009 ASSERT_EQ(protocol, set_protocol);
2010 }
2011 }
2012}
2013
Yabin Cui17393b02015-03-21 15:08:25 -07002014struct PthreadMutex {
2015 pthread_mutex_t lock;
2016
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002017 explicit PthreadMutex(int mutex_type, int protocol = PTHREAD_PRIO_NONE) {
2018 init(mutex_type, protocol);
Yabin Cui17393b02015-03-21 15:08:25 -07002019 }
2020
2021 ~PthreadMutex() {
2022 destroy();
2023 }
2024
2025 private:
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002026 void init(int mutex_type, int protocol) {
Yabin Cui17393b02015-03-21 15:08:25 -07002027 pthread_mutexattr_t attr;
2028 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
2029 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, mutex_type));
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002030 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, protocol));
Yabin Cui17393b02015-03-21 15:08:25 -07002031 ASSERT_EQ(0, pthread_mutex_init(&lock, &attr));
2032 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
2033 }
2034
2035 void destroy() {
2036 ASSERT_EQ(0, pthread_mutex_destroy(&lock));
2037 }
2038
2039 DISALLOW_COPY_AND_ASSIGN(PthreadMutex);
2040};
Derek Xue41996952014-09-25 11:05:32 +01002041
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002042static int UnlockFromAnotherThread(pthread_mutex_t* mutex) {
2043 pthread_t thread;
2044 pthread_create(&thread, nullptr, [](void* mutex_voidp) -> void* {
2045 pthread_mutex_t* mutex = static_cast<pthread_mutex_t*>(mutex_voidp);
2046 intptr_t result = pthread_mutex_unlock(mutex);
2047 return reinterpret_cast<void*>(result);
2048 }, mutex);
2049 void* result;
2050 EXPECT_EQ(0, pthread_join(thread, &result));
2051 return reinterpret_cast<intptr_t>(result);
2052};
2053
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002054static void TestPthreadMutexLockNormal(int protocol) {
2055 PthreadMutex m(PTHREAD_MUTEX_NORMAL, protocol);
Derek Xue41996952014-09-25 11:05:32 +01002056
Yabin Cui17393b02015-03-21 15:08:25 -07002057 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002058 if (protocol == PTHREAD_PRIO_INHERIT) {
2059 ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock));
2060 }
Yabin Cui17393b02015-03-21 15:08:25 -07002061 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08002062 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
2063 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
2064 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01002065}
2066
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002067static void TestPthreadMutexLockErrorCheck(int protocol) {
2068 PthreadMutex m(PTHREAD_MUTEX_ERRORCHECK, protocol);
Derek Xue41996952014-09-25 11:05:32 +01002069
Yabin Cui17393b02015-03-21 15:08:25 -07002070 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002071 ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07002072 ASSERT_EQ(EDEADLK, pthread_mutex_lock(&m.lock));
2073 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2074 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002075 if (protocol == PTHREAD_PRIO_NONE) {
2076 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
2077 } else {
2078 ASSERT_EQ(EDEADLK, pthread_mutex_trylock(&m.lock));
2079 }
Yabin Cui17393b02015-03-21 15:08:25 -07002080 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2081 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01002082}
2083
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002084static void TestPthreadMutexLockRecursive(int protocol) {
2085 PthreadMutex m(PTHREAD_MUTEX_RECURSIVE, protocol);
Derek Xue41996952014-09-25 11:05:32 +01002086
Yabin Cui17393b02015-03-21 15:08:25 -07002087 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002088 ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07002089 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Ryan Prichard4b6c0f52019-04-18 22:47:04 -07002090 ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07002091 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2092 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2093 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08002094 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
2095 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07002096 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2097 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
2098}
2099
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002100TEST(pthread, pthread_mutex_lock_NORMAL) {
2101 TestPthreadMutexLockNormal(PTHREAD_PRIO_NONE);
2102}
2103
2104TEST(pthread, pthread_mutex_lock_ERRORCHECK) {
2105 TestPthreadMutexLockErrorCheck(PTHREAD_PRIO_NONE);
2106}
2107
2108TEST(pthread, pthread_mutex_lock_RECURSIVE) {
2109 TestPthreadMutexLockRecursive(PTHREAD_PRIO_NONE);
2110}
2111
2112TEST(pthread, pthread_mutex_lock_pi) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002113 TestPthreadMutexLockNormal(PTHREAD_PRIO_INHERIT);
2114 TestPthreadMutexLockErrorCheck(PTHREAD_PRIO_INHERIT);
2115 TestPthreadMutexLockRecursive(PTHREAD_PRIO_INHERIT);
2116}
2117
Yabin Cui5a00ba72018-01-26 17:32:31 -08002118TEST(pthread, pthread_mutex_pi_count_limit) {
2119#if defined(__BIONIC__) && !defined(__LP64__)
2120 // Bionic only supports 65536 pi mutexes in 32-bit programs.
2121 pthread_mutexattr_t attr;
2122 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
2123 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT));
2124 std::vector<pthread_mutex_t> mutexes(65536);
2125 // Test if we can use 65536 pi mutexes at the same time.
2126 // Run 2 times to check if freed pi mutexes can be recycled.
2127 for (int repeat = 0; repeat < 2; ++repeat) {
2128 for (auto& m : mutexes) {
2129 ASSERT_EQ(0, pthread_mutex_init(&m, &attr));
2130 }
2131 pthread_mutex_t m;
2132 ASSERT_EQ(ENOMEM, pthread_mutex_init(&m, &attr));
2133 for (auto& m : mutexes) {
2134 ASSERT_EQ(0, pthread_mutex_lock(&m));
2135 }
2136 for (auto& m : mutexes) {
2137 ASSERT_EQ(0, pthread_mutex_unlock(&m));
2138 }
2139 for (auto& m : mutexes) {
2140 ASSERT_EQ(0, pthread_mutex_destroy(&m));
2141 }
2142 }
2143 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
2144#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002145 GTEST_SKIP() << "pi mutex count not limited to 64Ki";
Yabin Cui5a00ba72018-01-26 17:32:31 -08002146#endif
2147}
2148
Yabin Cui17393b02015-03-21 15:08:25 -07002149TEST(pthread, pthread_mutex_init_same_as_static_initializers) {
2150 pthread_mutex_t lock_normal = PTHREAD_MUTEX_INITIALIZER;
2151 PthreadMutex m1(PTHREAD_MUTEX_NORMAL);
2152 ASSERT_EQ(0, memcmp(&lock_normal, &m1.lock, sizeof(pthread_mutex_t)));
2153 pthread_mutex_destroy(&lock_normal);
2154
2155 pthread_mutex_t lock_errorcheck = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
2156 PthreadMutex m2(PTHREAD_MUTEX_ERRORCHECK);
2157 ASSERT_EQ(0, memcmp(&lock_errorcheck, &m2.lock, sizeof(pthread_mutex_t)));
2158 pthread_mutex_destroy(&lock_errorcheck);
2159
2160 pthread_mutex_t lock_recursive = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
2161 PthreadMutex m3(PTHREAD_MUTEX_RECURSIVE);
2162 ASSERT_EQ(0, memcmp(&lock_recursive, &m3.lock, sizeof(pthread_mutex_t)));
2163 ASSERT_EQ(0, pthread_mutex_destroy(&lock_recursive));
Derek Xue41996952014-09-25 11:05:32 +01002164}
Yabin Cui5a00ba72018-01-26 17:32:31 -08002165
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002166class MutexWakeupHelper {
2167 private:
Yabin Cui17393b02015-03-21 15:08:25 -07002168 PthreadMutex m;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002169 enum Progress {
2170 LOCK_INITIALIZED,
2171 LOCK_WAITING,
2172 LOCK_RELEASED,
2173 LOCK_ACCESSED
2174 };
2175 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -07002176 std::atomic<pid_t> tid;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002177
2178 static void thread_fn(MutexWakeupHelper* helper) {
Yabin Cuif7969852015-04-02 17:47:48 -07002179 helper->tid = gettid();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002180 ASSERT_EQ(LOCK_INITIALIZED, helper->progress);
2181 helper->progress = LOCK_WAITING;
2182
Yabin Cui17393b02015-03-21 15:08:25 -07002183 ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002184 ASSERT_EQ(LOCK_RELEASED, helper->progress);
Yabin Cui17393b02015-03-21 15:08:25 -07002185 ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002186
2187 helper->progress = LOCK_ACCESSED;
2188 }
2189
2190 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -07002191 explicit MutexWakeupHelper(int mutex_type) : m(mutex_type) {
Yabin Cui17393b02015-03-21 15:08:25 -07002192 }
2193
2194 void test() {
2195 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002196 progress = LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -07002197 tid = 0;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002198
2199 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002200 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002201 reinterpret_cast<void* (*)(void*)>(MutexWakeupHelper::thread_fn), this));
2202
Yabin Cuif7969852015-04-02 17:47:48 -07002203 WaitUntilThreadSleep(tid);
2204 ASSERT_EQ(LOCK_WAITING, progress);
2205
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002206 progress = LOCK_RELEASED;
Yabin Cui17393b02015-03-21 15:08:25 -07002207 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002208
Yi Kong32bc0fc2018-08-02 17:31:13 -07002209 ASSERT_EQ(0, pthread_join(thread, nullptr));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002210 ASSERT_EQ(LOCK_ACCESSED, progress);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002211 }
2212};
2213
2214TEST(pthread, pthread_mutex_NORMAL_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07002215 MutexWakeupHelper helper(PTHREAD_MUTEX_NORMAL);
2216 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002217}
2218
2219TEST(pthread, pthread_mutex_ERRORCHECK_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07002220 MutexWakeupHelper helper(PTHREAD_MUTEX_ERRORCHECK);
2221 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002222}
2223
2224TEST(pthread, pthread_mutex_RECURSIVE_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07002225 MutexWakeupHelper helper(PTHREAD_MUTEX_RECURSIVE);
2226 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002227}
2228
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002229static int GetThreadPriority(pid_t tid) {
2230 // sched_getparam() returns the static priority of a thread, which can't reflect a thread's
2231 // priority after priority inheritance. So read /proc/<pid>/stat to get the dynamic priority.
2232 std::string filename = android::base::StringPrintf("/proc/%d/stat", tid);
2233 std::string content;
2234 int result = INT_MAX;
2235 if (!android::base::ReadFileToString(filename, &content)) {
2236 return result;
2237 }
2238 std::vector<std::string> strs = android::base::Split(content, " ");
2239 if (strs.size() < 18) {
2240 return result;
2241 }
2242 if (!android::base::ParseInt(strs[17], &result)) {
2243 return INT_MAX;
2244 }
2245 return result;
2246}
2247
2248class PIMutexWakeupHelper {
2249private:
2250 PthreadMutex m;
2251 int protocol;
2252 enum Progress {
2253 LOCK_INITIALIZED,
2254 LOCK_CHILD_READY,
2255 LOCK_WAITING,
2256 LOCK_RELEASED,
2257 };
2258 std::atomic<Progress> progress;
2259 std::atomic<pid_t> main_tid;
2260 std::atomic<pid_t> child_tid;
2261 PthreadMutex start_thread_m;
2262
2263 static void thread_fn(PIMutexWakeupHelper* helper) {
2264 helper->child_tid = gettid();
2265 ASSERT_EQ(LOCK_INITIALIZED, helper->progress);
2266 ASSERT_EQ(0, setpriority(PRIO_PROCESS, gettid(), 1));
2267 ASSERT_EQ(21, GetThreadPriority(gettid()));
2268 ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock));
2269 helper->progress = LOCK_CHILD_READY;
2270 ASSERT_EQ(0, pthread_mutex_lock(&helper->start_thread_m.lock));
2271
2272 ASSERT_EQ(0, pthread_mutex_unlock(&helper->start_thread_m.lock));
2273 WaitUntilThreadSleep(helper->main_tid);
2274 ASSERT_EQ(LOCK_WAITING, helper->progress);
2275
2276 if (helper->protocol == PTHREAD_PRIO_INHERIT) {
2277 ASSERT_EQ(20, GetThreadPriority(gettid()));
2278 } else {
2279 ASSERT_EQ(21, GetThreadPriority(gettid()));
2280 }
2281 helper->progress = LOCK_RELEASED;
2282 ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock));
2283 }
2284
2285public:
2286 explicit PIMutexWakeupHelper(int mutex_type, int protocol)
2287 : m(mutex_type, protocol), protocol(protocol), start_thread_m(PTHREAD_MUTEX_NORMAL) {
2288 }
2289
2290 void test() {
2291 ASSERT_EQ(0, pthread_mutex_lock(&start_thread_m.lock));
2292 main_tid = gettid();
2293 ASSERT_EQ(20, GetThreadPriority(main_tid));
2294 progress = LOCK_INITIALIZED;
2295 child_tid = 0;
2296
2297 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002298 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002299 reinterpret_cast<void* (*)(void*)>(PIMutexWakeupHelper::thread_fn), this));
2300
2301 WaitUntilThreadSleep(child_tid);
2302 ASSERT_EQ(LOCK_CHILD_READY, progress);
2303 ASSERT_EQ(0, pthread_mutex_unlock(&start_thread_m.lock));
2304 progress = LOCK_WAITING;
2305 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
2306
2307 ASSERT_EQ(LOCK_RELEASED, progress);
2308 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2309 ASSERT_EQ(0, pthread_join(thread, nullptr));
2310 }
2311};
2312
2313TEST(pthread, pthread_mutex_pi_wakeup) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002314 for (int type : {PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_RECURSIVE, PTHREAD_MUTEX_ERRORCHECK}) {
2315 for (int protocol : {PTHREAD_PRIO_INHERIT}) {
2316 PIMutexWakeupHelper helper(type, protocol);
2317 helper.test();
2318 }
2319 }
2320}
2321
Yabin Cui140f3672015-02-03 10:32:00 -08002322TEST(pthread, pthread_mutex_owner_tid_limit) {
Yabin Cuie69c2452015-02-13 16:21:25 -08002323#if defined(__BIONIC__) && !defined(__LP64__)
Yabin Cui140f3672015-02-03 10:32:00 -08002324 FILE* fp = fopen("/proc/sys/kernel/pid_max", "r");
Yi Kong32bc0fc2018-08-02 17:31:13 -07002325 ASSERT_TRUE(fp != nullptr);
Yabin Cui140f3672015-02-03 10:32:00 -08002326 long pid_max;
2327 ASSERT_EQ(1, fscanf(fp, "%ld", &pid_max));
2328 fclose(fp);
Yabin Cuie69c2452015-02-13 16:21:25 -08002329 // Bionic's pthread_mutex implementation on 32-bit devices uses 16 bits to represent owner tid.
Yabin Cui140f3672015-02-03 10:32:00 -08002330 ASSERT_LE(pid_max, 65536);
Yabin Cuie69c2452015-02-13 16:21:25 -08002331#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002332 GTEST_SKIP() << "pthread_mutex supports 32-bit tid";
Yabin Cuie69c2452015-02-13 16:21:25 -08002333#endif
Yabin Cui140f3672015-02-03 10:32:00 -08002334}
Yabin Cuib5845722015-03-16 22:46:42 -07002335
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002336static void pthread_mutex_timedlock_helper(clockid_t clock,
2337 int (*lock_function)(pthread_mutex_t* __mutex,
2338 const timespec* __timeout)) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08002339 pthread_mutex_t m;
2340 ASSERT_EQ(0, pthread_mutex_init(&m, nullptr));
2341
2342 // If the mutex is already locked, pthread_mutex_timedlock should time out.
2343 ASSERT_EQ(0, pthread_mutex_lock(&m));
2344
2345 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002346 ASSERT_EQ(0, clock_gettime(clock, &ts));
2347 ASSERT_EQ(ETIMEDOUT, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002348 ts.tv_nsec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002349 ASSERT_EQ(EINVAL, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002350 ts.tv_nsec = NS_PER_S;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002351 ASSERT_EQ(EINVAL, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002352 ts.tv_nsec = NS_PER_S - 1;
2353 ts.tv_sec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002354 ASSERT_EQ(ETIMEDOUT, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002355
2356 // If the mutex is unlocked, pthread_mutex_timedlock should succeed.
2357 ASSERT_EQ(0, pthread_mutex_unlock(&m));
2358
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002359 ASSERT_EQ(0, clock_gettime(clock, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002360 ts.tv_sec += 1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002361 ASSERT_EQ(0, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002362
2363 ASSERT_EQ(0, pthread_mutex_unlock(&m));
2364 ASSERT_EQ(0, pthread_mutex_destroy(&m));
2365}
2366
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002367TEST(pthread, pthread_mutex_timedlock) {
2368 pthread_mutex_timedlock_helper(CLOCK_REALTIME, pthread_mutex_timedlock);
2369}
2370
2371TEST(pthread, pthread_mutex_timedlock_monotonic_np) {
2372#if defined(__BIONIC__)
2373 pthread_mutex_timedlock_helper(CLOCK_MONOTONIC, pthread_mutex_timedlock_monotonic_np);
2374#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002375 GTEST_SKIP() << "pthread_mutex_timedlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002376#endif // __BIONIC__
2377}
2378
Tom Cherry69010802019-05-07 20:33:05 -07002379TEST(pthread, pthread_mutex_clocklock) {
2380#if defined(__BIONIC__)
2381 pthread_mutex_timedlock_helper(
2382 CLOCK_MONOTONIC, [](pthread_mutex_t* __mutex, const timespec* __timeout) {
2383 return pthread_mutex_clocklock(__mutex, CLOCK_MONOTONIC, __timeout);
2384 });
2385 pthread_mutex_timedlock_helper(
2386 CLOCK_REALTIME, [](pthread_mutex_t* __mutex, const timespec* __timeout) {
2387 return pthread_mutex_clocklock(__mutex, CLOCK_REALTIME, __timeout);
2388 });
2389#else // __BIONIC__
2390 GTEST_SKIP() << "pthread_mutex_clocklock not available";
2391#endif // __BIONIC__
2392}
2393
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002394static void pthread_mutex_timedlock_pi_helper(clockid_t clock,
2395 int (*lock_function)(pthread_mutex_t* __mutex,
2396 const timespec* __timeout)) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002397 PthreadMutex m(PTHREAD_MUTEX_NORMAL, PTHREAD_PRIO_INHERIT);
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002398
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002399 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002400 clock_gettime(clock, &ts);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002401 ts.tv_sec += 1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002402 ASSERT_EQ(0, lock_function(&m.lock, &ts));
2403
2404 struct ThreadArgs {
2405 clockid_t clock;
2406 int (*lock_function)(pthread_mutex_t* __mutex, const timespec* __timeout);
2407 PthreadMutex& m;
2408 };
2409
2410 ThreadArgs thread_args = {
2411 .clock = clock,
2412 .lock_function = lock_function,
2413 .m = m,
2414 };
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002415
2416 auto ThreadFn = [](void* arg) -> void* {
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002417 auto args = static_cast<ThreadArgs*>(arg);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002418 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002419 clock_gettime(args->clock, &ts);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002420 ts.tv_sec += 1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002421 intptr_t result = args->lock_function(&args->m.lock, &ts);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002422 return reinterpret_cast<void*>(result);
2423 };
2424
2425 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002426 ASSERT_EQ(0, pthread_create(&thread, nullptr, ThreadFn, &thread_args));
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002427 void* result;
2428 ASSERT_EQ(0, pthread_join(thread, &result));
2429 ASSERT_EQ(ETIMEDOUT, reinterpret_cast<intptr_t>(result));
2430 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2431}
2432
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002433TEST(pthread, pthread_mutex_timedlock_pi) {
2434 pthread_mutex_timedlock_pi_helper(CLOCK_REALTIME, pthread_mutex_timedlock);
2435}
2436
2437TEST(pthread, pthread_mutex_timedlock_monotonic_np_pi) {
2438#if defined(__BIONIC__)
2439 pthread_mutex_timedlock_pi_helper(CLOCK_MONOTONIC, pthread_mutex_timedlock_monotonic_np);
2440#else // __BIONIC__
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002441 GTEST_SKIP() << "pthread_mutex_timedlock_monotonic_np not available";
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002442#endif // __BIONIC__
2443}
2444
Tom Cherry69010802019-05-07 20:33:05 -07002445TEST(pthread, pthread_mutex_clocklock_pi) {
2446#if defined(__BIONIC__)
2447 pthread_mutex_timedlock_pi_helper(
2448 CLOCK_MONOTONIC, [](pthread_mutex_t* __mutex, const timespec* __timeout) {
2449 return pthread_mutex_clocklock(__mutex, CLOCK_MONOTONIC, __timeout);
2450 });
2451 pthread_mutex_timedlock_pi_helper(
2452 CLOCK_REALTIME, [](pthread_mutex_t* __mutex, const timespec* __timeout) {
2453 return pthread_mutex_clocklock(__mutex, CLOCK_REALTIME, __timeout);
2454 });
2455#else // __BIONIC__
2456 GTEST_SKIP() << "pthread_mutex_clocklock not available";
2457#endif // __BIONIC__
2458}
2459
2460TEST(pthread, pthread_mutex_clocklock_invalid) {
2461#if defined(__BIONIC__)
2462 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
2463 timespec ts;
2464 EXPECT_EQ(EINVAL, pthread_mutex_clocklock(&mutex, CLOCK_PROCESS_CPUTIME_ID, &ts));
2465#else // __BIONIC__
2466 GTEST_SKIP() << "pthread_mutex_clocklock not available";
2467#endif // __BIONIC__
2468}
2469
Elliott Hughese657eb42021-02-18 17:11:56 -08002470TEST_F(pthread_DeathTest, pthread_mutex_using_destroyed_mutex) {
Yabin Cui9651fdf2018-03-14 12:02:21 -07002471#if defined(__BIONIC__)
2472 pthread_mutex_t m;
2473 ASSERT_EQ(0, pthread_mutex_init(&m, nullptr));
2474 ASSERT_EQ(0, pthread_mutex_destroy(&m));
2475 ASSERT_EXIT(pthread_mutex_lock(&m), ::testing::KilledBySignal(SIGABRT),
2476 "pthread_mutex_lock called on a destroyed mutex");
2477 ASSERT_EXIT(pthread_mutex_unlock(&m), ::testing::KilledBySignal(SIGABRT),
2478 "pthread_mutex_unlock called on a destroyed mutex");
2479 ASSERT_EXIT(pthread_mutex_trylock(&m), ::testing::KilledBySignal(SIGABRT),
2480 "pthread_mutex_trylock called on a destroyed mutex");
2481 timespec ts;
2482 ASSERT_EXIT(pthread_mutex_timedlock(&m, &ts), ::testing::KilledBySignal(SIGABRT),
2483 "pthread_mutex_timedlock called on a destroyed mutex");
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002484 ASSERT_EXIT(pthread_mutex_timedlock_monotonic_np(&m, &ts), ::testing::KilledBySignal(SIGABRT),
2485 "pthread_mutex_timedlock_monotonic_np called on a destroyed mutex");
Tom Cherry69010802019-05-07 20:33:05 -07002486 ASSERT_EXIT(pthread_mutex_clocklock(&m, CLOCK_MONOTONIC, &ts), ::testing::KilledBySignal(SIGABRT),
2487 "pthread_mutex_clocklock called on a destroyed mutex");
2488 ASSERT_EXIT(pthread_mutex_clocklock(&m, CLOCK_REALTIME, &ts), ::testing::KilledBySignal(SIGABRT),
2489 "pthread_mutex_clocklock called on a destroyed mutex");
2490 ASSERT_EXIT(pthread_mutex_clocklock(&m, CLOCK_PROCESS_CPUTIME_ID, &ts),
2491 ::testing::KilledBySignal(SIGABRT),
2492 "pthread_mutex_clocklock called on a destroyed mutex");
Yabin Cui9651fdf2018-03-14 12:02:21 -07002493 ASSERT_EXIT(pthread_mutex_destroy(&m), ::testing::KilledBySignal(SIGABRT),
2494 "pthread_mutex_destroy called on a destroyed mutex");
2495#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002496 GTEST_SKIP() << "bionic-only test";
Yabin Cui9651fdf2018-03-14 12:02:21 -07002497#endif
2498}
2499
Yabin Cuib5845722015-03-16 22:46:42 -07002500class StrictAlignmentAllocator {
2501 public:
2502 void* allocate(size_t size, size_t alignment) {
2503 char* p = new char[size + alignment * 2];
2504 allocated_array.push_back(p);
2505 while (!is_strict_aligned(p, alignment)) {
2506 ++p;
2507 }
2508 return p;
2509 }
2510
2511 ~StrictAlignmentAllocator() {
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07002512 for (const auto& p : allocated_array) {
2513 delete[] p;
Yabin Cuib5845722015-03-16 22:46:42 -07002514 }
2515 }
2516
2517 private:
2518 bool is_strict_aligned(char* p, size_t alignment) {
2519 return (reinterpret_cast<uintptr_t>(p) % (alignment * 2)) == alignment;
2520 }
2521
2522 std::vector<char*> allocated_array;
2523};
2524
2525TEST(pthread, pthread_types_allow_four_bytes_alignment) {
2526#if defined(__BIONIC__)
2527 // For binary compatibility with old version, we need to allow 4-byte aligned data for pthread types.
2528 StrictAlignmentAllocator allocator;
2529 pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(
2530 allocator.allocate(sizeof(pthread_mutex_t), 4));
Yi Kong32bc0fc2018-08-02 17:31:13 -07002531 ASSERT_EQ(0, pthread_mutex_init(mutex, nullptr));
Yabin Cuib5845722015-03-16 22:46:42 -07002532 ASSERT_EQ(0, pthread_mutex_lock(mutex));
2533 ASSERT_EQ(0, pthread_mutex_unlock(mutex));
2534 ASSERT_EQ(0, pthread_mutex_destroy(mutex));
2535
2536 pthread_cond_t* cond = reinterpret_cast<pthread_cond_t*>(
2537 allocator.allocate(sizeof(pthread_cond_t), 4));
Yi Kong32bc0fc2018-08-02 17:31:13 -07002538 ASSERT_EQ(0, pthread_cond_init(cond, nullptr));
Yabin Cuib5845722015-03-16 22:46:42 -07002539 ASSERT_EQ(0, pthread_cond_signal(cond));
2540 ASSERT_EQ(0, pthread_cond_broadcast(cond));
2541 ASSERT_EQ(0, pthread_cond_destroy(cond));
2542
2543 pthread_rwlock_t* rwlock = reinterpret_cast<pthread_rwlock_t*>(
2544 allocator.allocate(sizeof(pthread_rwlock_t), 4));
Yi Kong32bc0fc2018-08-02 17:31:13 -07002545 ASSERT_EQ(0, pthread_rwlock_init(rwlock, nullptr));
Yabin Cuib5845722015-03-16 22:46:42 -07002546 ASSERT_EQ(0, pthread_rwlock_rdlock(rwlock));
2547 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
2548 ASSERT_EQ(0, pthread_rwlock_wrlock(rwlock));
2549 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
2550 ASSERT_EQ(0, pthread_rwlock_destroy(rwlock));
2551
2552#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002553 GTEST_SKIP() << "bionic-only test";
Yabin Cuib5845722015-03-16 22:46:42 -07002554#endif
2555}
Christopher Ferris60907c72015-06-09 18:46:15 -07002556
2557TEST(pthread, pthread_mutex_lock_null_32) {
2558#if defined(__BIONIC__) && !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -07002559 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return
2560 // EINVAL in that case: http://b/19995172.
2561 //
2562 // We decorate the public defintion with _Nonnull so that people recompiling
2563 // their code with get a warning and might fix their bug, but need to pass
2564 // NULL here to test that we remain compatible.
2565 pthread_mutex_t* null_value = nullptr;
2566 ASSERT_EQ(EINVAL, pthread_mutex_lock(null_value));
Christopher Ferris60907c72015-06-09 18:46:15 -07002567#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002568 GTEST_SKIP() << "32-bit bionic-only test";
Christopher Ferris60907c72015-06-09 18:46:15 -07002569#endif
2570}
2571
2572TEST(pthread, pthread_mutex_unlock_null_32) {
2573#if defined(__BIONIC__) && !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -07002574 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return
2575 // EINVAL in that case: http://b/19995172.
2576 //
2577 // We decorate the public defintion with _Nonnull so that people recompiling
2578 // their code with get a warning and might fix their bug, but need to pass
2579 // NULL here to test that we remain compatible.
2580 pthread_mutex_t* null_value = nullptr;
2581 ASSERT_EQ(EINVAL, pthread_mutex_unlock(null_value));
Christopher Ferris60907c72015-06-09 18:46:15 -07002582#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002583 GTEST_SKIP() << "32-bit bionic-only test";
Christopher Ferris60907c72015-06-09 18:46:15 -07002584#endif
2585}
2586
2587TEST_F(pthread_DeathTest, pthread_mutex_lock_null_64) {
2588#if defined(__BIONIC__) && defined(__LP64__)
2589 pthread_mutex_t* null_value = nullptr;
2590 ASSERT_EXIT(pthread_mutex_lock(null_value), testing::KilledBySignal(SIGSEGV), "");
2591#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002592 GTEST_SKIP() << "64-bit bionic-only test";
Christopher Ferris60907c72015-06-09 18:46:15 -07002593#endif
2594}
2595
2596TEST_F(pthread_DeathTest, pthread_mutex_unlock_null_64) {
2597#if defined(__BIONIC__) && defined(__LP64__)
2598 pthread_mutex_t* null_value = nullptr;
2599 ASSERT_EXIT(pthread_mutex_unlock(null_value), testing::KilledBySignal(SIGSEGV), "");
2600#else
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002601 GTEST_SKIP() << "64-bit bionic-only test";
Christopher Ferris60907c72015-06-09 18:46:15 -07002602#endif
2603}
Yabin Cui33ac04a2015-09-22 11:16:15 -07002604
2605extern _Unwind_Reason_Code FrameCounter(_Unwind_Context* ctx, void* arg);
2606
2607static volatile bool signal_handler_on_altstack_done;
2608
Josh Gao61db9ac2017-03-15 19:42:05 -07002609__attribute__((__noinline__))
2610static void signal_handler_backtrace() {
2611 // Check if we have enough stack space for unwinding.
2612 int count = 0;
2613 _Unwind_Backtrace(FrameCounter, &count);
2614 ASSERT_GT(count, 0);
2615}
2616
2617__attribute__((__noinline__))
2618static void signal_handler_logging() {
2619 // Check if we have enough stack space for logging.
2620 std::string s(2048, '*');
2621 GTEST_LOG_(INFO) << s;
2622 signal_handler_on_altstack_done = true;
2623}
2624
2625__attribute__((__noinline__))
2626static void signal_handler_snprintf() {
2627 // Check if we have enough stack space for snprintf to a PATH_MAX buffer, plus some extra.
2628 char buf[PATH_MAX + 2048];
2629 ASSERT_GT(snprintf(buf, sizeof(buf), "/proc/%d/status", getpid()), 0);
2630}
2631
Yabin Cui33ac04a2015-09-22 11:16:15 -07002632static void SignalHandlerOnAltStack(int signo, siginfo_t*, void*) {
2633 ASSERT_EQ(SIGUSR1, signo);
Josh Gao61db9ac2017-03-15 19:42:05 -07002634 signal_handler_backtrace();
2635 signal_handler_logging();
2636 signal_handler_snprintf();
Yabin Cui33ac04a2015-09-22 11:16:15 -07002637}
2638
Josh Gao415daa82017-03-06 17:45:33 -08002639TEST(pthread, big_enough_signal_stack) {
Yabin Cui33ac04a2015-09-22 11:16:15 -07002640 signal_handler_on_altstack_done = false;
2641 ScopedSignalHandler handler(SIGUSR1, SignalHandlerOnAltStack, SA_SIGINFO | SA_ONSTACK);
2642 kill(getpid(), SIGUSR1);
2643 ASSERT_TRUE(signal_handler_on_altstack_done);
2644}
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002645
2646TEST(pthread, pthread_barrierattr_smoke) {
2647 pthread_barrierattr_t attr;
2648 ASSERT_EQ(0, pthread_barrierattr_init(&attr));
2649 int pshared;
2650 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
2651 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
2652 ASSERT_EQ(0, pthread_barrierattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
2653 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
2654 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
2655 ASSERT_EQ(0, pthread_barrierattr_destroy(&attr));
2656}
2657
Yabin Cui81d27972016-03-22 13:45:55 -07002658struct BarrierTestHelperData {
2659 size_t thread_count;
2660 pthread_barrier_t barrier;
2661 std::atomic<int> finished_mask;
2662 std::atomic<int> serial_thread_count;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002663 size_t iteration_count;
Yabin Cui81d27972016-03-22 13:45:55 -07002664 std::atomic<size_t> finished_iteration_count;
2665
2666 BarrierTestHelperData(size_t thread_count, size_t iteration_count)
2667 : thread_count(thread_count), finished_mask(0), serial_thread_count(0),
2668 iteration_count(iteration_count), finished_iteration_count(0) {
2669 }
2670};
2671
2672struct BarrierTestHelperArg {
2673 int id;
2674 BarrierTestHelperData* data;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002675};
2676
2677static void BarrierTestHelper(BarrierTestHelperArg* arg) {
Yabin Cui81d27972016-03-22 13:45:55 -07002678 for (size_t i = 0; i < arg->data->iteration_count; ++i) {
2679 int result = pthread_barrier_wait(&arg->data->barrier);
2680 if (result == PTHREAD_BARRIER_SERIAL_THREAD) {
2681 arg->data->serial_thread_count++;
2682 } else {
2683 ASSERT_EQ(0, result);
2684 }
Yabin Cuid5c04c52017-05-02 12:57:39 -07002685 int mask = arg->data->finished_mask.fetch_or(1 << arg->id);
Yabin Cuiab4cddc2017-05-02 16:18:13 -07002686 mask |= 1 << arg->id;
Yabin Cuid5c04c52017-05-02 12:57:39 -07002687 if (mask == ((1 << arg->data->thread_count) - 1)) {
Yabin Cui81d27972016-03-22 13:45:55 -07002688 ASSERT_EQ(1, arg->data->serial_thread_count);
2689 arg->data->finished_iteration_count++;
2690 arg->data->finished_mask = 0;
2691 arg->data->serial_thread_count = 0;
2692 }
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002693 }
2694}
2695
2696TEST(pthread, pthread_barrier_smoke) {
2697 const size_t BARRIER_ITERATION_COUNT = 10;
2698 const size_t BARRIER_THREAD_COUNT = 10;
Yabin Cui81d27972016-03-22 13:45:55 -07002699 BarrierTestHelperData data(BARRIER_THREAD_COUNT, BARRIER_ITERATION_COUNT);
2700 ASSERT_EQ(0, pthread_barrier_init(&data.barrier, nullptr, data.thread_count));
2701 std::vector<pthread_t> threads(data.thread_count);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002702 std::vector<BarrierTestHelperArg> args(threads.size());
2703 for (size_t i = 0; i < threads.size(); ++i) {
Yabin Cui81d27972016-03-22 13:45:55 -07002704 args[i].id = i;
2705 args[i].data = &data;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002706 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
2707 reinterpret_cast<void* (*)(void*)>(BarrierTestHelper), &args[i]));
2708 }
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002709 for (size_t i = 0; i < threads.size(); ++i) {
2710 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
2711 }
Yabin Cui81d27972016-03-22 13:45:55 -07002712 ASSERT_EQ(data.iteration_count, data.finished_iteration_count);
2713 ASSERT_EQ(0, pthread_barrier_destroy(&data.barrier));
2714}
2715
2716struct BarrierDestroyTestArg {
2717 std::atomic<int> tid;
2718 pthread_barrier_t* barrier;
2719};
2720
2721static void BarrierDestroyTestHelper(BarrierDestroyTestArg* arg) {
2722 arg->tid = gettid();
2723 ASSERT_EQ(0, pthread_barrier_wait(arg->barrier));
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002724}
2725
2726TEST(pthread, pthread_barrier_destroy) {
2727 pthread_barrier_t barrier;
2728 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, 2));
2729 pthread_t thread;
Yabin Cui81d27972016-03-22 13:45:55 -07002730 BarrierDestroyTestArg arg;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002731 arg.tid = 0;
2732 arg.barrier = &barrier;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002733 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui81d27972016-03-22 13:45:55 -07002734 reinterpret_cast<void* (*)(void*)>(BarrierDestroyTestHelper), &arg));
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002735 WaitUntilThreadSleep(arg.tid);
2736 ASSERT_EQ(EBUSY, pthread_barrier_destroy(&barrier));
2737 ASSERT_EQ(PTHREAD_BARRIER_SERIAL_THREAD, pthread_barrier_wait(&barrier));
2738 // Verify if the barrier can be destroyed directly after pthread_barrier_wait().
2739 ASSERT_EQ(0, pthread_barrier_destroy(&barrier));
2740 ASSERT_EQ(0, pthread_join(thread, nullptr));
2741#if defined(__BIONIC__)
2742 ASSERT_EQ(EINVAL, pthread_barrier_destroy(&barrier));
2743#endif
2744}
2745
2746struct BarrierOrderingTestHelperArg {
2747 pthread_barrier_t* barrier;
2748 size_t* array;
2749 size_t array_length;
2750 size_t id;
2751};
2752
2753void BarrierOrderingTestHelper(BarrierOrderingTestHelperArg* arg) {
2754 const size_t ITERATION_COUNT = 10000;
2755 for (size_t i = 1; i <= ITERATION_COUNT; ++i) {
2756 arg->array[arg->id] = i;
Yabin Cuic9a659c2015-11-05 15:36:08 -08002757 int result = pthread_barrier_wait(arg->barrier);
2758 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002759 for (size_t j = 0; j < arg->array_length; ++j) {
2760 ASSERT_EQ(i, arg->array[j]);
2761 }
Yabin Cuic9a659c2015-11-05 15:36:08 -08002762 result = pthread_barrier_wait(arg->barrier);
2763 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002764 }
2765}
2766
2767TEST(pthread, pthread_barrier_check_ordering) {
2768 const size_t THREAD_COUNT = 4;
2769 pthread_barrier_t barrier;
2770 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, THREAD_COUNT));
2771 size_t array[THREAD_COUNT];
2772 std::vector<pthread_t> threads(THREAD_COUNT);
2773 std::vector<BarrierOrderingTestHelperArg> args(THREAD_COUNT);
2774 for (size_t i = 0; i < THREAD_COUNT; ++i) {
2775 args[i].barrier = &barrier;
2776 args[i].array = array;
2777 args[i].array_length = THREAD_COUNT;
2778 args[i].id = i;
2779 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
2780 reinterpret_cast<void* (*)(void*)>(BarrierOrderingTestHelper),
2781 &args[i]));
2782 }
2783 for (size_t i = 0; i < THREAD_COUNT; ++i) {
2784 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
2785 }
2786}
Yabin Cuife3a83a2015-11-17 16:03:18 -08002787
Elliott Hughes463faad2018-07-06 14:34:49 -07002788TEST(pthread, pthread_barrier_init_zero_count) {
2789 pthread_barrier_t barrier;
2790 ASSERT_EQ(EINVAL, pthread_barrier_init(&barrier, nullptr, 0));
2791}
2792
Yabin Cuife3a83a2015-11-17 16:03:18 -08002793TEST(pthread, pthread_spinlock_smoke) {
2794 pthread_spinlock_t lock;
2795 ASSERT_EQ(0, pthread_spin_init(&lock, 0));
2796 ASSERT_EQ(0, pthread_spin_trylock(&lock));
2797 ASSERT_EQ(0, pthread_spin_unlock(&lock));
2798 ASSERT_EQ(0, pthread_spin_lock(&lock));
2799 ASSERT_EQ(EBUSY, pthread_spin_trylock(&lock));
2800 ASSERT_EQ(0, pthread_spin_unlock(&lock));
2801 ASSERT_EQ(0, pthread_spin_destroy(&lock));
2802}
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002803
Elliott Hughes8aecba72017-10-17 15:34:41 -07002804TEST(pthread, pthread_attr_getdetachstate__pthread_attr_setdetachstate) {
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002805 pthread_attr_t attr;
2806 ASSERT_EQ(0, pthread_attr_init(&attr));
2807
Elliott Hughes8aecba72017-10-17 15:34:41 -07002808 int state;
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002809 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002810 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2811 ASSERT_EQ(PTHREAD_CREATE_DETACHED, state);
2812
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002813 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002814 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2815 ASSERT_EQ(PTHREAD_CREATE_JOINABLE, state);
2816
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002817 ASSERT_EQ(EINVAL, pthread_attr_setdetachstate(&attr, 123));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002818 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2819 ASSERT_EQ(PTHREAD_CREATE_JOINABLE, state);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002820}
2821
2822TEST(pthread, pthread_create__mmap_failures) {
Evgeny Eltsinb4f7aaa2020-06-09 15:49:20 +02002823 // After thread is successfully created, native_bridge might need more memory to run it.
2824 SKIP_WITH_NATIVE_BRIDGE;
2825
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002826 pthread_attr_t attr;
2827 ASSERT_EQ(0, pthread_attr_init(&attr));
2828 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
2829
2830 const auto kPageSize = sysconf(_SC_PAGE_SIZE);
2831
Elliott Hughes57512982017-10-02 22:49:18 -07002832 // Use up all the VMAs. By default this is 64Ki (though some will already be in use).
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002833 std::vector<void*> pages;
Elliott Hughes57512982017-10-02 22:49:18 -07002834 pages.reserve(64 * 1024);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002835 int prot = PROT_NONE;
2836 while (true) {
2837 void* page = mmap(nullptr, kPageSize, prot, MAP_ANON|MAP_PRIVATE, -1, 0);
2838 if (page == MAP_FAILED) break;
2839 pages.push_back(page);
2840 prot = (prot == PROT_NONE) ? PROT_READ : PROT_NONE;
2841 }
2842
2843 // Try creating threads, freeing up a page each time we fail.
2844 size_t EAGAIN_count = 0;
2845 size_t i = 0;
2846 for (; i < pages.size(); ++i) {
2847 pthread_t t;
2848 int status = pthread_create(&t, &attr, IdFn, nullptr);
2849 if (status != EAGAIN) break;
2850 ++EAGAIN_count;
2851 ASSERT_EQ(0, munmap(pages[i], kPageSize));
2852 }
2853
Ryan Prichard45d13492019-01-03 02:51:30 -08002854 // Creating a thread uses at least three VMAs: the combined stack and TLS, and a guard on each
2855 // side. So we should have seen at least three failures.
2856 ASSERT_GE(EAGAIN_count, 3U);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002857
2858 for (; i < pages.size(); ++i) {
2859 ASSERT_EQ(0, munmap(pages[i], kPageSize));
2860 }
2861}
Elliott Hughesdff08ce2017-10-16 09:58:45 -07002862
2863TEST(pthread, pthread_setschedparam) {
2864 sched_param p = { .sched_priority = INT_MIN };
2865 ASSERT_EQ(EINVAL, pthread_setschedparam(pthread_self(), INT_MIN, &p));
2866}
2867
2868TEST(pthread, pthread_setschedprio) {
2869 ASSERT_EQ(EINVAL, pthread_setschedprio(pthread_self(), INT_MIN));
2870}
Elliott Hughes8aecba72017-10-17 15:34:41 -07002871
2872TEST(pthread, pthread_attr_getinheritsched__pthread_attr_setinheritsched) {
2873 pthread_attr_t attr;
2874 ASSERT_EQ(0, pthread_attr_init(&attr));
2875
2876 int state;
2877 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2878 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
2879 ASSERT_EQ(PTHREAD_INHERIT_SCHED, state);
2880
2881 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
2882 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
2883 ASSERT_EQ(PTHREAD_EXPLICIT_SCHED, state);
2884
2885 ASSERT_EQ(EINVAL, pthread_attr_setinheritsched(&attr, 123));
2886 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
2887 ASSERT_EQ(PTHREAD_EXPLICIT_SCHED, state);
2888}
2889
2890TEST(pthread, pthread_attr_setinheritsched__PTHREAD_INHERIT_SCHED__PTHREAD_EXPLICIT_SCHED) {
2891 pthread_attr_t attr;
2892 ASSERT_EQ(0, pthread_attr_init(&attr));
2893
2894 // If we set invalid scheduling attributes but choose to inherit, everything's fine...
2895 sched_param param = { .sched_priority = sched_get_priority_max(SCHED_FIFO) + 1 };
2896 ASSERT_EQ(0, pthread_attr_setschedparam(&attr, &param));
2897 ASSERT_EQ(0, pthread_attr_setschedpolicy(&attr, SCHED_FIFO));
2898 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2899
2900 pthread_t t;
2901 ASSERT_EQ(0, pthread_create(&t, &attr, IdFn, nullptr));
2902 ASSERT_EQ(0, pthread_join(t, nullptr));
2903
Elliott Hughes7a660662017-10-30 09:26:06 -07002904#if defined(__LP64__)
2905 // If we ask to use them, though, we'll see a failure...
Elliott Hughes8aecba72017-10-17 15:34:41 -07002906 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
2907 ASSERT_EQ(EINVAL, pthread_create(&t, &attr, IdFn, nullptr));
Elliott Hughes7a660662017-10-30 09:26:06 -07002908#else
2909 // For backwards compatibility with broken apps, we just ignore failures
2910 // to set scheduler attributes on LP32.
2911#endif
Elliott Hughes8aecba72017-10-17 15:34:41 -07002912}
2913
2914TEST(pthread, pthread_attr_setinheritsched_PTHREAD_INHERIT_SCHED_takes_effect) {
2915 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
2916 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO, &param);
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002917 if (rc == EPERM) GTEST_SKIP() << "pthread_setschedparam failed with EPERM";
Elliott Hughes8aecba72017-10-17 15:34:41 -07002918 ASSERT_EQ(0, rc);
2919
2920 pthread_attr_t attr;
2921 ASSERT_EQ(0, pthread_attr_init(&attr));
2922 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2923
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002924 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07002925 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002926 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002927 int actual_policy;
2928 sched_param actual_param;
2929 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
2930 ASSERT_EQ(SCHED_FIFO, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002931 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07002932 ASSERT_EQ(0, pthread_join(t, nullptr));
2933}
2934
2935TEST(pthread, pthread_attr_setinheritsched_PTHREAD_EXPLICIT_SCHED_takes_effect) {
2936 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
2937 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO, &param);
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002938 if (rc == EPERM) GTEST_SKIP() << "pthread_setschedparam failed with EPERM";
Elliott Hughes8aecba72017-10-17 15:34:41 -07002939 ASSERT_EQ(0, rc);
2940
2941 pthread_attr_t attr;
2942 ASSERT_EQ(0, pthread_attr_init(&attr));
2943 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
2944 ASSERT_EQ(0, pthread_attr_setschedpolicy(&attr, SCHED_OTHER));
2945
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002946 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07002947 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002948 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002949 int actual_policy;
2950 sched_param actual_param;
2951 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
2952 ASSERT_EQ(SCHED_OTHER, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002953 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07002954 ASSERT_EQ(0, pthread_join(t, nullptr));
2955}
2956
2957TEST(pthread, pthread_attr_setinheritsched__takes_effect_despite_SCHED_RESET_ON_FORK) {
2958 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
2959 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param);
Elliott Hughesbcaa4542019-03-08 15:20:23 -08002960 if (rc == EPERM) GTEST_SKIP() << "pthread_setschedparam failed with EPERM";
Elliott Hughes8aecba72017-10-17 15:34:41 -07002961 ASSERT_EQ(0, rc);
2962
2963 pthread_attr_t attr;
2964 ASSERT_EQ(0, pthread_attr_init(&attr));
2965 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2966
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002967 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07002968 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002969 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002970 int actual_policy;
2971 sched_param actual_param;
2972 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
2973 ASSERT_EQ(SCHED_FIFO | SCHED_RESET_ON_FORK, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002974 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07002975 ASSERT_EQ(0, pthread_join(t, nullptr));
2976}
Peter Collingbourne5d3aa862020-09-11 15:05:17 -07002977
2978extern "C" bool android_run_on_all_threads(bool (*func)(void*), void* arg);
2979
2980TEST(pthread, run_on_all_threads) {
2981#if defined(__BIONIC__)
2982 pthread_t t;
2983 ASSERT_EQ(
2984 0, pthread_create(
2985 &t, nullptr,
2986 [](void*) -> void* {
2987 pthread_attr_t detached;
2988 if (pthread_attr_init(&detached) != 0 ||
2989 pthread_attr_setdetachstate(&detached, PTHREAD_CREATE_DETACHED) != 0) {
2990 return reinterpret_cast<void*>(errno);
2991 }
2992
2993 for (int i = 0; i != 1000; ++i) {
2994 pthread_t t1, t2;
2995 if (pthread_create(
2996 &t1, &detached, [](void*) -> void* { return nullptr; }, nullptr) != 0 ||
2997 pthread_create(
2998 &t2, nullptr, [](void*) -> void* { return nullptr; }, nullptr) != 0 ||
2999 pthread_join(t2, nullptr) != 0) {
3000 return reinterpret_cast<void*>(errno);
3001 }
3002 }
3003
3004 if (pthread_attr_destroy(&detached) != 0) {
3005 return reinterpret_cast<void*>(errno);
3006 }
3007 return nullptr;
3008 },
3009 nullptr));
3010
3011 for (int i = 0; i != 1000; ++i) {
3012 ASSERT_TRUE(android_run_on_all_threads([](void* arg) { return arg == nullptr; }, nullptr));
3013 }
3014
3015 void *retval;
3016 ASSERT_EQ(0, pthread_join(t, &retval));
3017 ASSERT_EQ(nullptr, retval);
3018#else
3019 GTEST_SKIP() << "bionic-only test";
3020#endif
3021}