blob: e6bd1ef20c989723c886f07223abe4c6a1e8a6bc [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
340 // Let the main thread know we're running.
341 pthread_mutex_unlock(&data->mutex);
342
343 // And wait for the main thread to exit.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700344 pthread_join(data->main_thread, nullptr);
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800345
Yi Kong32bc0fc2018-08-02 17:31:13 -0700346 return nullptr;
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800347 }
348};
Elliott Hughes4f251be2012-11-01 16:33:29 -0700349
Elliott Hughes7fd803c2013-02-14 16:33:52 -0800350// Even though this isn't really a death test, we have to say "DeathTest" here so gtest knows to
351// run this test (which exits normally) in its own process.
Yabin Cui9df70402014-11-05 18:01:01 -0800352
353class pthread_DeathTest : public BionicDeathTest {};
354
355TEST_F(pthread_DeathTest, pthread_bug_37410) {
Elliott Hughes4f251be2012-11-01 16:33:29 -0700356 // http://code.google.com/p/android/issues/detail?id=37410
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800357 ASSERT_EXIT(TestBug37410::main(), ::testing::ExitedWithCode(0), "");
Elliott Hughes4f251be2012-11-01 16:33:29 -0700358}
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800359
360static void* SignalHandlerFn(void* arg) {
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800361 sigset64_t wait_set;
362 sigfillset64(&wait_set);
363 return reinterpret_cast<void*>(sigwait64(&wait_set, reinterpret_cast<int*>(arg)));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800364}
365
366TEST(pthread, pthread_sigmask) {
Elliott Hughes19e62322013-10-15 11:23:57 -0700367 // Check that SIGUSR1 isn't blocked.
368 sigset_t original_set;
369 sigemptyset(&original_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700370 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, nullptr, &original_set));
Elliott Hughes19e62322013-10-15 11:23:57 -0700371 ASSERT_FALSE(sigismember(&original_set, SIGUSR1));
372
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800373 // Block SIGUSR1.
374 sigset_t set;
375 sigemptyset(&set);
376 sigaddset(&set, SIGUSR1);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700377 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, &set, nullptr));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800378
Elliott Hughes19e62322013-10-15 11:23:57 -0700379 // Check that SIGUSR1 is blocked.
380 sigset_t final_set;
381 sigemptyset(&final_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700382 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, nullptr, &final_set));
Elliott Hughes19e62322013-10-15 11:23:57 -0700383 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
384 // ...and that sigprocmask agrees with pthread_sigmask.
385 sigemptyset(&final_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700386 ASSERT_EQ(0, sigprocmask(SIG_BLOCK, nullptr, &final_set));
Elliott Hughes19e62322013-10-15 11:23:57 -0700387 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
388
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800389 // Spawn a thread that calls sigwait and tells us what it received.
390 pthread_t signal_thread;
391 int received_signal = -1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700392 ASSERT_EQ(0, pthread_create(&signal_thread, nullptr, SignalHandlerFn, &received_signal));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800393
394 // Send that thread SIGUSR1.
395 pthread_kill(signal_thread, SIGUSR1);
396
397 // See what it got.
398 void* join_result;
399 ASSERT_EQ(0, pthread_join(signal_thread, &join_result));
400 ASSERT_EQ(SIGUSR1, received_signal);
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700401 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
Elliott Hughes19e62322013-10-15 11:23:57 -0700402
403 // Restore the original signal mask.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700404 ASSERT_EQ(0, pthread_sigmask(SIG_SETMASK, &original_set, nullptr));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800405}
Elliott Hughes5e3fc432013-02-11 16:36:48 -0800406
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800407TEST(pthread, pthread_sigmask64_SIGTRMIN) {
408 // Check that SIGRTMIN isn't blocked.
409 sigset64_t original_set;
410 sigemptyset64(&original_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700411 ASSERT_EQ(0, pthread_sigmask64(SIG_BLOCK, nullptr, &original_set));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800412 ASSERT_FALSE(sigismember64(&original_set, SIGRTMIN));
413
414 // Block SIGRTMIN.
415 sigset64_t set;
416 sigemptyset64(&set);
417 sigaddset64(&set, SIGRTMIN);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700418 ASSERT_EQ(0, pthread_sigmask64(SIG_BLOCK, &set, nullptr));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800419
420 // Check that SIGRTMIN is blocked.
421 sigset64_t final_set;
422 sigemptyset64(&final_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700423 ASSERT_EQ(0, pthread_sigmask64(SIG_BLOCK, nullptr, &final_set));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800424 ASSERT_TRUE(sigismember64(&final_set, SIGRTMIN));
425 // ...and that sigprocmask64 agrees with pthread_sigmask64.
426 sigemptyset64(&final_set);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700427 ASSERT_EQ(0, sigprocmask64(SIG_BLOCK, nullptr, &final_set));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800428 ASSERT_TRUE(sigismember64(&final_set, SIGRTMIN));
429
430 // Spawn a thread that calls sigwait64 and tells us what it received.
431 pthread_t signal_thread;
432 int received_signal = -1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700433 ASSERT_EQ(0, pthread_create(&signal_thread, nullptr, SignalHandlerFn, &received_signal));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800434
435 // Send that thread SIGRTMIN.
436 pthread_kill(signal_thread, SIGRTMIN);
437
438 // See what it got.
439 void* join_result;
440 ASSERT_EQ(0, pthread_join(signal_thread, &join_result));
441 ASSERT_EQ(SIGRTMIN, received_signal);
442 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
443
444 // Restore the original signal mask.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700445 ASSERT_EQ(0, pthread_sigmask64(SIG_SETMASK, &original_set, nullptr));
Elliott Hughes5905d6f2018-01-30 15:09:51 -0800446}
447
Elliott Hughes725b2a92016-03-23 11:20:47 -0700448static void test_pthread_setname_np__pthread_getname_np(pthread_t t) {
449 ASSERT_EQ(0, pthread_setname_np(t, "short"));
450 char name[32];
451 ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name)));
452 ASSERT_STREQ("short", name);
453
Elliott Hughesd1aea302015-04-25 10:05:24 -0700454 // The limit is 15 characters --- the kernel's buffer is 16, but includes a NUL.
Elliott Hughes725b2a92016-03-23 11:20:47 -0700455 ASSERT_EQ(0, pthread_setname_np(t, "123456789012345"));
456 ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name)));
457 ASSERT_STREQ("123456789012345", name);
458
459 ASSERT_EQ(ERANGE, pthread_setname_np(t, "1234567890123456"));
460
461 // The passed-in buffer should be at least 16 bytes.
462 ASSERT_EQ(0, pthread_getname_np(t, name, 16));
463 ASSERT_EQ(ERANGE, pthread_getname_np(t, name, 15));
Elliott Hughes3e898472013-02-12 16:40:24 +0000464}
465
Elliott Hughes725b2a92016-03-23 11:20:47 -0700466TEST(pthread, pthread_setname_np__pthread_getname_np__self) {
467 test_pthread_setname_np__pthread_getname_np(pthread_self());
Elliott Hughes3e898472013-02-12 16:40:24 +0000468}
469
Elliott Hughes725b2a92016-03-23 11:20:47 -0700470TEST(pthread, pthread_setname_np__pthread_getname_np__other) {
471 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800472
Elliott Hughes725b2a92016-03-23 11:20:47 -0700473 pthread_t t;
Elliott Hughes4d098ca2016-04-11 12:43:05 -0700474 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
475 test_pthread_setname_np__pthread_getname_np(t);
476 spin_helper.UnSpin();
477 ASSERT_EQ(0, pthread_join(t, nullptr));
478}
479
480// http://b/28051133: a kernel misfeature means that you can't change the
481// name of another thread if you've set PR_SET_DUMPABLE to 0.
482TEST(pthread, pthread_setname_np__pthread_getname_np__other_PR_SET_DUMPABLE) {
483 ASSERT_EQ(0, prctl(PR_SET_DUMPABLE, 0)) << strerror(errno);
484
485 SpinFunctionHelper spin_helper;
486
487 pthread_t t;
488 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
Elliott Hughes725b2a92016-03-23 11:20:47 -0700489 test_pthread_setname_np__pthread_getname_np(t);
490 spin_helper.UnSpin();
491 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes3e898472013-02-12 16:40:24 +0000492}
493
Elliott Hughes11859d42017-02-13 17:59:29 -0800494TEST_F(pthread_DeathTest, pthread_setname_np__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000495 pthread_t dead_thread;
496 MakeDeadThread(dead_thread);
497
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800498 EXPECT_DEATH(pthread_setname_np(dead_thread, "short 3"),
499 "invalid pthread_t (.*) passed to pthread_setname_np");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800500}
501
502TEST_F(pthread_DeathTest, pthread_setname_np__null_thread) {
503 pthread_t null_thread = 0;
504 EXPECT_EQ(ENOENT, pthread_setname_np(null_thread, "short 3"));
Elliott Hughes11859d42017-02-13 17:59:29 -0800505}
506
507TEST_F(pthread_DeathTest, pthread_getname_np__no_such_thread) {
508 pthread_t dead_thread;
509 MakeDeadThread(dead_thread);
510
Elliott Hughesbcb15292017-02-07 21:05:30 +0000511 char name[64];
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800512 EXPECT_DEATH(pthread_getname_np(dead_thread, name, sizeof(name)),
513 "invalid pthread_t (.*) passed to pthread_getname_np");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800514}
515
516TEST_F(pthread_DeathTest, pthread_getname_np__null_thread) {
517 pthread_t null_thread = 0;
518
519 char name[64];
520 EXPECT_EQ(ENOENT, pthread_getname_np(null_thread, name, sizeof(name)));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000521}
522
Elliott Hughes9d23e042013-02-15 19:21:51 -0800523TEST(pthread, pthread_kill__0) {
524 // Signal 0 just tests that the thread exists, so it's safe to call on ourselves.
525 ASSERT_EQ(0, pthread_kill(pthread_self(), 0));
526}
527
528TEST(pthread, pthread_kill__invalid_signal) {
529 ASSERT_EQ(EINVAL, pthread_kill(pthread_self(), -1));
530}
531
Elliott Hughesfae89fc2013-02-21 11:22:23 -0800532static void pthread_kill__in_signal_handler_helper(int signal_number) {
533 static int count = 0;
534 ASSERT_EQ(SIGALRM, signal_number);
535 if (++count == 1) {
536 // Can we call pthread_kill from a signal handler?
537 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
538 }
539}
540
541TEST(pthread, pthread_kill__in_signal_handler) {
Elliott Hughes4b558f52014-03-04 15:58:02 -0800542 ScopedSignalHandler ssh(SIGALRM, pthread_kill__in_signal_handler_helper);
Elliott Hughesfae89fc2013-02-21 11:22:23 -0800543 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
544}
545
Josh Gaoddf757e2018-10-17 15:23:03 -0700546TEST(pthread, pthread_kill__exited_thread) {
547 static std::promise<pid_t> tid_promise;
548 pthread_t thread;
549 ASSERT_EQ(0, pthread_create(&thread, nullptr,
550 [](void*) -> void* {
551 tid_promise.set_value(gettid());
552 return nullptr;
553 },
554 nullptr));
555
556 pid_t tid = tid_promise.get_future().get();
557 while (TEMP_FAILURE_RETRY(syscall(__NR_tgkill, getpid(), tid, 0)) != -1) {
558 continue;
559 }
560 ASSERT_EQ(ESRCH, errno);
561
562 ASSERT_EQ(ESRCH, pthread_kill(thread, 0));
563}
564
Elliott Hughes11859d42017-02-13 17:59:29 -0800565TEST_F(pthread_DeathTest, pthread_detach__no_such_thread) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000566 pthread_t dead_thread;
567 MakeDeadThread(dead_thread);
568
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800569 EXPECT_DEATH(pthread_detach(dead_thread),
570 "invalid pthread_t (.*) passed to pthread_detach");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800571}
572
573TEST_F(pthread_DeathTest, pthread_detach__null_thread) {
574 pthread_t null_thread = 0;
575 EXPECT_EQ(ESRCH, pthread_detach(null_thread));
Elliott Hughes7484c212017-02-02 02:41:38 +0000576}
577
Jeff Hao9b06cc32013-08-15 14:51:16 -0700578TEST(pthread, pthread_getcpuclockid__clock_gettime) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700579 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800580
Jeff Hao9b06cc32013-08-15 14:51:16 -0700581 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700582 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
Jeff Hao9b06cc32013-08-15 14:51:16 -0700583
584 clockid_t c;
585 ASSERT_EQ(0, pthread_getcpuclockid(t, &c));
586 timespec ts;
587 ASSERT_EQ(0, clock_gettime(c, &ts));
Elliott Hughes725b2a92016-03-23 11:20:47 -0700588 spin_helper.UnSpin();
Yabin Cuia36158a2015-11-16 21:06:16 -0800589 ASSERT_EQ(0, pthread_join(t, nullptr));
Jeff Hao9b06cc32013-08-15 14:51:16 -0700590}
591
Elliott Hughes11859d42017-02-13 17:59:29 -0800592TEST_F(pthread_DeathTest, pthread_getcpuclockid__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000593 pthread_t dead_thread;
594 MakeDeadThread(dead_thread);
595
596 clockid_t c;
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800597 EXPECT_DEATH(pthread_getcpuclockid(dead_thread, &c),
598 "invalid pthread_t (.*) passed to pthread_getcpuclockid");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800599}
600
601TEST_F(pthread_DeathTest, pthread_getcpuclockid__null_thread) {
602 pthread_t null_thread = 0;
603 clockid_t c;
604 EXPECT_EQ(ESRCH, pthread_getcpuclockid(null_thread, &c));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000605}
606
Elliott Hughes11859d42017-02-13 17:59:29 -0800607TEST_F(pthread_DeathTest, pthread_getschedparam__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000608 pthread_t dead_thread;
609 MakeDeadThread(dead_thread);
610
611 int policy;
612 sched_param param;
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800613 EXPECT_DEATH(pthread_getschedparam(dead_thread, &policy, &param),
614 "invalid pthread_t (.*) passed to pthread_getschedparam");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800615}
616
617TEST_F(pthread_DeathTest, pthread_getschedparam__null_thread) {
618 pthread_t null_thread = 0;
619 int policy;
620 sched_param param;
621 EXPECT_EQ(ESRCH, pthread_getschedparam(null_thread, &policy, &param));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000622}
623
Elliott Hughes11859d42017-02-13 17:59:29 -0800624TEST_F(pthread_DeathTest, pthread_setschedparam__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000625 pthread_t dead_thread;
626 MakeDeadThread(dead_thread);
627
628 int policy = 0;
629 sched_param param;
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800630 EXPECT_DEATH(pthread_setschedparam(dead_thread, policy, &param),
631 "invalid pthread_t (.*) passed to pthread_setschedparam");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800632}
633
634TEST_F(pthread_DeathTest, pthread_setschedparam__null_thread) {
635 pthread_t null_thread = 0;
636 int policy = 0;
637 sched_param param;
638 EXPECT_EQ(ESRCH, pthread_setschedparam(null_thread, policy, &param));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000639}
640
Elliott Hughesdff08ce2017-10-16 09:58:45 -0700641TEST_F(pthread_DeathTest, pthread_setschedprio__no_such_thread) {
642 pthread_t dead_thread;
643 MakeDeadThread(dead_thread);
644
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800645 EXPECT_DEATH(pthread_setschedprio(dead_thread, 123),
646 "invalid pthread_t (.*) passed to pthread_setschedprio");
Elliott Hughesdff08ce2017-10-16 09:58:45 -0700647}
648
649TEST_F(pthread_DeathTest, pthread_setschedprio__null_thread) {
650 pthread_t null_thread = 0;
651 EXPECT_EQ(ESRCH, pthread_setschedprio(null_thread, 123));
652}
653
Elliott Hughes11859d42017-02-13 17:59:29 -0800654TEST_F(pthread_DeathTest, pthread_join__no_such_thread) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000655 pthread_t dead_thread;
656 MakeDeadThread(dead_thread);
657
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800658 EXPECT_DEATH(pthread_join(dead_thread, nullptr),
659 "invalid pthread_t (.*) passed to pthread_join");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800660}
661
662TEST_F(pthread_DeathTest, pthread_join__null_thread) {
663 pthread_t null_thread = 0;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700664 EXPECT_EQ(ESRCH, pthread_join(null_thread, nullptr));
Elliott Hughes7484c212017-02-02 02:41:38 +0000665}
666
Elliott Hughes11859d42017-02-13 17:59:29 -0800667TEST_F(pthread_DeathTest, pthread_kill__no_such_thread) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000668 pthread_t dead_thread;
669 MakeDeadThread(dead_thread);
670
Elliott Hughes5bb113c2019-02-01 16:31:10 -0800671 EXPECT_DEATH(pthread_kill(dead_thread, 0),
672 "invalid pthread_t (.*) passed to pthread_kill");
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800673}
674
675TEST_F(pthread_DeathTest, pthread_kill__null_thread) {
676 pthread_t null_thread = 0;
677 EXPECT_EQ(ESRCH, pthread_kill(null_thread, 0));
Elliott Hughes7484c212017-02-02 02:41:38 +0000678}
679
msg5550f020d12013-06-06 14:59:28 -0400680TEST(pthread, pthread_join__multijoin) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700681 SpinFunctionHelper spin_helper;
msg5550f020d12013-06-06 14:59:28 -0400682
683 pthread_t t1;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700684 ASSERT_EQ(0, pthread_create(&t1, nullptr, spin_helper.GetFunction(), nullptr));
msg5550f020d12013-06-06 14:59:28 -0400685
686 pthread_t t2;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700687 ASSERT_EQ(0, pthread_create(&t2, nullptr, JoinFn, reinterpret_cast<void*>(t1)));
msg5550f020d12013-06-06 14:59:28 -0400688
689 sleep(1); // (Give t2 a chance to call pthread_join.)
690
691 // Multiple joins to the same thread should fail.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700692 ASSERT_EQ(EINVAL, pthread_join(t1, nullptr));
msg5550f020d12013-06-06 14:59:28 -0400693
Elliott Hughes725b2a92016-03-23 11:20:47 -0700694 spin_helper.UnSpin();
msg5550f020d12013-06-06 14:59:28 -0400695
696 // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes).
697 void* join_result;
698 ASSERT_EQ(0, pthread_join(t2, &join_result));
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700699 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
msg5550f020d12013-06-06 14:59:28 -0400700}
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700701
Elliott Hughes70b24b12013-11-15 11:51:07 -0800702TEST(pthread, pthread_join__race) {
703 // http://b/11693195 --- pthread_join could return before the thread had actually exited.
704 // If the joiner unmapped the thread's stack, that could lead to SIGSEGV in the thread.
705 for (size_t i = 0; i < 1024; ++i) {
Yabin Cuia36158a2015-11-16 21:06:16 -0800706 size_t stack_size = 640*1024;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700707 void* stack = mmap(nullptr, stack_size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
Elliott Hughes70b24b12013-11-15 11:51:07 -0800708
709 pthread_attr_t a;
710 pthread_attr_init(&a);
711 pthread_attr_setstack(&a, stack, stack_size);
712
713 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700714 ASSERT_EQ(0, pthread_create(&t, &a, IdFn, nullptr));
715 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes70b24b12013-11-15 11:51:07 -0800716 ASSERT_EQ(0, munmap(stack, stack_size));
717 }
718}
719
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700720static void* GetActualGuardSizeFn(void* arg) {
721 pthread_attr_t attributes;
722 pthread_getattr_np(pthread_self(), &attributes);
723 pthread_attr_getguardsize(&attributes, reinterpret_cast<size_t*>(arg));
Yi Kong32bc0fc2018-08-02 17:31:13 -0700724 return nullptr;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700725}
726
727static size_t GetActualGuardSize(const pthread_attr_t& attributes) {
728 size_t result;
729 pthread_t t;
730 pthread_create(&t, &attributes, GetActualGuardSizeFn, &result);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700731 pthread_join(t, nullptr);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700732 return result;
733}
734
735static void* GetActualStackSizeFn(void* arg) {
736 pthread_attr_t attributes;
737 pthread_getattr_np(pthread_self(), &attributes);
738 pthread_attr_getstacksize(&attributes, reinterpret_cast<size_t*>(arg));
Yi Kong32bc0fc2018-08-02 17:31:13 -0700739 return nullptr;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700740}
741
742static size_t GetActualStackSize(const pthread_attr_t& attributes) {
743 size_t result;
744 pthread_t t;
745 pthread_create(&t, &attributes, GetActualStackSizeFn, &result);
Yi Kong32bc0fc2018-08-02 17:31:13 -0700746 pthread_join(t, nullptr);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700747 return result;
748}
749
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700750TEST(pthread, pthread_attr_setguardsize_tiny) {
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700751 pthread_attr_t attributes;
752 ASSERT_EQ(0, pthread_attr_init(&attributes));
753
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700754 // No such thing as too small: will be rounded up to one page by pthread_create.
755 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 128));
756 size_t guard_size;
757 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
758 ASSERT_EQ(128U, guard_size);
759 ASSERT_EQ(4096U, GetActualGuardSize(attributes));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700760}
761
762TEST(pthread, pthread_attr_setguardsize_reasonable) {
763 pthread_attr_t attributes;
764 ASSERT_EQ(0, pthread_attr_init(&attributes));
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700765
766 // Large enough and a multiple of the page size.
767 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700768 size_t guard_size;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700769 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
770 ASSERT_EQ(32*1024U, guard_size);
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700771 ASSERT_EQ(32*1024U, GetActualGuardSize(attributes));
772}
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700773
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700774TEST(pthread, pthread_attr_setguardsize_needs_rounding) {
775 pthread_attr_t attributes;
776 ASSERT_EQ(0, pthread_attr_init(&attributes));
777
778 // Large enough but not a multiple of the page size.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700779 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024 + 1));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700780 size_t guard_size;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700781 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
782 ASSERT_EQ(32*1024U + 1, guard_size);
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700783 ASSERT_EQ(36*1024U, GetActualGuardSize(attributes));
784}
785
786TEST(pthread, pthread_attr_setguardsize_enormous) {
787 pthread_attr_t attributes;
788 ASSERT_EQ(0, pthread_attr_init(&attributes));
789
790 // Larger than the stack itself. (Historically we mistakenly carved
791 // the guard out of the stack itself, rather than adding it after the
792 // end.)
793 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024*1024));
794 size_t guard_size;
795 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
796 ASSERT_EQ(32*1024*1024U, guard_size);
797 ASSERT_EQ(32*1024*1024U, GetActualGuardSize(attributes));
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700798}
799
800TEST(pthread, pthread_attr_setstacksize) {
801 pthread_attr_t attributes;
802 ASSERT_EQ(0, pthread_attr_init(&attributes));
803
804 // Get the default stack size.
805 size_t default_stack_size;
806 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &default_stack_size));
807
808 // Too small.
809 ASSERT_EQ(EINVAL, pthread_attr_setstacksize(&attributes, 128));
810 size_t stack_size;
811 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
812 ASSERT_EQ(default_stack_size, stack_size);
813 ASSERT_GE(GetActualStackSize(attributes), default_stack_size);
814
Yabin Cui917d3902015-01-08 12:32:42 -0800815 // Large enough and a multiple of the page size; may be rounded up by pthread_create.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700816 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024));
817 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
818 ASSERT_EQ(32*1024U, stack_size);
Yabin Cui917d3902015-01-08 12:32:42 -0800819 ASSERT_GE(GetActualStackSize(attributes), 32*1024U);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700820
Yabin Cui917d3902015-01-08 12:32:42 -0800821 // Large enough but not aligned; will be rounded up by pthread_create.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700822 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024 + 1));
823 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
824 ASSERT_EQ(32*1024U + 1, stack_size);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800825#if defined(__BIONIC__)
Yabin Cui917d3902015-01-08 12:32:42 -0800826 ASSERT_GT(GetActualStackSize(attributes), 32*1024U + 1);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800827#else // __BIONIC__
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700828 // glibc rounds down, in violation of POSIX. They document this in their BUGS section.
829 ASSERT_EQ(GetActualStackSize(attributes), 32*1024U);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800830#endif // __BIONIC__
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700831}
Elliott Hughesc3f11402013-10-30 14:40:09 -0700832
Yabin Cui76615da2015-03-17 14:22:09 -0700833TEST(pthread, pthread_rwlockattr_smoke) {
834 pthread_rwlockattr_t attr;
835 ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
836
837 int pshared_value_array[] = {PTHREAD_PROCESS_PRIVATE, PTHREAD_PROCESS_SHARED};
838 for (size_t i = 0; i < sizeof(pshared_value_array) / sizeof(pshared_value_array[0]); ++i) {
839 ASSERT_EQ(0, pthread_rwlockattr_setpshared(&attr, pshared_value_array[i]));
840 int pshared;
841 ASSERT_EQ(0, pthread_rwlockattr_getpshared(&attr, &pshared));
842 ASSERT_EQ(pshared_value_array[i], pshared);
843 }
844
845 int kind_array[] = {PTHREAD_RWLOCK_PREFER_READER_NP,
846 PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP};
847 for (size_t i = 0; i < sizeof(kind_array) / sizeof(kind_array[0]); ++i) {
848 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_array[i]));
849 int kind;
850 ASSERT_EQ(0, pthread_rwlockattr_getkind_np(&attr, &kind));
851 ASSERT_EQ(kind_array[i], kind);
852 }
853
854 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
855}
856
857TEST(pthread, pthread_rwlock_init_same_as_PTHREAD_RWLOCK_INITIALIZER) {
858 pthread_rwlock_t lock1 = PTHREAD_RWLOCK_INITIALIZER;
859 pthread_rwlock_t lock2;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700860 ASSERT_EQ(0, pthread_rwlock_init(&lock2, nullptr));
Yabin Cui76615da2015-03-17 14:22:09 -0700861 ASSERT_EQ(0, memcmp(&lock1, &lock2, sizeof(lock1)));
862}
863
Elliott Hughesc3f11402013-10-30 14:40:09 -0700864TEST(pthread, pthread_rwlock_smoke) {
865 pthread_rwlock_t l;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700866 ASSERT_EQ(0, pthread_rwlock_init(&l, nullptr));
Elliott Hughesc3f11402013-10-30 14:40:09 -0700867
Calin Juravle76f352e2014-05-19 13:41:10 +0100868 // Single read lock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700869 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
870 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
871
Calin Juravle76f352e2014-05-19 13:41:10 +0100872 // Multiple read lock
873 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
874 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
875 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
876 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
877
878 // Write lock
Calin Juravle92687e42014-05-22 19:21:22 +0100879 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
880 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100881
882 // Try writer lock
883 ASSERT_EQ(0, pthread_rwlock_trywrlock(&l));
884 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
885 ASSERT_EQ(EBUSY, pthread_rwlock_tryrdlock(&l));
886 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
887
888 // Try reader lock
889 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
890 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
891 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
892 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
893 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
894
895 // Try writer lock after unlock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700896 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
897 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
898
Calin Juravle76f352e2014-05-19 13:41:10 +0100899 // EDEADLK in "read after write"
900 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
901 ASSERT_EQ(EDEADLK, pthread_rwlock_rdlock(&l));
902 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
903
904 // EDEADLK in "write after write"
905 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
906 ASSERT_EQ(EDEADLK, pthread_rwlock_wrlock(&l));
907 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100908
Elliott Hughesc3f11402013-10-30 14:40:09 -0700909 ASSERT_EQ(0, pthread_rwlock_destroy(&l));
910}
911
Yabin Cui08ee8d22015-02-11 17:04:36 -0800912struct RwlockWakeupHelperArg {
913 pthread_rwlock_t lock;
914 enum Progress {
915 LOCK_INITIALIZED,
916 LOCK_WAITING,
917 LOCK_RELEASED,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800918 LOCK_ACCESSED,
919 LOCK_TIMEDOUT,
Yabin Cui08ee8d22015-02-11 17:04:36 -0800920 };
921 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -0700922 std::atomic<pid_t> tid;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800923 std::function<int (pthread_rwlock_t*)> trylock_function;
924 std::function<int (pthread_rwlock_t*)> lock_function;
925 std::function<int (pthread_rwlock_t*, const timespec*)> timed_lock_function;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -0800926 clockid_t clock;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800927};
928
Yabin Cuic9a659c2015-11-05 15:36:08 -0800929static void pthread_rwlock_wakeup_helper(RwlockWakeupHelperArg* arg) {
Yabin Cuif7969852015-04-02 17:47:48 -0700930 arg->tid = gettid();
Yabin Cui08ee8d22015-02-11 17:04:36 -0800931 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
932 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
933
Yabin Cuic9a659c2015-11-05 15:36:08 -0800934 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
935 ASSERT_EQ(0, arg->lock_function(&arg->lock));
Yabin Cui08ee8d22015-02-11 17:04:36 -0800936 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_RELEASED, arg->progress);
937 ASSERT_EQ(0, pthread_rwlock_unlock(&arg->lock));
938
939 arg->progress = RwlockWakeupHelperArg::LOCK_ACCESSED;
940}
941
Yabin Cuic9a659c2015-11-05 15:36:08 -0800942static void test_pthread_rwlock_reader_wakeup_writer(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -0800943 RwlockWakeupHelperArg wakeup_arg;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700944 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -0800945 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
946 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -0700947 wakeup_arg.tid = 0;
Tom Cherry60ddedf2018-02-20 15:40:02 -0800948 wakeup_arg.trylock_function = &pthread_rwlock_trywrlock;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800949 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800950
951 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700952 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800953 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -0700954 WaitUntilThreadSleep(wakeup_arg.tid);
955 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
956
Yabin Cui08ee8d22015-02-11 17:04:36 -0800957 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
958 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
959
Yi Kong32bc0fc2018-08-02 17:31:13 -0700960 ASSERT_EQ(0, pthread_join(thread, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -0800961 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
962 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
963}
964
Yabin Cuic9a659c2015-11-05 15:36:08 -0800965TEST(pthread, pthread_rwlock_reader_wakeup_writer) {
966 test_pthread_rwlock_reader_wakeup_writer(pthread_rwlock_wrlock);
Yabin Cui08ee8d22015-02-11 17:04:36 -0800967}
968
Yabin Cuic9a659c2015-11-05 15:36:08 -0800969TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait) {
970 timespec ts;
971 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
972 ts.tv_sec += 1;
973 test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) {
974 return pthread_rwlock_timedwrlock(lock, &ts);
975 });
976}
977
Tom Cherryc6b5bcd2018-03-05 14:14:44 -0800978TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait_monotonic_np) {
979#if defined(__BIONIC__)
980 timespec ts;
981 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
982 ts.tv_sec += 1;
983 test_pthread_rwlock_reader_wakeup_writer(
984 [&](pthread_rwlock_t* lock) { return pthread_rwlock_timedwrlock_monotonic_np(lock, &ts); });
985#else // __BIONIC__
986 GTEST_LOG_(INFO) << "This test does nothing since pthread_rwlock_timedwrlock_monotonic_np is "
987 "only supported on bionic";
988#endif // __BIONIC__
989}
990
Yabin Cuic9a659c2015-11-05 15:36:08 -0800991static void test_pthread_rwlock_writer_wakeup_reader(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -0800992 RwlockWakeupHelperArg wakeup_arg;
Yi Kong32bc0fc2018-08-02 17:31:13 -0700993 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -0800994 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
995 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -0700996 wakeup_arg.tid = 0;
Tom Cherry60ddedf2018-02-20 15:40:02 -0800997 wakeup_arg.trylock_function = &pthread_rwlock_tryrdlock;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800998 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800999
1000 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001001 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cuic9a659c2015-11-05 15:36:08 -08001002 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -07001003 WaitUntilThreadSleep(wakeup_arg.tid);
1004 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
1005
Yabin Cui08ee8d22015-02-11 17:04:36 -08001006 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
1007 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
1008
Yi Kong32bc0fc2018-08-02 17:31:13 -07001009 ASSERT_EQ(0, pthread_join(thread, nullptr));
Yabin Cui08ee8d22015-02-11 17:04:36 -08001010 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
1011 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
1012}
1013
Yabin Cuic9a659c2015-11-05 15:36:08 -08001014TEST(pthread, pthread_rwlock_writer_wakeup_reader) {
1015 test_pthread_rwlock_writer_wakeup_reader(pthread_rwlock_rdlock);
1016}
1017
1018TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait) {
1019 timespec ts;
1020 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1021 ts.tv_sec += 1;
1022 test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) {
1023 return pthread_rwlock_timedrdlock(lock, &ts);
1024 });
1025}
1026
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001027TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait_monotonic_np) {
1028#if defined(__BIONIC__)
1029 timespec ts;
1030 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1031 ts.tv_sec += 1;
1032 test_pthread_rwlock_writer_wakeup_reader(
1033 [&](pthread_rwlock_t* lock) { return pthread_rwlock_timedrdlock_monotonic_np(lock, &ts); });
1034#else // __BIONIC__
1035 GTEST_LOG_(INFO) << "This test does nothing since pthread_rwlock_timedrdlock_monotonic_np is "
1036 "only supported on bionic";
1037#endif // __BIONIC__
1038}
1039
Yabin Cuic9a659c2015-11-05 15:36:08 -08001040static void pthread_rwlock_wakeup_timeout_helper(RwlockWakeupHelperArg* arg) {
1041 arg->tid = gettid();
1042 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
1043 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
1044
1045 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
1046
1047 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001048 ASSERT_EQ(0, clock_gettime(arg->clock, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001049 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
1050 ts.tv_nsec = -1;
1051 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
1052 ts.tv_nsec = NS_PER_S;
1053 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
1054 ts.tv_nsec = NS_PER_S - 1;
1055 ts.tv_sec = -1;
1056 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001057 ASSERT_EQ(0, clock_gettime(arg->clock, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001058 ts.tv_sec += 1;
1059 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
1060 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, arg->progress);
1061 arg->progress = RwlockWakeupHelperArg::LOCK_TIMEDOUT;
1062}
1063
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001064static void pthread_rwlock_timedrdlock_timeout_helper(
1065 clockid_t clock, int (*lock_function)(pthread_rwlock_t* __rwlock, const timespec* __timeout)) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001066 RwlockWakeupHelperArg wakeup_arg;
1067 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
1068 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
1069 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
1070 wakeup_arg.tid = 0;
Tom Cherry60ddedf2018-02-20 15:40:02 -08001071 wakeup_arg.trylock_function = &pthread_rwlock_tryrdlock;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001072 wakeup_arg.timed_lock_function = lock_function;
1073 wakeup_arg.clock = clock;
1074
1075 pthread_t thread;
1076 ASSERT_EQ(0, pthread_create(&thread, nullptr,
1077 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
1078 WaitUntilThreadSleep(wakeup_arg.tid);
1079 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
1080
1081 ASSERT_EQ(0, pthread_join(thread, nullptr));
1082 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
1083 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
1084 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
1085}
1086
1087TEST(pthread, pthread_rwlock_timedrdlock_timeout) {
1088 pthread_rwlock_timedrdlock_timeout_helper(CLOCK_REALTIME, pthread_rwlock_timedrdlock);
1089}
1090
1091TEST(pthread, pthread_rwlock_timedrdlock_monotonic_np_timeout) {
1092#if defined(__BIONIC__)
1093 pthread_rwlock_timedrdlock_timeout_helper(CLOCK_MONOTONIC,
1094 pthread_rwlock_timedrdlock_monotonic_np);
1095#else // __BIONIC__
1096 GTEST_LOG_(INFO) << "This test does nothing since pthread_rwlock_timedrdlock_monotonic_np is "
1097 "only supported on bionic";
1098#endif // __BIONIC__
1099}
1100
1101static void pthread_rwlock_timedwrlock_timeout_helper(
1102 clockid_t clock, int (*lock_function)(pthread_rwlock_t* __rwlock, const timespec* __timeout)) {
1103 RwlockWakeupHelperArg wakeup_arg;
1104 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
1105 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
1106 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
1107 wakeup_arg.tid = 0;
1108 wakeup_arg.trylock_function = &pthread_rwlock_trywrlock;
1109 wakeup_arg.timed_lock_function = lock_function;
1110 wakeup_arg.clock = clock;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001111
1112 pthread_t thread;
1113 ASSERT_EQ(0, pthread_create(&thread, nullptr,
1114 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
1115 WaitUntilThreadSleep(wakeup_arg.tid);
1116 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
1117
1118 ASSERT_EQ(0, pthread_join(thread, nullptr));
1119 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
1120 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
1121 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
1122}
1123
1124TEST(pthread, pthread_rwlock_timedwrlock_timeout) {
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001125 pthread_rwlock_timedwrlock_timeout_helper(CLOCK_REALTIME, pthread_rwlock_timedwrlock);
1126}
Yabin Cuic9a659c2015-11-05 15:36:08 -08001127
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001128TEST(pthread, pthread_rwlock_timedwrlock_monotonic_np_timeout) {
1129#if defined(__BIONIC__)
1130 pthread_rwlock_timedwrlock_timeout_helper(CLOCK_MONOTONIC,
1131 pthread_rwlock_timedwrlock_monotonic_np);
1132#else // __BIONIC__
1133 GTEST_LOG_(INFO) << "This test does nothing since pthread_rwlock_timedwrlock_monotonic_np is "
1134 "only supported on bionic";
1135#endif // __BIONIC__
Yabin Cuic9a659c2015-11-05 15:36:08 -08001136}
1137
Yabin Cui76615da2015-03-17 14:22:09 -07001138class RwlockKindTestHelper {
1139 private:
1140 struct ThreadArg {
1141 RwlockKindTestHelper* helper;
1142 std::atomic<pid_t>& tid;
1143
1144 ThreadArg(RwlockKindTestHelper* helper, std::atomic<pid_t>& tid)
1145 : helper(helper), tid(tid) { }
1146 };
1147
1148 public:
1149 pthread_rwlock_t lock;
1150
1151 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -07001152 explicit RwlockKindTestHelper(int kind_type) {
Yabin Cui76615da2015-03-17 14:22:09 -07001153 InitRwlock(kind_type);
1154 }
1155
1156 ~RwlockKindTestHelper() {
1157 DestroyRwlock();
1158 }
1159
1160 void CreateWriterThread(pthread_t& thread, std::atomic<pid_t>& tid) {
1161 tid = 0;
1162 ThreadArg* arg = new ThreadArg(this, tid);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001163 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui76615da2015-03-17 14:22:09 -07001164 reinterpret_cast<void* (*)(void*)>(WriterThreadFn), arg));
1165 }
1166
1167 void CreateReaderThread(pthread_t& thread, std::atomic<pid_t>& tid) {
1168 tid = 0;
1169 ThreadArg* arg = new ThreadArg(this, tid);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001170 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui76615da2015-03-17 14:22:09 -07001171 reinterpret_cast<void* (*)(void*)>(ReaderThreadFn), arg));
1172 }
1173
1174 private:
1175 void InitRwlock(int kind_type) {
1176 pthread_rwlockattr_t attr;
1177 ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
1178 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_type));
1179 ASSERT_EQ(0, pthread_rwlock_init(&lock, &attr));
1180 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
1181 }
1182
1183 void DestroyRwlock() {
1184 ASSERT_EQ(0, pthread_rwlock_destroy(&lock));
1185 }
1186
1187 static void WriterThreadFn(ThreadArg* arg) {
1188 arg->tid = gettid();
1189
1190 RwlockKindTestHelper* helper = arg->helper;
1191 ASSERT_EQ(0, pthread_rwlock_wrlock(&helper->lock));
1192 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
1193 delete arg;
1194 }
1195
1196 static void ReaderThreadFn(ThreadArg* arg) {
1197 arg->tid = gettid();
1198
1199 RwlockKindTestHelper* helper = arg->helper;
1200 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper->lock));
1201 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
1202 delete arg;
1203 }
1204};
1205
1206TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_READER_NP) {
1207 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_READER_NP);
1208 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
1209
1210 pthread_t writer_thread;
1211 std::atomic<pid_t> writer_tid;
1212 helper.CreateWriterThread(writer_thread, writer_tid);
1213 WaitUntilThreadSleep(writer_tid);
1214
1215 pthread_t reader_thread;
1216 std::atomic<pid_t> reader_tid;
1217 helper.CreateReaderThread(reader_thread, reader_tid);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001218 ASSERT_EQ(0, pthread_join(reader_thread, nullptr));
Yabin Cui76615da2015-03-17 14:22:09 -07001219
1220 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
Yi Kong32bc0fc2018-08-02 17:31:13 -07001221 ASSERT_EQ(0, pthread_join(writer_thread, nullptr));
Yabin Cui76615da2015-03-17 14:22:09 -07001222}
1223
1224TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP) {
1225 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
1226 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
1227
1228 pthread_t writer_thread;
1229 std::atomic<pid_t> writer_tid;
1230 helper.CreateWriterThread(writer_thread, writer_tid);
1231 WaitUntilThreadSleep(writer_tid);
1232
1233 pthread_t reader_thread;
1234 std::atomic<pid_t> reader_tid;
1235 helper.CreateReaderThread(reader_thread, reader_tid);
1236 WaitUntilThreadSleep(reader_tid);
1237
1238 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
Yi Kong32bc0fc2018-08-02 17:31:13 -07001239 ASSERT_EQ(0, pthread_join(writer_thread, nullptr));
1240 ASSERT_EQ(0, pthread_join(reader_thread, nullptr));
Yabin Cui76615da2015-03-17 14:22:09 -07001241}
1242
Elliott Hughes1728b232014-05-14 10:02:03 -07001243static int g_once_fn_call_count = 0;
Elliott Hughesc3f11402013-10-30 14:40:09 -07001244static void OnceFn() {
Elliott Hughes1728b232014-05-14 10:02:03 -07001245 ++g_once_fn_call_count;
Elliott Hughesc3f11402013-10-30 14:40:09 -07001246}
1247
1248TEST(pthread, pthread_once_smoke) {
1249 pthread_once_t once_control = PTHREAD_ONCE_INIT;
1250 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
1251 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
Elliott Hughes1728b232014-05-14 10:02:03 -07001252 ASSERT_EQ(1, g_once_fn_call_count);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001253}
1254
Elliott Hughes3694ec62014-05-14 11:46:08 -07001255static std::string pthread_once_1934122_result = "";
1256
1257static void Routine2() {
1258 pthread_once_1934122_result += "2";
1259}
1260
1261static void Routine1() {
1262 pthread_once_t once_control_2 = PTHREAD_ONCE_INIT;
1263 pthread_once_1934122_result += "1";
1264 pthread_once(&once_control_2, &Routine2);
1265}
1266
1267TEST(pthread, pthread_once_1934122) {
1268 // Very old versions of Android couldn't call pthread_once from a
1269 // pthread_once init routine. http://b/1934122.
1270 pthread_once_t once_control_1 = PTHREAD_ONCE_INIT;
1271 ASSERT_EQ(0, pthread_once(&once_control_1, &Routine1));
1272 ASSERT_EQ("12", pthread_once_1934122_result);
1273}
1274
Elliott Hughes1728b232014-05-14 10:02:03 -07001275static int g_atfork_prepare_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001276static void AtForkPrepare1() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 1; }
1277static void AtForkPrepare2() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -07001278static int g_atfork_parent_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001279static void AtForkParent1() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 1; }
1280static void AtForkParent2() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -07001281static int g_atfork_child_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001282static void AtForkChild1() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 1; }
1283static void AtForkChild2() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 2; }
Elliott Hughesc3f11402013-10-30 14:40:09 -07001284
Dmitriy Ivanov00e37812014-11-20 16:53:47 -08001285TEST(pthread, pthread_atfork_smoke) {
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001286 ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1));
1287 ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2));
Elliott Hughesc3f11402013-10-30 14:40:09 -07001288
Elliott Hughes33697a02016-01-26 13:04:57 -08001289 pid_t pid = fork();
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001290 ASSERT_NE(-1, pid) << strerror(errno);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001291
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001292 // Child and parent calls are made in the order they were registered.
1293 if (pid == 0) {
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001294 ASSERT_EQ(12, g_atfork_child_calls);
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001295 _exit(0);
1296 }
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001297 ASSERT_EQ(12, g_atfork_parent_calls);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001298
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001299 // Prepare calls are made in the reverse order.
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001300 ASSERT_EQ(21, g_atfork_prepare_calls);
Elliott Hughes33697a02016-01-26 13:04:57 -08001301 AssertChildExited(pid, 0);
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001302}
1303
Elliott Hughesc3f11402013-10-30 14:40:09 -07001304TEST(pthread, pthread_attr_getscope) {
1305 pthread_attr_t attr;
1306 ASSERT_EQ(0, pthread_attr_init(&attr));
1307
1308 int scope;
1309 ASSERT_EQ(0, pthread_attr_getscope(&attr, &scope));
1310 ASSERT_EQ(PTHREAD_SCOPE_SYSTEM, scope);
1311}
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001312
1313TEST(pthread, pthread_condattr_init) {
1314 pthread_condattr_t attr;
1315 pthread_condattr_init(&attr);
1316
1317 clockid_t clock;
1318 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1319 ASSERT_EQ(CLOCK_REALTIME, clock);
1320
1321 int pshared;
1322 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1323 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
1324}
1325
1326TEST(pthread, pthread_condattr_setclock) {
1327 pthread_condattr_t attr;
1328 pthread_condattr_init(&attr);
1329
1330 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_REALTIME));
1331 clockid_t clock;
1332 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1333 ASSERT_EQ(CLOCK_REALTIME, clock);
1334
1335 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1336 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1337 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1338
1339 ASSERT_EQ(EINVAL, pthread_condattr_setclock(&attr, CLOCK_PROCESS_CPUTIME_ID));
1340}
1341
1342TEST(pthread, pthread_cond_broadcast__preserves_condattr_flags) {
Yabin Cui32651b82015-03-13 20:30:00 -07001343#if defined(__BIONIC__)
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001344 pthread_condattr_t attr;
1345 pthread_condattr_init(&attr);
1346
1347 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1348 ASSERT_EQ(0, pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
1349
1350 pthread_cond_t cond_var;
1351 ASSERT_EQ(0, pthread_cond_init(&cond_var, &attr));
1352
1353 ASSERT_EQ(0, pthread_cond_signal(&cond_var));
1354 ASSERT_EQ(0, pthread_cond_broadcast(&cond_var));
1355
Yabin Cui32651b82015-03-13 20:30:00 -07001356 attr = static_cast<pthread_condattr_t>(*reinterpret_cast<uint32_t*>(cond_var.__private));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001357 clockid_t clock;
1358 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1359 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1360 int pshared;
1361 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1362 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
Yabin Cui32651b82015-03-13 20:30:00 -07001363#else // !defined(__BIONIC__)
1364 GTEST_LOG_(INFO) << "This tests a bionic implementation detail.\n";
1365#endif // !defined(__BIONIC__)
1366}
1367
1368class pthread_CondWakeupTest : public ::testing::Test {
1369 protected:
1370 pthread_mutex_t mutex;
1371 pthread_cond_t cond;
1372
1373 enum Progress {
1374 INITIALIZED,
1375 WAITING,
1376 SIGNALED,
1377 FINISHED,
1378 };
1379 std::atomic<Progress> progress;
1380 pthread_t thread;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001381 std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function;
Yabin Cui32651b82015-03-13 20:30:00 -07001382
1383 protected:
Yabin Cuic9a659c2015-11-05 15:36:08 -08001384 void SetUp() override {
1385 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1386 }
1387
1388 void InitCond(clockid_t clock=CLOCK_REALTIME) {
1389 pthread_condattr_t attr;
1390 ASSERT_EQ(0, pthread_condattr_init(&attr));
1391 ASSERT_EQ(0, pthread_condattr_setclock(&attr, clock));
1392 ASSERT_EQ(0, pthread_cond_init(&cond, &attr));
1393 ASSERT_EQ(0, pthread_condattr_destroy(&attr));
1394 }
1395
1396 void StartWaitingThread(std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function) {
Yabin Cui32651b82015-03-13 20:30:00 -07001397 progress = INITIALIZED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001398 this->wait_function = wait_function;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001399 ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(WaitThreadFn), this));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001400 while (progress != WAITING) {
Yabin Cui32651b82015-03-13 20:30:00 -07001401 usleep(5000);
1402 }
1403 usleep(5000);
1404 }
1405
Yabin Cuic9a659c2015-11-05 15:36:08 -08001406 void TearDown() override {
1407 ASSERT_EQ(0, pthread_join(thread, nullptr));
1408 ASSERT_EQ(FINISHED, progress);
1409 ASSERT_EQ(0, pthread_cond_destroy(&cond));
1410 ASSERT_EQ(0, pthread_mutex_destroy(&mutex));
1411 }
1412
Yabin Cui32651b82015-03-13 20:30:00 -07001413 private:
1414 static void WaitThreadFn(pthread_CondWakeupTest* test) {
1415 ASSERT_EQ(0, pthread_mutex_lock(&test->mutex));
1416 test->progress = WAITING;
1417 while (test->progress == WAITING) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001418 ASSERT_EQ(0, test->wait_function(&test->cond, &test->mutex));
Yabin Cui32651b82015-03-13 20:30:00 -07001419 }
1420 ASSERT_EQ(SIGNALED, test->progress);
1421 test->progress = FINISHED;
1422 ASSERT_EQ(0, pthread_mutex_unlock(&test->mutex));
1423 }
1424};
1425
Yabin Cuic9a659c2015-11-05 15:36:08 -08001426TEST_F(pthread_CondWakeupTest, signal_wait) {
1427 InitCond();
1428 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1429 return pthread_cond_wait(cond, mutex);
1430 });
Yabin Cui32651b82015-03-13 20:30:00 -07001431 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001432 ASSERT_EQ(0, pthread_cond_signal(&cond));
Yabin Cui32651b82015-03-13 20:30:00 -07001433}
1434
Yabin Cuic9a659c2015-11-05 15:36:08 -08001435TEST_F(pthread_CondWakeupTest, broadcast_wait) {
1436 InitCond();
1437 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1438 return pthread_cond_wait(cond, mutex);
1439 });
Yabin Cui32651b82015-03-13 20:30:00 -07001440 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001441 ASSERT_EQ(0, pthread_cond_broadcast(&cond));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001442}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001443
Yabin Cuic9a659c2015-11-05 15:36:08 -08001444TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_REALTIME) {
1445 InitCond(CLOCK_REALTIME);
Elliott Hughes0e714a52014-03-03 16:42:47 -08001446 timespec ts;
1447 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001448 ts.tv_sec += 1;
1449 StartWaitingThread([&](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1450 return pthread_cond_timedwait(cond, mutex, &ts);
1451 });
1452 progress = SIGNALED;
1453 ASSERT_EQ(0, pthread_cond_signal(&cond));
1454}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001455
Yabin Cuic9a659c2015-11-05 15:36:08 -08001456TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC) {
1457 InitCond(CLOCK_MONOTONIC);
1458 timespec ts;
1459 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1460 ts.tv_sec += 1;
1461 StartWaitingThread([&](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1462 return pthread_cond_timedwait(cond, mutex, &ts);
1463 });
1464 progress = SIGNALED;
1465 ASSERT_EQ(0, pthread_cond_signal(&cond));
1466}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001467
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001468TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC_np) {
1469#if defined(__BIONIC__)
1470 InitCond(CLOCK_REALTIME);
1471 timespec ts;
1472 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1473 ts.tv_sec += 1;
1474 StartWaitingThread([&](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1475 return pthread_cond_timedwait_monotonic_np(cond, mutex, &ts);
1476 });
1477 progress = SIGNALED;
1478 ASSERT_EQ(0, pthread_cond_signal(&cond));
1479#else // __BIONIC__
1480 GTEST_LOG_(INFO) << "This test does nothing since pthread_cond_timedwait_monotonic_np is only "
1481 "supported on bionic";
1482#endif // __BIONIC__
1483}
1484
1485static void pthread_cond_timedwait_timeout_helper(clockid_t clock,
1486 int (*wait_function)(pthread_cond_t* __cond,
1487 pthread_mutex_t* __mutex,
1488 const timespec* __timeout)) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001489 pthread_mutex_t mutex;
1490 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1491 pthread_cond_t cond;
1492 ASSERT_EQ(0, pthread_cond_init(&cond, nullptr));
1493 ASSERT_EQ(0, pthread_mutex_lock(&mutex));
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001494
Yabin Cuic9a659c2015-11-05 15:36:08 -08001495 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001496 ASSERT_EQ(0, clock_gettime(clock, &ts));
1497 ASSERT_EQ(ETIMEDOUT, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001498 ts.tv_nsec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001499 ASSERT_EQ(EINVAL, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001500 ts.tv_nsec = NS_PER_S;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001501 ASSERT_EQ(EINVAL, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001502 ts.tv_nsec = NS_PER_S - 1;
1503 ts.tv_sec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001504 ASSERT_EQ(ETIMEDOUT, wait_function(&cond, &mutex, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001505 ASSERT_EQ(0, pthread_mutex_unlock(&mutex));
Elliott Hughes0e714a52014-03-03 16:42:47 -08001506}
Elliott Hughes57b7a612014-08-25 17:26:50 -07001507
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08001508TEST(pthread, pthread_cond_timedwait_timeout) {
1509 pthread_cond_timedwait_timeout_helper(CLOCK_REALTIME, pthread_cond_timedwait);
1510}
1511
1512TEST(pthread, pthread_cond_timedwait_monotonic_np_timeout) {
1513#if defined(__BIONIC__)
1514 pthread_cond_timedwait_timeout_helper(CLOCK_MONOTONIC, pthread_cond_timedwait_monotonic_np);
1515#else // __BIONIC__
1516 GTEST_LOG_(INFO) << "This test does nothing since pthread_cond_timedwait_monotonic_np is only "
1517 "supported on bionic";
1518#endif // __BIONIC__
1519}
1520
Elliott Hughes57b7a612014-08-25 17:26:50 -07001521TEST(pthread, pthread_attr_getstack__main_thread) {
1522 // This test is only meaningful for the main thread, so make sure we're running on it!
1523 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1524
1525 // Get the main thread's attributes.
1526 pthread_attr_t attributes;
1527 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1528
1529 // Check that we correctly report that the main thread has no guard page.
1530 size_t guard_size;
1531 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
1532 ASSERT_EQ(0U, guard_size); // The main thread has no guard page.
1533
1534 // Get the stack base and the stack size (both ways).
1535 void* stack_base;
1536 size_t stack_size;
1537 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1538 size_t stack_size2;
1539 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1540
1541 // The two methods of asking for the stack size should agree.
1542 EXPECT_EQ(stack_size, stack_size2);
1543
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001544#if defined(__BIONIC__)
dimitry6dfa5b52018-01-30 13:24:28 +01001545 // Find stack in /proc/self/maps using a pointer to the stack.
1546 //
1547 // We do not use "[stack]" label because in native-bridge environment it is not
1548 // guaranteed to point to the right stack. A native bridge implementation may
1549 // keep separate stack for the guest code.
Yi Kong32bc0fc2018-08-02 17:31:13 -07001550 void* maps_stack_hi = nullptr;
Elliott Hughes15dfd632015-09-22 16:40:14 -07001551 std::vector<map_record> maps;
1552 ASSERT_TRUE(Maps::parse_maps(&maps));
dimitry6dfa5b52018-01-30 13:24:28 +01001553 uintptr_t stack_address = reinterpret_cast<uintptr_t>(&maps_stack_hi);
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07001554 for (const auto& map : maps) {
dimitry6dfa5b52018-01-30 13:24:28 +01001555 if (map.addr_start <= stack_address && map.addr_end > stack_address){
Elliott Hughes15dfd632015-09-22 16:40:14 -07001556 maps_stack_hi = reinterpret_cast<void*>(map.addr_end);
Elliott Hughes57b7a612014-08-25 17:26:50 -07001557 break;
1558 }
1559 }
Elliott Hughes57b7a612014-08-25 17:26:50 -07001560
dimitry6dfa5b52018-01-30 13:24:28 +01001561 // The high address of the /proc/self/maps stack region should equal stack_base + stack_size.
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001562 // Remember that the stack grows down (and is mapped in on demand), so the low address of the
1563 // region isn't very interesting.
1564 EXPECT_EQ(maps_stack_hi, reinterpret_cast<uint8_t*>(stack_base) + stack_size);
1565
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001566 // The stack size should correspond to RLIMIT_STACK.
Elliott Hughes57b7a612014-08-25 17:26:50 -07001567 rlimit rl;
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001568 ASSERT_EQ(0, getrlimit(RLIMIT_STACK, &rl));
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001569 uint64_t original_rlim_cur = rl.rlim_cur;
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001570 if (rl.rlim_cur == RLIM_INFINITY) {
1571 rl.rlim_cur = 8 * 1024 * 1024; // Bionic reports unlimited stacks as 8MiB.
1572 }
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001573 EXPECT_EQ(rl.rlim_cur, stack_size);
1574
Tom Cherryb8ab6182017-04-05 16:20:29 -07001575 auto guard = android::base::make_scope_guard([&rl, original_rlim_cur]() {
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001576 rl.rlim_cur = original_rlim_cur;
1577 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1578 });
1579
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001580 //
1581 // What if RLIMIT_STACK is smaller than the stack's current extent?
1582 //
Elliott Hughes57b7a612014-08-25 17:26:50 -07001583 rl.rlim_cur = rl.rlim_max = 1024; // 1KiB. We know the stack must be at least a page already.
1584 rl.rlim_max = RLIM_INFINITY;
1585 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1586
1587 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1588 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1589 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1590
1591 EXPECT_EQ(stack_size, stack_size2);
1592 ASSERT_EQ(1024U, stack_size);
1593
1594 //
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001595 // What if RLIMIT_STACK isn't a whole number of pages?
Elliott Hughes57b7a612014-08-25 17:26:50 -07001596 //
1597 rl.rlim_cur = rl.rlim_max = 6666; // Not a whole number of pages.
1598 rl.rlim_max = RLIM_INFINITY;
1599 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1600
1601 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1602 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1603 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1604
1605 EXPECT_EQ(stack_size, stack_size2);
1606 ASSERT_EQ(6666U, stack_size);
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001607#endif
Elliott Hughes57b7a612014-08-25 17:26:50 -07001608}
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001609
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001610struct GetStackSignalHandlerArg {
1611 volatile bool done;
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001612 void* signal_stack_base;
1613 size_t signal_stack_size;
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001614 void* main_stack_base;
1615 size_t main_stack_size;
1616};
1617
1618static GetStackSignalHandlerArg getstack_signal_handler_arg;
1619
1620static void getstack_signal_handler(int sig) {
1621 ASSERT_EQ(SIGUSR1, sig);
1622 // Use sleep() to make current thread be switched out by the kernel to provoke the error.
1623 sleep(1);
1624 pthread_attr_t attr;
1625 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1626 void* stack_base;
1627 size_t stack_size;
1628 ASSERT_EQ(0, pthread_attr_getstack(&attr, &stack_base, &stack_size));
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001629
1630 // Verify if the stack used by the signal handler is the alternate stack just registered.
1631 ASSERT_LE(getstack_signal_handler_arg.signal_stack_base, &attr);
1632 ASSERT_LT(static_cast<void*>(&attr),
1633 static_cast<char*>(getstack_signal_handler_arg.signal_stack_base) +
1634 getstack_signal_handler_arg.signal_stack_size);
1635
1636 // Verify if the main thread's stack got in the signal handler is correct.
1637 ASSERT_EQ(getstack_signal_handler_arg.main_stack_base, stack_base);
1638 ASSERT_LE(getstack_signal_handler_arg.main_stack_size, stack_size);
1639
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001640 getstack_signal_handler_arg.done = true;
1641}
1642
1643// The previous code obtained the main thread's stack by reading the entry in
1644// /proc/self/task/<pid>/maps that was labeled [stack]. Unfortunately, on x86/x86_64, the kernel
1645// relies on sp0 in task state segment(tss) to label the stack map with [stack]. If the kernel
1646// switches a process while the main thread is in an alternate stack, then the kernel will label
1647// the wrong map with [stack]. This test verifies that when the above situation happens, the main
1648// thread's stack is found correctly.
1649TEST(pthread, pthread_attr_getstack_in_signal_handler) {
Yabin Cui61e4d462016-03-07 17:44:58 -08001650 // This test is only meaningful for the main thread, so make sure we're running on it!
1651 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1652
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001653 const size_t sig_stack_size = 16 * 1024;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001654 void* sig_stack = mmap(nullptr, sig_stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS,
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001655 -1, 0);
1656 ASSERT_NE(MAP_FAILED, sig_stack);
1657 stack_t ss;
1658 ss.ss_sp = sig_stack;
1659 ss.ss_size = sig_stack_size;
1660 ss.ss_flags = 0;
1661 stack_t oss;
1662 ASSERT_EQ(0, sigaltstack(&ss, &oss));
1663
Yabin Cui61e4d462016-03-07 17:44:58 -08001664 pthread_attr_t attr;
1665 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1666 void* main_stack_base;
1667 size_t main_stack_size;
1668 ASSERT_EQ(0, pthread_attr_getstack(&attr, &main_stack_base, &main_stack_size));
1669
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001670 ScopedSignalHandler handler(SIGUSR1, getstack_signal_handler, SA_ONSTACK);
1671 getstack_signal_handler_arg.done = false;
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001672 getstack_signal_handler_arg.signal_stack_base = sig_stack;
1673 getstack_signal_handler_arg.signal_stack_size = sig_stack_size;
1674 getstack_signal_handler_arg.main_stack_base = main_stack_base;
1675 getstack_signal_handler_arg.main_stack_size = main_stack_size;
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001676 kill(getpid(), SIGUSR1);
1677 ASSERT_EQ(true, getstack_signal_handler_arg.done);
1678
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001679 ASSERT_EQ(0, sigaltstack(&oss, nullptr));
1680 ASSERT_EQ(0, munmap(sig_stack, sig_stack_size));
1681}
1682
Yabin Cui917d3902015-01-08 12:32:42 -08001683static void pthread_attr_getstack_18908062_helper(void*) {
1684 char local_variable;
1685 pthread_attr_t attributes;
1686 pthread_getattr_np(pthread_self(), &attributes);
1687 void* stack_base;
1688 size_t stack_size;
1689 pthread_attr_getstack(&attributes, &stack_base, &stack_size);
1690
1691 // Test whether &local_variable is in [stack_base, stack_base + stack_size).
1692 ASSERT_LE(reinterpret_cast<char*>(stack_base), &local_variable);
1693 ASSERT_LT(&local_variable, reinterpret_cast<char*>(stack_base) + stack_size);
1694}
1695
1696// Check whether something on stack is in the range of
1697// [stack_base, stack_base + stack_size). see b/18908062.
1698TEST(pthread, pthread_attr_getstack_18908062) {
1699 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001700 ASSERT_EQ(0, pthread_create(&t, nullptr,
Yabin Cui917d3902015-01-08 12:32:42 -08001701 reinterpret_cast<void* (*)(void*)>(pthread_attr_getstack_18908062_helper),
Yi Kong32bc0fc2018-08-02 17:31:13 -07001702 nullptr));
1703 ASSERT_EQ(0, pthread_join(t, nullptr));
Yabin Cui917d3902015-01-08 12:32:42 -08001704}
1705
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001706#if defined(__BIONIC__)
Elliott Hughesf2083612015-11-11 13:32:28 -08001707static pthread_mutex_t pthread_gettid_np_mutex = PTHREAD_MUTEX_INITIALIZER;
1708
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001709static void* pthread_gettid_np_helper(void* arg) {
1710 *reinterpret_cast<pid_t*>(arg) = gettid();
Elliott Hughesf2083612015-11-11 13:32:28 -08001711
1712 // Wait for our parent to call pthread_gettid_np on us before exiting.
1713 pthread_mutex_lock(&pthread_gettid_np_mutex);
1714 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001715 return nullptr;
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001716}
1717#endif
1718
1719TEST(pthread, pthread_gettid_np) {
1720#if defined(__BIONIC__)
1721 ASSERT_EQ(gettid(), pthread_gettid_np(pthread_self()));
1722
Elliott Hughesf2083612015-11-11 13:32:28 -08001723 // Ensure the other thread doesn't exit until after we've called
1724 // pthread_gettid_np on it.
1725 pthread_mutex_lock(&pthread_gettid_np_mutex);
1726
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001727 pid_t t_gettid_result;
1728 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001729 pthread_create(&t, nullptr, pthread_gettid_np_helper, &t_gettid_result);
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001730
1731 pid_t t_pthread_gettid_np_result = pthread_gettid_np(t);
1732
Elliott Hughesf2083612015-11-11 13:32:28 -08001733 // Release the other thread and wait for it to exit.
1734 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Yi Kong32bc0fc2018-08-02 17:31:13 -07001735 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001736
1737 ASSERT_EQ(t_gettid_result, t_pthread_gettid_np_result);
1738#else
1739 GTEST_LOG_(INFO) << "This test does nothing.\n";
1740#endif
1741}
Elliott Hughes34c987a2014-09-22 16:01:26 -07001742
1743static size_t cleanup_counter = 0;
1744
Derek Xue41996952014-09-25 11:05:32 +01001745static void AbortCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001746 abort();
1747}
1748
Derek Xue41996952014-09-25 11:05:32 +01001749static void CountCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001750 ++cleanup_counter;
1751}
1752
Derek Xue41996952014-09-25 11:05:32 +01001753static void PthreadCleanupTester() {
Yi Kong32bc0fc2018-08-02 17:31:13 -07001754 pthread_cleanup_push(CountCleanupRoutine, nullptr);
1755 pthread_cleanup_push(CountCleanupRoutine, nullptr);
1756 pthread_cleanup_push(AbortCleanupRoutine, nullptr);
Elliott Hughes34c987a2014-09-22 16:01:26 -07001757
1758 pthread_cleanup_pop(0); // Pop the abort without executing it.
1759 pthread_cleanup_pop(1); // Pop one count while executing it.
1760 ASSERT_EQ(1U, cleanup_counter);
1761 // Exit while the other count is still on the cleanup stack.
Yi Kong32bc0fc2018-08-02 17:31:13 -07001762 pthread_exit(nullptr);
Elliott Hughes34c987a2014-09-22 16:01:26 -07001763
1764 // Calls to pthread_cleanup_pop/pthread_cleanup_push must always be balanced.
1765 pthread_cleanup_pop(0);
1766}
1767
Derek Xue41996952014-09-25 11:05:32 +01001768static void* PthreadCleanupStartRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001769 PthreadCleanupTester();
Yi Kong32bc0fc2018-08-02 17:31:13 -07001770 return nullptr;
Elliott Hughes34c987a2014-09-22 16:01:26 -07001771}
1772
1773TEST(pthread, pthread_cleanup_push__pthread_cleanup_pop) {
1774 pthread_t t;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001775 ASSERT_EQ(0, pthread_create(&t, nullptr, PthreadCleanupStartRoutine, nullptr));
1776 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes34c987a2014-09-22 16:01:26 -07001777 ASSERT_EQ(2U, cleanup_counter);
1778}
Derek Xue41996952014-09-25 11:05:32 +01001779
1780TEST(pthread, PTHREAD_MUTEX_DEFAULT_is_PTHREAD_MUTEX_NORMAL) {
1781 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_DEFAULT);
1782}
1783
1784TEST(pthread, pthread_mutexattr_gettype) {
1785 pthread_mutexattr_t attr;
1786 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1787
1788 int attr_type;
1789
1790 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL));
1791 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1792 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, attr_type);
1793
1794 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK));
1795 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1796 ASSERT_EQ(PTHREAD_MUTEX_ERRORCHECK, attr_type);
1797
1798 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE));
1799 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1800 ASSERT_EQ(PTHREAD_MUTEX_RECURSIVE, attr_type);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001801
1802 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
1803}
1804
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001805TEST(pthread, pthread_mutexattr_protocol) {
1806 pthread_mutexattr_t attr;
1807 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1808
1809 int protocol;
1810 ASSERT_EQ(0, pthread_mutexattr_getprotocol(&attr, &protocol));
1811 ASSERT_EQ(PTHREAD_PRIO_NONE, protocol);
1812 for (size_t repeat = 0; repeat < 2; ++repeat) {
1813 for (int set_protocol : {PTHREAD_PRIO_NONE, PTHREAD_PRIO_INHERIT}) {
1814 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, set_protocol));
1815 ASSERT_EQ(0, pthread_mutexattr_getprotocol(&attr, &protocol));
1816 ASSERT_EQ(protocol, set_protocol);
1817 }
1818 }
1819}
1820
Yabin Cui17393b02015-03-21 15:08:25 -07001821struct PthreadMutex {
1822 pthread_mutex_t lock;
1823
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001824 explicit PthreadMutex(int mutex_type, int protocol = PTHREAD_PRIO_NONE) {
1825 init(mutex_type, protocol);
Yabin Cui17393b02015-03-21 15:08:25 -07001826 }
1827
1828 ~PthreadMutex() {
1829 destroy();
1830 }
1831
1832 private:
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001833 void init(int mutex_type, int protocol) {
Yabin Cui17393b02015-03-21 15:08:25 -07001834 pthread_mutexattr_t attr;
1835 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1836 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, mutex_type));
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001837 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, protocol));
Yabin Cui17393b02015-03-21 15:08:25 -07001838 ASSERT_EQ(0, pthread_mutex_init(&lock, &attr));
1839 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
1840 }
1841
1842 void destroy() {
1843 ASSERT_EQ(0, pthread_mutex_destroy(&lock));
1844 }
1845
1846 DISALLOW_COPY_AND_ASSIGN(PthreadMutex);
1847};
Derek Xue41996952014-09-25 11:05:32 +01001848
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001849static void TestPthreadMutexLockNormal(int protocol) {
1850 PthreadMutex m(PTHREAD_MUTEX_NORMAL, protocol);
Derek Xue41996952014-09-25 11:05:32 +01001851
Yabin Cui17393b02015-03-21 15:08:25 -07001852 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1853 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08001854 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
1855 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
1856 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01001857}
1858
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001859static void TestPthreadMutexLockErrorCheck(int protocol) {
1860 PthreadMutex m(PTHREAD_MUTEX_ERRORCHECK, protocol);
Derek Xue41996952014-09-25 11:05:32 +01001861
Yabin Cui17393b02015-03-21 15:08:25 -07001862 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1863 ASSERT_EQ(EDEADLK, pthread_mutex_lock(&m.lock));
1864 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1865 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001866 if (protocol == PTHREAD_PRIO_NONE) {
1867 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
1868 } else {
1869 ASSERT_EQ(EDEADLK, pthread_mutex_trylock(&m.lock));
1870 }
Yabin Cui17393b02015-03-21 15:08:25 -07001871 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1872 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01001873}
1874
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001875static void TestPthreadMutexLockRecursive(int protocol) {
1876 PthreadMutex m(PTHREAD_MUTEX_RECURSIVE, protocol);
Derek Xue41996952014-09-25 11:05:32 +01001877
Yabin Cui17393b02015-03-21 15:08:25 -07001878 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1879 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1880 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1881 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1882 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08001883 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
1884 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07001885 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1886 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
1887}
1888
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001889TEST(pthread, pthread_mutex_lock_NORMAL) {
1890 TestPthreadMutexLockNormal(PTHREAD_PRIO_NONE);
1891}
1892
1893TEST(pthread, pthread_mutex_lock_ERRORCHECK) {
1894 TestPthreadMutexLockErrorCheck(PTHREAD_PRIO_NONE);
1895}
1896
1897TEST(pthread, pthread_mutex_lock_RECURSIVE) {
1898 TestPthreadMutexLockRecursive(PTHREAD_PRIO_NONE);
1899}
1900
1901TEST(pthread, pthread_mutex_lock_pi) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001902 TestPthreadMutexLockNormal(PTHREAD_PRIO_INHERIT);
1903 TestPthreadMutexLockErrorCheck(PTHREAD_PRIO_INHERIT);
1904 TestPthreadMutexLockRecursive(PTHREAD_PRIO_INHERIT);
1905}
1906
Yabin Cui5a00ba72018-01-26 17:32:31 -08001907TEST(pthread, pthread_mutex_pi_count_limit) {
1908#if defined(__BIONIC__) && !defined(__LP64__)
1909 // Bionic only supports 65536 pi mutexes in 32-bit programs.
1910 pthread_mutexattr_t attr;
1911 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1912 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT));
1913 std::vector<pthread_mutex_t> mutexes(65536);
1914 // Test if we can use 65536 pi mutexes at the same time.
1915 // Run 2 times to check if freed pi mutexes can be recycled.
1916 for (int repeat = 0; repeat < 2; ++repeat) {
1917 for (auto& m : mutexes) {
1918 ASSERT_EQ(0, pthread_mutex_init(&m, &attr));
1919 }
1920 pthread_mutex_t m;
1921 ASSERT_EQ(ENOMEM, pthread_mutex_init(&m, &attr));
1922 for (auto& m : mutexes) {
1923 ASSERT_EQ(0, pthread_mutex_lock(&m));
1924 }
1925 for (auto& m : mutexes) {
1926 ASSERT_EQ(0, pthread_mutex_unlock(&m));
1927 }
1928 for (auto& m : mutexes) {
1929 ASSERT_EQ(0, pthread_mutex_destroy(&m));
1930 }
1931 }
1932 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
1933#else
1934 GTEST_LOG_(INFO) << "This test does nothing as pi mutex count isn't limited.\n";
1935#endif
1936}
1937
Yabin Cui17393b02015-03-21 15:08:25 -07001938TEST(pthread, pthread_mutex_init_same_as_static_initializers) {
1939 pthread_mutex_t lock_normal = PTHREAD_MUTEX_INITIALIZER;
1940 PthreadMutex m1(PTHREAD_MUTEX_NORMAL);
1941 ASSERT_EQ(0, memcmp(&lock_normal, &m1.lock, sizeof(pthread_mutex_t)));
1942 pthread_mutex_destroy(&lock_normal);
1943
1944 pthread_mutex_t lock_errorcheck = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
1945 PthreadMutex m2(PTHREAD_MUTEX_ERRORCHECK);
1946 ASSERT_EQ(0, memcmp(&lock_errorcheck, &m2.lock, sizeof(pthread_mutex_t)));
1947 pthread_mutex_destroy(&lock_errorcheck);
1948
1949 pthread_mutex_t lock_recursive = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
1950 PthreadMutex m3(PTHREAD_MUTEX_RECURSIVE);
1951 ASSERT_EQ(0, memcmp(&lock_recursive, &m3.lock, sizeof(pthread_mutex_t)));
1952 ASSERT_EQ(0, pthread_mutex_destroy(&lock_recursive));
Derek Xue41996952014-09-25 11:05:32 +01001953}
Yabin Cui5a00ba72018-01-26 17:32:31 -08001954
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001955class MutexWakeupHelper {
1956 private:
Yabin Cui17393b02015-03-21 15:08:25 -07001957 PthreadMutex m;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001958 enum Progress {
1959 LOCK_INITIALIZED,
1960 LOCK_WAITING,
1961 LOCK_RELEASED,
1962 LOCK_ACCESSED
1963 };
1964 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -07001965 std::atomic<pid_t> tid;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001966
1967 static void thread_fn(MutexWakeupHelper* helper) {
Yabin Cuif7969852015-04-02 17:47:48 -07001968 helper->tid = gettid();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001969 ASSERT_EQ(LOCK_INITIALIZED, helper->progress);
1970 helper->progress = LOCK_WAITING;
1971
Yabin Cui17393b02015-03-21 15:08:25 -07001972 ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001973 ASSERT_EQ(LOCK_RELEASED, helper->progress);
Yabin Cui17393b02015-03-21 15:08:25 -07001974 ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001975
1976 helper->progress = LOCK_ACCESSED;
1977 }
1978
1979 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -07001980 explicit MutexWakeupHelper(int mutex_type) : m(mutex_type) {
Yabin Cui17393b02015-03-21 15:08:25 -07001981 }
1982
1983 void test() {
1984 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001985 progress = LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -07001986 tid = 0;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001987
1988 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07001989 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001990 reinterpret_cast<void* (*)(void*)>(MutexWakeupHelper::thread_fn), this));
1991
Yabin Cuif7969852015-04-02 17:47:48 -07001992 WaitUntilThreadSleep(tid);
1993 ASSERT_EQ(LOCK_WAITING, progress);
1994
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001995 progress = LOCK_RELEASED;
Yabin Cui17393b02015-03-21 15:08:25 -07001996 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001997
Yi Kong32bc0fc2018-08-02 17:31:13 -07001998 ASSERT_EQ(0, pthread_join(thread, nullptr));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001999 ASSERT_EQ(LOCK_ACCESSED, progress);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002000 }
2001};
2002
2003TEST(pthread, pthread_mutex_NORMAL_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07002004 MutexWakeupHelper helper(PTHREAD_MUTEX_NORMAL);
2005 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002006}
2007
2008TEST(pthread, pthread_mutex_ERRORCHECK_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07002009 MutexWakeupHelper helper(PTHREAD_MUTEX_ERRORCHECK);
2010 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002011}
2012
2013TEST(pthread, pthread_mutex_RECURSIVE_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07002014 MutexWakeupHelper helper(PTHREAD_MUTEX_RECURSIVE);
2015 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08002016}
2017
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002018static int GetThreadPriority(pid_t tid) {
2019 // sched_getparam() returns the static priority of a thread, which can't reflect a thread's
2020 // priority after priority inheritance. So read /proc/<pid>/stat to get the dynamic priority.
2021 std::string filename = android::base::StringPrintf("/proc/%d/stat", tid);
2022 std::string content;
2023 int result = INT_MAX;
2024 if (!android::base::ReadFileToString(filename, &content)) {
2025 return result;
2026 }
2027 std::vector<std::string> strs = android::base::Split(content, " ");
2028 if (strs.size() < 18) {
2029 return result;
2030 }
2031 if (!android::base::ParseInt(strs[17], &result)) {
2032 return INT_MAX;
2033 }
2034 return result;
2035}
2036
2037class PIMutexWakeupHelper {
2038private:
2039 PthreadMutex m;
2040 int protocol;
2041 enum Progress {
2042 LOCK_INITIALIZED,
2043 LOCK_CHILD_READY,
2044 LOCK_WAITING,
2045 LOCK_RELEASED,
2046 };
2047 std::atomic<Progress> progress;
2048 std::atomic<pid_t> main_tid;
2049 std::atomic<pid_t> child_tid;
2050 PthreadMutex start_thread_m;
2051
2052 static void thread_fn(PIMutexWakeupHelper* helper) {
2053 helper->child_tid = gettid();
2054 ASSERT_EQ(LOCK_INITIALIZED, helper->progress);
2055 ASSERT_EQ(0, setpriority(PRIO_PROCESS, gettid(), 1));
2056 ASSERT_EQ(21, GetThreadPriority(gettid()));
2057 ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock));
2058 helper->progress = LOCK_CHILD_READY;
2059 ASSERT_EQ(0, pthread_mutex_lock(&helper->start_thread_m.lock));
2060
2061 ASSERT_EQ(0, pthread_mutex_unlock(&helper->start_thread_m.lock));
2062 WaitUntilThreadSleep(helper->main_tid);
2063 ASSERT_EQ(LOCK_WAITING, helper->progress);
2064
2065 if (helper->protocol == PTHREAD_PRIO_INHERIT) {
2066 ASSERT_EQ(20, GetThreadPriority(gettid()));
2067 } else {
2068 ASSERT_EQ(21, GetThreadPriority(gettid()));
2069 }
2070 helper->progress = LOCK_RELEASED;
2071 ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock));
2072 }
2073
2074public:
2075 explicit PIMutexWakeupHelper(int mutex_type, int protocol)
2076 : m(mutex_type, protocol), protocol(protocol), start_thread_m(PTHREAD_MUTEX_NORMAL) {
2077 }
2078
2079 void test() {
2080 ASSERT_EQ(0, pthread_mutex_lock(&start_thread_m.lock));
2081 main_tid = gettid();
2082 ASSERT_EQ(20, GetThreadPriority(main_tid));
2083 progress = LOCK_INITIALIZED;
2084 child_tid = 0;
2085
2086 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002087 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002088 reinterpret_cast<void* (*)(void*)>(PIMutexWakeupHelper::thread_fn), this));
2089
2090 WaitUntilThreadSleep(child_tid);
2091 ASSERT_EQ(LOCK_CHILD_READY, progress);
2092 ASSERT_EQ(0, pthread_mutex_unlock(&start_thread_m.lock));
2093 progress = LOCK_WAITING;
2094 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
2095
2096 ASSERT_EQ(LOCK_RELEASED, progress);
2097 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2098 ASSERT_EQ(0, pthread_join(thread, nullptr));
2099 }
2100};
2101
2102TEST(pthread, pthread_mutex_pi_wakeup) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002103 for (int type : {PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_RECURSIVE, PTHREAD_MUTEX_ERRORCHECK}) {
2104 for (int protocol : {PTHREAD_PRIO_INHERIT}) {
2105 PIMutexWakeupHelper helper(type, protocol);
2106 helper.test();
2107 }
2108 }
2109}
2110
Yabin Cui140f3672015-02-03 10:32:00 -08002111TEST(pthread, pthread_mutex_owner_tid_limit) {
Yabin Cuie69c2452015-02-13 16:21:25 -08002112#if defined(__BIONIC__) && !defined(__LP64__)
Yabin Cui140f3672015-02-03 10:32:00 -08002113 FILE* fp = fopen("/proc/sys/kernel/pid_max", "r");
Yi Kong32bc0fc2018-08-02 17:31:13 -07002114 ASSERT_TRUE(fp != nullptr);
Yabin Cui140f3672015-02-03 10:32:00 -08002115 long pid_max;
2116 ASSERT_EQ(1, fscanf(fp, "%ld", &pid_max));
2117 fclose(fp);
Yabin Cuie69c2452015-02-13 16:21:25 -08002118 // Bionic's pthread_mutex implementation on 32-bit devices uses 16 bits to represent owner tid.
Yabin Cui140f3672015-02-03 10:32:00 -08002119 ASSERT_LE(pid_max, 65536);
Yabin Cuie69c2452015-02-13 16:21:25 -08002120#else
2121 GTEST_LOG_(INFO) << "This test does nothing as 32-bit tid is supported by pthread_mutex.\n";
2122#endif
Yabin Cui140f3672015-02-03 10:32:00 -08002123}
Yabin Cuib5845722015-03-16 22:46:42 -07002124
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002125static void pthread_mutex_timedlock_helper(clockid_t clock,
2126 int (*lock_function)(pthread_mutex_t* __mutex,
2127 const timespec* __timeout)) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08002128 pthread_mutex_t m;
2129 ASSERT_EQ(0, pthread_mutex_init(&m, nullptr));
2130
2131 // If the mutex is already locked, pthread_mutex_timedlock should time out.
2132 ASSERT_EQ(0, pthread_mutex_lock(&m));
2133
2134 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002135 ASSERT_EQ(0, clock_gettime(clock, &ts));
2136 ASSERT_EQ(ETIMEDOUT, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002137 ts.tv_nsec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002138 ASSERT_EQ(EINVAL, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002139 ts.tv_nsec = NS_PER_S;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002140 ASSERT_EQ(EINVAL, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002141 ts.tv_nsec = NS_PER_S - 1;
2142 ts.tv_sec = -1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002143 ASSERT_EQ(ETIMEDOUT, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002144
2145 // If the mutex is unlocked, pthread_mutex_timedlock should succeed.
2146 ASSERT_EQ(0, pthread_mutex_unlock(&m));
2147
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002148 ASSERT_EQ(0, clock_gettime(clock, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002149 ts.tv_sec += 1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002150 ASSERT_EQ(0, lock_function(&m, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08002151
2152 ASSERT_EQ(0, pthread_mutex_unlock(&m));
2153 ASSERT_EQ(0, pthread_mutex_destroy(&m));
2154}
2155
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002156TEST(pthread, pthread_mutex_timedlock) {
2157 pthread_mutex_timedlock_helper(CLOCK_REALTIME, pthread_mutex_timedlock);
2158}
2159
2160TEST(pthread, pthread_mutex_timedlock_monotonic_np) {
2161#if defined(__BIONIC__)
2162 pthread_mutex_timedlock_helper(CLOCK_MONOTONIC, pthread_mutex_timedlock_monotonic_np);
2163#else // __BIONIC__
2164 GTEST_LOG_(INFO) << "This test does nothing since pthread_mutex_timedlock_monotonic_np is only "
2165 "supported on bionic";
2166#endif // __BIONIC__
2167}
2168
2169static void pthread_mutex_timedlock_pi_helper(clockid_t clock,
2170 int (*lock_function)(pthread_mutex_t* __mutex,
2171 const timespec* __timeout)) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002172 PthreadMutex m(PTHREAD_MUTEX_NORMAL, PTHREAD_PRIO_INHERIT);
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002173
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002174 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002175 clock_gettime(clock, &ts);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002176 ts.tv_sec += 1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002177 ASSERT_EQ(0, lock_function(&m.lock, &ts));
2178
2179 struct ThreadArgs {
2180 clockid_t clock;
2181 int (*lock_function)(pthread_mutex_t* __mutex, const timespec* __timeout);
2182 PthreadMutex& m;
2183 };
2184
2185 ThreadArgs thread_args = {
2186 .clock = clock,
2187 .lock_function = lock_function,
2188 .m = m,
2189 };
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002190
2191 auto ThreadFn = [](void* arg) -> void* {
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002192 auto args = static_cast<ThreadArgs*>(arg);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002193 timespec ts;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002194 clock_gettime(args->clock, &ts);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002195 ts.tv_sec += 1;
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002196 intptr_t result = args->lock_function(&args->m.lock, &ts);
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002197 return reinterpret_cast<void*>(result);
2198 };
2199
2200 pthread_t thread;
Yi Kong32bc0fc2018-08-02 17:31:13 -07002201 ASSERT_EQ(0, pthread_create(&thread, nullptr, ThreadFn, &thread_args));
Yabin Cui6b9c85b2018-01-23 12:56:18 -08002202 void* result;
2203 ASSERT_EQ(0, pthread_join(thread, &result));
2204 ASSERT_EQ(ETIMEDOUT, reinterpret_cast<intptr_t>(result));
2205 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
2206}
2207
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002208TEST(pthread, pthread_mutex_timedlock_pi) {
2209 pthread_mutex_timedlock_pi_helper(CLOCK_REALTIME, pthread_mutex_timedlock);
2210}
2211
2212TEST(pthread, pthread_mutex_timedlock_monotonic_np_pi) {
2213#if defined(__BIONIC__)
2214 pthread_mutex_timedlock_pi_helper(CLOCK_MONOTONIC, pthread_mutex_timedlock_monotonic_np);
2215#else // __BIONIC__
2216 GTEST_LOG_(INFO) << "This test does nothing since pthread_mutex_timedlock_monotonic_np is only "
2217 "supported on bionic";
2218#endif // __BIONIC__
2219}
2220
Yabin Cui9651fdf2018-03-14 12:02:21 -07002221TEST(pthread, pthread_mutex_using_destroyed_mutex) {
2222#if defined(__BIONIC__)
2223 pthread_mutex_t m;
2224 ASSERT_EQ(0, pthread_mutex_init(&m, nullptr));
2225 ASSERT_EQ(0, pthread_mutex_destroy(&m));
2226 ASSERT_EXIT(pthread_mutex_lock(&m), ::testing::KilledBySignal(SIGABRT),
2227 "pthread_mutex_lock called on a destroyed mutex");
2228 ASSERT_EXIT(pthread_mutex_unlock(&m), ::testing::KilledBySignal(SIGABRT),
2229 "pthread_mutex_unlock called on a destroyed mutex");
2230 ASSERT_EXIT(pthread_mutex_trylock(&m), ::testing::KilledBySignal(SIGABRT),
2231 "pthread_mutex_trylock called on a destroyed mutex");
2232 timespec ts;
2233 ASSERT_EXIT(pthread_mutex_timedlock(&m, &ts), ::testing::KilledBySignal(SIGABRT),
2234 "pthread_mutex_timedlock called on a destroyed mutex");
Tom Cherryc6b5bcd2018-03-05 14:14:44 -08002235 ASSERT_EXIT(pthread_mutex_timedlock_monotonic_np(&m, &ts), ::testing::KilledBySignal(SIGABRT),
2236 "pthread_mutex_timedlock_monotonic_np called on a destroyed mutex");
Yabin Cui9651fdf2018-03-14 12:02:21 -07002237 ASSERT_EXIT(pthread_mutex_destroy(&m), ::testing::KilledBySignal(SIGABRT),
2238 "pthread_mutex_destroy called on a destroyed mutex");
2239#else
2240 GTEST_LOG_(INFO) << "This test tests bionic pthread mutex implementation details.";
2241#endif
2242}
2243
Yabin Cuib5845722015-03-16 22:46:42 -07002244class StrictAlignmentAllocator {
2245 public:
2246 void* allocate(size_t size, size_t alignment) {
2247 char* p = new char[size + alignment * 2];
2248 allocated_array.push_back(p);
2249 while (!is_strict_aligned(p, alignment)) {
2250 ++p;
2251 }
2252 return p;
2253 }
2254
2255 ~StrictAlignmentAllocator() {
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07002256 for (const auto& p : allocated_array) {
2257 delete[] p;
Yabin Cuib5845722015-03-16 22:46:42 -07002258 }
2259 }
2260
2261 private:
2262 bool is_strict_aligned(char* p, size_t alignment) {
2263 return (reinterpret_cast<uintptr_t>(p) % (alignment * 2)) == alignment;
2264 }
2265
2266 std::vector<char*> allocated_array;
2267};
2268
2269TEST(pthread, pthread_types_allow_four_bytes_alignment) {
2270#if defined(__BIONIC__)
2271 // For binary compatibility with old version, we need to allow 4-byte aligned data for pthread types.
2272 StrictAlignmentAllocator allocator;
2273 pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(
2274 allocator.allocate(sizeof(pthread_mutex_t), 4));
Yi Kong32bc0fc2018-08-02 17:31:13 -07002275 ASSERT_EQ(0, pthread_mutex_init(mutex, nullptr));
Yabin Cuib5845722015-03-16 22:46:42 -07002276 ASSERT_EQ(0, pthread_mutex_lock(mutex));
2277 ASSERT_EQ(0, pthread_mutex_unlock(mutex));
2278 ASSERT_EQ(0, pthread_mutex_destroy(mutex));
2279
2280 pthread_cond_t* cond = reinterpret_cast<pthread_cond_t*>(
2281 allocator.allocate(sizeof(pthread_cond_t), 4));
Yi Kong32bc0fc2018-08-02 17:31:13 -07002282 ASSERT_EQ(0, pthread_cond_init(cond, nullptr));
Yabin Cuib5845722015-03-16 22:46:42 -07002283 ASSERT_EQ(0, pthread_cond_signal(cond));
2284 ASSERT_EQ(0, pthread_cond_broadcast(cond));
2285 ASSERT_EQ(0, pthread_cond_destroy(cond));
2286
2287 pthread_rwlock_t* rwlock = reinterpret_cast<pthread_rwlock_t*>(
2288 allocator.allocate(sizeof(pthread_rwlock_t), 4));
Yi Kong32bc0fc2018-08-02 17:31:13 -07002289 ASSERT_EQ(0, pthread_rwlock_init(rwlock, nullptr));
Yabin Cuib5845722015-03-16 22:46:42 -07002290 ASSERT_EQ(0, pthread_rwlock_rdlock(rwlock));
2291 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
2292 ASSERT_EQ(0, pthread_rwlock_wrlock(rwlock));
2293 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
2294 ASSERT_EQ(0, pthread_rwlock_destroy(rwlock));
2295
2296#else
2297 GTEST_LOG_(INFO) << "This test tests bionic implementation details.";
2298#endif
2299}
Christopher Ferris60907c72015-06-09 18:46:15 -07002300
2301TEST(pthread, pthread_mutex_lock_null_32) {
2302#if defined(__BIONIC__) && !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -07002303 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return
2304 // EINVAL in that case: http://b/19995172.
2305 //
2306 // We decorate the public defintion with _Nonnull so that people recompiling
2307 // their code with get a warning and might fix their bug, but need to pass
2308 // NULL here to test that we remain compatible.
2309 pthread_mutex_t* null_value = nullptr;
2310 ASSERT_EQ(EINVAL, pthread_mutex_lock(null_value));
Christopher Ferris60907c72015-06-09 18:46:15 -07002311#else
2312 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 32 bit devices.";
2313#endif
2314}
2315
2316TEST(pthread, pthread_mutex_unlock_null_32) {
2317#if defined(__BIONIC__) && !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -07002318 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return
2319 // EINVAL in that case: http://b/19995172.
2320 //
2321 // We decorate the public defintion with _Nonnull so that people recompiling
2322 // their code with get a warning and might fix their bug, but need to pass
2323 // NULL here to test that we remain compatible.
2324 pthread_mutex_t* null_value = nullptr;
2325 ASSERT_EQ(EINVAL, pthread_mutex_unlock(null_value));
Christopher Ferris60907c72015-06-09 18:46:15 -07002326#else
2327 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 32 bit devices.";
2328#endif
2329}
2330
2331TEST_F(pthread_DeathTest, pthread_mutex_lock_null_64) {
2332#if defined(__BIONIC__) && defined(__LP64__)
2333 pthread_mutex_t* null_value = nullptr;
2334 ASSERT_EXIT(pthread_mutex_lock(null_value), testing::KilledBySignal(SIGSEGV), "");
2335#else
2336 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 64 bit devices.";
2337#endif
2338}
2339
2340TEST_F(pthread_DeathTest, pthread_mutex_unlock_null_64) {
2341#if defined(__BIONIC__) && defined(__LP64__)
2342 pthread_mutex_t* null_value = nullptr;
2343 ASSERT_EXIT(pthread_mutex_unlock(null_value), testing::KilledBySignal(SIGSEGV), "");
2344#else
2345 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 64 bit devices.";
2346#endif
2347}
Yabin Cui33ac04a2015-09-22 11:16:15 -07002348
2349extern _Unwind_Reason_Code FrameCounter(_Unwind_Context* ctx, void* arg);
2350
2351static volatile bool signal_handler_on_altstack_done;
2352
Josh Gao61db9ac2017-03-15 19:42:05 -07002353__attribute__((__noinline__))
2354static void signal_handler_backtrace() {
2355 // Check if we have enough stack space for unwinding.
2356 int count = 0;
2357 _Unwind_Backtrace(FrameCounter, &count);
2358 ASSERT_GT(count, 0);
2359}
2360
2361__attribute__((__noinline__))
2362static void signal_handler_logging() {
2363 // Check if we have enough stack space for logging.
2364 std::string s(2048, '*');
2365 GTEST_LOG_(INFO) << s;
2366 signal_handler_on_altstack_done = true;
2367}
2368
2369__attribute__((__noinline__))
2370static void signal_handler_snprintf() {
2371 // Check if we have enough stack space for snprintf to a PATH_MAX buffer, plus some extra.
2372 char buf[PATH_MAX + 2048];
2373 ASSERT_GT(snprintf(buf, sizeof(buf), "/proc/%d/status", getpid()), 0);
2374}
2375
Yabin Cui33ac04a2015-09-22 11:16:15 -07002376static void SignalHandlerOnAltStack(int signo, siginfo_t*, void*) {
2377 ASSERT_EQ(SIGUSR1, signo);
Josh Gao61db9ac2017-03-15 19:42:05 -07002378 signal_handler_backtrace();
2379 signal_handler_logging();
2380 signal_handler_snprintf();
Yabin Cui33ac04a2015-09-22 11:16:15 -07002381}
2382
Josh Gao415daa82017-03-06 17:45:33 -08002383TEST(pthread, big_enough_signal_stack) {
Yabin Cui33ac04a2015-09-22 11:16:15 -07002384 signal_handler_on_altstack_done = false;
2385 ScopedSignalHandler handler(SIGUSR1, SignalHandlerOnAltStack, SA_SIGINFO | SA_ONSTACK);
2386 kill(getpid(), SIGUSR1);
2387 ASSERT_TRUE(signal_handler_on_altstack_done);
2388}
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002389
2390TEST(pthread, pthread_barrierattr_smoke) {
2391 pthread_barrierattr_t attr;
2392 ASSERT_EQ(0, pthread_barrierattr_init(&attr));
2393 int pshared;
2394 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
2395 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
2396 ASSERT_EQ(0, pthread_barrierattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
2397 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
2398 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
2399 ASSERT_EQ(0, pthread_barrierattr_destroy(&attr));
2400}
2401
Yabin Cui81d27972016-03-22 13:45:55 -07002402struct BarrierTestHelperData {
2403 size_t thread_count;
2404 pthread_barrier_t barrier;
2405 std::atomic<int> finished_mask;
2406 std::atomic<int> serial_thread_count;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002407 size_t iteration_count;
Yabin Cui81d27972016-03-22 13:45:55 -07002408 std::atomic<size_t> finished_iteration_count;
2409
2410 BarrierTestHelperData(size_t thread_count, size_t iteration_count)
2411 : thread_count(thread_count), finished_mask(0), serial_thread_count(0),
2412 iteration_count(iteration_count), finished_iteration_count(0) {
2413 }
2414};
2415
2416struct BarrierTestHelperArg {
2417 int id;
2418 BarrierTestHelperData* data;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002419};
2420
2421static void BarrierTestHelper(BarrierTestHelperArg* arg) {
Yabin Cui81d27972016-03-22 13:45:55 -07002422 for (size_t i = 0; i < arg->data->iteration_count; ++i) {
2423 int result = pthread_barrier_wait(&arg->data->barrier);
2424 if (result == PTHREAD_BARRIER_SERIAL_THREAD) {
2425 arg->data->serial_thread_count++;
2426 } else {
2427 ASSERT_EQ(0, result);
2428 }
Yabin Cuid5c04c52017-05-02 12:57:39 -07002429 int mask = arg->data->finished_mask.fetch_or(1 << arg->id);
Yabin Cuiab4cddc2017-05-02 16:18:13 -07002430 mask |= 1 << arg->id;
Yabin Cuid5c04c52017-05-02 12:57:39 -07002431 if (mask == ((1 << arg->data->thread_count) - 1)) {
Yabin Cui81d27972016-03-22 13:45:55 -07002432 ASSERT_EQ(1, arg->data->serial_thread_count);
2433 arg->data->finished_iteration_count++;
2434 arg->data->finished_mask = 0;
2435 arg->data->serial_thread_count = 0;
2436 }
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002437 }
2438}
2439
2440TEST(pthread, pthread_barrier_smoke) {
2441 const size_t BARRIER_ITERATION_COUNT = 10;
2442 const size_t BARRIER_THREAD_COUNT = 10;
Yabin Cui81d27972016-03-22 13:45:55 -07002443 BarrierTestHelperData data(BARRIER_THREAD_COUNT, BARRIER_ITERATION_COUNT);
2444 ASSERT_EQ(0, pthread_barrier_init(&data.barrier, nullptr, data.thread_count));
2445 std::vector<pthread_t> threads(data.thread_count);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002446 std::vector<BarrierTestHelperArg> args(threads.size());
2447 for (size_t i = 0; i < threads.size(); ++i) {
Yabin Cui81d27972016-03-22 13:45:55 -07002448 args[i].id = i;
2449 args[i].data = &data;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002450 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
2451 reinterpret_cast<void* (*)(void*)>(BarrierTestHelper), &args[i]));
2452 }
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002453 for (size_t i = 0; i < threads.size(); ++i) {
2454 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
2455 }
Yabin Cui81d27972016-03-22 13:45:55 -07002456 ASSERT_EQ(data.iteration_count, data.finished_iteration_count);
2457 ASSERT_EQ(0, pthread_barrier_destroy(&data.barrier));
2458}
2459
2460struct BarrierDestroyTestArg {
2461 std::atomic<int> tid;
2462 pthread_barrier_t* barrier;
2463};
2464
2465static void BarrierDestroyTestHelper(BarrierDestroyTestArg* arg) {
2466 arg->tid = gettid();
2467 ASSERT_EQ(0, pthread_barrier_wait(arg->barrier));
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002468}
2469
2470TEST(pthread, pthread_barrier_destroy) {
2471 pthread_barrier_t barrier;
2472 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, 2));
2473 pthread_t thread;
Yabin Cui81d27972016-03-22 13:45:55 -07002474 BarrierDestroyTestArg arg;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002475 arg.tid = 0;
2476 arg.barrier = &barrier;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002477 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui81d27972016-03-22 13:45:55 -07002478 reinterpret_cast<void* (*)(void*)>(BarrierDestroyTestHelper), &arg));
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002479 WaitUntilThreadSleep(arg.tid);
2480 ASSERT_EQ(EBUSY, pthread_barrier_destroy(&barrier));
2481 ASSERT_EQ(PTHREAD_BARRIER_SERIAL_THREAD, pthread_barrier_wait(&barrier));
2482 // Verify if the barrier can be destroyed directly after pthread_barrier_wait().
2483 ASSERT_EQ(0, pthread_barrier_destroy(&barrier));
2484 ASSERT_EQ(0, pthread_join(thread, nullptr));
2485#if defined(__BIONIC__)
2486 ASSERT_EQ(EINVAL, pthread_barrier_destroy(&barrier));
2487#endif
2488}
2489
2490struct BarrierOrderingTestHelperArg {
2491 pthread_barrier_t* barrier;
2492 size_t* array;
2493 size_t array_length;
2494 size_t id;
2495};
2496
2497void BarrierOrderingTestHelper(BarrierOrderingTestHelperArg* arg) {
2498 const size_t ITERATION_COUNT = 10000;
2499 for (size_t i = 1; i <= ITERATION_COUNT; ++i) {
2500 arg->array[arg->id] = i;
Yabin Cuic9a659c2015-11-05 15:36:08 -08002501 int result = pthread_barrier_wait(arg->barrier);
2502 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002503 for (size_t j = 0; j < arg->array_length; ++j) {
2504 ASSERT_EQ(i, arg->array[j]);
2505 }
Yabin Cuic9a659c2015-11-05 15:36:08 -08002506 result = pthread_barrier_wait(arg->barrier);
2507 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002508 }
2509}
2510
2511TEST(pthread, pthread_barrier_check_ordering) {
2512 const size_t THREAD_COUNT = 4;
2513 pthread_barrier_t barrier;
2514 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, THREAD_COUNT));
2515 size_t array[THREAD_COUNT];
2516 std::vector<pthread_t> threads(THREAD_COUNT);
2517 std::vector<BarrierOrderingTestHelperArg> args(THREAD_COUNT);
2518 for (size_t i = 0; i < THREAD_COUNT; ++i) {
2519 args[i].barrier = &barrier;
2520 args[i].array = array;
2521 args[i].array_length = THREAD_COUNT;
2522 args[i].id = i;
2523 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
2524 reinterpret_cast<void* (*)(void*)>(BarrierOrderingTestHelper),
2525 &args[i]));
2526 }
2527 for (size_t i = 0; i < THREAD_COUNT; ++i) {
2528 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
2529 }
2530}
Yabin Cuife3a83a2015-11-17 16:03:18 -08002531
Elliott Hughes463faad2018-07-06 14:34:49 -07002532TEST(pthread, pthread_barrier_init_zero_count) {
2533 pthread_barrier_t barrier;
2534 ASSERT_EQ(EINVAL, pthread_barrier_init(&barrier, nullptr, 0));
2535}
2536
Yabin Cuife3a83a2015-11-17 16:03:18 -08002537TEST(pthread, pthread_spinlock_smoke) {
2538 pthread_spinlock_t lock;
2539 ASSERT_EQ(0, pthread_spin_init(&lock, 0));
2540 ASSERT_EQ(0, pthread_spin_trylock(&lock));
2541 ASSERT_EQ(0, pthread_spin_unlock(&lock));
2542 ASSERT_EQ(0, pthread_spin_lock(&lock));
2543 ASSERT_EQ(EBUSY, pthread_spin_trylock(&lock));
2544 ASSERT_EQ(0, pthread_spin_unlock(&lock));
2545 ASSERT_EQ(0, pthread_spin_destroy(&lock));
2546}
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002547
Elliott Hughes8aecba72017-10-17 15:34:41 -07002548TEST(pthread, pthread_attr_getdetachstate__pthread_attr_setdetachstate) {
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002549 pthread_attr_t attr;
2550 ASSERT_EQ(0, pthread_attr_init(&attr));
2551
Elliott Hughes8aecba72017-10-17 15:34:41 -07002552 int state;
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002553 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002554 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2555 ASSERT_EQ(PTHREAD_CREATE_DETACHED, state);
2556
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002557 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002558 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2559 ASSERT_EQ(PTHREAD_CREATE_JOINABLE, state);
2560
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002561 ASSERT_EQ(EINVAL, pthread_attr_setdetachstate(&attr, 123));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002562 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2563 ASSERT_EQ(PTHREAD_CREATE_JOINABLE, state);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002564}
2565
2566TEST(pthread, pthread_create__mmap_failures) {
2567 pthread_attr_t attr;
2568 ASSERT_EQ(0, pthread_attr_init(&attr));
2569 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
2570
2571 const auto kPageSize = sysconf(_SC_PAGE_SIZE);
2572
Elliott Hughes57512982017-10-02 22:49:18 -07002573 // Use up all the VMAs. By default this is 64Ki (though some will already be in use).
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002574 std::vector<void*> pages;
Elliott Hughes57512982017-10-02 22:49:18 -07002575 pages.reserve(64 * 1024);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002576 int prot = PROT_NONE;
2577 while (true) {
2578 void* page = mmap(nullptr, kPageSize, prot, MAP_ANON|MAP_PRIVATE, -1, 0);
2579 if (page == MAP_FAILED) break;
2580 pages.push_back(page);
2581 prot = (prot == PROT_NONE) ? PROT_READ : PROT_NONE;
2582 }
2583
2584 // Try creating threads, freeing up a page each time we fail.
2585 size_t EAGAIN_count = 0;
2586 size_t i = 0;
2587 for (; i < pages.size(); ++i) {
2588 pthread_t t;
2589 int status = pthread_create(&t, &attr, IdFn, nullptr);
2590 if (status != EAGAIN) break;
2591 ++EAGAIN_count;
2592 ASSERT_EQ(0, munmap(pages[i], kPageSize));
2593 }
2594
Ryan Prichard45d13492019-01-03 02:51:30 -08002595 // Creating a thread uses at least three VMAs: the combined stack and TLS, and a guard on each
2596 // side. So we should have seen at least three failures.
2597 ASSERT_GE(EAGAIN_count, 3U);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002598
2599 for (; i < pages.size(); ++i) {
2600 ASSERT_EQ(0, munmap(pages[i], kPageSize));
2601 }
2602}
Elliott Hughesdff08ce2017-10-16 09:58:45 -07002603
2604TEST(pthread, pthread_setschedparam) {
2605 sched_param p = { .sched_priority = INT_MIN };
2606 ASSERT_EQ(EINVAL, pthread_setschedparam(pthread_self(), INT_MIN, &p));
2607}
2608
2609TEST(pthread, pthread_setschedprio) {
2610 ASSERT_EQ(EINVAL, pthread_setschedprio(pthread_self(), INT_MIN));
2611}
Elliott Hughes8aecba72017-10-17 15:34:41 -07002612
2613TEST(pthread, pthread_attr_getinheritsched__pthread_attr_setinheritsched) {
2614 pthread_attr_t attr;
2615 ASSERT_EQ(0, pthread_attr_init(&attr));
2616
2617 int state;
2618 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2619 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
2620 ASSERT_EQ(PTHREAD_INHERIT_SCHED, state);
2621
2622 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
2623 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
2624 ASSERT_EQ(PTHREAD_EXPLICIT_SCHED, state);
2625
2626 ASSERT_EQ(EINVAL, pthread_attr_setinheritsched(&attr, 123));
2627 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
2628 ASSERT_EQ(PTHREAD_EXPLICIT_SCHED, state);
2629}
2630
2631TEST(pthread, pthread_attr_setinheritsched__PTHREAD_INHERIT_SCHED__PTHREAD_EXPLICIT_SCHED) {
2632 pthread_attr_t attr;
2633 ASSERT_EQ(0, pthread_attr_init(&attr));
2634
2635 // If we set invalid scheduling attributes but choose to inherit, everything's fine...
2636 sched_param param = { .sched_priority = sched_get_priority_max(SCHED_FIFO) + 1 };
2637 ASSERT_EQ(0, pthread_attr_setschedparam(&attr, &param));
2638 ASSERT_EQ(0, pthread_attr_setschedpolicy(&attr, SCHED_FIFO));
2639 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2640
2641 pthread_t t;
2642 ASSERT_EQ(0, pthread_create(&t, &attr, IdFn, nullptr));
2643 ASSERT_EQ(0, pthread_join(t, nullptr));
2644
Elliott Hughes7a660662017-10-30 09:26:06 -07002645#if defined(__LP64__)
2646 // If we ask to use them, though, we'll see a failure...
Elliott Hughes8aecba72017-10-17 15:34:41 -07002647 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
2648 ASSERT_EQ(EINVAL, pthread_create(&t, &attr, IdFn, nullptr));
Elliott Hughes7a660662017-10-30 09:26:06 -07002649#else
2650 // For backwards compatibility with broken apps, we just ignore failures
2651 // to set scheduler attributes on LP32.
2652#endif
Elliott Hughes8aecba72017-10-17 15:34:41 -07002653}
2654
2655TEST(pthread, pthread_attr_setinheritsched_PTHREAD_INHERIT_SCHED_takes_effect) {
2656 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
2657 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO, &param);
2658 if (rc == EPERM) {
2659 GTEST_LOG_(INFO) << "pthread_setschedparam failed with EPERM, skipping test\n";
2660 return;
2661 }
2662 ASSERT_EQ(0, rc);
2663
2664 pthread_attr_t attr;
2665 ASSERT_EQ(0, pthread_attr_init(&attr));
2666 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2667
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002668 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07002669 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002670 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002671 int actual_policy;
2672 sched_param actual_param;
2673 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
2674 ASSERT_EQ(SCHED_FIFO, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002675 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07002676 ASSERT_EQ(0, pthread_join(t, nullptr));
2677}
2678
2679TEST(pthread, pthread_attr_setinheritsched_PTHREAD_EXPLICIT_SCHED_takes_effect) {
2680 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
2681 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO, &param);
2682 if (rc == EPERM) {
2683 GTEST_LOG_(INFO) << "pthread_setschedparam failed with EPERM, skipping test\n";
2684 return;
2685 }
2686 ASSERT_EQ(0, rc);
2687
2688 pthread_attr_t attr;
2689 ASSERT_EQ(0, pthread_attr_init(&attr));
2690 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
2691 ASSERT_EQ(0, pthread_attr_setschedpolicy(&attr, SCHED_OTHER));
2692
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002693 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07002694 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002695 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002696 int actual_policy;
2697 sched_param actual_param;
2698 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
2699 ASSERT_EQ(SCHED_OTHER, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002700 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07002701 ASSERT_EQ(0, pthread_join(t, nullptr));
2702}
2703
2704TEST(pthread, pthread_attr_setinheritsched__takes_effect_despite_SCHED_RESET_ON_FORK) {
2705 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
2706 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param);
2707 if (rc == EPERM) {
2708 GTEST_LOG_(INFO) << "pthread_setschedparam failed with EPERM, skipping test\n";
2709 return;
2710 }
2711 ASSERT_EQ(0, rc);
2712
2713 pthread_attr_t attr;
2714 ASSERT_EQ(0, pthread_attr_init(&attr));
2715 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2716
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002717 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07002718 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002719 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002720 int actual_policy;
2721 sched_param actual_param;
2722 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
2723 ASSERT_EQ(SCHED_FIFO | SCHED_RESET_ON_FORK, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002724 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07002725 ASSERT_EQ(0, pthread_join(t, nullptr));
2726}