blob: 973ca5340ae707417b4d699322969ae10956fbe4 [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>
Yabin Cui6b9c85b2018-01-23 12:56:18 -080041#include <android-base/strings.h>
Tom Cherryb8ab6182017-04-05 16:20:29 -070042
Yabin Cuic9a659c2015-11-05 15:36:08 -080043#include "private/bionic_constants.h"
Yabin Cui17393b02015-03-21 15:08:25 -070044#include "BionicDeathTest.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 Hughesbfeab1b2012-09-05 17:47:37 -070048TEST(pthread, pthread_key_create) {
49 pthread_key_t key;
Yi Kong32bc0fc2018-08-02 17:31:13 -070050 ASSERT_EQ(0, pthread_key_create(&key, nullptr));
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070051 ASSERT_EQ(0, pthread_key_delete(key));
52 // Can't delete a key that's already been deleted.
53 ASSERT_EQ(EINVAL, pthread_key_delete(key));
54}
Elliott Hughes4d014e12012-09-07 16:47:54 -070055
Dan Albertc4bcc752014-09-30 11:48:24 -070056TEST(pthread, pthread_keys_max) {
Yabin Cui6c238f22014-12-11 20:50:41 -080057 // POSIX says PTHREAD_KEYS_MAX should be at least _POSIX_THREAD_KEYS_MAX.
58 ASSERT_GE(PTHREAD_KEYS_MAX, _POSIX_THREAD_KEYS_MAX);
Dan Albertc4bcc752014-09-30 11:48:24 -070059}
Elliott Hughes718a5b52014-01-28 17:02:03 -080060
Yabin Cui6c238f22014-12-11 20:50:41 -080061TEST(pthread, sysconf_SC_THREAD_KEYS_MAX_eq_PTHREAD_KEYS_MAX) {
Dan Albertc4bcc752014-09-30 11:48:24 -070062 int sysconf_max = sysconf(_SC_THREAD_KEYS_MAX);
Yabin Cui6c238f22014-12-11 20:50:41 -080063 ASSERT_EQ(sysconf_max, PTHREAD_KEYS_MAX);
Dan Albertc4bcc752014-09-30 11:48:24 -070064}
65
66TEST(pthread, pthread_key_many_distinct) {
Yabin Cui6c238f22014-12-11 20:50:41 -080067 // As gtest uses pthread keys, we can't allocate exactly PTHREAD_KEYS_MAX
68 // pthread keys, but We should be able to allocate at least this many keys.
69 int nkeys = PTHREAD_KEYS_MAX / 2;
Dan Albertc4bcc752014-09-30 11:48:24 -070070 std::vector<pthread_key_t> keys;
71
Tom Cherryb8ab6182017-04-05 16:20:29 -070072 auto scope_guard = android::base::make_scope_guard([&keys] {
Elliott Hughes0b2acdf2015-10-02 18:25:19 -070073 for (const auto& key : keys) {
Dan Albertc4bcc752014-09-30 11:48:24 -070074 EXPECT_EQ(0, pthread_key_delete(key));
75 }
76 });
77
78 for (int i = 0; i < nkeys; ++i) {
79 pthread_key_t key;
Elliott Hughes61706932015-03-31 10:56:58 -070080 // If this fails, it's likely that LIBC_PTHREAD_KEY_RESERVED_COUNT is wrong.
Yi Kong32bc0fc2018-08-02 17:31:13 -070081 ASSERT_EQ(0, pthread_key_create(&key, nullptr)) << i << " of " << nkeys;
Dan Albertc4bcc752014-09-30 11:48:24 -070082 keys.push_back(key);
83 ASSERT_EQ(0, pthread_setspecific(key, reinterpret_cast<void*>(i)));
84 }
85
86 for (int i = keys.size() - 1; i >= 0; --i) {
87 ASSERT_EQ(reinterpret_cast<void*>(i), pthread_getspecific(keys.back()));
88 pthread_key_t key = keys.back();
89 keys.pop_back();
90 ASSERT_EQ(0, pthread_key_delete(key));
91 }
92}
93
Yabin Cui6c238f22014-12-11 20:50:41 -080094TEST(pthread, pthread_key_not_exceed_PTHREAD_KEYS_MAX) {
Elliott Hughes44b53ad2013-02-11 20:18:47 +000095 std::vector<pthread_key_t> keys;
Dan Albertc4bcc752014-09-30 11:48:24 -070096 int rv = 0;
Yabin Cui6c238f22014-12-11 20:50:41 -080097
98 // Pthread keys are used by gtest, so PTHREAD_KEYS_MAX should
99 // be more than we are allowed to allocate now.
100 for (int i = 0; i < PTHREAD_KEYS_MAX; i++) {
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000101 pthread_key_t key;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700102 rv = pthread_key_create(&key, nullptr);
Dan Albertc4bcc752014-09-30 11:48:24 -0700103 if (rv == EAGAIN) {
104 break;
105 }
106 EXPECT_EQ(0, rv);
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000107 keys.push_back(key);
108 }
109
Dan Albertc4bcc752014-09-30 11:48:24 -0700110 // Don't leak keys.
Elliott Hughes0b2acdf2015-10-02 18:25:19 -0700111 for (const auto& key : keys) {
Dan Albertc4bcc752014-09-30 11:48:24 -0700112 EXPECT_EQ(0, pthread_key_delete(key));
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000113 }
Dan Albertc4bcc752014-09-30 11:48:24 -0700114 keys.clear();
115
116 // We should have eventually reached the maximum number of keys and received
117 // EAGAIN.
118 ASSERT_EQ(EAGAIN, rv);
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000119}
120
Elliott Hughesebb770f2014-06-25 13:46:46 -0700121TEST(pthread, pthread_key_delete) {
122 void* expected = reinterpret_cast<void*>(1234);
123 pthread_key_t key;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700124 ASSERT_EQ(0, pthread_key_create(&key, nullptr));
Elliott Hughesebb770f2014-06-25 13:46:46 -0700125 ASSERT_EQ(0, pthread_setspecific(key, expected));
126 ASSERT_EQ(expected, pthread_getspecific(key));
127 ASSERT_EQ(0, pthread_key_delete(key));
Yi Kong32bc0fc2018-08-02 17:31:13 -0700128 // After deletion, pthread_getspecific returns nullptr.
129 ASSERT_EQ(nullptr, pthread_getspecific(key));
Elliott Hughesebb770f2014-06-25 13:46:46 -0700130 // And you can't use pthread_setspecific with the deleted key.
131 ASSERT_EQ(EINVAL, pthread_setspecific(key, expected));
132}
133
Elliott Hughes40a52172014-07-30 14:48:10 -0700134TEST(pthread, pthread_key_fork) {
135 void* expected = reinterpret_cast<void*>(1234);
136 pthread_key_t key;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700137 ASSERT_EQ(0, pthread_key_create(&key, nullptr));
Elliott Hughes40a52172014-07-30 14:48:10 -0700138 ASSERT_EQ(0, pthread_setspecific(key, expected));
139 ASSERT_EQ(expected, pthread_getspecific(key));
140
141 pid_t pid = fork();
142 ASSERT_NE(-1, pid) << strerror(errno);
143
144 if (pid == 0) {
145 // The surviving thread inherits all the forking thread's TLS values...
146 ASSERT_EQ(expected, pthread_getspecific(key));
147 _exit(99);
148 }
149
Elliott Hughes33697a02016-01-26 13:04:57 -0800150 AssertChildExited(pid, 99);
Elliott Hughes40a52172014-07-30 14:48:10 -0700151
152 ASSERT_EQ(expected, pthread_getspecific(key));
Dan Albert1d53ae22014-09-02 15:24:26 -0700153 ASSERT_EQ(0, pthread_key_delete(key));
Elliott Hughes40a52172014-07-30 14:48:10 -0700154}
155
156static void* DirtyKeyFn(void* key) {
157 return pthread_getspecific(*reinterpret_cast<pthread_key_t*>(key));
158}
159
160TEST(pthread, pthread_key_dirty) {
161 pthread_key_t key;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700162 ASSERT_EQ(0, pthread_key_create(&key, nullptr));
Elliott Hughes40a52172014-07-30 14:48:10 -0700163
Yabin Cuia36158a2015-11-16 21:06:16 -0800164 size_t stack_size = 640 * 1024;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700165 void* stack = mmap(nullptr, stack_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
Elliott Hughes40a52172014-07-30 14:48:10 -0700166 ASSERT_NE(MAP_FAILED, stack);
167 memset(stack, 0xff, stack_size);
168
169 pthread_attr_t attr;
170 ASSERT_EQ(0, pthread_attr_init(&attr));
171 ASSERT_EQ(0, pthread_attr_setstack(&attr, stack, stack_size));
172
173 pthread_t t;
174 ASSERT_EQ(0, pthread_create(&t, &attr, DirtyKeyFn, &key));
175
176 void* result;
177 ASSERT_EQ(0, pthread_join(t, &result));
178 ASSERT_EQ(nullptr, result); // Not ~0!
179
180 ASSERT_EQ(0, munmap(stack, stack_size));
Dan Albert1d53ae22014-09-02 15:24:26 -0700181 ASSERT_EQ(0, pthread_key_delete(key));
Elliott Hughes40a52172014-07-30 14:48:10 -0700182}
183
Yabin Cui5ddbb3f2015-03-05 20:35:32 -0800184TEST(pthread, static_pthread_key_used_before_creation) {
185#if defined(__BIONIC__)
186 // See http://b/19625804. The bug is about a static/global pthread key being used before creation.
187 // So here tests if the static/global default value 0 can be detected as invalid key.
188 static pthread_key_t key;
189 ASSERT_EQ(nullptr, pthread_getspecific(key));
190 ASSERT_EQ(EINVAL, pthread_setspecific(key, nullptr));
191 ASSERT_EQ(EINVAL, pthread_key_delete(key));
192#else
193 GTEST_LOG_(INFO) << "This test tests bionic pthread key implementation detail.\n";
194#endif
195}
196
Elliott Hughes4d014e12012-09-07 16:47:54 -0700197static void* IdFn(void* arg) {
198 return arg;
199}
200
Yabin Cui63481602014-12-01 17:41:04 -0800201class SpinFunctionHelper {
202 public:
203 SpinFunctionHelper() {
204 SpinFunctionHelper::spin_flag_ = true;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400205 }
Elliott Hughes0bd9d132017-11-02 13:11:13 -0700206
Yabin Cui63481602014-12-01 17:41:04 -0800207 ~SpinFunctionHelper() {
208 UnSpin();
209 }
Elliott Hughes0bd9d132017-11-02 13:11:13 -0700210
Yabin Cui63481602014-12-01 17:41:04 -0800211 auto GetFunction() -> void* (*)(void*) {
212 return SpinFunctionHelper::SpinFn;
213 }
214
215 void UnSpin() {
216 SpinFunctionHelper::spin_flag_ = false;
217 }
218
219 private:
220 static void* SpinFn(void*) {
221 while (spin_flag_) {}
Yi Kong32bc0fc2018-08-02 17:31:13 -0700222 return nullptr;
Yabin Cui63481602014-12-01 17:41:04 -0800223 }
Yabin Cuia36158a2015-11-16 21:06:16 -0800224 static std::atomic<bool> spin_flag_;
Yabin Cui63481602014-12-01 17:41:04 -0800225};
226
227// It doesn't matter if spin_flag_ is used in several tests,
228// because it is always set to false after each test. Each thread
229// loops on spin_flag_ can find it becomes false at some time.
Yabin Cuia36158a2015-11-16 21:06:16 -0800230std::atomic<bool> SpinFunctionHelper::spin_flag_;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400231
Elliott Hughes4d014e12012-09-07 16:47:54 -0700232static void* JoinFn(void* arg) {
Yi Kong32bc0fc2018-08-02 17:31:13 -0700233 return reinterpret_cast<void*>(pthread_join(reinterpret_cast<pthread_t>(arg), nullptr));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700234}
235
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400236static void AssertDetached(pthread_t t, bool is_detached) {
237 pthread_attr_t attr;
238 ASSERT_EQ(0, pthread_getattr_np(t, &attr));
239 int detach_state;
240 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &detach_state));
241 pthread_attr_destroy(&attr);
242 ASSERT_EQ(is_detached, (detach_state == PTHREAD_CREATE_DETACHED));
243}
244
Elliott Hughes7484c212017-02-02 02:41:38 +0000245static void MakeDeadThread(pthread_t& t) {
Yi Kong32bc0fc2018-08-02 17:31:13 -0700246 ASSERT_EQ(0, pthread_create(&t, nullptr, IdFn, nullptr));
247 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes7484c212017-02-02 02:41:38 +0000248}
249
Elliott Hughes4d014e12012-09-07 16:47:54 -0700250TEST(pthread, pthread_create) {
251 void* expected_result = reinterpret_cast<void*>(123);
252 // Can we create a thread?
253 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700254 ASSERT_EQ(0, pthread_create(&t, nullptr, IdFn, expected_result));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700255 // If we join, do we get the expected value back?
256 void* result;
257 ASSERT_EQ(0, pthread_join(t, &result));
258 ASSERT_EQ(expected_result, result);
259}
260
Elliott Hughes3e898472013-02-12 16:40:24 +0000261TEST(pthread, pthread_create_EAGAIN) {
262 pthread_attr_t attributes;
263 ASSERT_EQ(0, pthread_attr_init(&attributes));
264 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, static_cast<size_t>(-1) & ~(getpagesize() - 1)));
265
266 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700267 ASSERT_EQ(EAGAIN, pthread_create(&t, &attributes, IdFn, nullptr));
Elliott Hughes3e898472013-02-12 16:40:24 +0000268}
269
Elliott Hughes4d014e12012-09-07 16:47:54 -0700270TEST(pthread, pthread_no_join_after_detach) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700271 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800272
Elliott Hughes4d014e12012-09-07 16:47:54 -0700273 pthread_t t1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700274 ASSERT_EQ(0, pthread_create(&t1, nullptr, spin_helper.GetFunction(), nullptr));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700275
276 // After a pthread_detach...
277 ASSERT_EQ(0, pthread_detach(t1));
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400278 AssertDetached(t1, true);
Elliott Hughes4d014e12012-09-07 16:47:54 -0700279
280 // ...pthread_join should fail.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700281 ASSERT_EQ(EINVAL, pthread_join(t1, nullptr));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700282}
283
284TEST(pthread, pthread_no_op_detach_after_join) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700285 SpinFunctionHelper spin_helper;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400286
Elliott Hughes4d014e12012-09-07 16:47:54 -0700287 pthread_t t1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700288 ASSERT_EQ(0, pthread_create(&t1, nullptr, spin_helper.GetFunction(), nullptr));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700289
290 // If thread 2 is already waiting to join thread 1...
291 pthread_t t2;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700292 ASSERT_EQ(0, pthread_create(&t2, nullptr, JoinFn, reinterpret_cast<void*>(t1)));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700293
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400294 sleep(1); // (Give t2 a chance to call pthread_join.)
Elliott Hughes4d014e12012-09-07 16:47:54 -0700295
Yabin Cuibbb04322015-03-19 15:19:25 -0700296#if defined(__BIONIC__)
297 ASSERT_EQ(EINVAL, pthread_detach(t1));
298#else
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400299 ASSERT_EQ(0, pthread_detach(t1));
Yabin Cuibbb04322015-03-19 15:19:25 -0700300#endif
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400301 AssertDetached(t1, false);
302
Elliott Hughes725b2a92016-03-23 11:20:47 -0700303 spin_helper.UnSpin();
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400304
305 // ...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 -0700306 void* join_result;
307 ASSERT_EQ(0, pthread_join(t2, &join_result));
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700308 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700309}
Elliott Hughes14f19592012-10-29 10:19:44 -0700310
311TEST(pthread, pthread_join_self) {
Yi Kong32bc0fc2018-08-02 17:31:13 -0700312 ASSERT_EQ(EDEADLK, pthread_join(pthread_self(), nullptr));
Elliott Hughes14f19592012-10-29 10:19:44 -0700313}
Elliott Hughes4f251be2012-11-01 16:33:29 -0700314
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800315struct TestBug37410 {
316 pthread_t main_thread;
317 pthread_mutex_t mutex;
Elliott Hughes4f251be2012-11-01 16:33:29 -0700318
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800319 static void main() {
320 TestBug37410 data;
321 data.main_thread = pthread_self();
Yi Kong32bc0fc2018-08-02 17:31:13 -0700322 ASSERT_EQ(0, pthread_mutex_init(&data.mutex, nullptr));
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800323 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
324
325 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700326 ASSERT_EQ(0, pthread_create(&t, nullptr, TestBug37410::thread_fn, reinterpret_cast<void*>(&data)));
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800327
328 // Wait for the thread to be running...
329 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
330 ASSERT_EQ(0, pthread_mutex_unlock(&data.mutex));
331
332 // ...and exit.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700333 pthread_exit(nullptr);
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800334 }
335
336 private:
337 static void* thread_fn(void* arg) {
338 TestBug37410* data = reinterpret_cast<TestBug37410*>(arg);
339
Evgenii Stepanov352853a2019-02-05 17:37:37 -0800340 // Unlocking data->mutex will cause the main thread to exit, invalidating *data. Save the handle.
341 pthread_t main_thread = data->main_thread;
342
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800343 // Let the main thread know we're running.
344 pthread_mutex_unlock(&data->mutex);
345
346 // And wait for the main thread to exit.
Evgenii Stepanov352853a2019-02-05 17:37:37 -0800347 pthread_join(main_thread, nullptr);
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800348
Yi Kong32bc0fc2018-08-02 17:31:13 -0700349 return nullptr;
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800350 }
351};
Elliott Hughes4f251be2012-11-01 16:33:29 -0700352
Elliott Hughes7fd803c2013-02-14 16:33:52 -0800353// Even though this isn't really a death test, we have to say "DeathTest" here so gtest knows to
354// run this test (which exits normally) in its own process.
Yabin Cui9df70402014-11-05 18:01:01 -0800355
356class pthread_DeathTest : public BionicDeathTest {};
357
358TEST_F(pthread_DeathTest, pthread_bug_37410) {
Elliott Hughes4f251be2012-11-01 16:33:29 -0700359 // http://code.google.com/p/android/issues/detail?id=37410
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800360 ASSERT_EXIT(TestBug37410::main(), ::testing::ExitedWithCode(0), "");
Elliott Hughes4f251be2012-11-01 16:33:29 -0700361}
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800362
363static void* SignalHandlerFn(void* arg) {
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800364 sigset64_t wait_set;
365 sigfillset64(&wait_set);
366 return reinterpret_cast<void*>(sigwait64(&wait_set, reinterpret_cast<int*>(arg)));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800367}
368
369TEST(pthread, pthread_sigmask) {
Elliott Hughes19e62322013-10-15 11:23:57 -0700370 // Check that SIGUSR1 isn't blocked.
371 sigset_t original_set;
372 sigemptyset(&original_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700373 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, nullptr, &original_set));
Elliott Hughes19e62322013-10-15 11:23:57 -0700374 ASSERT_FALSE(sigismember(&original_set, SIGUSR1));
375
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800376 // Block SIGUSR1.
377 sigset_t set;
378 sigemptyset(&set);
379 sigaddset(&set, SIGUSR1);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700380 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, &set, nullptr));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800381
Elliott Hughes19e62322013-10-15 11:23:57 -0700382 // Check that SIGUSR1 is blocked.
383 sigset_t final_set;
384 sigemptyset(&final_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700385 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, nullptr, &final_set));
Elliott Hughes19e62322013-10-15 11:23:57 -0700386 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
387 // ...and that sigprocmask agrees with pthread_sigmask.
388 sigemptyset(&final_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700389 ASSERT_EQ(0, sigprocmask(SIG_BLOCK, nullptr, &final_set));
Elliott Hughes19e62322013-10-15 11:23:57 -0700390 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
391
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800392 // Spawn a thread that calls sigwait and tells us what it received.
393 pthread_t signal_thread;
394 int received_signal = -1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700395 ASSERT_EQ(0, pthread_create(&signal_thread, nullptr, SignalHandlerFn, &received_signal));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800396
397 // Send that thread SIGUSR1.
398 pthread_kill(signal_thread, SIGUSR1);
399
400 // See what it got.
401 void* join_result;
402 ASSERT_EQ(0, pthread_join(signal_thread, &join_result));
403 ASSERT_EQ(SIGUSR1, received_signal);
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700404 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
Elliott Hughes19e62322013-10-15 11:23:57 -0700405
406 // Restore the original signal mask.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700407 ASSERT_EQ(0, pthread_sigmask(SIG_SETMASK, &original_set, nullptr));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800408}
Elliott Hughes5e3fc432013-02-11 16:36:48 -0800409
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800410TEST(pthread, pthread_sigmask64_SIGTRMIN) {
411 // Check that SIGRTMIN isn't blocked.
412 sigset64_t original_set;
413 sigemptyset64(&original_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700414 ASSERT_EQ(0, pthread_sigmask64(SIG_BLOCK, nullptr, &original_set));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800415 ASSERT_FALSE(sigismember64(&original_set, SIGRTMIN));
416
417 // Block SIGRTMIN.
418 sigset64_t set;
419 sigemptyset64(&set);
420 sigaddset64(&set, SIGRTMIN);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700421 ASSERT_EQ(0, pthread_sigmask64(SIG_BLOCK, &set, nullptr));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800422
423 // Check that SIGRTMIN is blocked.
424 sigset64_t final_set;
425 sigemptyset64(&final_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700426 ASSERT_EQ(0, pthread_sigmask64(SIG_BLOCK, nullptr, &final_set));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800427 ASSERT_TRUE(sigismember64(&final_set, SIGRTMIN));
428 // ...and that sigprocmask64 agrees with pthread_sigmask64.
429 sigemptyset64(&final_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700430 ASSERT_EQ(0, sigprocmask64(SIG_BLOCK, nullptr, &final_set));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800431 ASSERT_TRUE(sigismember64(&final_set, SIGRTMIN));
432
433 // Spawn a thread that calls sigwait64 and tells us what it received.
434 pthread_t signal_thread;
435 int received_signal = -1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700436 ASSERT_EQ(0, pthread_create(&signal_thread, nullptr, SignalHandlerFn, &received_signal));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800437
438 // Send that thread SIGRTMIN.
439 pthread_kill(signal_thread, SIGRTMIN);
440
441 // See what it got.
442 void* join_result;
443 ASSERT_EQ(0, pthread_join(signal_thread, &join_result));
444 ASSERT_EQ(SIGRTMIN, received_signal);
445 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
446
447 // Restore the original signal mask.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700448 ASSERT_EQ(0, pthread_sigmask64(SIG_SETMASK, &original_set, nullptr));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800449}
450
Elliott Hughes725b2a92016-03-23 11:20:47 -0700451static void test_pthread_setname_np__pthread_getname_np(pthread_t t) {
452 ASSERT_EQ(0, pthread_setname_np(t, "short"));
453 char name[32];
454 ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name)));
455 ASSERT_STREQ("short", name);
456
Elliott Hughesd1aea302015-04-25 10:05:24 -0700457 // The limit is 15 characters --- the kernel's buffer is 16, but includes a NUL.
Elliott Hughes725b2a92016-03-23 11:20:47 -0700458 ASSERT_EQ(0, pthread_setname_np(t, "123456789012345"));
459 ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name)));
460 ASSERT_STREQ("123456789012345", name);
461
462 ASSERT_EQ(ERANGE, pthread_setname_np(t, "1234567890123456"));
463
464 // The passed-in buffer should be at least 16 bytes.
465 ASSERT_EQ(0, pthread_getname_np(t, name, 16));
466 ASSERT_EQ(ERANGE, pthread_getname_np(t, name, 15));
Elliott Hughes3e898472013-02-12 16:40:24 +0000467}
468
Elliott Hughes725b2a92016-03-23 11:20:47 -0700469TEST(pthread, pthread_setname_np__pthread_getname_np__self) {
470 test_pthread_setname_np__pthread_getname_np(pthread_self());
Elliott Hughes3e898472013-02-12 16:40:24 +0000471}
472
Elliott Hughes725b2a92016-03-23 11:20:47 -0700473TEST(pthread, pthread_setname_np__pthread_getname_np__other) {
474 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800475
Elliott Hughes725b2a92016-03-23 11:20:47 -0700476 pthread_t t;
Elliott Hughes4d098ca2016-04-11 12:43:05 -0700477 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
478 test_pthread_setname_np__pthread_getname_np(t);
479 spin_helper.UnSpin();
480 ASSERT_EQ(0, pthread_join(t, nullptr));
481}
482
483// http://b/28051133: a kernel misfeature means that you can't change the
484// name of another thread if you've set PR_SET_DUMPABLE to 0.
485TEST(pthread, pthread_setname_np__pthread_getname_np__other_PR_SET_DUMPABLE) {
486 ASSERT_EQ(0, prctl(PR_SET_DUMPABLE, 0)) << strerror(errno);
487
488 SpinFunctionHelper spin_helper;
489
490 pthread_t t;
491 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
Elliott Hughes725b2a92016-03-23 11:20:47 -0700492 test_pthread_setname_np__pthread_getname_np(t);
493 spin_helper.UnSpin();
494 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes3e898472013-02-12 16:40:24 +0000495}
496
Elliott Hughes11859d42017-02-13 17:59:29 -0800497TEST_F(pthread_DeathTest, pthread_setname_np__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000498 pthread_t dead_thread;
499 MakeDeadThread(dead_thread);
500
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800501 EXPECT_DEATH(pthread_setname_np(dead_thread, "short 3"),
502 "invalid pthread_t (.*) passed to pthread_setname_np");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800503}
504
505TEST_F(pthread_DeathTest, pthread_setname_np__null_thread) {
506 pthread_t null_thread = 0;
507 EXPECT_EQ(ENOENT, pthread_setname_np(null_thread, "short 3"));
Elliott Hughes11859d42017-02-13 17:59:29 -0800508}
509
510TEST_F(pthread_DeathTest, pthread_getname_np__no_such_thread) {
511 pthread_t dead_thread;
512 MakeDeadThread(dead_thread);
513
Elliott Hughesbcb15292017-02-07 21:05:30 +0000514 char name[64];
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800515 EXPECT_DEATH(pthread_getname_np(dead_thread, name, sizeof(name)),
516 "invalid pthread_t (.*) passed to pthread_getname_np");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800517}
518
519TEST_F(pthread_DeathTest, pthread_getname_np__null_thread) {
520 pthread_t null_thread = 0;
521
522 char name[64];
523 EXPECT_EQ(ENOENT, pthread_getname_np(null_thread, name, sizeof(name)));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000524}
525
Elliott Hughes9d23e042013-02-15 19:21:51 -0800526TEST(pthread, pthread_kill__0) {
527 // Signal 0 just tests that the thread exists, so it's safe to call on ourselves.
528 ASSERT_EQ(0, pthread_kill(pthread_self(), 0));
529}
530
531TEST(pthread, pthread_kill__invalid_signal) {
532 ASSERT_EQ(EINVAL, pthread_kill(pthread_self(), -1));
533}
534
Elliott Hughesfae89fc2013-02-21 11:22:23 -0800535static void pthread_kill__in_signal_handler_helper(int signal_number) {
536 static int count = 0;
537 ASSERT_EQ(SIGALRM, signal_number);
538 if (++count == 1) {
539 // Can we call pthread_kill from a signal handler?
540 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
541 }
542}
543
544TEST(pthread, pthread_kill__in_signal_handler) {
Elliott Hughes4b558f52014-03-04 15:58:02 -0800545 ScopedSignalHandler ssh(SIGALRM, pthread_kill__in_signal_handler_helper);
Elliott Hughesfae89fc2013-02-21 11:22:23 -0800546 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
547}
548
Josh Gaoddf757e2018-10-17 15:23:03 -0700549TEST(pthread, pthread_kill__exited_thread) {
550 static std::promise<pid_t> tid_promise;
551 pthread_t thread;
552 ASSERT_EQ(0, pthread_create(&thread, nullptr,
553 [](void*) -> void* {
554 tid_promise.set_value(gettid());
555 return nullptr;
556 },
557 nullptr));
558
559 pid_t tid = tid_promise.get_future().get();
560 while (TEMP_FAILURE_RETRY(syscall(__NR_tgkill, getpid(), tid, 0)) != -1) {
561 continue;
562 }
563 ASSERT_EQ(ESRCH, errno);
564
565 ASSERT_EQ(ESRCH, pthread_kill(thread, 0));
566}
567
Elliott Hughes11859d42017-02-13 17:59:29 -0800568TEST_F(pthread_DeathTest, pthread_detach__no_such_thread) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000569 pthread_t dead_thread;
570 MakeDeadThread(dead_thread);
571
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800572 EXPECT_DEATH(pthread_detach(dead_thread),
573 "invalid pthread_t (.*) passed to pthread_detach");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800574}
575
576TEST_F(pthread_DeathTest, pthread_detach__null_thread) {
577 pthread_t null_thread = 0;
578 EXPECT_EQ(ESRCH, pthread_detach(null_thread));
Elliott Hughes7484c212017-02-02 02:41:38 +0000579}
580
Jeff Hao9b06cc32013-08-15 14:51:16 -0700581TEST(pthread, pthread_getcpuclockid__clock_gettime) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700582 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800583
Jeff Hao9b06cc32013-08-15 14:51:16 -0700584 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700585 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
Jeff Hao9b06cc32013-08-15 14:51:16 -0700586
587 clockid_t c;
588 ASSERT_EQ(0, pthread_getcpuclockid(t, &c));
589 timespec ts;
590 ASSERT_EQ(0, clock_gettime(c, &ts));
Elliott Hughes725b2a92016-03-23 11:20:47 -0700591 spin_helper.UnSpin();
Yabin Cuia36158a2015-11-16 21:06:16 -0800592 ASSERT_EQ(0, pthread_join(t, nullptr));
Jeff Hao9b06cc32013-08-15 14:51:16 -0700593}
594
Elliott Hughes11859d42017-02-13 17:59:29 -0800595TEST_F(pthread_DeathTest, pthread_getcpuclockid__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000596 pthread_t dead_thread;
597 MakeDeadThread(dead_thread);
598
599 clockid_t c;
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800600 EXPECT_DEATH(pthread_getcpuclockid(dead_thread, &c),
601 "invalid pthread_t (.*) passed to pthread_getcpuclockid");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800602}
603
604TEST_F(pthread_DeathTest, pthread_getcpuclockid__null_thread) {
605 pthread_t null_thread = 0;
606 clockid_t c;
607 EXPECT_EQ(ESRCH, pthread_getcpuclockid(null_thread, &c));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000608}
609
Elliott Hughes11859d42017-02-13 17:59:29 -0800610TEST_F(pthread_DeathTest, pthread_getschedparam__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000611 pthread_t dead_thread;
612 MakeDeadThread(dead_thread);
613
614 int policy;
615 sched_param param;
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800616 EXPECT_DEATH(pthread_getschedparam(dead_thread, &policy, &param),
617 "invalid pthread_t (.*) passed to pthread_getschedparam");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800618}
619
620TEST_F(pthread_DeathTest, pthread_getschedparam__null_thread) {
621 pthread_t null_thread = 0;
622 int policy;
623 sched_param param;
624 EXPECT_EQ(ESRCH, pthread_getschedparam(null_thread, &policy, &param));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000625}
626
Elliott Hughes11859d42017-02-13 17:59:29 -0800627TEST_F(pthread_DeathTest, pthread_setschedparam__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000628 pthread_t dead_thread;
629 MakeDeadThread(dead_thread);
630
631 int policy = 0;
632 sched_param param;
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800633 EXPECT_DEATH(pthread_setschedparam(dead_thread, policy, &param),
634 "invalid pthread_t (.*) passed to pthread_setschedparam");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800635}
636
637TEST_F(pthread_DeathTest, pthread_setschedparam__null_thread) {
638 pthread_t null_thread = 0;
639 int policy = 0;
640 sched_param param;
641 EXPECT_EQ(ESRCH, pthread_setschedparam(null_thread, policy, &param));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000642}
643
Elliott Hughesdff08ce2017-10-16 09:58:45 -0700644TEST_F(pthread_DeathTest, pthread_setschedprio__no_such_thread) {
645 pthread_t dead_thread;
646 MakeDeadThread(dead_thread);
647
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800648 EXPECT_DEATH(pthread_setschedprio(dead_thread, 123),
649 "invalid pthread_t (.*) passed to pthread_setschedprio");
Elliott Hughesdff08ce2017-10-16 09:58:45 -0700650}
651
652TEST_F(pthread_DeathTest, pthread_setschedprio__null_thread) {
653 pthread_t null_thread = 0;
654 EXPECT_EQ(ESRCH, pthread_setschedprio(null_thread, 123));
655}
656
Elliott Hughes11859d42017-02-13 17:59:29 -0800657TEST_F(pthread_DeathTest, pthread_join__no_such_thread) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000658 pthread_t dead_thread;
659 MakeDeadThread(dead_thread);
660
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800661 EXPECT_DEATH(pthread_join(dead_thread, nullptr),
662 "invalid pthread_t (.*) passed to pthread_join");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800663}
664
665TEST_F(pthread_DeathTest, pthread_join__null_thread) {
666 pthread_t null_thread = 0;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700667 EXPECT_EQ(ESRCH, pthread_join(null_thread, nullptr));
Elliott Hughes7484c212017-02-02 02:41:38 +0000668}
669
Elliott Hughes11859d42017-02-13 17:59:29 -0800670TEST_F(pthread_DeathTest, pthread_kill__no_such_thread) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000671 pthread_t dead_thread;
672 MakeDeadThread(dead_thread);
673
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800674 EXPECT_DEATH(pthread_kill(dead_thread, 0),
675 "invalid pthread_t (.*) passed to pthread_kill");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800676}
677
678TEST_F(pthread_DeathTest, pthread_kill__null_thread) {
679 pthread_t null_thread = 0;
680 EXPECT_EQ(ESRCH, pthread_kill(null_thread, 0));
Elliott Hughes7484c212017-02-02 02:41:38 +0000681}
682
msg5550f020d12013-06-06 14:59:28 -0400683TEST(pthread, pthread_join__multijoin) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700684 SpinFunctionHelper spin_helper;
msg5550f020d12013-06-06 14:59:28 -0400685
686 pthread_t t1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700687 ASSERT_EQ(0, pthread_create(&t1, nullptr, spin_helper.GetFunction(), nullptr));
msg5550f020d12013-06-06 14:59:28 -0400688
689 pthread_t t2;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700690 ASSERT_EQ(0, pthread_create(&t2, nullptr, JoinFn, reinterpret_cast<void*>(t1)));
msg5550f020d12013-06-06 14:59:28 -0400691
692 sleep(1); // (Give t2 a chance to call pthread_join.)
693
694 // Multiple joins to the same thread should fail.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700695 ASSERT_EQ(EINVAL, pthread_join(t1, nullptr));
msg5550f020d12013-06-06 14:59:28 -0400696
Elliott Hughes725b2a92016-03-23 11:20:47 -0700697 spin_helper.UnSpin();
msg5550f020d12013-06-06 14:59:28 -0400698
699 // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes).
700 void* join_result;
701 ASSERT_EQ(0, pthread_join(t2, &join_result));
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700702 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
msg5550f020d12013-06-06 14:59:28 -0400703}
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700704
Elliott Hughes70b24b12013-11-15 11:51:07 -0800705TEST(pthread, pthread_join__race) {
706 // http://b/11693195 --- pthread_join could return before the thread had actually exited.
707 // If the joiner unmapped the thread's stack, that could lead to SIGSEGV in the thread.
708 for (size_t i = 0; i < 1024; ++i) {
Yabin Cuia36158a2015-11-16 21:06:16 -0800709 size_t stack_size = 640*1024;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700710 void* stack = mmap(nullptr, stack_size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
Elliott Hughes70b24b12013-11-15 11:51:07 -0800711
712 pthread_attr_t a;
713 pthread_attr_init(&a);
714 pthread_attr_setstack(&a, stack, stack_size);
715
716 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700717 ASSERT_EQ(0, pthread_create(&t, &a, IdFn, nullptr));
718 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes70b24b12013-11-15 11:51:07 -0800719 ASSERT_EQ(0, munmap(stack, stack_size));
720 }
721}
722
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700723static void* GetActualGuardSizeFn(void* arg) {
724 pthread_attr_t attributes;
725 pthread_getattr_np(pthread_self(), &attributes);
726 pthread_attr_getguardsize(&attributes, reinterpret_cast<size_t*>(arg));
Yi Kong32bc0fc2018-08-02 17:31:13 -0700727 return nullptr;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700728}
729
730static size_t GetActualGuardSize(const pthread_attr_t& attributes) {
731 size_t result;
732 pthread_t t;
733 pthread_create(&t, &attributes, GetActualGuardSizeFn, &result);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700734 pthread_join(t, nullptr);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700735 return result;
736}
737
738static void* GetActualStackSizeFn(void* arg) {
739 pthread_attr_t attributes;
740 pthread_getattr_np(pthread_self(), &attributes);
741 pthread_attr_getstacksize(&attributes, reinterpret_cast<size_t*>(arg));
Yi Kong32bc0fc2018-08-02 17:31:13 -0700742 return nullptr;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700743}
744
745static size_t GetActualStackSize(const pthread_attr_t& attributes) {
746 size_t result;
747 pthread_t t;
748 pthread_create(&t, &attributes, GetActualStackSizeFn, &result);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700749 pthread_join(t, nullptr);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700750 return result;
751}
752
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700753TEST(pthread, pthread_attr_setguardsize_tiny) {
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700754 pthread_attr_t attributes;
755 ASSERT_EQ(0, pthread_attr_init(&attributes));
756
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700757 // No such thing as too small: will be rounded up to one page by pthread_create.
758 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 128));
759 size_t guard_size;
760 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
761 ASSERT_EQ(128U, guard_size);
762 ASSERT_EQ(4096U, GetActualGuardSize(attributes));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700763}
764
765TEST(pthread, pthread_attr_setguardsize_reasonable) {
766 pthread_attr_t attributes;
767 ASSERT_EQ(0, pthread_attr_init(&attributes));
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700768
769 // Large enough and a multiple of the page size.
770 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700771 size_t guard_size;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700772 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
773 ASSERT_EQ(32*1024U, guard_size);
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700774 ASSERT_EQ(32*1024U, GetActualGuardSize(attributes));
775}
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700776
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700777TEST(pthread, pthread_attr_setguardsize_needs_rounding) {
778 pthread_attr_t attributes;
779 ASSERT_EQ(0, pthread_attr_init(&attributes));
780
781 // Large enough but not a multiple of the page size.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700782 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024 + 1));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700783 size_t guard_size;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700784 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
785 ASSERT_EQ(32*1024U + 1, guard_size);
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700786 ASSERT_EQ(36*1024U, GetActualGuardSize(attributes));
787}
788
789TEST(pthread, pthread_attr_setguardsize_enormous) {
790 pthread_attr_t attributes;
791 ASSERT_EQ(0, pthread_attr_init(&attributes));
792
793 // Larger than the stack itself. (Historically we mistakenly carved
794 // the guard out of the stack itself, rather than adding it after the
795 // end.)
796 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024*1024));
797 size_t guard_size;
798 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
799 ASSERT_EQ(32*1024*1024U, guard_size);
800 ASSERT_EQ(32*1024*1024U, GetActualGuardSize(attributes));
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700801}
802
803TEST(pthread, pthread_attr_setstacksize) {
804 pthread_attr_t attributes;
805 ASSERT_EQ(0, pthread_attr_init(&attributes));
806
807 // Get the default stack size.
808 size_t default_stack_size;
809 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &default_stack_size));
810
811 // Too small.
812 ASSERT_EQ(EINVAL, pthread_attr_setstacksize(&attributes, 128));
813 size_t stack_size;
814 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
815 ASSERT_EQ(default_stack_size, stack_size);
816 ASSERT_GE(GetActualStackSize(attributes), default_stack_size);
817
Yabin Cui917d3902015-01-08 12:32:42 -0800818 // Large enough and a multiple of the page size; may be rounded up by pthread_create.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700819 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024));
820 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
821 ASSERT_EQ(32*1024U, stack_size);
Yabin Cui917d3902015-01-08 12:32:42 -0800822 ASSERT_GE(GetActualStackSize(attributes), 32*1024U);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700823
Yabin Cui917d3902015-01-08 12:32:42 -0800824 // Large enough but not aligned; will be rounded up by pthread_create.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700825 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024 + 1));
826 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
827 ASSERT_EQ(32*1024U + 1, stack_size);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800828#if defined(__BIONIC__)
Yabin Cui917d3902015-01-08 12:32:42 -0800829 ASSERT_GT(GetActualStackSize(attributes), 32*1024U + 1);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800830#else // __BIONIC__
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700831 // glibc rounds down, in violation of POSIX. They document this in their BUGS section.
832 ASSERT_EQ(GetActualStackSize(attributes), 32*1024U);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800833#endif // __BIONIC__
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700834}
Elliott Hughesc3f11402013-10-30 14:40:09 -0700835
Yabin Cui76615da2015-03-17 14:22:09 -0700836TEST(pthread, pthread_rwlockattr_smoke) {
837 pthread_rwlockattr_t attr;
838 ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
839
840 int pshared_value_array[] = {PTHREAD_PROCESS_PRIVATE, PTHREAD_PROCESS_SHARED};
841 for (size_t i = 0; i < sizeof(pshared_value_array) / sizeof(pshared_value_array[0]); ++i) {
842 ASSERT_EQ(0, pthread_rwlockattr_setpshared(&attr, pshared_value_array[i]));
843 int pshared;
844 ASSERT_EQ(0, pthread_rwlockattr_getpshared(&attr, &pshared));
845 ASSERT_EQ(pshared_value_array[i], pshared);
846 }
847
848 int kind_array[] = {PTHREAD_RWLOCK_PREFER_READER_NP,
849 PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP};
850 for (size_t i = 0; i < sizeof(kind_array) / sizeof(kind_array[0]); ++i) {
851 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_array[i]));
852 int kind;
853 ASSERT_EQ(0, pthread_rwlockattr_getkind_np(&attr, &kind));
854 ASSERT_EQ(kind_array[i], kind);
855 }
856
857 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
858}
859
860TEST(pthread, pthread_rwlock_init_same_as_PTHREAD_RWLOCK_INITIALIZER) {
861 pthread_rwlock_t lock1 = PTHREAD_RWLOCK_INITIALIZER;
862 pthread_rwlock_t lock2;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700863 ASSERT_EQ(0, pthread_rwlock_init(&lock2, nullptr));
Yabin Cui76615da2015-03-17 14:22:09 -0700864 ASSERT_EQ(0, memcmp(&lock1, &lock2, sizeof(lock1)));
865}
866
Elliott Hughesc3f11402013-10-30 14:40:09 -0700867TEST(pthread, pthread_rwlock_smoke) {
868 pthread_rwlock_t l;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700869 ASSERT_EQ(0, pthread_rwlock_init(&l, nullptr));
Elliott Hughesc3f11402013-10-30 14:40:09 -0700870
Calin Juravle76f352e2014-05-19 13:41:10 +0100871 // Single read lock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700872 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
873 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
874
Calin Juravle76f352e2014-05-19 13:41:10 +0100875 // Multiple read lock
876 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
877 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
878 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
879 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
880
881 // Write lock
Calin Juravle92687e42014-05-22 19:21:22 +0100882 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
883 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100884
885 // Try writer lock
886 ASSERT_EQ(0, pthread_rwlock_trywrlock(&l));
887 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
888 ASSERT_EQ(EBUSY, pthread_rwlock_tryrdlock(&l));
889 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
890
891 // Try reader lock
892 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
893 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
894 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
895 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
896 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
897
898 // Try writer lock after unlock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700899 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
900 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
901
Calin Juravle76f352e2014-05-19 13:41:10 +0100902 // EDEADLK in "read after write"
903 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
904 ASSERT_EQ(EDEADLK, pthread_rwlock_rdlock(&l));
905 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
906
907 // EDEADLK in "write after write"
908 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
909 ASSERT_EQ(EDEADLK, pthread_rwlock_wrlock(&l));
910 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100911
Elliott Hughesc3f11402013-10-30 14:40:09 -0700912 ASSERT_EQ(0, pthread_rwlock_destroy(&l));
913}
914
Yabin Cui08ee8d22015-02-11 17:04:36 -0800915struct RwlockWakeupHelperArg {
916 pthread_rwlock_t lock;
917 enum Progress {
918 LOCK_INITIALIZED,
919 LOCK_WAITING,
920 LOCK_RELEASED,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800921 LOCK_ACCESSED,
922 LOCK_TIMEDOUT,
Yabin Cui08ee8d22015-02-11 17:04:36 -0800923 };
924 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -0700925 std::atomic<pid_t> tid;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800926 std::function<int (pthread_rwlock_t*)> trylock_function;
927 std::function<int (pthread_rwlock_t*)> lock_function;
928 std::function<int (pthread_rwlock_t*, const timespec*)> timed_lock_function;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -0800929 clockid_t clock;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800930};
931
Yabin Cuic9a659c2015-11-05 15:36:08 -0800932static void pthread_rwlock_wakeup_helper(RwlockWakeupHelperArg* arg) {
Yabin Cuif7969852015-04-02 17:47:48 -0700933 arg->tid = gettid();
Yabin Cui08ee8d22015-02-11 17:04:36 -0800934 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
935 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
936
Yabin Cuic9a659c2015-11-05 15:36:08 -0800937 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
938 ASSERT_EQ(0, arg->lock_function(&arg->lock));
Yabin Cui08ee8d22015-02-11 17:04:36 -0800939 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_RELEASED, arg->progress);
940 ASSERT_EQ(0, pthread_rwlock_unlock(&arg->lock));
941
942 arg->progress = RwlockWakeupHelperArg::LOCK_ACCESSED;
943}
944
Yabin Cuic9a659c2015-11-05 15:36:08 -0800945static void test_pthread_rwlock_reader_wakeup_writer(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -0800946 RwlockWakeupHelperArg wakeup_arg;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700947 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -0800948 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
949 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -0700950 wakeup_arg.tid = 0;
Tom Cherry60ddedf2018-02-20 15:40:02 -0800951 wakeup_arg.trylock_function = &pthread_rwlock_trywrlock;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800952 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800953
954 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700955 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800956 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -0700957 WaitUntilThreadSleep(wakeup_arg.tid);
958 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
959
Yabin Cui08ee8d22015-02-11 17:04:36 -0800960 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
961 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
962
Yi Kong32bc0fc2018-08-02 17:31:13 -0700963 ASSERT_EQ(0, pthread_join(thread, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -0800964 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
965 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
966}
967
Yabin Cuic9a659c2015-11-05 15:36:08 -0800968TEST(pthread, pthread_rwlock_reader_wakeup_writer) {
969 test_pthread_rwlock_reader_wakeup_writer(pthread_rwlock_wrlock);
Yabin Cui08ee8d22015-02-11 17:04:36 -0800970}
971
Yabin Cuic9a659c2015-11-05 15:36:08 -0800972TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait) {
973 timespec ts;
974 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
975 ts.tv_sec += 1;
976 test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) {
977 return pthread_rwlock_timedwrlock(lock, &ts);
978 });
979}
980
Tom Cherryc6b5bcd2018-03-05 14:14:44 -0800981TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait_monotonic_np) {
982#if defined(__BIONIC__)
983 timespec ts;
984 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
985 ts.tv_sec += 1;
986 test_pthread_rwlock_reader_wakeup_writer(
987 [&](pthread_rwlock_t* lock) { return pthread_rwlock_timedwrlock_monotonic_np(lock, &ts); });
988#else // __BIONIC__
989 GTEST_LOG_(INFO) << "This test does nothing since pthread_rwlock_timedwrlock_monotonic_np is "
990 "only supported on bionic";
991#endif // __BIONIC__
992}
993
Yabin Cuic9a659c2015-11-05 15:36:08 -0800994static void test_pthread_rwlock_writer_wakeup_reader(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -0800995 RwlockWakeupHelperArg wakeup_arg;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700996 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -0800997 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
998 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -0700999 wakeup_arg.tid = 0;
Tom Cherry60ddedf2018-02-20 15:40:02 -08001000 wakeup_arg.trylock_function = &pthread_rwlock_tryrdlock;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001001 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -08001002
1003 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001004 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cuic9a659c2015-11-05 15:36:08 -08001005 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -07001006 WaitUntilThreadSleep(wakeup_arg.tid);
1007 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
1008
Yabin Cui08ee8d22015-02-11 17:04:36 -08001009 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
1010 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
1011
Yi Kong32bc0fc2018-08-02 17:31:13 -07001012 ASSERT_EQ(0, pthread_join(thread, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -08001013 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
1014 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
1015}
1016
Yabin Cuic9a659c2015-11-05 15:36:08 -08001017TEST(pthread, pthread_rwlock_writer_wakeup_reader) {
1018 test_pthread_rwlock_writer_wakeup_reader(pthread_rwlock_rdlock);
1019}
1020
1021TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait) {
1022 timespec ts;
1023 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1024 ts.tv_sec += 1;
1025 test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) {
1026 return pthread_rwlock_timedrdlock(lock, &ts);
1027 });
1028}
1029
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001030TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait_monotonic_np) {
1031#if defined(__BIONIC__)
1032 timespec ts;
1033 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1034 ts.tv_sec += 1;
1035 test_pthread_rwlock_writer_wakeup_reader(
1036 [&](pthread_rwlock_t* lock) { return pthread_rwlock_timedrdlock_monotonic_np(lock, &ts); });
1037#else // __BIONIC__
1038 GTEST_LOG_(INFO) << "This test does nothing since pthread_rwlock_timedrdlock_monotonic_np is "
1039 "only supported on bionic";
1040#endif // __BIONIC__
1041}
1042
Yabin Cuic9a659c2015-11-05 15:36:08 -08001043static void pthread_rwlock_wakeup_timeout_helper(RwlockWakeupHelperArg* arg) {
1044 arg->tid = gettid();
1045 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
1046 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
1047
1048 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
1049
1050 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001051 ASSERT_EQ(0, clock_gettime(arg->clock, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001052 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
1053 ts.tv_nsec = -1;
1054 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
1055 ts.tv_nsec = NS_PER_S;
1056 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
1057 ts.tv_nsec = NS_PER_S - 1;
1058 ts.tv_sec = -1;
1059 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001060 ASSERT_EQ(0, clock_gettime(arg->clock, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001061 ts.tv_sec += 1;
1062 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
1063 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, arg->progress);
1064 arg->progress = RwlockWakeupHelperArg::LOCK_TIMEDOUT;
1065}
1066
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001067static void pthread_rwlock_timedrdlock_timeout_helper(
1068 clockid_t clock, int (*lock_function)(pthread_rwlock_t* __rwlock, const timespec* __timeout)) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001069 RwlockWakeupHelperArg wakeup_arg;
1070 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
1071 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
1072 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
1073 wakeup_arg.tid = 0;
Tom Cherry60ddedf2018-02-20 15:40:02 -08001074 wakeup_arg.trylock_function = &pthread_rwlock_tryrdlock;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001075 wakeup_arg.timed_lock_function = lock_function;
1076 wakeup_arg.clock = clock;
1077
1078 pthread_t thread;
1079 ASSERT_EQ(0, pthread_create(&thread, nullptr,
1080 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
1081 WaitUntilThreadSleep(wakeup_arg.tid);
1082 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
1083
1084 ASSERT_EQ(0, pthread_join(thread, nullptr));
1085 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
1086 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
1087 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
1088}
1089
1090TEST(pthread, pthread_rwlock_timedrdlock_timeout) {
1091 pthread_rwlock_timedrdlock_timeout_helper(CLOCK_REALTIME, pthread_rwlock_timedrdlock);
1092}
1093
1094TEST(pthread, pthread_rwlock_timedrdlock_monotonic_np_timeout) {
1095#if defined(__BIONIC__)
1096 pthread_rwlock_timedrdlock_timeout_helper(CLOCK_MONOTONIC,
1097 pthread_rwlock_timedrdlock_monotonic_np);
1098#else // __BIONIC__
1099 GTEST_LOG_(INFO) << "This test does nothing since pthread_rwlock_timedrdlock_monotonic_np is "
1100 "only supported on bionic";
1101#endif // __BIONIC__
1102}
1103
1104static void pthread_rwlock_timedwrlock_timeout_helper(
1105 clockid_t clock, int (*lock_function)(pthread_rwlock_t* __rwlock, const timespec* __timeout)) {
1106 RwlockWakeupHelperArg wakeup_arg;
1107 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
1108 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
1109 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
1110 wakeup_arg.tid = 0;
1111 wakeup_arg.trylock_function = &pthread_rwlock_trywrlock;
1112 wakeup_arg.timed_lock_function = lock_function;
1113 wakeup_arg.clock = clock;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001114
1115 pthread_t thread;
1116 ASSERT_EQ(0, pthread_create(&thread, nullptr,
1117 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
1118 WaitUntilThreadSleep(wakeup_arg.tid);
1119 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
1120
1121 ASSERT_EQ(0, pthread_join(thread, nullptr));
1122 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
1123 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
1124 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
1125}
1126
1127TEST(pthread, pthread_rwlock_timedwrlock_timeout) {
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001128 pthread_rwlock_timedwrlock_timeout_helper(CLOCK_REALTIME, pthread_rwlock_timedwrlock);
1129}
Yabin Cuic9a659c2015-11-05 15:36:08 -08001130
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001131TEST(pthread, pthread_rwlock_timedwrlock_monotonic_np_timeout) {
1132#if defined(__BIONIC__)
1133 pthread_rwlock_timedwrlock_timeout_helper(CLOCK_MONOTONIC,
1134 pthread_rwlock_timedwrlock_monotonic_np);
1135#else // __BIONIC__
1136 GTEST_LOG_(INFO) << "This test does nothing since pthread_rwlock_timedwrlock_monotonic_np is "
1137 "only supported on bionic";
1138#endif // __BIONIC__
Yabin Cuic9a659c2015-11-05 15:36:08 -08001139}
1140
Yabin Cui76615da2015-03-17 14:22:09 -07001141class RwlockKindTestHelper {
1142 private:
1143 struct ThreadArg {
1144 RwlockKindTestHelper* helper;
1145 std::atomic<pid_t>& tid;
1146
1147 ThreadArg(RwlockKindTestHelper* helper, std::atomic<pid_t>& tid)
1148 : helper(helper), tid(tid) { }
1149 };
1150
1151 public:
1152 pthread_rwlock_t lock;
1153
1154 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -07001155 explicit RwlockKindTestHelper(int kind_type) {
Yabin Cui76615da2015-03-17 14:22:09 -07001156 InitRwlock(kind_type);
1157 }
1158
1159 ~RwlockKindTestHelper() {
1160 DestroyRwlock();
1161 }
1162
1163 void CreateWriterThread(pthread_t& thread, std::atomic<pid_t>& tid) {
1164 tid = 0;
1165 ThreadArg* arg = new ThreadArg(this, tid);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001166 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui76615da2015-03-17 14:22:09 -07001167 reinterpret_cast<void* (*)(void*)>(WriterThreadFn), arg));
1168 }
1169
1170 void CreateReaderThread(pthread_t& thread, std::atomic<pid_t>& tid) {
1171 tid = 0;
1172 ThreadArg* arg = new ThreadArg(this, tid);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001173 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui76615da2015-03-17 14:22:09 -07001174 reinterpret_cast<void* (*)(void*)>(ReaderThreadFn), arg));
1175 }
1176
1177 private:
1178 void InitRwlock(int kind_type) {
1179 pthread_rwlockattr_t attr;
1180 ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
1181 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_type));
1182 ASSERT_EQ(0, pthread_rwlock_init(&lock, &attr));
1183 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
1184 }
1185
1186 void DestroyRwlock() {
1187 ASSERT_EQ(0, pthread_rwlock_destroy(&lock));
1188 }
1189
1190 static void WriterThreadFn(ThreadArg* arg) {
1191 arg->tid = gettid();
1192
1193 RwlockKindTestHelper* helper = arg->helper;
1194 ASSERT_EQ(0, pthread_rwlock_wrlock(&helper->lock));
1195 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
1196 delete arg;
1197 }
1198
1199 static void ReaderThreadFn(ThreadArg* arg) {
1200 arg->tid = gettid();
1201
1202 RwlockKindTestHelper* helper = arg->helper;
1203 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper->lock));
1204 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
1205 delete arg;
1206 }
1207};
1208
1209TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_READER_NP) {
1210 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_READER_NP);
1211 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
1212
1213 pthread_t writer_thread;
1214 std::atomic<pid_t> writer_tid;
1215 helper.CreateWriterThread(writer_thread, writer_tid);
1216 WaitUntilThreadSleep(writer_tid);
1217
1218 pthread_t reader_thread;
1219 std::atomic<pid_t> reader_tid;
1220 helper.CreateReaderThread(reader_thread, reader_tid);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001221 ASSERT_EQ(0, pthread_join(reader_thread, nullptr));
Yabin Cui76615da2015-03-17 14:22:09 -07001222
1223 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
Yi Kong32bc0fc2018-08-02 17:31:13 -07001224 ASSERT_EQ(0, pthread_join(writer_thread, nullptr));
Yabin Cui76615da2015-03-17 14:22:09 -07001225}
1226
1227TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP) {
1228 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
1229 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
1230
1231 pthread_t writer_thread;
1232 std::atomic<pid_t> writer_tid;
1233 helper.CreateWriterThread(writer_thread, writer_tid);
1234 WaitUntilThreadSleep(writer_tid);
1235
1236 pthread_t reader_thread;
1237 std::atomic<pid_t> reader_tid;
1238 helper.CreateReaderThread(reader_thread, reader_tid);
1239 WaitUntilThreadSleep(reader_tid);
1240
1241 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
Yi Kong32bc0fc2018-08-02 17:31:13 -07001242 ASSERT_EQ(0, pthread_join(writer_thread, nullptr));
1243 ASSERT_EQ(0, pthread_join(reader_thread, nullptr));
Yabin Cui76615da2015-03-17 14:22:09 -07001244}
1245
Elliott Hughes1728b232014-05-14 10:02:03 -07001246static int g_once_fn_call_count = 0;
Elliott Hughesc3f11402013-10-30 14:40:09 -07001247static void OnceFn() {
Elliott Hughes1728b232014-05-14 10:02:03 -07001248 ++g_once_fn_call_count;
Elliott Hughesc3f11402013-10-30 14:40:09 -07001249}
1250
1251TEST(pthread, pthread_once_smoke) {
1252 pthread_once_t once_control = PTHREAD_ONCE_INIT;
1253 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
1254 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
Elliott Hughes1728b232014-05-14 10:02:03 -07001255 ASSERT_EQ(1, g_once_fn_call_count);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001256}
1257
Elliott Hughes3694ec62014-05-14 11:46:08 -07001258static std::string pthread_once_1934122_result = "";
1259
1260static void Routine2() {
1261 pthread_once_1934122_result += "2";
1262}
1263
1264static void Routine1() {
1265 pthread_once_t once_control_2 = PTHREAD_ONCE_INIT;
1266 pthread_once_1934122_result += "1";
1267 pthread_once(&once_control_2, &Routine2);
1268}
1269
1270TEST(pthread, pthread_once_1934122) {
1271 // Very old versions of Android couldn't call pthread_once from a
1272 // pthread_once init routine. http://b/1934122.
1273 pthread_once_t once_control_1 = PTHREAD_ONCE_INIT;
1274 ASSERT_EQ(0, pthread_once(&once_control_1, &Routine1));
1275 ASSERT_EQ("12", pthread_once_1934122_result);
1276}
1277
Elliott Hughes1728b232014-05-14 10:02:03 -07001278static int g_atfork_prepare_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001279static void AtForkPrepare1() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 1; }
1280static void AtForkPrepare2() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -07001281static int g_atfork_parent_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001282static void AtForkParent1() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 1; }
1283static void AtForkParent2() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -07001284static int g_atfork_child_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001285static void AtForkChild1() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 1; }
1286static void AtForkChild2() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 2; }
Elliott Hughesc3f11402013-10-30 14:40:09 -07001287
Dmitriy Ivanov00e37812014-11-20 16:53:47 -08001288TEST(pthread, pthread_atfork_smoke) {
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001289 ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1));
1290 ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2));
Elliott Hughesc3f11402013-10-30 14:40:09 -07001291
Elliott Hughes33697a02016-01-26 13:04:57 -08001292 pid_t pid = fork();
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001293 ASSERT_NE(-1, pid) << strerror(errno);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001294
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001295 // Child and parent calls are made in the order they were registered.
1296 if (pid == 0) {
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001297 ASSERT_EQ(12, g_atfork_child_calls);
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001298 _exit(0);
1299 }
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001300 ASSERT_EQ(12, g_atfork_parent_calls);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001301
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001302 // Prepare calls are made in the reverse order.
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001303 ASSERT_EQ(21, g_atfork_prepare_calls);
Elliott Hughes33697a02016-01-26 13:04:57 -08001304 AssertChildExited(pid, 0);
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001305}
1306
Elliott Hughesc3f11402013-10-30 14:40:09 -07001307TEST(pthread, pthread_attr_getscope) {
1308 pthread_attr_t attr;
1309 ASSERT_EQ(0, pthread_attr_init(&attr));
1310
1311 int scope;
1312 ASSERT_EQ(0, pthread_attr_getscope(&attr, &scope));
1313 ASSERT_EQ(PTHREAD_SCOPE_SYSTEM, scope);
1314}
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001315
1316TEST(pthread, pthread_condattr_init) {
1317 pthread_condattr_t attr;
1318 pthread_condattr_init(&attr);
1319
1320 clockid_t clock;
1321 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1322 ASSERT_EQ(CLOCK_REALTIME, clock);
1323
1324 int pshared;
1325 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1326 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
1327}
1328
1329TEST(pthread, pthread_condattr_setclock) {
1330 pthread_condattr_t attr;
1331 pthread_condattr_init(&attr);
1332
1333 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_REALTIME));
1334 clockid_t clock;
1335 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1336 ASSERT_EQ(CLOCK_REALTIME, clock);
1337
1338 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1339 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1340 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1341
1342 ASSERT_EQ(EINVAL, pthread_condattr_setclock(&attr, CLOCK_PROCESS_CPUTIME_ID));
1343}
1344
1345TEST(pthread, pthread_cond_broadcast__preserves_condattr_flags) {
Yabin Cui32651b82015-03-13 20:30:00 -07001346#if defined(__BIONIC__)
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001347 pthread_condattr_t attr;
1348 pthread_condattr_init(&attr);
1349
1350 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1351 ASSERT_EQ(0, pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
1352
1353 pthread_cond_t cond_var;
1354 ASSERT_EQ(0, pthread_cond_init(&cond_var, &attr));
1355
1356 ASSERT_EQ(0, pthread_cond_signal(&cond_var));
1357 ASSERT_EQ(0, pthread_cond_broadcast(&cond_var));
1358
Yabin Cui32651b82015-03-13 20:30:00 -07001359 attr = static_cast<pthread_condattr_t>(*reinterpret_cast<uint32_t*>(cond_var.__private));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001360 clockid_t clock;
1361 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1362 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1363 int pshared;
1364 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1365 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
Yabin Cui32651b82015-03-13 20:30:00 -07001366#else // !defined(__BIONIC__)
1367 GTEST_LOG_(INFO) << "This tests a bionic implementation detail.\n";
1368#endif // !defined(__BIONIC__)
1369}
1370
1371class pthread_CondWakeupTest : public ::testing::Test {
1372 protected:
1373 pthread_mutex_t mutex;
1374 pthread_cond_t cond;
1375
1376 enum Progress {
1377 INITIALIZED,
1378 WAITING,
1379 SIGNALED,
1380 FINISHED,
1381 };
1382 std::atomic<Progress> progress;
1383 pthread_t thread;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001384 std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function;
Yabin Cui32651b82015-03-13 20:30:00 -07001385
1386 protected:
Yabin Cuic9a659c2015-11-05 15:36:08 -08001387 void SetUp() override {
1388 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1389 }
1390
1391 void InitCond(clockid_t clock=CLOCK_REALTIME) {
1392 pthread_condattr_t attr;
1393 ASSERT_EQ(0, pthread_condattr_init(&attr));
1394 ASSERT_EQ(0, pthread_condattr_setclock(&attr, clock));
1395 ASSERT_EQ(0, pthread_cond_init(&cond, &attr));
1396 ASSERT_EQ(0, pthread_condattr_destroy(&attr));
1397 }
1398
1399 void StartWaitingThread(std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function) {
Yabin Cui32651b82015-03-13 20:30:00 -07001400 progress = INITIALIZED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001401 this->wait_function = wait_function;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001402 ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(WaitThreadFn), this));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001403 while (progress != WAITING) {
Yabin Cui32651b82015-03-13 20:30:00 -07001404 usleep(5000);
1405 }
1406 usleep(5000);
1407 }
1408
Yabin Cuic9a659c2015-11-05 15:36:08 -08001409 void TearDown() override {
1410 ASSERT_EQ(0, pthread_join(thread, nullptr));
1411 ASSERT_EQ(FINISHED, progress);
1412 ASSERT_EQ(0, pthread_cond_destroy(&cond));
1413 ASSERT_EQ(0, pthread_mutex_destroy(&mutex));
1414 }
1415
Yabin Cui32651b82015-03-13 20:30:00 -07001416 private:
1417 static void WaitThreadFn(pthread_CondWakeupTest* test) {
1418 ASSERT_EQ(0, pthread_mutex_lock(&test->mutex));
1419 test->progress = WAITING;
1420 while (test->progress == WAITING) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001421 ASSERT_EQ(0, test->wait_function(&test->cond, &test->mutex));
Yabin Cui32651b82015-03-13 20:30:00 -07001422 }
1423 ASSERT_EQ(SIGNALED, test->progress);
1424 test->progress = FINISHED;
1425 ASSERT_EQ(0, pthread_mutex_unlock(&test->mutex));
1426 }
1427};
1428
Yabin Cuic9a659c2015-11-05 15:36:08 -08001429TEST_F(pthread_CondWakeupTest, signal_wait) {
1430 InitCond();
1431 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1432 return pthread_cond_wait(cond, mutex);
1433 });
Yabin Cui32651b82015-03-13 20:30:00 -07001434 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001435 ASSERT_EQ(0, pthread_cond_signal(&cond));
Yabin Cui32651b82015-03-13 20:30:00 -07001436}
1437
Yabin Cuic9a659c2015-11-05 15:36:08 -08001438TEST_F(pthread_CondWakeupTest, broadcast_wait) {
1439 InitCond();
1440 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1441 return pthread_cond_wait(cond, mutex);
1442 });
Yabin Cui32651b82015-03-13 20:30:00 -07001443 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001444 ASSERT_EQ(0, pthread_cond_broadcast(&cond));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001445}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001446
Yabin Cuic9a659c2015-11-05 15:36:08 -08001447TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_REALTIME) {
1448 InitCond(CLOCK_REALTIME);
Elliott Hughes0e714a52014-03-03 16:42:47 -08001449 timespec ts;
1450 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001451 ts.tv_sec += 1;
1452 StartWaitingThread([&](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1453 return pthread_cond_timedwait(cond, mutex, &ts);
1454 });
1455 progress = SIGNALED;
1456 ASSERT_EQ(0, pthread_cond_signal(&cond));
1457}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001458
Yabin Cuic9a659c2015-11-05 15:36:08 -08001459TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC) {
1460 InitCond(CLOCK_MONOTONIC);
1461 timespec ts;
1462 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1463 ts.tv_sec += 1;
1464 StartWaitingThread([&](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1465 return pthread_cond_timedwait(cond, mutex, &ts);
1466 });
1467 progress = SIGNALED;
1468 ASSERT_EQ(0, pthread_cond_signal(&cond));
1469}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001470
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001471TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC_np) {
1472#if defined(__BIONIC__)
1473 InitCond(CLOCK_REALTIME);
1474 timespec ts;
1475 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1476 ts.tv_sec += 1;
1477 StartWaitingThread([&](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1478 return pthread_cond_timedwait_monotonic_np(cond, mutex, &ts);
1479 });
1480 progress = SIGNALED;
1481 ASSERT_EQ(0, pthread_cond_signal(&cond));
1482#else // __BIONIC__
1483 GTEST_LOG_(INFO) << "This test does nothing since pthread_cond_timedwait_monotonic_np is only "
1484 "supported on bionic";
1485#endif // __BIONIC__
1486}
1487
1488static void pthread_cond_timedwait_timeout_helper(clockid_t clock,
1489 int (*wait_function)(pthread_cond_t* __cond,
1490 pthread_mutex_t* __mutex,
1491 const timespec* __timeout)) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001492 pthread_mutex_t mutex;
1493 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1494 pthread_cond_t cond;
1495 ASSERT_EQ(0, pthread_cond_init(&cond, nullptr));
1496 ASSERT_EQ(0, pthread_mutex_lock(&mutex));
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001497
Yabin Cuic9a659c2015-11-05 15:36:08 -08001498 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001499 ASSERT_EQ(0, clock_gettime(clock, &ts));
1500 ASSERT_EQ(ETIMEDOUT, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001501 ts.tv_nsec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001502 ASSERT_EQ(EINVAL, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001503 ts.tv_nsec = NS_PER_S;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001504 ASSERT_EQ(EINVAL, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001505 ts.tv_nsec = NS_PER_S - 1;
1506 ts.tv_sec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001507 ASSERT_EQ(ETIMEDOUT, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001508 ASSERT_EQ(0, pthread_mutex_unlock(&mutex));
Elliott Hughes0e714a52014-03-03 16:42:47 -08001509}
Elliott Hughes57b7a612014-08-25 17:26:50 -07001510
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001511TEST(pthread, pthread_cond_timedwait_timeout) {
1512 pthread_cond_timedwait_timeout_helper(CLOCK_REALTIME, pthread_cond_timedwait);
1513}
1514
1515TEST(pthread, pthread_cond_timedwait_monotonic_np_timeout) {
1516#if defined(__BIONIC__)
1517 pthread_cond_timedwait_timeout_helper(CLOCK_MONOTONIC, pthread_cond_timedwait_monotonic_np);
1518#else // __BIONIC__
1519 GTEST_LOG_(INFO) << "This test does nothing since pthread_cond_timedwait_monotonic_np is only "
1520 "supported on bionic";
1521#endif // __BIONIC__
1522}
1523
Elliott Hughes57b7a612014-08-25 17:26:50 -07001524TEST(pthread, pthread_attr_getstack__main_thread) {
1525 // This test is only meaningful for the main thread, so make sure we're running on it!
1526 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1527
1528 // Get the main thread's attributes.
1529 pthread_attr_t attributes;
1530 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1531
1532 // Check that we correctly report that the main thread has no guard page.
1533 size_t guard_size;
1534 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
1535 ASSERT_EQ(0U, guard_size); // The main thread has no guard page.
1536
1537 // Get the stack base and the stack size (both ways).
1538 void* stack_base;
1539 size_t stack_size;
1540 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1541 size_t stack_size2;
1542 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1543
1544 // The two methods of asking for the stack size should agree.
1545 EXPECT_EQ(stack_size, stack_size2);
1546
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001547#if defined(__BIONIC__)
dimitry6dfa5b52018-01-30 13:24:28 +01001548 // Find stack in /proc/self/maps using a pointer to the stack.
1549 //
1550 // We do not use "[stack]" label because in native-bridge environment it is not
1551 // guaranteed to point to the right stack. A native bridge implementation may
1552 // keep separate stack for the guest code.
Yi Kong32bc0fc2018-08-02 17:31:13 -07001553 void* maps_stack_hi = nullptr;
Elliott Hughes15dfd632015-09-22 16:40:14 -07001554 std::vector<map_record> maps;
1555 ASSERT_TRUE(Maps::parse_maps(&maps));
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08001556 uintptr_t stack_address = reinterpret_cast<uintptr_t>(untag_address(&maps_stack_hi));
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07001557 for (const auto& map : maps) {
dimitry6dfa5b52018-01-30 13:24:28 +01001558 if (map.addr_start <= stack_address && map.addr_end > stack_address){
Elliott Hughes15dfd632015-09-22 16:40:14 -07001559 maps_stack_hi = reinterpret_cast<void*>(map.addr_end);
Elliott Hughes57b7a612014-08-25 17:26:50 -07001560 break;
1561 }
1562 }
Elliott Hughes57b7a612014-08-25 17:26:50 -07001563
dimitry6dfa5b52018-01-30 13:24:28 +01001564 // The high address of the /proc/self/maps stack region should equal stack_base + stack_size.
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001565 // Remember that the stack grows down (and is mapped in on demand), so the low address of the
1566 // region isn't very interesting.
1567 EXPECT_EQ(maps_stack_hi, reinterpret_cast<uint8_t*>(stack_base) + stack_size);
1568
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001569 // The stack size should correspond to RLIMIT_STACK.
Elliott Hughes57b7a612014-08-25 17:26:50 -07001570 rlimit rl;
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001571 ASSERT_EQ(0, getrlimit(RLIMIT_STACK, &rl));
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001572 uint64_t original_rlim_cur = rl.rlim_cur;
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001573 if (rl.rlim_cur == RLIM_INFINITY) {
1574 rl.rlim_cur = 8 * 1024 * 1024; // Bionic reports unlimited stacks as 8MiB.
1575 }
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001576 EXPECT_EQ(rl.rlim_cur, stack_size);
1577
Tom Cherryb8ab6182017-04-05 16:20:29 -07001578 auto guard = android::base::make_scope_guard([&rl, original_rlim_cur]() {
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001579 rl.rlim_cur = original_rlim_cur;
1580 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1581 });
1582
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001583 //
1584 // What if RLIMIT_STACK is smaller than the stack's current extent?
1585 //
Elliott Hughes57b7a612014-08-25 17:26:50 -07001586 rl.rlim_cur = rl.rlim_max = 1024; // 1KiB. We know the stack must be at least a page already.
1587 rl.rlim_max = RLIM_INFINITY;
1588 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1589
1590 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1591 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1592 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1593
1594 EXPECT_EQ(stack_size, stack_size2);
1595 ASSERT_EQ(1024U, stack_size);
1596
1597 //
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001598 // What if RLIMIT_STACK isn't a whole number of pages?
Elliott Hughes57b7a612014-08-25 17:26:50 -07001599 //
1600 rl.rlim_cur = rl.rlim_max = 6666; // Not a whole number of pages.
1601 rl.rlim_max = RLIM_INFINITY;
1602 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1603
1604 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1605 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1606 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1607
1608 EXPECT_EQ(stack_size, stack_size2);
1609 ASSERT_EQ(6666U, stack_size);
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001610#endif
Elliott Hughes57b7a612014-08-25 17:26:50 -07001611}
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001612
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001613struct GetStackSignalHandlerArg {
1614 volatile bool done;
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001615 void* signal_stack_base;
1616 size_t signal_stack_size;
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001617 void* main_stack_base;
1618 size_t main_stack_size;
1619};
1620
1621static GetStackSignalHandlerArg getstack_signal_handler_arg;
1622
1623static void getstack_signal_handler(int sig) {
1624 ASSERT_EQ(SIGUSR1, sig);
1625 // Use sleep() to make current thread be switched out by the kernel to provoke the error.
1626 sleep(1);
1627 pthread_attr_t attr;
1628 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1629 void* stack_base;
1630 size_t stack_size;
1631 ASSERT_EQ(0, pthread_attr_getstack(&attr, &stack_base, &stack_size));
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001632
1633 // Verify if the stack used by the signal handler is the alternate stack just registered.
1634 ASSERT_LE(getstack_signal_handler_arg.signal_stack_base, &attr);
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08001635 ASSERT_LT(static_cast<void*>(untag_address(&attr)),
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001636 static_cast<char*>(getstack_signal_handler_arg.signal_stack_base) +
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08001637 getstack_signal_handler_arg.signal_stack_size);
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001638
1639 // Verify if the main thread's stack got in the signal handler is correct.
1640 ASSERT_EQ(getstack_signal_handler_arg.main_stack_base, stack_base);
1641 ASSERT_LE(getstack_signal_handler_arg.main_stack_size, stack_size);
1642
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001643 getstack_signal_handler_arg.done = true;
1644}
1645
1646// The previous code obtained the main thread's stack by reading the entry in
1647// /proc/self/task/<pid>/maps that was labeled [stack]. Unfortunately, on x86/x86_64, the kernel
1648// relies on sp0 in task state segment(tss) to label the stack map with [stack]. If the kernel
1649// switches a process while the main thread is in an alternate stack, then the kernel will label
1650// the wrong map with [stack]. This test verifies that when the above situation happens, the main
1651// thread's stack is found correctly.
1652TEST(pthread, pthread_attr_getstack_in_signal_handler) {
Yabin Cui61e4d462016-03-07 17:44:58 -08001653 // This test is only meaningful for the main thread, so make sure we're running on it!
1654 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1655
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001656 const size_t sig_stack_size = 16 * 1024;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001657 void* sig_stack = mmap(nullptr, sig_stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS,
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001658 -1, 0);
1659 ASSERT_NE(MAP_FAILED, sig_stack);
1660 stack_t ss;
1661 ss.ss_sp = sig_stack;
1662 ss.ss_size = sig_stack_size;
1663 ss.ss_flags = 0;
1664 stack_t oss;
1665 ASSERT_EQ(0, sigaltstack(&ss, &oss));
1666
Yabin Cui61e4d462016-03-07 17:44:58 -08001667 pthread_attr_t attr;
1668 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1669 void* main_stack_base;
1670 size_t main_stack_size;
1671 ASSERT_EQ(0, pthread_attr_getstack(&attr, &main_stack_base, &main_stack_size));
1672
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001673 ScopedSignalHandler handler(SIGUSR1, getstack_signal_handler, SA_ONSTACK);
1674 getstack_signal_handler_arg.done = false;
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001675 getstack_signal_handler_arg.signal_stack_base = sig_stack;
1676 getstack_signal_handler_arg.signal_stack_size = sig_stack_size;
1677 getstack_signal_handler_arg.main_stack_base = main_stack_base;
1678 getstack_signal_handler_arg.main_stack_size = main_stack_size;
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001679 kill(getpid(), SIGUSR1);
1680 ASSERT_EQ(true, getstack_signal_handler_arg.done);
1681
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001682 ASSERT_EQ(0, sigaltstack(&oss, nullptr));
1683 ASSERT_EQ(0, munmap(sig_stack, sig_stack_size));
1684}
1685
Yabin Cui917d3902015-01-08 12:32:42 -08001686static void pthread_attr_getstack_18908062_helper(void*) {
1687 char local_variable;
1688 pthread_attr_t attributes;
1689 pthread_getattr_np(pthread_self(), &attributes);
1690 void* stack_base;
1691 size_t stack_size;
1692 pthread_attr_getstack(&attributes, &stack_base, &stack_size);
1693
1694 // Test whether &local_variable is in [stack_base, stack_base + stack_size).
1695 ASSERT_LE(reinterpret_cast<char*>(stack_base), &local_variable);
Evgenii Stepanov7cc67062019-02-05 18:43:34 -08001696 ASSERT_LT(untag_address(&local_variable), reinterpret_cast<char*>(stack_base) + stack_size);
Yabin Cui917d3902015-01-08 12:32:42 -08001697}
1698
1699// Check whether something on stack is in the range of
1700// [stack_base, stack_base + stack_size). see b/18908062.
1701TEST(pthread, pthread_attr_getstack_18908062) {
1702 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001703 ASSERT_EQ(0, pthread_create(&t, nullptr,
Yabin Cui917d3902015-01-08 12:32:42 -08001704 reinterpret_cast<void* (*)(void*)>(pthread_attr_getstack_18908062_helper),
Yi Kong32bc0fc2018-08-02 17:31:13 -07001705 nullptr));
1706 ASSERT_EQ(0, pthread_join(t, nullptr));
Yabin Cui917d3902015-01-08 12:32:42 -08001707}
1708
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001709#if defined(__BIONIC__)
Elliott Hughesf2083612015-11-11 13:32:28 -08001710static pthread_mutex_t pthread_gettid_np_mutex = PTHREAD_MUTEX_INITIALIZER;
1711
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001712static void* pthread_gettid_np_helper(void* arg) {
1713 *reinterpret_cast<pid_t*>(arg) = gettid();
Elliott Hughesf2083612015-11-11 13:32:28 -08001714
1715 // Wait for our parent to call pthread_gettid_np on us before exiting.
1716 pthread_mutex_lock(&pthread_gettid_np_mutex);
1717 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001718 return nullptr;
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001719}
1720#endif
1721
1722TEST(pthread, pthread_gettid_np) {
1723#if defined(__BIONIC__)
1724 ASSERT_EQ(gettid(), pthread_gettid_np(pthread_self()));
1725
Elliott Hughesf2083612015-11-11 13:32:28 -08001726 // Ensure the other thread doesn't exit until after we've called
1727 // pthread_gettid_np on it.
1728 pthread_mutex_lock(&pthread_gettid_np_mutex);
1729
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001730 pid_t t_gettid_result;
1731 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001732 pthread_create(&t, nullptr, pthread_gettid_np_helper, &t_gettid_result);
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001733
1734 pid_t t_pthread_gettid_np_result = pthread_gettid_np(t);
1735
Elliott Hughesf2083612015-11-11 13:32:28 -08001736 // Release the other thread and wait for it to exit.
1737 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001738 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001739
1740 ASSERT_EQ(t_gettid_result, t_pthread_gettid_np_result);
1741#else
1742 GTEST_LOG_(INFO) << "This test does nothing.\n";
1743#endif
1744}
Elliott Hughes34c987a2014-09-22 16:01:26 -07001745
1746static size_t cleanup_counter = 0;
1747
Derek Xue41996952014-09-25 11:05:32 +01001748static void AbortCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001749 abort();
1750}
1751
Derek Xue41996952014-09-25 11:05:32 +01001752static void CountCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001753 ++cleanup_counter;
1754}
1755
Derek Xue41996952014-09-25 11:05:32 +01001756static void PthreadCleanupTester() {
Yi Kong32bc0fc2018-08-02 17:31:13 -07001757 pthread_cleanup_push(CountCleanupRoutine, nullptr);
1758 pthread_cleanup_push(CountCleanupRoutine, nullptr);
1759 pthread_cleanup_push(AbortCleanupRoutine, nullptr);
Elliott Hughes34c987a2014-09-22 16:01:26 -07001760
1761 pthread_cleanup_pop(0); // Pop the abort without executing it.
1762 pthread_cleanup_pop(1); // Pop one count while executing it.
1763 ASSERT_EQ(1U, cleanup_counter);
1764 // Exit while the other count is still on the cleanup stack.
Yi Kong32bc0fc2018-08-02 17:31:13 -07001765 pthread_exit(nullptr);
Elliott Hughes34c987a2014-09-22 16:01:26 -07001766
1767 // Calls to pthread_cleanup_pop/pthread_cleanup_push must always be balanced.
1768 pthread_cleanup_pop(0);
1769}
1770
Derek Xue41996952014-09-25 11:05:32 +01001771static void* PthreadCleanupStartRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001772 PthreadCleanupTester();
Yi Kong32bc0fc2018-08-02 17:31:13 -07001773 return nullptr;
Elliott Hughes34c987a2014-09-22 16:01:26 -07001774}
1775
1776TEST(pthread, pthread_cleanup_push__pthread_cleanup_pop) {
1777 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001778 ASSERT_EQ(0, pthread_create(&t, nullptr, PthreadCleanupStartRoutine, nullptr));
1779 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes34c987a2014-09-22 16:01:26 -07001780 ASSERT_EQ(2U, cleanup_counter);
1781}
Derek Xue41996952014-09-25 11:05:32 +01001782
1783TEST(pthread, PTHREAD_MUTEX_DEFAULT_is_PTHREAD_MUTEX_NORMAL) {
1784 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_DEFAULT);
1785}
1786
1787TEST(pthread, pthread_mutexattr_gettype) {
1788 pthread_mutexattr_t attr;
1789 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1790
1791 int attr_type;
1792
1793 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL));
1794 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1795 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, attr_type);
1796
1797 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK));
1798 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1799 ASSERT_EQ(PTHREAD_MUTEX_ERRORCHECK, attr_type);
1800
1801 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE));
1802 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1803 ASSERT_EQ(PTHREAD_MUTEX_RECURSIVE, attr_type);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001804
1805 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
1806}
1807
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001808TEST(pthread, pthread_mutexattr_protocol) {
1809 pthread_mutexattr_t attr;
1810 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1811
1812 int protocol;
1813 ASSERT_EQ(0, pthread_mutexattr_getprotocol(&attr, &protocol));
1814 ASSERT_EQ(PTHREAD_PRIO_NONE, protocol);
1815 for (size_t repeat = 0; repeat < 2; ++repeat) {
1816 for (int set_protocol : {PTHREAD_PRIO_NONE, PTHREAD_PRIO_INHERIT}) {
1817 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, set_protocol));
1818 ASSERT_EQ(0, pthread_mutexattr_getprotocol(&attr, &protocol));
1819 ASSERT_EQ(protocol, set_protocol);
1820 }
1821 }
1822}
1823
Yabin Cui17393b02015-03-21 15:08:25 -07001824struct PthreadMutex {
1825 pthread_mutex_t lock;
1826
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001827 explicit PthreadMutex(int mutex_type, int protocol = PTHREAD_PRIO_NONE) {
1828 init(mutex_type, protocol);
Yabin Cui17393b02015-03-21 15:08:25 -07001829 }
1830
1831 ~PthreadMutex() {
1832 destroy();
1833 }
1834
1835 private:
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001836 void init(int mutex_type, int protocol) {
Yabin Cui17393b02015-03-21 15:08:25 -07001837 pthread_mutexattr_t attr;
1838 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1839 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, mutex_type));
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001840 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, protocol));
Yabin Cui17393b02015-03-21 15:08:25 -07001841 ASSERT_EQ(0, pthread_mutex_init(&lock, &attr));
1842 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
1843 }
1844
1845 void destroy() {
1846 ASSERT_EQ(0, pthread_mutex_destroy(&lock));
1847 }
1848
1849 DISALLOW_COPY_AND_ASSIGN(PthreadMutex);
1850};
Derek Xue41996952014-09-25 11:05:32 +01001851
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001852static void TestPthreadMutexLockNormal(int protocol) {
1853 PthreadMutex m(PTHREAD_MUTEX_NORMAL, protocol);
Derek Xue41996952014-09-25 11:05:32 +01001854
Yabin Cui17393b02015-03-21 15:08:25 -07001855 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1856 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08001857 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
1858 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
1859 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01001860}
1861
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001862static void TestPthreadMutexLockErrorCheck(int protocol) {
1863 PthreadMutex m(PTHREAD_MUTEX_ERRORCHECK, protocol);
Derek Xue41996952014-09-25 11:05:32 +01001864
Yabin Cui17393b02015-03-21 15:08:25 -07001865 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1866 ASSERT_EQ(EDEADLK, pthread_mutex_lock(&m.lock));
1867 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1868 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001869 if (protocol == PTHREAD_PRIO_NONE) {
1870 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
1871 } else {
1872 ASSERT_EQ(EDEADLK, pthread_mutex_trylock(&m.lock));
1873 }
Yabin Cui17393b02015-03-21 15:08:25 -07001874 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1875 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01001876}
1877
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001878static void TestPthreadMutexLockRecursive(int protocol) {
1879 PthreadMutex m(PTHREAD_MUTEX_RECURSIVE, protocol);
Derek Xue41996952014-09-25 11:05:32 +01001880
Yabin Cui17393b02015-03-21 15:08:25 -07001881 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1882 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1883 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1884 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1885 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08001886 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
1887 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07001888 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1889 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
1890}
1891
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001892TEST(pthread, pthread_mutex_lock_NORMAL) {
1893 TestPthreadMutexLockNormal(PTHREAD_PRIO_NONE);
1894}
1895
1896TEST(pthread, pthread_mutex_lock_ERRORCHECK) {
1897 TestPthreadMutexLockErrorCheck(PTHREAD_PRIO_NONE);
1898}
1899
1900TEST(pthread, pthread_mutex_lock_RECURSIVE) {
1901 TestPthreadMutexLockRecursive(PTHREAD_PRIO_NONE);
1902}
1903
1904TEST(pthread, pthread_mutex_lock_pi) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001905 TestPthreadMutexLockNormal(PTHREAD_PRIO_INHERIT);
1906 TestPthreadMutexLockErrorCheck(PTHREAD_PRIO_INHERIT);
1907 TestPthreadMutexLockRecursive(PTHREAD_PRIO_INHERIT);
1908}
1909
Yabin Cui5a00ba72018-01-26 17:32:31 -08001910TEST(pthread, pthread_mutex_pi_count_limit) {
1911#if defined(__BIONIC__) && !defined(__LP64__)
1912 // Bionic only supports 65536 pi mutexes in 32-bit programs.
1913 pthread_mutexattr_t attr;
1914 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1915 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT));
1916 std::vector<pthread_mutex_t> mutexes(65536);
1917 // Test if we can use 65536 pi mutexes at the same time.
1918 // Run 2 times to check if freed pi mutexes can be recycled.
1919 for (int repeat = 0; repeat < 2; ++repeat) {
1920 for (auto& m : mutexes) {
1921 ASSERT_EQ(0, pthread_mutex_init(&m, &attr));
1922 }
1923 pthread_mutex_t m;
1924 ASSERT_EQ(ENOMEM, pthread_mutex_init(&m, &attr));
1925 for (auto& m : mutexes) {
1926 ASSERT_EQ(0, pthread_mutex_lock(&m));
1927 }
1928 for (auto& m : mutexes) {
1929 ASSERT_EQ(0, pthread_mutex_unlock(&m));
1930 }
1931 for (auto& m : mutexes) {
1932 ASSERT_EQ(0, pthread_mutex_destroy(&m));
1933 }
1934 }
1935 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
1936#else
1937 GTEST_LOG_(INFO) << "This test does nothing as pi mutex count isn't limited.\n";
1938#endif
1939}
1940
Yabin Cui17393b02015-03-21 15:08:25 -07001941TEST(pthread, pthread_mutex_init_same_as_static_initializers) {
1942 pthread_mutex_t lock_normal = PTHREAD_MUTEX_INITIALIZER;
1943 PthreadMutex m1(PTHREAD_MUTEX_NORMAL);
1944 ASSERT_EQ(0, memcmp(&lock_normal, &m1.lock, sizeof(pthread_mutex_t)));
1945 pthread_mutex_destroy(&lock_normal);
1946
1947 pthread_mutex_t lock_errorcheck = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
1948 PthreadMutex m2(PTHREAD_MUTEX_ERRORCHECK);
1949 ASSERT_EQ(0, memcmp(&lock_errorcheck, &m2.lock, sizeof(pthread_mutex_t)));
1950 pthread_mutex_destroy(&lock_errorcheck);
1951
1952 pthread_mutex_t lock_recursive = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
1953 PthreadMutex m3(PTHREAD_MUTEX_RECURSIVE);
1954 ASSERT_EQ(0, memcmp(&lock_recursive, &m3.lock, sizeof(pthread_mutex_t)));
1955 ASSERT_EQ(0, pthread_mutex_destroy(&lock_recursive));
Derek Xue41996952014-09-25 11:05:32 +01001956}
Yabin Cui5a00ba72018-01-26 17:32:31 -08001957
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001958class MutexWakeupHelper {
1959 private:
Yabin Cui17393b02015-03-21 15:08:25 -07001960 PthreadMutex m;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001961 enum Progress {
1962 LOCK_INITIALIZED,
1963 LOCK_WAITING,
1964 LOCK_RELEASED,
1965 LOCK_ACCESSED
1966 };
1967 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -07001968 std::atomic<pid_t> tid;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001969
1970 static void thread_fn(MutexWakeupHelper* helper) {
Yabin Cuif7969852015-04-02 17:47:48 -07001971 helper->tid = gettid();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001972 ASSERT_EQ(LOCK_INITIALIZED, helper->progress);
1973 helper->progress = LOCK_WAITING;
1974
Yabin Cui17393b02015-03-21 15:08:25 -07001975 ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001976 ASSERT_EQ(LOCK_RELEASED, helper->progress);
Yabin Cui17393b02015-03-21 15:08:25 -07001977 ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001978
1979 helper->progress = LOCK_ACCESSED;
1980 }
1981
1982 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -07001983 explicit MutexWakeupHelper(int mutex_type) : m(mutex_type) {
Yabin Cui17393b02015-03-21 15:08:25 -07001984 }
1985
1986 void test() {
1987 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001988 progress = LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -07001989 tid = 0;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001990
1991 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001992 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001993 reinterpret_cast<void* (*)(void*)>(MutexWakeupHelper::thread_fn), this));
1994
Yabin Cuif7969852015-04-02 17:47:48 -07001995 WaitUntilThreadSleep(tid);
1996 ASSERT_EQ(LOCK_WAITING, progress);
1997
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001998 progress = LOCK_RELEASED;
Yabin Cui17393b02015-03-21 15:08:25 -07001999 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002000
Yi Kong32bc0fc2018-08-02 17:31:13 -07002001 ASSERT_EQ(0, pthread_join(thread, nullptr));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002002 ASSERT_EQ(LOCK_ACCESSED, progress);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002003 }
2004};
2005
2006TEST(pthread, pthread_mutex_NORMAL_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07002007 MutexWakeupHelper helper(PTHREAD_MUTEX_NORMAL);
2008 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002009}
2010
2011TEST(pthread, pthread_mutex_ERRORCHECK_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07002012 MutexWakeupHelper helper(PTHREAD_MUTEX_ERRORCHECK);
2013 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002014}
2015
2016TEST(pthread, pthread_mutex_RECURSIVE_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07002017 MutexWakeupHelper helper(PTHREAD_MUTEX_RECURSIVE);
2018 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002019}
2020
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002021static int GetThreadPriority(pid_t tid) {
2022 // sched_getparam() returns the static priority of a thread, which can't reflect a thread's
2023 // priority after priority inheritance. So read /proc/<pid>/stat to get the dynamic priority.
2024 std::string filename = android::base::StringPrintf("/proc/%d/stat", tid);
2025 std::string content;
2026 int result = INT_MAX;
2027 if (!android::base::ReadFileToString(filename, &content)) {
2028 return result;
2029 }
2030 std::vector<std::string> strs = android::base::Split(content, " ");
2031 if (strs.size() < 18) {
2032 return result;
2033 }
2034 if (!android::base::ParseInt(strs[17], &result)) {
2035 return INT_MAX;
2036 }
2037 return result;
2038}
2039
2040class PIMutexWakeupHelper {
2041private:
2042 PthreadMutex m;
2043 int protocol;
2044 enum Progress {
2045 LOCK_INITIALIZED,
2046 LOCK_CHILD_READY,
2047 LOCK_WAITING,
2048 LOCK_RELEASED,
2049 };
2050 std::atomic<Progress> progress;
2051 std::atomic<pid_t> main_tid;
2052 std::atomic<pid_t> child_tid;
2053 PthreadMutex start_thread_m;
2054
2055 static void thread_fn(PIMutexWakeupHelper* helper) {
2056 helper->child_tid = gettid();
2057 ASSERT_EQ(LOCK_INITIALIZED, helper->progress);
2058 ASSERT_EQ(0, setpriority(PRIO_PROCESS, gettid(), 1));
2059 ASSERT_EQ(21, GetThreadPriority(gettid()));
2060 ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock));
2061 helper->progress = LOCK_CHILD_READY;
2062 ASSERT_EQ(0, pthread_mutex_lock(&helper->start_thread_m.lock));
2063
2064 ASSERT_EQ(0, pthread_mutex_unlock(&helper->start_thread_m.lock));
2065 WaitUntilThreadSleep(helper->main_tid);
2066 ASSERT_EQ(LOCK_WAITING, helper->progress);
2067
2068 if (helper->protocol == PTHREAD_PRIO_INHERIT) {
2069 ASSERT_EQ(20, GetThreadPriority(gettid()));
2070 } else {
2071 ASSERT_EQ(21, GetThreadPriority(gettid()));
2072 }
2073 helper->progress = LOCK_RELEASED;
2074 ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock));
2075 }
2076
2077public:
2078 explicit PIMutexWakeupHelper(int mutex_type, int protocol)
2079 : m(mutex_type, protocol), protocol(protocol), start_thread_m(PTHREAD_MUTEX_NORMAL) {
2080 }
2081
2082 void test() {
2083 ASSERT_EQ(0, pthread_mutex_lock(&start_thread_m.lock));
2084 main_tid = gettid();
2085 ASSERT_EQ(20, GetThreadPriority(main_tid));
2086 progress = LOCK_INITIALIZED;
2087 child_tid = 0;
2088
2089 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002090 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002091 reinterpret_cast<void* (*)(void*)>(PIMutexWakeupHelper::thread_fn), this));
2092
2093 WaitUntilThreadSleep(child_tid);
2094 ASSERT_EQ(LOCK_CHILD_READY, progress);
2095 ASSERT_EQ(0, pthread_mutex_unlock(&start_thread_m.lock));
2096 progress = LOCK_WAITING;
2097 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
2098
2099 ASSERT_EQ(LOCK_RELEASED, progress);
2100 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2101 ASSERT_EQ(0, pthread_join(thread, nullptr));
2102 }
2103};
2104
2105TEST(pthread, pthread_mutex_pi_wakeup) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002106 for (int type : {PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_RECURSIVE, PTHREAD_MUTEX_ERRORCHECK}) {
2107 for (int protocol : {PTHREAD_PRIO_INHERIT}) {
2108 PIMutexWakeupHelper helper(type, protocol);
2109 helper.test();
2110 }
2111 }
2112}
2113
Yabin Cui140f3672015-02-03 10:32:00 -08002114TEST(pthread, pthread_mutex_owner_tid_limit) {
Yabin Cuie69c2452015-02-13 16:21:25 -08002115#if defined(__BIONIC__) && !defined(__LP64__)
Yabin Cui140f3672015-02-03 10:32:00 -08002116 FILE* fp = fopen("/proc/sys/kernel/pid_max", "r");
Yi Kong32bc0fc2018-08-02 17:31:13 -07002117 ASSERT_TRUE(fp != nullptr);
Yabin Cui140f3672015-02-03 10:32:00 -08002118 long pid_max;
2119 ASSERT_EQ(1, fscanf(fp, "%ld", &pid_max));
2120 fclose(fp);
Yabin Cuie69c2452015-02-13 16:21:25 -08002121 // Bionic's pthread_mutex implementation on 32-bit devices uses 16 bits to represent owner tid.
Yabin Cui140f3672015-02-03 10:32:00 -08002122 ASSERT_LE(pid_max, 65536);
Yabin Cuie69c2452015-02-13 16:21:25 -08002123#else
2124 GTEST_LOG_(INFO) << "This test does nothing as 32-bit tid is supported by pthread_mutex.\n";
2125#endif
Yabin Cui140f3672015-02-03 10:32:00 -08002126}
Yabin Cuib5845722015-03-16 22:46:42 -07002127
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002128static void pthread_mutex_timedlock_helper(clockid_t clock,
2129 int (*lock_function)(pthread_mutex_t* __mutex,
2130 const timespec* __timeout)) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08002131 pthread_mutex_t m;
2132 ASSERT_EQ(0, pthread_mutex_init(&m, nullptr));
2133
2134 // If the mutex is already locked, pthread_mutex_timedlock should time out.
2135 ASSERT_EQ(0, pthread_mutex_lock(&m));
2136
2137 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002138 ASSERT_EQ(0, clock_gettime(clock, &ts));
2139 ASSERT_EQ(ETIMEDOUT, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002140 ts.tv_nsec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002141 ASSERT_EQ(EINVAL, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002142 ts.tv_nsec = NS_PER_S;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002143 ASSERT_EQ(EINVAL, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002144 ts.tv_nsec = NS_PER_S - 1;
2145 ts.tv_sec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002146 ASSERT_EQ(ETIMEDOUT, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002147
2148 // If the mutex is unlocked, pthread_mutex_timedlock should succeed.
2149 ASSERT_EQ(0, pthread_mutex_unlock(&m));
2150
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002151 ASSERT_EQ(0, clock_gettime(clock, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002152 ts.tv_sec += 1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002153 ASSERT_EQ(0, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002154
2155 ASSERT_EQ(0, pthread_mutex_unlock(&m));
2156 ASSERT_EQ(0, pthread_mutex_destroy(&m));
2157}
2158
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002159TEST(pthread, pthread_mutex_timedlock) {
2160 pthread_mutex_timedlock_helper(CLOCK_REALTIME, pthread_mutex_timedlock);
2161}
2162
2163TEST(pthread, pthread_mutex_timedlock_monotonic_np) {
2164#if defined(__BIONIC__)
2165 pthread_mutex_timedlock_helper(CLOCK_MONOTONIC, pthread_mutex_timedlock_monotonic_np);
2166#else // __BIONIC__
2167 GTEST_LOG_(INFO) << "This test does nothing since pthread_mutex_timedlock_monotonic_np is only "
2168 "supported on bionic";
2169#endif // __BIONIC__
2170}
2171
2172static void pthread_mutex_timedlock_pi_helper(clockid_t clock,
2173 int (*lock_function)(pthread_mutex_t* __mutex,
2174 const timespec* __timeout)) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002175 PthreadMutex m(PTHREAD_MUTEX_NORMAL, PTHREAD_PRIO_INHERIT);
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002176
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002177 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002178 clock_gettime(clock, &ts);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002179 ts.tv_sec += 1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002180 ASSERT_EQ(0, lock_function(&m.lock, &ts));
2181
2182 struct ThreadArgs {
2183 clockid_t clock;
2184 int (*lock_function)(pthread_mutex_t* __mutex, const timespec* __timeout);
2185 PthreadMutex& m;
2186 };
2187
2188 ThreadArgs thread_args = {
2189 .clock = clock,
2190 .lock_function = lock_function,
2191 .m = m,
2192 };
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002193
2194 auto ThreadFn = [](void* arg) -> void* {
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002195 auto args = static_cast<ThreadArgs*>(arg);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002196 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002197 clock_gettime(args->clock, &ts);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002198 ts.tv_sec += 1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002199 intptr_t result = args->lock_function(&args->m.lock, &ts);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002200 return reinterpret_cast<void*>(result);
2201 };
2202
2203 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002204 ASSERT_EQ(0, pthread_create(&thread, nullptr, ThreadFn, &thread_args));
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002205 void* result;
2206 ASSERT_EQ(0, pthread_join(thread, &result));
2207 ASSERT_EQ(ETIMEDOUT, reinterpret_cast<intptr_t>(result));
2208 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2209}
2210
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002211TEST(pthread, pthread_mutex_timedlock_pi) {
2212 pthread_mutex_timedlock_pi_helper(CLOCK_REALTIME, pthread_mutex_timedlock);
2213}
2214
2215TEST(pthread, pthread_mutex_timedlock_monotonic_np_pi) {
2216#if defined(__BIONIC__)
2217 pthread_mutex_timedlock_pi_helper(CLOCK_MONOTONIC, pthread_mutex_timedlock_monotonic_np);
2218#else // __BIONIC__
2219 GTEST_LOG_(INFO) << "This test does nothing since pthread_mutex_timedlock_monotonic_np is only "
2220 "supported on bionic";
2221#endif // __BIONIC__
2222}
2223
Yabin Cui9651fdf2018-03-14 12:02:21 -07002224TEST(pthread, pthread_mutex_using_destroyed_mutex) {
2225#if defined(__BIONIC__)
2226 pthread_mutex_t m;
2227 ASSERT_EQ(0, pthread_mutex_init(&m, nullptr));
2228 ASSERT_EQ(0, pthread_mutex_destroy(&m));
2229 ASSERT_EXIT(pthread_mutex_lock(&m), ::testing::KilledBySignal(SIGABRT),
2230 "pthread_mutex_lock called on a destroyed mutex");
2231 ASSERT_EXIT(pthread_mutex_unlock(&m), ::testing::KilledBySignal(SIGABRT),
2232 "pthread_mutex_unlock called on a destroyed mutex");
2233 ASSERT_EXIT(pthread_mutex_trylock(&m), ::testing::KilledBySignal(SIGABRT),
2234 "pthread_mutex_trylock called on a destroyed mutex");
2235 timespec ts;
2236 ASSERT_EXIT(pthread_mutex_timedlock(&m, &ts), ::testing::KilledBySignal(SIGABRT),
2237 "pthread_mutex_timedlock called on a destroyed mutex");
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002238 ASSERT_EXIT(pthread_mutex_timedlock_monotonic_np(&m, &ts), ::testing::KilledBySignal(SIGABRT),
2239 "pthread_mutex_timedlock_monotonic_np called on a destroyed mutex");
Yabin Cui9651fdf2018-03-14 12:02:21 -07002240 ASSERT_EXIT(pthread_mutex_destroy(&m), ::testing::KilledBySignal(SIGABRT),
2241 "pthread_mutex_destroy called on a destroyed mutex");
2242#else
2243 GTEST_LOG_(INFO) << "This test tests bionic pthread mutex implementation details.";
2244#endif
2245}
2246
Yabin Cuib5845722015-03-16 22:46:42 -07002247class StrictAlignmentAllocator {
2248 public:
2249 void* allocate(size_t size, size_t alignment) {
2250 char* p = new char[size + alignment * 2];
2251 allocated_array.push_back(p);
2252 while (!is_strict_aligned(p, alignment)) {
2253 ++p;
2254 }
2255 return p;
2256 }
2257
2258 ~StrictAlignmentAllocator() {
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07002259 for (const auto& p : allocated_array) {
2260 delete[] p;
Yabin Cuib5845722015-03-16 22:46:42 -07002261 }
2262 }
2263
2264 private:
2265 bool is_strict_aligned(char* p, size_t alignment) {
2266 return (reinterpret_cast<uintptr_t>(p) % (alignment * 2)) == alignment;
2267 }
2268
2269 std::vector<char*> allocated_array;
2270};
2271
2272TEST(pthread, pthread_types_allow_four_bytes_alignment) {
2273#if defined(__BIONIC__)
2274 // For binary compatibility with old version, we need to allow 4-byte aligned data for pthread types.
2275 StrictAlignmentAllocator allocator;
2276 pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(
2277 allocator.allocate(sizeof(pthread_mutex_t), 4));
Yi Kong32bc0fc2018-08-02 17:31:13 -07002278 ASSERT_EQ(0, pthread_mutex_init(mutex, nullptr));
Yabin Cuib5845722015-03-16 22:46:42 -07002279 ASSERT_EQ(0, pthread_mutex_lock(mutex));
2280 ASSERT_EQ(0, pthread_mutex_unlock(mutex));
2281 ASSERT_EQ(0, pthread_mutex_destroy(mutex));
2282
2283 pthread_cond_t* cond = reinterpret_cast<pthread_cond_t*>(
2284 allocator.allocate(sizeof(pthread_cond_t), 4));
Yi Kong32bc0fc2018-08-02 17:31:13 -07002285 ASSERT_EQ(0, pthread_cond_init(cond, nullptr));
Yabin Cuib5845722015-03-16 22:46:42 -07002286 ASSERT_EQ(0, pthread_cond_signal(cond));
2287 ASSERT_EQ(0, pthread_cond_broadcast(cond));
2288 ASSERT_EQ(0, pthread_cond_destroy(cond));
2289
2290 pthread_rwlock_t* rwlock = reinterpret_cast<pthread_rwlock_t*>(
2291 allocator.allocate(sizeof(pthread_rwlock_t), 4));
Yi Kong32bc0fc2018-08-02 17:31:13 -07002292 ASSERT_EQ(0, pthread_rwlock_init(rwlock, nullptr));
Yabin Cuib5845722015-03-16 22:46:42 -07002293 ASSERT_EQ(0, pthread_rwlock_rdlock(rwlock));
2294 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
2295 ASSERT_EQ(0, pthread_rwlock_wrlock(rwlock));
2296 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
2297 ASSERT_EQ(0, pthread_rwlock_destroy(rwlock));
2298
2299#else
2300 GTEST_LOG_(INFO) << "This test tests bionic implementation details.";
2301#endif
2302}
Christopher Ferris60907c72015-06-09 18:46:15 -07002303
2304TEST(pthread, pthread_mutex_lock_null_32) {
2305#if defined(__BIONIC__) && !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -07002306 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return
2307 // EINVAL in that case: http://b/19995172.
2308 //
2309 // We decorate the public defintion with _Nonnull so that people recompiling
2310 // their code with get a warning and might fix their bug, but need to pass
2311 // NULL here to test that we remain compatible.
2312 pthread_mutex_t* null_value = nullptr;
2313 ASSERT_EQ(EINVAL, pthread_mutex_lock(null_value));
Christopher Ferris60907c72015-06-09 18:46:15 -07002314#else
2315 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 32 bit devices.";
2316#endif
2317}
2318
2319TEST(pthread, pthread_mutex_unlock_null_32) {
2320#if defined(__BIONIC__) && !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -07002321 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return
2322 // EINVAL in that case: http://b/19995172.
2323 //
2324 // We decorate the public defintion with _Nonnull so that people recompiling
2325 // their code with get a warning and might fix their bug, but need to pass
2326 // NULL here to test that we remain compatible.
2327 pthread_mutex_t* null_value = nullptr;
2328 ASSERT_EQ(EINVAL, pthread_mutex_unlock(null_value));
Christopher Ferris60907c72015-06-09 18:46:15 -07002329#else
2330 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 32 bit devices.";
2331#endif
2332}
2333
2334TEST_F(pthread_DeathTest, pthread_mutex_lock_null_64) {
2335#if defined(__BIONIC__) && defined(__LP64__)
2336 pthread_mutex_t* null_value = nullptr;
2337 ASSERT_EXIT(pthread_mutex_lock(null_value), testing::KilledBySignal(SIGSEGV), "");
2338#else
2339 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 64 bit devices.";
2340#endif
2341}
2342
2343TEST_F(pthread_DeathTest, pthread_mutex_unlock_null_64) {
2344#if defined(__BIONIC__) && defined(__LP64__)
2345 pthread_mutex_t* null_value = nullptr;
2346 ASSERT_EXIT(pthread_mutex_unlock(null_value), testing::KilledBySignal(SIGSEGV), "");
2347#else
2348 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 64 bit devices.";
2349#endif
2350}
Yabin Cui33ac04a2015-09-22 11:16:15 -07002351
2352extern _Unwind_Reason_Code FrameCounter(_Unwind_Context* ctx, void* arg);
2353
2354static volatile bool signal_handler_on_altstack_done;
2355
Josh Gao61db9ac2017-03-15 19:42:05 -07002356__attribute__((__noinline__))
2357static void signal_handler_backtrace() {
2358 // Check if we have enough stack space for unwinding.
2359 int count = 0;
2360 _Unwind_Backtrace(FrameCounter, &count);
2361 ASSERT_GT(count, 0);
2362}
2363
2364__attribute__((__noinline__))
2365static void signal_handler_logging() {
2366 // Check if we have enough stack space for logging.
2367 std::string s(2048, '*');
2368 GTEST_LOG_(INFO) << s;
2369 signal_handler_on_altstack_done = true;
2370}
2371
2372__attribute__((__noinline__))
2373static void signal_handler_snprintf() {
2374 // Check if we have enough stack space for snprintf to a PATH_MAX buffer, plus some extra.
2375 char buf[PATH_MAX + 2048];
2376 ASSERT_GT(snprintf(buf, sizeof(buf), "/proc/%d/status", getpid()), 0);
2377}
2378
Yabin Cui33ac04a2015-09-22 11:16:15 -07002379static void SignalHandlerOnAltStack(int signo, siginfo_t*, void*) {
2380 ASSERT_EQ(SIGUSR1, signo);
Josh Gao61db9ac2017-03-15 19:42:05 -07002381 signal_handler_backtrace();
2382 signal_handler_logging();
2383 signal_handler_snprintf();
Yabin Cui33ac04a2015-09-22 11:16:15 -07002384}
2385
Josh Gao415daa82017-03-06 17:45:33 -08002386TEST(pthread, big_enough_signal_stack) {
Yabin Cui33ac04a2015-09-22 11:16:15 -07002387 signal_handler_on_altstack_done = false;
2388 ScopedSignalHandler handler(SIGUSR1, SignalHandlerOnAltStack, SA_SIGINFO | SA_ONSTACK);
2389 kill(getpid(), SIGUSR1);
2390 ASSERT_TRUE(signal_handler_on_altstack_done);
2391}
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002392
2393TEST(pthread, pthread_barrierattr_smoke) {
2394 pthread_barrierattr_t attr;
2395 ASSERT_EQ(0, pthread_barrierattr_init(&attr));
2396 int pshared;
2397 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
2398 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
2399 ASSERT_EQ(0, pthread_barrierattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
2400 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
2401 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
2402 ASSERT_EQ(0, pthread_barrierattr_destroy(&attr));
2403}
2404
Yabin Cui81d27972016-03-22 13:45:55 -07002405struct BarrierTestHelperData {
2406 size_t thread_count;
2407 pthread_barrier_t barrier;
2408 std::atomic<int> finished_mask;
2409 std::atomic<int> serial_thread_count;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002410 size_t iteration_count;
Yabin Cui81d27972016-03-22 13:45:55 -07002411 std::atomic<size_t> finished_iteration_count;
2412
2413 BarrierTestHelperData(size_t thread_count, size_t iteration_count)
2414 : thread_count(thread_count), finished_mask(0), serial_thread_count(0),
2415 iteration_count(iteration_count), finished_iteration_count(0) {
2416 }
2417};
2418
2419struct BarrierTestHelperArg {
2420 int id;
2421 BarrierTestHelperData* data;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002422};
2423
2424static void BarrierTestHelper(BarrierTestHelperArg* arg) {
Yabin Cui81d27972016-03-22 13:45:55 -07002425 for (size_t i = 0; i < arg->data->iteration_count; ++i) {
2426 int result = pthread_barrier_wait(&arg->data->barrier);
2427 if (result == PTHREAD_BARRIER_SERIAL_THREAD) {
2428 arg->data->serial_thread_count++;
2429 } else {
2430 ASSERT_EQ(0, result);
2431 }
Yabin Cuid5c04c52017-05-02 12:57:39 -07002432 int mask = arg->data->finished_mask.fetch_or(1 << arg->id);
Yabin Cuiab4cddc2017-05-02 16:18:13 -07002433 mask |= 1 << arg->id;
Yabin Cuid5c04c52017-05-02 12:57:39 -07002434 if (mask == ((1 << arg->data->thread_count) - 1)) {
Yabin Cui81d27972016-03-22 13:45:55 -07002435 ASSERT_EQ(1, arg->data->serial_thread_count);
2436 arg->data->finished_iteration_count++;
2437 arg->data->finished_mask = 0;
2438 arg->data->serial_thread_count = 0;
2439 }
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002440 }
2441}
2442
2443TEST(pthread, pthread_barrier_smoke) {
2444 const size_t BARRIER_ITERATION_COUNT = 10;
2445 const size_t BARRIER_THREAD_COUNT = 10;
Yabin Cui81d27972016-03-22 13:45:55 -07002446 BarrierTestHelperData data(BARRIER_THREAD_COUNT, BARRIER_ITERATION_COUNT);
2447 ASSERT_EQ(0, pthread_barrier_init(&data.barrier, nullptr, data.thread_count));
2448 std::vector<pthread_t> threads(data.thread_count);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002449 std::vector<BarrierTestHelperArg> args(threads.size());
2450 for (size_t i = 0; i < threads.size(); ++i) {
Yabin Cui81d27972016-03-22 13:45:55 -07002451 args[i].id = i;
2452 args[i].data = &data;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002453 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
2454 reinterpret_cast<void* (*)(void*)>(BarrierTestHelper), &args[i]));
2455 }
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002456 for (size_t i = 0; i < threads.size(); ++i) {
2457 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
2458 }
Yabin Cui81d27972016-03-22 13:45:55 -07002459 ASSERT_EQ(data.iteration_count, data.finished_iteration_count);
2460 ASSERT_EQ(0, pthread_barrier_destroy(&data.barrier));
2461}
2462
2463struct BarrierDestroyTestArg {
2464 std::atomic<int> tid;
2465 pthread_barrier_t* barrier;
2466};
2467
2468static void BarrierDestroyTestHelper(BarrierDestroyTestArg* arg) {
2469 arg->tid = gettid();
2470 ASSERT_EQ(0, pthread_barrier_wait(arg->barrier));
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002471}
2472
2473TEST(pthread, pthread_barrier_destroy) {
2474 pthread_barrier_t barrier;
2475 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, 2));
2476 pthread_t thread;
Yabin Cui81d27972016-03-22 13:45:55 -07002477 BarrierDestroyTestArg arg;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002478 arg.tid = 0;
2479 arg.barrier = &barrier;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002480 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui81d27972016-03-22 13:45:55 -07002481 reinterpret_cast<void* (*)(void*)>(BarrierDestroyTestHelper), &arg));
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002482 WaitUntilThreadSleep(arg.tid);
2483 ASSERT_EQ(EBUSY, pthread_barrier_destroy(&barrier));
2484 ASSERT_EQ(PTHREAD_BARRIER_SERIAL_THREAD, pthread_barrier_wait(&barrier));
2485 // Verify if the barrier can be destroyed directly after pthread_barrier_wait().
2486 ASSERT_EQ(0, pthread_barrier_destroy(&barrier));
2487 ASSERT_EQ(0, pthread_join(thread, nullptr));
2488#if defined(__BIONIC__)
2489 ASSERT_EQ(EINVAL, pthread_barrier_destroy(&barrier));
2490#endif
2491}
2492
2493struct BarrierOrderingTestHelperArg {
2494 pthread_barrier_t* barrier;
2495 size_t* array;
2496 size_t array_length;
2497 size_t id;
2498};
2499
2500void BarrierOrderingTestHelper(BarrierOrderingTestHelperArg* arg) {
2501 const size_t ITERATION_COUNT = 10000;
2502 for (size_t i = 1; i <= ITERATION_COUNT; ++i) {
2503 arg->array[arg->id] = i;
Yabin Cuic9a659c2015-11-05 15:36:08 -08002504 int result = pthread_barrier_wait(arg->barrier);
2505 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002506 for (size_t j = 0; j < arg->array_length; ++j) {
2507 ASSERT_EQ(i, arg->array[j]);
2508 }
Yabin Cuic9a659c2015-11-05 15:36:08 -08002509 result = pthread_barrier_wait(arg->barrier);
2510 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002511 }
2512}
2513
2514TEST(pthread, pthread_barrier_check_ordering) {
2515 const size_t THREAD_COUNT = 4;
2516 pthread_barrier_t barrier;
2517 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, THREAD_COUNT));
2518 size_t array[THREAD_COUNT];
2519 std::vector<pthread_t> threads(THREAD_COUNT);
2520 std::vector<BarrierOrderingTestHelperArg> args(THREAD_COUNT);
2521 for (size_t i = 0; i < THREAD_COUNT; ++i) {
2522 args[i].barrier = &barrier;
2523 args[i].array = array;
2524 args[i].array_length = THREAD_COUNT;
2525 args[i].id = i;
2526 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
2527 reinterpret_cast<void* (*)(void*)>(BarrierOrderingTestHelper),
2528 &args[i]));
2529 }
2530 for (size_t i = 0; i < THREAD_COUNT; ++i) {
2531 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
2532 }
2533}
Yabin Cuife3a83a2015-11-17 16:03:18 -08002534
Elliott Hughes463faad2018-07-06 14:34:49 -07002535TEST(pthread, pthread_barrier_init_zero_count) {
2536 pthread_barrier_t barrier;
2537 ASSERT_EQ(EINVAL, pthread_barrier_init(&barrier, nullptr, 0));
2538}
2539
Yabin Cuife3a83a2015-11-17 16:03:18 -08002540TEST(pthread, pthread_spinlock_smoke) {
2541 pthread_spinlock_t lock;
2542 ASSERT_EQ(0, pthread_spin_init(&lock, 0));
2543 ASSERT_EQ(0, pthread_spin_trylock(&lock));
2544 ASSERT_EQ(0, pthread_spin_unlock(&lock));
2545 ASSERT_EQ(0, pthread_spin_lock(&lock));
2546 ASSERT_EQ(EBUSY, pthread_spin_trylock(&lock));
2547 ASSERT_EQ(0, pthread_spin_unlock(&lock));
2548 ASSERT_EQ(0, pthread_spin_destroy(&lock));
2549}
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002550
Elliott Hughes8aecba72017-10-17 15:34:41 -07002551TEST(pthread, pthread_attr_getdetachstate__pthread_attr_setdetachstate) {
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002552 pthread_attr_t attr;
2553 ASSERT_EQ(0, pthread_attr_init(&attr));
2554
Elliott Hughes8aecba72017-10-17 15:34:41 -07002555 int state;
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002556 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002557 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2558 ASSERT_EQ(PTHREAD_CREATE_DETACHED, state);
2559
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002560 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002561 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2562 ASSERT_EQ(PTHREAD_CREATE_JOINABLE, state);
2563
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002564 ASSERT_EQ(EINVAL, pthread_attr_setdetachstate(&attr, 123));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002565 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2566 ASSERT_EQ(PTHREAD_CREATE_JOINABLE, state);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002567}
2568
2569TEST(pthread, pthread_create__mmap_failures) {
2570 pthread_attr_t attr;
2571 ASSERT_EQ(0, pthread_attr_init(&attr));
2572 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
2573
2574 const auto kPageSize = sysconf(_SC_PAGE_SIZE);
2575
Elliott Hughes57512982017-10-02 22:49:18 -07002576 // Use up all the VMAs. By default this is 64Ki (though some will already be in use).
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002577 std::vector<void*> pages;
Elliott Hughes57512982017-10-02 22:49:18 -07002578 pages.reserve(64 * 1024);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002579 int prot = PROT_NONE;
2580 while (true) {
2581 void* page = mmap(nullptr, kPageSize, prot, MAP_ANON|MAP_PRIVATE, -1, 0);
2582 if (page == MAP_FAILED) break;
2583 pages.push_back(page);
2584 prot = (prot == PROT_NONE) ? PROT_READ : PROT_NONE;
2585 }
2586
2587 // Try creating threads, freeing up a page each time we fail.
2588 size_t EAGAIN_count = 0;
2589 size_t i = 0;
2590 for (; i < pages.size(); ++i) {
2591 pthread_t t;
2592 int status = pthread_create(&t, &attr, IdFn, nullptr);
2593 if (status != EAGAIN) break;
2594 ++EAGAIN_count;
2595 ASSERT_EQ(0, munmap(pages[i], kPageSize));
2596 }
2597
Ryan Prichard45d13492019-01-03 02:51:30 -08002598 // Creating a thread uses at least three VMAs: the combined stack and TLS, and a guard on each
2599 // side. So we should have seen at least three failures.
2600 ASSERT_GE(EAGAIN_count, 3U);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002601
2602 for (; i < pages.size(); ++i) {
2603 ASSERT_EQ(0, munmap(pages[i], kPageSize));
2604 }
2605}
Elliott Hughesdff08ce2017-10-16 09:58:45 -07002606
2607TEST(pthread, pthread_setschedparam) {
2608 sched_param p = { .sched_priority = INT_MIN };
2609 ASSERT_EQ(EINVAL, pthread_setschedparam(pthread_self(), INT_MIN, &p));
2610}
2611
2612TEST(pthread, pthread_setschedprio) {
2613 ASSERT_EQ(EINVAL, pthread_setschedprio(pthread_self(), INT_MIN));
2614}
Elliott Hughes8aecba72017-10-17 15:34:41 -07002615
2616TEST(pthread, pthread_attr_getinheritsched__pthread_attr_setinheritsched) {
2617 pthread_attr_t attr;
2618 ASSERT_EQ(0, pthread_attr_init(&attr));
2619
2620 int state;
2621 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2622 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
2623 ASSERT_EQ(PTHREAD_INHERIT_SCHED, state);
2624
2625 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
2626 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
2627 ASSERT_EQ(PTHREAD_EXPLICIT_SCHED, state);
2628
2629 ASSERT_EQ(EINVAL, pthread_attr_setinheritsched(&attr, 123));
2630 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
2631 ASSERT_EQ(PTHREAD_EXPLICIT_SCHED, state);
2632}
2633
2634TEST(pthread, pthread_attr_setinheritsched__PTHREAD_INHERIT_SCHED__PTHREAD_EXPLICIT_SCHED) {
2635 pthread_attr_t attr;
2636 ASSERT_EQ(0, pthread_attr_init(&attr));
2637
2638 // If we set invalid scheduling attributes but choose to inherit, everything's fine...
2639 sched_param param = { .sched_priority = sched_get_priority_max(SCHED_FIFO) + 1 };
2640 ASSERT_EQ(0, pthread_attr_setschedparam(&attr, &param));
2641 ASSERT_EQ(0, pthread_attr_setschedpolicy(&attr, SCHED_FIFO));
2642 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2643
2644 pthread_t t;
2645 ASSERT_EQ(0, pthread_create(&t, &attr, IdFn, nullptr));
2646 ASSERT_EQ(0, pthread_join(t, nullptr));
2647
Elliott Hughes7a660662017-10-30 09:26:06 -07002648#if defined(__LP64__)
2649 // If we ask to use them, though, we'll see a failure...
Elliott Hughes8aecba72017-10-17 15:34:41 -07002650 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
2651 ASSERT_EQ(EINVAL, pthread_create(&t, &attr, IdFn, nullptr));
Elliott Hughes7a660662017-10-30 09:26:06 -07002652#else
2653 // For backwards compatibility with broken apps, we just ignore failures
2654 // to set scheduler attributes on LP32.
2655#endif
Elliott Hughes8aecba72017-10-17 15:34:41 -07002656}
2657
2658TEST(pthread, pthread_attr_setinheritsched_PTHREAD_INHERIT_SCHED_takes_effect) {
2659 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
2660 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO, &param);
2661 if (rc == EPERM) {
2662 GTEST_LOG_(INFO) << "pthread_setschedparam failed with EPERM, skipping test\n";
2663 return;
2664 }
2665 ASSERT_EQ(0, rc);
2666
2667 pthread_attr_t attr;
2668 ASSERT_EQ(0, pthread_attr_init(&attr));
2669 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2670
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002671 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07002672 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002673 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002674 int actual_policy;
2675 sched_param actual_param;
2676 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
2677 ASSERT_EQ(SCHED_FIFO, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002678 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07002679 ASSERT_EQ(0, pthread_join(t, nullptr));
2680}
2681
2682TEST(pthread, pthread_attr_setinheritsched_PTHREAD_EXPLICIT_SCHED_takes_effect) {
2683 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
2684 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO, &param);
2685 if (rc == EPERM) {
2686 GTEST_LOG_(INFO) << "pthread_setschedparam failed with EPERM, skipping test\n";
2687 return;
2688 }
2689 ASSERT_EQ(0, rc);
2690
2691 pthread_attr_t attr;
2692 ASSERT_EQ(0, pthread_attr_init(&attr));
2693 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
2694 ASSERT_EQ(0, pthread_attr_setschedpolicy(&attr, SCHED_OTHER));
2695
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002696 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07002697 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002698 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002699 int actual_policy;
2700 sched_param actual_param;
2701 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
2702 ASSERT_EQ(SCHED_OTHER, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002703 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07002704 ASSERT_EQ(0, pthread_join(t, nullptr));
2705}
2706
2707TEST(pthread, pthread_attr_setinheritsched__takes_effect_despite_SCHED_RESET_ON_FORK) {
2708 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
2709 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param);
2710 if (rc == EPERM) {
2711 GTEST_LOG_(INFO) << "pthread_setschedparam failed with EPERM, skipping test\n";
2712 return;
2713 }
2714 ASSERT_EQ(0, rc);
2715
2716 pthread_attr_t attr;
2717 ASSERT_EQ(0, pthread_attr_init(&attr));
2718 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2719
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002720 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07002721 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002722 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002723 int actual_policy;
2724 sched_param actual_param;
2725 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
2726 ASSERT_EQ(SCHED_FIFO | SCHED_RESET_ON_FORK, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002727 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07002728 ASSERT_EQ(0, pthread_join(t, nullptr));
2729}