blob: 9ecb10cbca6dd0c2f6e9860676afcd5016348722 [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>
Elliott Hughes57b7a612014-08-25 17:26:50 -070028#include <sys/syscall.h>
Narayan Kamath51e6cb32014-03-03 15:38:51 +000029#include <time.h>
Elliott Hughes4d014e12012-09-07 16:47:54 -070030#include <unistd.h>
Yabin Cui33ac04a2015-09-22 11:16:15 -070031#include <unwind.h>
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070032
Yabin Cui08ee8d22015-02-11 17:04:36 -080033#include <atomic>
Yabin Cuib5845722015-03-16 22:46:42 -070034#include <vector>
Yabin Cui08ee8d22015-02-11 17:04:36 -080035
Yabin Cui6b9c85b2018-01-23 12:56:18 -080036#include <android-base/parseint.h>
Tom Cherryb8ab6182017-04-05 16:20:29 -070037#include <android-base/scopeguard.h>
Yabin Cui6b9c85b2018-01-23 12:56:18 -080038#include <android-base/strings.h>
Tom Cherryb8ab6182017-04-05 16:20:29 -070039
Yabin Cuic9a659c2015-11-05 15:36:08 -080040#include "private/bionic_constants.h"
Yabin Cui17393b02015-03-21 15:08:25 -070041#include "private/bionic_macros.h"
Yabin Cui17393b02015-03-21 15:08:25 -070042#include "BionicDeathTest.h"
43#include "ScopedSignalHandler.h"
Elliott Hughes15dfd632015-09-22 16:40:14 -070044#include "utils.h"
45
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070046TEST(pthread, pthread_key_create) {
47 pthread_key_t key;
48 ASSERT_EQ(0, pthread_key_create(&key, NULL));
49 ASSERT_EQ(0, pthread_key_delete(key));
50 // Can't delete a key that's already been deleted.
51 ASSERT_EQ(EINVAL, pthread_key_delete(key));
52}
Elliott Hughes4d014e12012-09-07 16:47:54 -070053
Dan Albertc4bcc752014-09-30 11:48:24 -070054TEST(pthread, pthread_keys_max) {
Yabin Cui6c238f22014-12-11 20:50:41 -080055 // POSIX says PTHREAD_KEYS_MAX should be at least _POSIX_THREAD_KEYS_MAX.
56 ASSERT_GE(PTHREAD_KEYS_MAX, _POSIX_THREAD_KEYS_MAX);
Dan Albertc4bcc752014-09-30 11:48:24 -070057}
Elliott Hughes718a5b52014-01-28 17:02:03 -080058
Yabin Cui6c238f22014-12-11 20:50:41 -080059TEST(pthread, sysconf_SC_THREAD_KEYS_MAX_eq_PTHREAD_KEYS_MAX) {
Dan Albertc4bcc752014-09-30 11:48:24 -070060 int sysconf_max = sysconf(_SC_THREAD_KEYS_MAX);
Yabin Cui6c238f22014-12-11 20:50:41 -080061 ASSERT_EQ(sysconf_max, PTHREAD_KEYS_MAX);
Dan Albertc4bcc752014-09-30 11:48:24 -070062}
63
64TEST(pthread, pthread_key_many_distinct) {
Yabin Cui6c238f22014-12-11 20:50:41 -080065 // As gtest uses pthread keys, we can't allocate exactly PTHREAD_KEYS_MAX
66 // pthread keys, but We should be able to allocate at least this many keys.
67 int nkeys = PTHREAD_KEYS_MAX / 2;
Dan Albertc4bcc752014-09-30 11:48:24 -070068 std::vector<pthread_key_t> keys;
69
Tom Cherryb8ab6182017-04-05 16:20:29 -070070 auto scope_guard = android::base::make_scope_guard([&keys] {
Elliott Hughes0b2acdf2015-10-02 18:25:19 -070071 for (const auto& key : keys) {
Dan Albertc4bcc752014-09-30 11:48:24 -070072 EXPECT_EQ(0, pthread_key_delete(key));
73 }
74 });
75
76 for (int i = 0; i < nkeys; ++i) {
77 pthread_key_t key;
Elliott Hughes61706932015-03-31 10:56:58 -070078 // If this fails, it's likely that LIBC_PTHREAD_KEY_RESERVED_COUNT is wrong.
Dan Albertc4bcc752014-09-30 11:48:24 -070079 ASSERT_EQ(0, pthread_key_create(&key, NULL)) << i << " of " << nkeys;
80 keys.push_back(key);
81 ASSERT_EQ(0, pthread_setspecific(key, reinterpret_cast<void*>(i)));
82 }
83
84 for (int i = keys.size() - 1; i >= 0; --i) {
85 ASSERT_EQ(reinterpret_cast<void*>(i), pthread_getspecific(keys.back()));
86 pthread_key_t key = keys.back();
87 keys.pop_back();
88 ASSERT_EQ(0, pthread_key_delete(key));
89 }
90}
91
Yabin Cui6c238f22014-12-11 20:50:41 -080092TEST(pthread, pthread_key_not_exceed_PTHREAD_KEYS_MAX) {
Elliott Hughes44b53ad2013-02-11 20:18:47 +000093 std::vector<pthread_key_t> keys;
Dan Albertc4bcc752014-09-30 11:48:24 -070094 int rv = 0;
Yabin Cui6c238f22014-12-11 20:50:41 -080095
96 // Pthread keys are used by gtest, so PTHREAD_KEYS_MAX should
97 // be more than we are allowed to allocate now.
98 for (int i = 0; i < PTHREAD_KEYS_MAX; i++) {
Elliott Hughes44b53ad2013-02-11 20:18:47 +000099 pthread_key_t key;
Dan Albertc4bcc752014-09-30 11:48:24 -0700100 rv = pthread_key_create(&key, NULL);
101 if (rv == EAGAIN) {
102 break;
103 }
104 EXPECT_EQ(0, rv);
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000105 keys.push_back(key);
106 }
107
Dan Albertc4bcc752014-09-30 11:48:24 -0700108 // Don't leak keys.
Elliott Hughes0b2acdf2015-10-02 18:25:19 -0700109 for (const auto& key : keys) {
Dan Albertc4bcc752014-09-30 11:48:24 -0700110 EXPECT_EQ(0, pthread_key_delete(key));
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000111 }
Dan Albertc4bcc752014-09-30 11:48:24 -0700112 keys.clear();
113
114 // We should have eventually reached the maximum number of keys and received
115 // EAGAIN.
116 ASSERT_EQ(EAGAIN, rv);
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000117}
118
Elliott Hughesebb770f2014-06-25 13:46:46 -0700119TEST(pthread, pthread_key_delete) {
120 void* expected = reinterpret_cast<void*>(1234);
121 pthread_key_t key;
122 ASSERT_EQ(0, pthread_key_create(&key, NULL));
123 ASSERT_EQ(0, pthread_setspecific(key, expected));
124 ASSERT_EQ(expected, pthread_getspecific(key));
125 ASSERT_EQ(0, pthread_key_delete(key));
126 // After deletion, pthread_getspecific returns NULL.
127 ASSERT_EQ(NULL, pthread_getspecific(key));
128 // And you can't use pthread_setspecific with the deleted key.
129 ASSERT_EQ(EINVAL, pthread_setspecific(key, expected));
130}
131
Elliott Hughes40a52172014-07-30 14:48:10 -0700132TEST(pthread, pthread_key_fork) {
133 void* expected = reinterpret_cast<void*>(1234);
134 pthread_key_t key;
135 ASSERT_EQ(0, pthread_key_create(&key, NULL));
136 ASSERT_EQ(0, pthread_setspecific(key, expected));
137 ASSERT_EQ(expected, pthread_getspecific(key));
138
139 pid_t pid = fork();
140 ASSERT_NE(-1, pid) << strerror(errno);
141
142 if (pid == 0) {
143 // The surviving thread inherits all the forking thread's TLS values...
144 ASSERT_EQ(expected, pthread_getspecific(key));
145 _exit(99);
146 }
147
Elliott Hughes33697a02016-01-26 13:04:57 -0800148 AssertChildExited(pid, 99);
Elliott Hughes40a52172014-07-30 14:48:10 -0700149
150 ASSERT_EQ(expected, pthread_getspecific(key));
Dan Albert1d53ae22014-09-02 15:24:26 -0700151 ASSERT_EQ(0, pthread_key_delete(key));
Elliott Hughes40a52172014-07-30 14:48:10 -0700152}
153
154static void* DirtyKeyFn(void* key) {
155 return pthread_getspecific(*reinterpret_cast<pthread_key_t*>(key));
156}
157
158TEST(pthread, pthread_key_dirty) {
159 pthread_key_t key;
160 ASSERT_EQ(0, pthread_key_create(&key, NULL));
161
Yabin Cuia36158a2015-11-16 21:06:16 -0800162 size_t stack_size = 640 * 1024;
Elliott Hughes40a52172014-07-30 14:48:10 -0700163 void* stack = mmap(NULL, stack_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
164 ASSERT_NE(MAP_FAILED, stack);
165 memset(stack, 0xff, stack_size);
166
167 pthread_attr_t attr;
168 ASSERT_EQ(0, pthread_attr_init(&attr));
169 ASSERT_EQ(0, pthread_attr_setstack(&attr, stack, stack_size));
170
171 pthread_t t;
172 ASSERT_EQ(0, pthread_create(&t, &attr, DirtyKeyFn, &key));
173
174 void* result;
175 ASSERT_EQ(0, pthread_join(t, &result));
176 ASSERT_EQ(nullptr, result); // Not ~0!
177
178 ASSERT_EQ(0, munmap(stack, stack_size));
Dan Albert1d53ae22014-09-02 15:24:26 -0700179 ASSERT_EQ(0, pthread_key_delete(key));
Elliott Hughes40a52172014-07-30 14:48:10 -0700180}
181
Yabin Cui5ddbb3f2015-03-05 20:35:32 -0800182TEST(pthread, static_pthread_key_used_before_creation) {
183#if defined(__BIONIC__)
184 // See http://b/19625804. The bug is about a static/global pthread key being used before creation.
185 // So here tests if the static/global default value 0 can be detected as invalid key.
186 static pthread_key_t key;
187 ASSERT_EQ(nullptr, pthread_getspecific(key));
188 ASSERT_EQ(EINVAL, pthread_setspecific(key, nullptr));
189 ASSERT_EQ(EINVAL, pthread_key_delete(key));
190#else
191 GTEST_LOG_(INFO) << "This test tests bionic pthread key implementation detail.\n";
192#endif
193}
194
Elliott Hughes4d014e12012-09-07 16:47:54 -0700195static void* IdFn(void* arg) {
196 return arg;
197}
198
Yabin Cui63481602014-12-01 17:41:04 -0800199class SpinFunctionHelper {
200 public:
201 SpinFunctionHelper() {
202 SpinFunctionHelper::spin_flag_ = true;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400203 }
Elliott Hughes0bd9d132017-11-02 13:11:13 -0700204
Yabin Cui63481602014-12-01 17:41:04 -0800205 ~SpinFunctionHelper() {
206 UnSpin();
207 }
Elliott Hughes0bd9d132017-11-02 13:11:13 -0700208
Yabin Cui63481602014-12-01 17:41:04 -0800209 auto GetFunction() -> void* (*)(void*) {
210 return SpinFunctionHelper::SpinFn;
211 }
212
213 void UnSpin() {
214 SpinFunctionHelper::spin_flag_ = false;
215 }
216
217 private:
218 static void* SpinFn(void*) {
219 while (spin_flag_) {}
220 return NULL;
221 }
Yabin Cuia36158a2015-11-16 21:06:16 -0800222 static std::atomic<bool> spin_flag_;
Yabin Cui63481602014-12-01 17:41:04 -0800223};
224
225// It doesn't matter if spin_flag_ is used in several tests,
226// because it is always set to false after each test. Each thread
227// loops on spin_flag_ can find it becomes false at some time.
Yabin Cuia36158a2015-11-16 21:06:16 -0800228std::atomic<bool> SpinFunctionHelper::spin_flag_;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400229
Elliott Hughes4d014e12012-09-07 16:47:54 -0700230static void* JoinFn(void* arg) {
231 return reinterpret_cast<void*>(pthread_join(reinterpret_cast<pthread_t>(arg), NULL));
232}
233
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400234static void AssertDetached(pthread_t t, bool is_detached) {
235 pthread_attr_t attr;
236 ASSERT_EQ(0, pthread_getattr_np(t, &attr));
237 int detach_state;
238 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &detach_state));
239 pthread_attr_destroy(&attr);
240 ASSERT_EQ(is_detached, (detach_state == PTHREAD_CREATE_DETACHED));
241}
242
Elliott Hughes7484c212017-02-02 02:41:38 +0000243static void MakeDeadThread(pthread_t& t) {
244 ASSERT_EQ(0, pthread_create(&t, NULL, IdFn, NULL));
245 ASSERT_EQ(0, pthread_join(t, NULL));
246}
247
Elliott Hughes4d014e12012-09-07 16:47:54 -0700248TEST(pthread, pthread_create) {
249 void* expected_result = reinterpret_cast<void*>(123);
250 // Can we create a thread?
251 pthread_t t;
252 ASSERT_EQ(0, pthread_create(&t, NULL, IdFn, expected_result));
253 // If we join, do we get the expected value back?
254 void* result;
255 ASSERT_EQ(0, pthread_join(t, &result));
256 ASSERT_EQ(expected_result, result);
257}
258
Elliott Hughes3e898472013-02-12 16:40:24 +0000259TEST(pthread, pthread_create_EAGAIN) {
260 pthread_attr_t attributes;
261 ASSERT_EQ(0, pthread_attr_init(&attributes));
262 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, static_cast<size_t>(-1) & ~(getpagesize() - 1)));
263
264 pthread_t t;
265 ASSERT_EQ(EAGAIN, pthread_create(&t, &attributes, IdFn, NULL));
266}
267
Elliott Hughes4d014e12012-09-07 16:47:54 -0700268TEST(pthread, pthread_no_join_after_detach) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700269 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800270
Elliott Hughes4d014e12012-09-07 16:47:54 -0700271 pthread_t t1;
Elliott Hughes725b2a92016-03-23 11:20:47 -0700272 ASSERT_EQ(0, pthread_create(&t1, NULL, spin_helper.GetFunction(), NULL));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700273
274 // After a pthread_detach...
275 ASSERT_EQ(0, pthread_detach(t1));
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400276 AssertDetached(t1, true);
Elliott Hughes4d014e12012-09-07 16:47:54 -0700277
278 // ...pthread_join should fail.
Elliott Hughes34c987a2014-09-22 16:01:26 -0700279 ASSERT_EQ(EINVAL, pthread_join(t1, NULL));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700280}
281
282TEST(pthread, pthread_no_op_detach_after_join) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700283 SpinFunctionHelper spin_helper;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400284
Elliott Hughes4d014e12012-09-07 16:47:54 -0700285 pthread_t t1;
Elliott Hughes725b2a92016-03-23 11:20:47 -0700286 ASSERT_EQ(0, pthread_create(&t1, NULL, spin_helper.GetFunction(), NULL));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700287
288 // If thread 2 is already waiting to join thread 1...
289 pthread_t t2;
290 ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1)));
291
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400292 sleep(1); // (Give t2 a chance to call pthread_join.)
Elliott Hughes4d014e12012-09-07 16:47:54 -0700293
Yabin Cuibbb04322015-03-19 15:19:25 -0700294#if defined(__BIONIC__)
295 ASSERT_EQ(EINVAL, pthread_detach(t1));
296#else
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400297 ASSERT_EQ(0, pthread_detach(t1));
Yabin Cuibbb04322015-03-19 15:19:25 -0700298#endif
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400299 AssertDetached(t1, false);
300
Elliott Hughes725b2a92016-03-23 11:20:47 -0700301 spin_helper.UnSpin();
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400302
303 // ...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 -0700304 void* join_result;
305 ASSERT_EQ(0, pthread_join(t2, &join_result));
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700306 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700307}
Elliott Hughes14f19592012-10-29 10:19:44 -0700308
309TEST(pthread, pthread_join_self) {
Elliott Hughes34c987a2014-09-22 16:01:26 -0700310 ASSERT_EQ(EDEADLK, pthread_join(pthread_self(), NULL));
Elliott Hughes14f19592012-10-29 10:19:44 -0700311}
Elliott Hughes4f251be2012-11-01 16:33:29 -0700312
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800313struct TestBug37410 {
314 pthread_t main_thread;
315 pthread_mutex_t mutex;
Elliott Hughes4f251be2012-11-01 16:33:29 -0700316
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800317 static void main() {
318 TestBug37410 data;
319 data.main_thread = pthread_self();
320 ASSERT_EQ(0, pthread_mutex_init(&data.mutex, NULL));
321 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
322
323 pthread_t t;
324 ASSERT_EQ(0, pthread_create(&t, NULL, TestBug37410::thread_fn, reinterpret_cast<void*>(&data)));
325
326 // Wait for the thread to be running...
327 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
328 ASSERT_EQ(0, pthread_mutex_unlock(&data.mutex));
329
330 // ...and exit.
331 pthread_exit(NULL);
332 }
333
334 private:
335 static void* thread_fn(void* arg) {
336 TestBug37410* data = reinterpret_cast<TestBug37410*>(arg);
337
338 // Let the main thread know we're running.
339 pthread_mutex_unlock(&data->mutex);
340
341 // And wait for the main thread to exit.
342 pthread_join(data->main_thread, NULL);
343
344 return NULL;
345 }
346};
Elliott Hughes4f251be2012-11-01 16:33:29 -0700347
Elliott Hughes7fd803c2013-02-14 16:33:52 -0800348// Even though this isn't really a death test, we have to say "DeathTest" here so gtest knows to
349// run this test (which exits normally) in its own process.
Yabin Cui9df70402014-11-05 18:01:01 -0800350
351class pthread_DeathTest : public BionicDeathTest {};
352
353TEST_F(pthread_DeathTest, pthread_bug_37410) {
Elliott Hughes4f251be2012-11-01 16:33:29 -0700354 // http://code.google.com/p/android/issues/detail?id=37410
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800355 ASSERT_EXIT(TestBug37410::main(), ::testing::ExitedWithCode(0), "");
Elliott Hughes4f251be2012-11-01 16:33:29 -0700356}
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800357
358static void* SignalHandlerFn(void* arg) {
359 sigset_t wait_set;
360 sigfillset(&wait_set);
361 return reinterpret_cast<void*>(sigwait(&wait_set, reinterpret_cast<int*>(arg)));
362}
363
364TEST(pthread, pthread_sigmask) {
Elliott Hughes19e62322013-10-15 11:23:57 -0700365 // Check that SIGUSR1 isn't blocked.
366 sigset_t original_set;
367 sigemptyset(&original_set);
368 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, NULL, &original_set));
369 ASSERT_FALSE(sigismember(&original_set, SIGUSR1));
370
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800371 // Block SIGUSR1.
372 sigset_t set;
373 sigemptyset(&set);
374 sigaddset(&set, SIGUSR1);
375 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, &set, NULL));
376
Elliott Hughes19e62322013-10-15 11:23:57 -0700377 // Check that SIGUSR1 is blocked.
378 sigset_t final_set;
379 sigemptyset(&final_set);
380 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, NULL, &final_set));
381 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
382 // ...and that sigprocmask agrees with pthread_sigmask.
383 sigemptyset(&final_set);
384 ASSERT_EQ(0, sigprocmask(SIG_BLOCK, NULL, &final_set));
385 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
386
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800387 // Spawn a thread that calls sigwait and tells us what it received.
388 pthread_t signal_thread;
389 int received_signal = -1;
390 ASSERT_EQ(0, pthread_create(&signal_thread, NULL, SignalHandlerFn, &received_signal));
391
392 // Send that thread SIGUSR1.
393 pthread_kill(signal_thread, SIGUSR1);
394
395 // See what it got.
396 void* join_result;
397 ASSERT_EQ(0, pthread_join(signal_thread, &join_result));
398 ASSERT_EQ(SIGUSR1, received_signal);
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700399 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
Elliott Hughes19e62322013-10-15 11:23:57 -0700400
401 // Restore the original signal mask.
402 ASSERT_EQ(0, pthread_sigmask(SIG_SETMASK, &original_set, NULL));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800403}
Elliott Hughes5e3fc432013-02-11 16:36:48 -0800404
Elliott Hughes725b2a92016-03-23 11:20:47 -0700405static void test_pthread_setname_np__pthread_getname_np(pthread_t t) {
406 ASSERT_EQ(0, pthread_setname_np(t, "short"));
407 char name[32];
408 ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name)));
409 ASSERT_STREQ("short", name);
410
Elliott Hughesd1aea302015-04-25 10:05:24 -0700411 // The limit is 15 characters --- the kernel's buffer is 16, but includes a NUL.
Elliott Hughes725b2a92016-03-23 11:20:47 -0700412 ASSERT_EQ(0, pthread_setname_np(t, "123456789012345"));
413 ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name)));
414 ASSERT_STREQ("123456789012345", name);
415
416 ASSERT_EQ(ERANGE, pthread_setname_np(t, "1234567890123456"));
417
418 // The passed-in buffer should be at least 16 bytes.
419 ASSERT_EQ(0, pthread_getname_np(t, name, 16));
420 ASSERT_EQ(ERANGE, pthread_getname_np(t, name, 15));
Elliott Hughes3e898472013-02-12 16:40:24 +0000421}
422
Elliott Hughes725b2a92016-03-23 11:20:47 -0700423TEST(pthread, pthread_setname_np__pthread_getname_np__self) {
424 test_pthread_setname_np__pthread_getname_np(pthread_self());
Elliott Hughes3e898472013-02-12 16:40:24 +0000425}
426
Elliott Hughes725b2a92016-03-23 11:20:47 -0700427TEST(pthread, pthread_setname_np__pthread_getname_np__other) {
428 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800429
Elliott Hughes725b2a92016-03-23 11:20:47 -0700430 pthread_t t;
Elliott Hughes4d098ca2016-04-11 12:43:05 -0700431 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
432 test_pthread_setname_np__pthread_getname_np(t);
433 spin_helper.UnSpin();
434 ASSERT_EQ(0, pthread_join(t, nullptr));
435}
436
437// http://b/28051133: a kernel misfeature means that you can't change the
438// name of another thread if you've set PR_SET_DUMPABLE to 0.
439TEST(pthread, pthread_setname_np__pthread_getname_np__other_PR_SET_DUMPABLE) {
440 ASSERT_EQ(0, prctl(PR_SET_DUMPABLE, 0)) << strerror(errno);
441
442 SpinFunctionHelper spin_helper;
443
444 pthread_t t;
445 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
Elliott Hughes725b2a92016-03-23 11:20:47 -0700446 test_pthread_setname_np__pthread_getname_np(t);
447 spin_helper.UnSpin();
448 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes3e898472013-02-12 16:40:24 +0000449}
450
Elliott Hughes11859d42017-02-13 17:59:29 -0800451TEST_F(pthread_DeathTest, pthread_setname_np__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000452 pthread_t dead_thread;
453 MakeDeadThread(dead_thread);
454
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800455 EXPECT_DEATH(pthread_setname_np(dead_thread, "short 3"), "invalid pthread_t");
456}
457
458TEST_F(pthread_DeathTest, pthread_setname_np__null_thread) {
459 pthread_t null_thread = 0;
460 EXPECT_EQ(ENOENT, pthread_setname_np(null_thread, "short 3"));
Elliott Hughes11859d42017-02-13 17:59:29 -0800461}
462
463TEST_F(pthread_DeathTest, pthread_getname_np__no_such_thread) {
464 pthread_t dead_thread;
465 MakeDeadThread(dead_thread);
466
Elliott Hughesbcb15292017-02-07 21:05:30 +0000467 char name[64];
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800468 EXPECT_DEATH(pthread_getname_np(dead_thread, name, sizeof(name)), "invalid pthread_t");
469}
470
471TEST_F(pthread_DeathTest, pthread_getname_np__null_thread) {
472 pthread_t null_thread = 0;
473
474 char name[64];
475 EXPECT_EQ(ENOENT, pthread_getname_np(null_thread, name, sizeof(name)));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000476}
477
Elliott Hughes9d23e042013-02-15 19:21:51 -0800478TEST(pthread, pthread_kill__0) {
479 // Signal 0 just tests that the thread exists, so it's safe to call on ourselves.
480 ASSERT_EQ(0, pthread_kill(pthread_self(), 0));
481}
482
483TEST(pthread, pthread_kill__invalid_signal) {
484 ASSERT_EQ(EINVAL, pthread_kill(pthread_self(), -1));
485}
486
Elliott Hughesfae89fc2013-02-21 11:22:23 -0800487static void pthread_kill__in_signal_handler_helper(int signal_number) {
488 static int count = 0;
489 ASSERT_EQ(SIGALRM, signal_number);
490 if (++count == 1) {
491 // Can we call pthread_kill from a signal handler?
492 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
493 }
494}
495
496TEST(pthread, pthread_kill__in_signal_handler) {
Elliott Hughes4b558f52014-03-04 15:58:02 -0800497 ScopedSignalHandler ssh(SIGALRM, pthread_kill__in_signal_handler_helper);
Elliott Hughesfae89fc2013-02-21 11:22:23 -0800498 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
499}
500
Elliott Hughes11859d42017-02-13 17:59:29 -0800501TEST_F(pthread_DeathTest, pthread_detach__no_such_thread) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000502 pthread_t dead_thread;
503 MakeDeadThread(dead_thread);
504
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800505 EXPECT_DEATH(pthread_detach(dead_thread), "invalid pthread_t");
506}
507
508TEST_F(pthread_DeathTest, pthread_detach__null_thread) {
509 pthread_t null_thread = 0;
510 EXPECT_EQ(ESRCH, pthread_detach(null_thread));
Elliott Hughes7484c212017-02-02 02:41:38 +0000511}
512
Jeff Hao9b06cc32013-08-15 14:51:16 -0700513TEST(pthread, pthread_getcpuclockid__clock_gettime) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700514 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800515
Jeff Hao9b06cc32013-08-15 14:51:16 -0700516 pthread_t t;
Elliott Hughes725b2a92016-03-23 11:20:47 -0700517 ASSERT_EQ(0, pthread_create(&t, NULL, spin_helper.GetFunction(), NULL));
Jeff Hao9b06cc32013-08-15 14:51:16 -0700518
519 clockid_t c;
520 ASSERT_EQ(0, pthread_getcpuclockid(t, &c));
521 timespec ts;
522 ASSERT_EQ(0, clock_gettime(c, &ts));
Elliott Hughes725b2a92016-03-23 11:20:47 -0700523 spin_helper.UnSpin();
Yabin Cuia36158a2015-11-16 21:06:16 -0800524 ASSERT_EQ(0, pthread_join(t, nullptr));
Jeff Hao9b06cc32013-08-15 14:51:16 -0700525}
526
Elliott Hughes11859d42017-02-13 17:59:29 -0800527TEST_F(pthread_DeathTest, pthread_getcpuclockid__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000528 pthread_t dead_thread;
529 MakeDeadThread(dead_thread);
530
531 clockid_t c;
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800532 EXPECT_DEATH(pthread_getcpuclockid(dead_thread, &c), "invalid pthread_t");
533}
534
535TEST_F(pthread_DeathTest, pthread_getcpuclockid__null_thread) {
536 pthread_t null_thread = 0;
537 clockid_t c;
538 EXPECT_EQ(ESRCH, pthread_getcpuclockid(null_thread, &c));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000539}
540
Elliott Hughes11859d42017-02-13 17:59:29 -0800541TEST_F(pthread_DeathTest, pthread_getschedparam__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000542 pthread_t dead_thread;
543 MakeDeadThread(dead_thread);
544
545 int policy;
546 sched_param param;
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800547 EXPECT_DEATH(pthread_getschedparam(dead_thread, &policy, &param), "invalid pthread_t");
548}
549
550TEST_F(pthread_DeathTest, pthread_getschedparam__null_thread) {
551 pthread_t null_thread = 0;
552 int policy;
553 sched_param param;
554 EXPECT_EQ(ESRCH, pthread_getschedparam(null_thread, &policy, &param));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000555}
556
Elliott Hughes11859d42017-02-13 17:59:29 -0800557TEST_F(pthread_DeathTest, pthread_setschedparam__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000558 pthread_t dead_thread;
559 MakeDeadThread(dead_thread);
560
561 int policy = 0;
562 sched_param param;
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800563 EXPECT_DEATH(pthread_setschedparam(dead_thread, policy, &param), "invalid pthread_t");
564}
565
566TEST_F(pthread_DeathTest, pthread_setschedparam__null_thread) {
567 pthread_t null_thread = 0;
568 int policy = 0;
569 sched_param param;
570 EXPECT_EQ(ESRCH, pthread_setschedparam(null_thread, policy, &param));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000571}
572
Elliott Hughesdff08ce2017-10-16 09:58:45 -0700573TEST_F(pthread_DeathTest, pthread_setschedprio__no_such_thread) {
574 pthread_t dead_thread;
575 MakeDeadThread(dead_thread);
576
577 EXPECT_DEATH(pthread_setschedprio(dead_thread, 123), "invalid pthread_t");
578}
579
580TEST_F(pthread_DeathTest, pthread_setschedprio__null_thread) {
581 pthread_t null_thread = 0;
582 EXPECT_EQ(ESRCH, pthread_setschedprio(null_thread, 123));
583}
584
Elliott Hughes11859d42017-02-13 17:59:29 -0800585TEST_F(pthread_DeathTest, pthread_join__no_such_thread) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000586 pthread_t dead_thread;
587 MakeDeadThread(dead_thread);
588
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800589 EXPECT_DEATH(pthread_join(dead_thread, NULL), "invalid pthread_t");
590}
591
592TEST_F(pthread_DeathTest, pthread_join__null_thread) {
593 pthread_t null_thread = 0;
594 EXPECT_EQ(ESRCH, pthread_join(null_thread, NULL));
Elliott Hughes7484c212017-02-02 02:41:38 +0000595}
596
Elliott Hughes11859d42017-02-13 17:59:29 -0800597TEST_F(pthread_DeathTest, pthread_kill__no_such_thread) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000598 pthread_t dead_thread;
599 MakeDeadThread(dead_thread);
600
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800601 EXPECT_DEATH(pthread_kill(dead_thread, 0), "invalid pthread_t");
602}
603
604TEST_F(pthread_DeathTest, pthread_kill__null_thread) {
605 pthread_t null_thread = 0;
606 EXPECT_EQ(ESRCH, pthread_kill(null_thread, 0));
Elliott Hughes7484c212017-02-02 02:41:38 +0000607}
608
msg5550f020d12013-06-06 14:59:28 -0400609TEST(pthread, pthread_join__multijoin) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700610 SpinFunctionHelper spin_helper;
msg5550f020d12013-06-06 14:59:28 -0400611
612 pthread_t t1;
Elliott Hughes725b2a92016-03-23 11:20:47 -0700613 ASSERT_EQ(0, pthread_create(&t1, NULL, spin_helper.GetFunction(), NULL));
msg5550f020d12013-06-06 14:59:28 -0400614
615 pthread_t t2;
616 ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1)));
617
618 sleep(1); // (Give t2 a chance to call pthread_join.)
619
620 // Multiple joins to the same thread should fail.
621 ASSERT_EQ(EINVAL, pthread_join(t1, NULL));
622
Elliott Hughes725b2a92016-03-23 11:20:47 -0700623 spin_helper.UnSpin();
msg5550f020d12013-06-06 14:59:28 -0400624
625 // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes).
626 void* join_result;
627 ASSERT_EQ(0, pthread_join(t2, &join_result));
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700628 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
msg5550f020d12013-06-06 14:59:28 -0400629}
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700630
Elliott Hughes70b24b12013-11-15 11:51:07 -0800631TEST(pthread, pthread_join__race) {
632 // http://b/11693195 --- pthread_join could return before the thread had actually exited.
633 // If the joiner unmapped the thread's stack, that could lead to SIGSEGV in the thread.
634 for (size_t i = 0; i < 1024; ++i) {
Yabin Cuia36158a2015-11-16 21:06:16 -0800635 size_t stack_size = 640*1024;
Elliott Hughes70b24b12013-11-15 11:51:07 -0800636 void* stack = mmap(NULL, stack_size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
637
638 pthread_attr_t a;
639 pthread_attr_init(&a);
640 pthread_attr_setstack(&a, stack, stack_size);
641
642 pthread_t t;
643 ASSERT_EQ(0, pthread_create(&t, &a, IdFn, NULL));
644 ASSERT_EQ(0, pthread_join(t, NULL));
645 ASSERT_EQ(0, munmap(stack, stack_size));
646 }
647}
648
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700649static void* GetActualGuardSizeFn(void* arg) {
650 pthread_attr_t attributes;
651 pthread_getattr_np(pthread_self(), &attributes);
652 pthread_attr_getguardsize(&attributes, reinterpret_cast<size_t*>(arg));
653 return NULL;
654}
655
656static size_t GetActualGuardSize(const pthread_attr_t& attributes) {
657 size_t result;
658 pthread_t t;
659 pthread_create(&t, &attributes, GetActualGuardSizeFn, &result);
Elliott Hughes34c987a2014-09-22 16:01:26 -0700660 pthread_join(t, NULL);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700661 return result;
662}
663
664static void* GetActualStackSizeFn(void* arg) {
665 pthread_attr_t attributes;
666 pthread_getattr_np(pthread_self(), &attributes);
667 pthread_attr_getstacksize(&attributes, reinterpret_cast<size_t*>(arg));
668 return NULL;
669}
670
671static size_t GetActualStackSize(const pthread_attr_t& attributes) {
672 size_t result;
673 pthread_t t;
674 pthread_create(&t, &attributes, GetActualStackSizeFn, &result);
Elliott Hughes34c987a2014-09-22 16:01:26 -0700675 pthread_join(t, NULL);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700676 return result;
677}
678
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700679TEST(pthread, pthread_attr_setguardsize_tiny) {
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700680 pthread_attr_t attributes;
681 ASSERT_EQ(0, pthread_attr_init(&attributes));
682
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700683 // No such thing as too small: will be rounded up to one page by pthread_create.
684 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 128));
685 size_t guard_size;
686 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
687 ASSERT_EQ(128U, guard_size);
688 ASSERT_EQ(4096U, GetActualGuardSize(attributes));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700689}
690
691TEST(pthread, pthread_attr_setguardsize_reasonable) {
692 pthread_attr_t attributes;
693 ASSERT_EQ(0, pthread_attr_init(&attributes));
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700694
695 // Large enough and a multiple of the page size.
696 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700697 size_t guard_size;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700698 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
699 ASSERT_EQ(32*1024U, guard_size);
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700700 ASSERT_EQ(32*1024U, GetActualGuardSize(attributes));
701}
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700702
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700703TEST(pthread, pthread_attr_setguardsize_needs_rounding) {
704 pthread_attr_t attributes;
705 ASSERT_EQ(0, pthread_attr_init(&attributes));
706
707 // Large enough but not a multiple of the page size.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700708 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024 + 1));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700709 size_t guard_size;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700710 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
711 ASSERT_EQ(32*1024U + 1, guard_size);
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700712 ASSERT_EQ(36*1024U, GetActualGuardSize(attributes));
713}
714
715TEST(pthread, pthread_attr_setguardsize_enormous) {
716 pthread_attr_t attributes;
717 ASSERT_EQ(0, pthread_attr_init(&attributes));
718
719 // Larger than the stack itself. (Historically we mistakenly carved
720 // the guard out of the stack itself, rather than adding it after the
721 // end.)
722 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024*1024));
723 size_t guard_size;
724 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
725 ASSERT_EQ(32*1024*1024U, guard_size);
726 ASSERT_EQ(32*1024*1024U, GetActualGuardSize(attributes));
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700727}
728
729TEST(pthread, pthread_attr_setstacksize) {
730 pthread_attr_t attributes;
731 ASSERT_EQ(0, pthread_attr_init(&attributes));
732
733 // Get the default stack size.
734 size_t default_stack_size;
735 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &default_stack_size));
736
737 // Too small.
738 ASSERT_EQ(EINVAL, pthread_attr_setstacksize(&attributes, 128));
739 size_t stack_size;
740 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
741 ASSERT_EQ(default_stack_size, stack_size);
742 ASSERT_GE(GetActualStackSize(attributes), default_stack_size);
743
Yabin Cui917d3902015-01-08 12:32:42 -0800744 // Large enough and a multiple of the page size; may be rounded up by pthread_create.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700745 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024));
746 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
747 ASSERT_EQ(32*1024U, stack_size);
Yabin Cui917d3902015-01-08 12:32:42 -0800748 ASSERT_GE(GetActualStackSize(attributes), 32*1024U);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700749
Yabin Cui917d3902015-01-08 12:32:42 -0800750 // Large enough but not aligned; will be rounded up by pthread_create.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700751 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024 + 1));
752 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
753 ASSERT_EQ(32*1024U + 1, stack_size);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800754#if defined(__BIONIC__)
Yabin Cui917d3902015-01-08 12:32:42 -0800755 ASSERT_GT(GetActualStackSize(attributes), 32*1024U + 1);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800756#else // __BIONIC__
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700757 // glibc rounds down, in violation of POSIX. They document this in their BUGS section.
758 ASSERT_EQ(GetActualStackSize(attributes), 32*1024U);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800759#endif // __BIONIC__
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700760}
Elliott Hughesc3f11402013-10-30 14:40:09 -0700761
Yabin Cui76615da2015-03-17 14:22:09 -0700762TEST(pthread, pthread_rwlockattr_smoke) {
763 pthread_rwlockattr_t attr;
764 ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
765
766 int pshared_value_array[] = {PTHREAD_PROCESS_PRIVATE, PTHREAD_PROCESS_SHARED};
767 for (size_t i = 0; i < sizeof(pshared_value_array) / sizeof(pshared_value_array[0]); ++i) {
768 ASSERT_EQ(0, pthread_rwlockattr_setpshared(&attr, pshared_value_array[i]));
769 int pshared;
770 ASSERT_EQ(0, pthread_rwlockattr_getpshared(&attr, &pshared));
771 ASSERT_EQ(pshared_value_array[i], pshared);
772 }
773
774 int kind_array[] = {PTHREAD_RWLOCK_PREFER_READER_NP,
775 PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP};
776 for (size_t i = 0; i < sizeof(kind_array) / sizeof(kind_array[0]); ++i) {
777 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_array[i]));
778 int kind;
779 ASSERT_EQ(0, pthread_rwlockattr_getkind_np(&attr, &kind));
780 ASSERT_EQ(kind_array[i], kind);
781 }
782
783 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
784}
785
786TEST(pthread, pthread_rwlock_init_same_as_PTHREAD_RWLOCK_INITIALIZER) {
787 pthread_rwlock_t lock1 = PTHREAD_RWLOCK_INITIALIZER;
788 pthread_rwlock_t lock2;
789 ASSERT_EQ(0, pthread_rwlock_init(&lock2, NULL));
790 ASSERT_EQ(0, memcmp(&lock1, &lock2, sizeof(lock1)));
791}
792
Elliott Hughesc3f11402013-10-30 14:40:09 -0700793TEST(pthread, pthread_rwlock_smoke) {
794 pthread_rwlock_t l;
795 ASSERT_EQ(0, pthread_rwlock_init(&l, NULL));
796
Calin Juravle76f352e2014-05-19 13:41:10 +0100797 // Single read lock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700798 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
799 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
800
Calin Juravle76f352e2014-05-19 13:41:10 +0100801 // Multiple read lock
802 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
803 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
804 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
805 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
806
807 // Write lock
Calin Juravle92687e42014-05-22 19:21:22 +0100808 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
809 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100810
811 // Try writer lock
812 ASSERT_EQ(0, pthread_rwlock_trywrlock(&l));
813 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
814 ASSERT_EQ(EBUSY, pthread_rwlock_tryrdlock(&l));
815 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
816
817 // Try reader lock
818 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
819 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
820 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
821 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
822 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
823
824 // Try writer lock after unlock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700825 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
826 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
827
Calin Juravle76f352e2014-05-19 13:41:10 +0100828 // EDEADLK in "read after write"
829 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
830 ASSERT_EQ(EDEADLK, pthread_rwlock_rdlock(&l));
831 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
832
833 // EDEADLK in "write after write"
834 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
835 ASSERT_EQ(EDEADLK, pthread_rwlock_wrlock(&l));
836 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100837
Elliott Hughesc3f11402013-10-30 14:40:09 -0700838 ASSERT_EQ(0, pthread_rwlock_destroy(&l));
839}
840
Yabin Cui08ee8d22015-02-11 17:04:36 -0800841struct RwlockWakeupHelperArg {
842 pthread_rwlock_t lock;
843 enum Progress {
844 LOCK_INITIALIZED,
845 LOCK_WAITING,
846 LOCK_RELEASED,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800847 LOCK_ACCESSED,
848 LOCK_TIMEDOUT,
Yabin Cui08ee8d22015-02-11 17:04:36 -0800849 };
850 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -0700851 std::atomic<pid_t> tid;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800852 std::function<int (pthread_rwlock_t*)> trylock_function;
853 std::function<int (pthread_rwlock_t*)> lock_function;
854 std::function<int (pthread_rwlock_t*, const timespec*)> timed_lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800855};
856
Yabin Cuic9a659c2015-11-05 15:36:08 -0800857static void pthread_rwlock_wakeup_helper(RwlockWakeupHelperArg* arg) {
Yabin Cuif7969852015-04-02 17:47:48 -0700858 arg->tid = gettid();
Yabin Cui08ee8d22015-02-11 17:04:36 -0800859 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
860 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
861
Yabin Cuic9a659c2015-11-05 15:36:08 -0800862 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
863 ASSERT_EQ(0, arg->lock_function(&arg->lock));
Yabin Cui08ee8d22015-02-11 17:04:36 -0800864 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_RELEASED, arg->progress);
865 ASSERT_EQ(0, pthread_rwlock_unlock(&arg->lock));
866
867 arg->progress = RwlockWakeupHelperArg::LOCK_ACCESSED;
868}
869
Yabin Cuic9a659c2015-11-05 15:36:08 -0800870static void test_pthread_rwlock_reader_wakeup_writer(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -0800871 RwlockWakeupHelperArg wakeup_arg;
872 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, NULL));
873 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
874 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -0700875 wakeup_arg.tid = 0;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800876 wakeup_arg.trylock_function = pthread_rwlock_trywrlock;
877 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800878
879 pthread_t thread;
880 ASSERT_EQ(0, pthread_create(&thread, NULL,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800881 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -0700882 WaitUntilThreadSleep(wakeup_arg.tid);
883 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
884
Yabin Cui08ee8d22015-02-11 17:04:36 -0800885 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
886 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
887
888 ASSERT_EQ(0, pthread_join(thread, NULL));
889 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
890 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
891}
892
Yabin Cuic9a659c2015-11-05 15:36:08 -0800893TEST(pthread, pthread_rwlock_reader_wakeup_writer) {
894 test_pthread_rwlock_reader_wakeup_writer(pthread_rwlock_wrlock);
Yabin Cui08ee8d22015-02-11 17:04:36 -0800895}
896
Yabin Cuic9a659c2015-11-05 15:36:08 -0800897TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait) {
898 timespec ts;
899 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
900 ts.tv_sec += 1;
901 test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) {
902 return pthread_rwlock_timedwrlock(lock, &ts);
903 });
904}
905
906static void test_pthread_rwlock_writer_wakeup_reader(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -0800907 RwlockWakeupHelperArg wakeup_arg;
908 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, NULL));
909 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
910 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -0700911 wakeup_arg.tid = 0;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800912 wakeup_arg.trylock_function = pthread_rwlock_tryrdlock;
913 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800914
915 pthread_t thread;
916 ASSERT_EQ(0, pthread_create(&thread, NULL,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800917 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -0700918 WaitUntilThreadSleep(wakeup_arg.tid);
919 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
920
Yabin Cui08ee8d22015-02-11 17:04:36 -0800921 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
922 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
923
924 ASSERT_EQ(0, pthread_join(thread, NULL));
925 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
926 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
927}
928
Yabin Cuic9a659c2015-11-05 15:36:08 -0800929TEST(pthread, pthread_rwlock_writer_wakeup_reader) {
930 test_pthread_rwlock_writer_wakeup_reader(pthread_rwlock_rdlock);
931}
932
933TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait) {
934 timespec ts;
935 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
936 ts.tv_sec += 1;
937 test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) {
938 return pthread_rwlock_timedrdlock(lock, &ts);
939 });
940}
941
942static void pthread_rwlock_wakeup_timeout_helper(RwlockWakeupHelperArg* arg) {
943 arg->tid = gettid();
944 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
945 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
946
947 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
948
949 timespec ts;
950 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
951 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
952 ts.tv_nsec = -1;
953 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
954 ts.tv_nsec = NS_PER_S;
955 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
956 ts.tv_nsec = NS_PER_S - 1;
957 ts.tv_sec = -1;
958 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
959 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
960 ts.tv_sec += 1;
961 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
962 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, arg->progress);
963 arg->progress = RwlockWakeupHelperArg::LOCK_TIMEDOUT;
964}
965
966TEST(pthread, pthread_rwlock_timedrdlock_timeout) {
967 RwlockWakeupHelperArg wakeup_arg;
968 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
969 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
970 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
971 wakeup_arg.tid = 0;
972 wakeup_arg.trylock_function = pthread_rwlock_tryrdlock;
973 wakeup_arg.timed_lock_function = pthread_rwlock_timedrdlock;
974
975 pthread_t thread;
976 ASSERT_EQ(0, pthread_create(&thread, nullptr,
977 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
978 WaitUntilThreadSleep(wakeup_arg.tid);
979 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
980
981 ASSERT_EQ(0, pthread_join(thread, nullptr));
982 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
983 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
984 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
985}
986
987TEST(pthread, pthread_rwlock_timedwrlock_timeout) {
988 RwlockWakeupHelperArg wakeup_arg;
989 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
990 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
991 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
992 wakeup_arg.tid = 0;
993 wakeup_arg.trylock_function = pthread_rwlock_trywrlock;
994 wakeup_arg.timed_lock_function = pthread_rwlock_timedwrlock;
995
996 pthread_t thread;
997 ASSERT_EQ(0, pthread_create(&thread, nullptr,
998 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
999 WaitUntilThreadSleep(wakeup_arg.tid);
1000 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
1001
1002 ASSERT_EQ(0, pthread_join(thread, nullptr));
1003 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
1004 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
1005 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
1006}
1007
Yabin Cui76615da2015-03-17 14:22:09 -07001008class RwlockKindTestHelper {
1009 private:
1010 struct ThreadArg {
1011 RwlockKindTestHelper* helper;
1012 std::atomic<pid_t>& tid;
1013
1014 ThreadArg(RwlockKindTestHelper* helper, std::atomic<pid_t>& tid)
1015 : helper(helper), tid(tid) { }
1016 };
1017
1018 public:
1019 pthread_rwlock_t lock;
1020
1021 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -07001022 explicit RwlockKindTestHelper(int kind_type) {
Yabin Cui76615da2015-03-17 14:22:09 -07001023 InitRwlock(kind_type);
1024 }
1025
1026 ~RwlockKindTestHelper() {
1027 DestroyRwlock();
1028 }
1029
1030 void CreateWriterThread(pthread_t& thread, std::atomic<pid_t>& tid) {
1031 tid = 0;
1032 ThreadArg* arg = new ThreadArg(this, tid);
1033 ASSERT_EQ(0, pthread_create(&thread, NULL,
1034 reinterpret_cast<void* (*)(void*)>(WriterThreadFn), arg));
1035 }
1036
1037 void CreateReaderThread(pthread_t& thread, std::atomic<pid_t>& tid) {
1038 tid = 0;
1039 ThreadArg* arg = new ThreadArg(this, tid);
1040 ASSERT_EQ(0, pthread_create(&thread, NULL,
1041 reinterpret_cast<void* (*)(void*)>(ReaderThreadFn), arg));
1042 }
1043
1044 private:
1045 void InitRwlock(int kind_type) {
1046 pthread_rwlockattr_t attr;
1047 ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
1048 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_type));
1049 ASSERT_EQ(0, pthread_rwlock_init(&lock, &attr));
1050 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
1051 }
1052
1053 void DestroyRwlock() {
1054 ASSERT_EQ(0, pthread_rwlock_destroy(&lock));
1055 }
1056
1057 static void WriterThreadFn(ThreadArg* arg) {
1058 arg->tid = gettid();
1059
1060 RwlockKindTestHelper* helper = arg->helper;
1061 ASSERT_EQ(0, pthread_rwlock_wrlock(&helper->lock));
1062 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
1063 delete arg;
1064 }
1065
1066 static void ReaderThreadFn(ThreadArg* arg) {
1067 arg->tid = gettid();
1068
1069 RwlockKindTestHelper* helper = arg->helper;
1070 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper->lock));
1071 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
1072 delete arg;
1073 }
1074};
1075
1076TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_READER_NP) {
1077 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_READER_NP);
1078 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
1079
1080 pthread_t writer_thread;
1081 std::atomic<pid_t> writer_tid;
1082 helper.CreateWriterThread(writer_thread, writer_tid);
1083 WaitUntilThreadSleep(writer_tid);
1084
1085 pthread_t reader_thread;
1086 std::atomic<pid_t> reader_tid;
1087 helper.CreateReaderThread(reader_thread, reader_tid);
1088 ASSERT_EQ(0, pthread_join(reader_thread, NULL));
1089
1090 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
1091 ASSERT_EQ(0, pthread_join(writer_thread, NULL));
1092}
1093
1094TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP) {
1095 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
1096 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
1097
1098 pthread_t writer_thread;
1099 std::atomic<pid_t> writer_tid;
1100 helper.CreateWriterThread(writer_thread, writer_tid);
1101 WaitUntilThreadSleep(writer_tid);
1102
1103 pthread_t reader_thread;
1104 std::atomic<pid_t> reader_tid;
1105 helper.CreateReaderThread(reader_thread, reader_tid);
1106 WaitUntilThreadSleep(reader_tid);
1107
1108 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
1109 ASSERT_EQ(0, pthread_join(writer_thread, NULL));
1110 ASSERT_EQ(0, pthread_join(reader_thread, NULL));
1111}
1112
Elliott Hughes1728b232014-05-14 10:02:03 -07001113static int g_once_fn_call_count = 0;
Elliott Hughesc3f11402013-10-30 14:40:09 -07001114static void OnceFn() {
Elliott Hughes1728b232014-05-14 10:02:03 -07001115 ++g_once_fn_call_count;
Elliott Hughesc3f11402013-10-30 14:40:09 -07001116}
1117
1118TEST(pthread, pthread_once_smoke) {
1119 pthread_once_t once_control = PTHREAD_ONCE_INIT;
1120 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
1121 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
Elliott Hughes1728b232014-05-14 10:02:03 -07001122 ASSERT_EQ(1, g_once_fn_call_count);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001123}
1124
Elliott Hughes3694ec62014-05-14 11:46:08 -07001125static std::string pthread_once_1934122_result = "";
1126
1127static void Routine2() {
1128 pthread_once_1934122_result += "2";
1129}
1130
1131static void Routine1() {
1132 pthread_once_t once_control_2 = PTHREAD_ONCE_INIT;
1133 pthread_once_1934122_result += "1";
1134 pthread_once(&once_control_2, &Routine2);
1135}
1136
1137TEST(pthread, pthread_once_1934122) {
1138 // Very old versions of Android couldn't call pthread_once from a
1139 // pthread_once init routine. http://b/1934122.
1140 pthread_once_t once_control_1 = PTHREAD_ONCE_INIT;
1141 ASSERT_EQ(0, pthread_once(&once_control_1, &Routine1));
1142 ASSERT_EQ("12", pthread_once_1934122_result);
1143}
1144
Elliott Hughes1728b232014-05-14 10:02:03 -07001145static int g_atfork_prepare_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001146static void AtForkPrepare1() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 1; }
1147static void AtForkPrepare2() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -07001148static int g_atfork_parent_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001149static void AtForkParent1() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 1; }
1150static void AtForkParent2() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -07001151static int g_atfork_child_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001152static void AtForkChild1() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 1; }
1153static void AtForkChild2() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 2; }
Elliott Hughesc3f11402013-10-30 14:40:09 -07001154
Dmitriy Ivanov00e37812014-11-20 16:53:47 -08001155TEST(pthread, pthread_atfork_smoke) {
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001156 ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1));
1157 ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2));
Elliott Hughesc3f11402013-10-30 14:40:09 -07001158
Elliott Hughes33697a02016-01-26 13:04:57 -08001159 pid_t pid = fork();
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001160 ASSERT_NE(-1, pid) << strerror(errno);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001161
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001162 // Child and parent calls are made in the order they were registered.
1163 if (pid == 0) {
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001164 ASSERT_EQ(12, g_atfork_child_calls);
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001165 _exit(0);
1166 }
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001167 ASSERT_EQ(12, g_atfork_parent_calls);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001168
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001169 // Prepare calls are made in the reverse order.
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001170 ASSERT_EQ(21, g_atfork_prepare_calls);
Elliott Hughes33697a02016-01-26 13:04:57 -08001171 AssertChildExited(pid, 0);
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001172}
1173
Elliott Hughesc3f11402013-10-30 14:40:09 -07001174TEST(pthread, pthread_attr_getscope) {
1175 pthread_attr_t attr;
1176 ASSERT_EQ(0, pthread_attr_init(&attr));
1177
1178 int scope;
1179 ASSERT_EQ(0, pthread_attr_getscope(&attr, &scope));
1180 ASSERT_EQ(PTHREAD_SCOPE_SYSTEM, scope);
1181}
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001182
1183TEST(pthread, pthread_condattr_init) {
1184 pthread_condattr_t attr;
1185 pthread_condattr_init(&attr);
1186
1187 clockid_t clock;
1188 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1189 ASSERT_EQ(CLOCK_REALTIME, clock);
1190
1191 int pshared;
1192 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1193 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
1194}
1195
1196TEST(pthread, pthread_condattr_setclock) {
1197 pthread_condattr_t attr;
1198 pthread_condattr_init(&attr);
1199
1200 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_REALTIME));
1201 clockid_t clock;
1202 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1203 ASSERT_EQ(CLOCK_REALTIME, clock);
1204
1205 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1206 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1207 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1208
1209 ASSERT_EQ(EINVAL, pthread_condattr_setclock(&attr, CLOCK_PROCESS_CPUTIME_ID));
1210}
1211
1212TEST(pthread, pthread_cond_broadcast__preserves_condattr_flags) {
Yabin Cui32651b82015-03-13 20:30:00 -07001213#if defined(__BIONIC__)
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001214 pthread_condattr_t attr;
1215 pthread_condattr_init(&attr);
1216
1217 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1218 ASSERT_EQ(0, pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
1219
1220 pthread_cond_t cond_var;
1221 ASSERT_EQ(0, pthread_cond_init(&cond_var, &attr));
1222
1223 ASSERT_EQ(0, pthread_cond_signal(&cond_var));
1224 ASSERT_EQ(0, pthread_cond_broadcast(&cond_var));
1225
Yabin Cui32651b82015-03-13 20:30:00 -07001226 attr = static_cast<pthread_condattr_t>(*reinterpret_cast<uint32_t*>(cond_var.__private));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001227 clockid_t clock;
1228 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1229 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1230 int pshared;
1231 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1232 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
Yabin Cui32651b82015-03-13 20:30:00 -07001233#else // !defined(__BIONIC__)
1234 GTEST_LOG_(INFO) << "This tests a bionic implementation detail.\n";
1235#endif // !defined(__BIONIC__)
1236}
1237
1238class pthread_CondWakeupTest : public ::testing::Test {
1239 protected:
1240 pthread_mutex_t mutex;
1241 pthread_cond_t cond;
1242
1243 enum Progress {
1244 INITIALIZED,
1245 WAITING,
1246 SIGNALED,
1247 FINISHED,
1248 };
1249 std::atomic<Progress> progress;
1250 pthread_t thread;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001251 std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function;
Yabin Cui32651b82015-03-13 20:30:00 -07001252
1253 protected:
Yabin Cuic9a659c2015-11-05 15:36:08 -08001254 void SetUp() override {
1255 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1256 }
1257
1258 void InitCond(clockid_t clock=CLOCK_REALTIME) {
1259 pthread_condattr_t attr;
1260 ASSERT_EQ(0, pthread_condattr_init(&attr));
1261 ASSERT_EQ(0, pthread_condattr_setclock(&attr, clock));
1262 ASSERT_EQ(0, pthread_cond_init(&cond, &attr));
1263 ASSERT_EQ(0, pthread_condattr_destroy(&attr));
1264 }
1265
1266 void StartWaitingThread(std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function) {
Yabin Cui32651b82015-03-13 20:30:00 -07001267 progress = INITIALIZED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001268 this->wait_function = wait_function;
1269 ASSERT_EQ(0, pthread_create(&thread, NULL, reinterpret_cast<void* (*)(void*)>(WaitThreadFn), this));
1270 while (progress != WAITING) {
Yabin Cui32651b82015-03-13 20:30:00 -07001271 usleep(5000);
1272 }
1273 usleep(5000);
1274 }
1275
Yabin Cuic9a659c2015-11-05 15:36:08 -08001276 void TearDown() override {
1277 ASSERT_EQ(0, pthread_join(thread, nullptr));
1278 ASSERT_EQ(FINISHED, progress);
1279 ASSERT_EQ(0, pthread_cond_destroy(&cond));
1280 ASSERT_EQ(0, pthread_mutex_destroy(&mutex));
1281 }
1282
Yabin Cui32651b82015-03-13 20:30:00 -07001283 private:
1284 static void WaitThreadFn(pthread_CondWakeupTest* test) {
1285 ASSERT_EQ(0, pthread_mutex_lock(&test->mutex));
1286 test->progress = WAITING;
1287 while (test->progress == WAITING) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001288 ASSERT_EQ(0, test->wait_function(&test->cond, &test->mutex));
Yabin Cui32651b82015-03-13 20:30:00 -07001289 }
1290 ASSERT_EQ(SIGNALED, test->progress);
1291 test->progress = FINISHED;
1292 ASSERT_EQ(0, pthread_mutex_unlock(&test->mutex));
1293 }
1294};
1295
Yabin Cuic9a659c2015-11-05 15:36:08 -08001296TEST_F(pthread_CondWakeupTest, signal_wait) {
1297 InitCond();
1298 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1299 return pthread_cond_wait(cond, mutex);
1300 });
Yabin Cui32651b82015-03-13 20:30:00 -07001301 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001302 ASSERT_EQ(0, pthread_cond_signal(&cond));
Yabin Cui32651b82015-03-13 20:30:00 -07001303}
1304
Yabin Cuic9a659c2015-11-05 15:36:08 -08001305TEST_F(pthread_CondWakeupTest, broadcast_wait) {
1306 InitCond();
1307 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1308 return pthread_cond_wait(cond, mutex);
1309 });
Yabin Cui32651b82015-03-13 20:30:00 -07001310 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001311 ASSERT_EQ(0, pthread_cond_broadcast(&cond));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001312}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001313
Yabin Cuic9a659c2015-11-05 15:36:08 -08001314TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_REALTIME) {
1315 InitCond(CLOCK_REALTIME);
Elliott Hughes0e714a52014-03-03 16:42:47 -08001316 timespec ts;
1317 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001318 ts.tv_sec += 1;
1319 StartWaitingThread([&](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1320 return pthread_cond_timedwait(cond, mutex, &ts);
1321 });
1322 progress = SIGNALED;
1323 ASSERT_EQ(0, pthread_cond_signal(&cond));
1324}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001325
Yabin Cuic9a659c2015-11-05 15:36:08 -08001326TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC) {
1327 InitCond(CLOCK_MONOTONIC);
1328 timespec ts;
1329 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1330 ts.tv_sec += 1;
1331 StartWaitingThread([&](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1332 return pthread_cond_timedwait(cond, mutex, &ts);
1333 });
1334 progress = SIGNALED;
1335 ASSERT_EQ(0, pthread_cond_signal(&cond));
1336}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001337
Yabin Cuic9a659c2015-11-05 15:36:08 -08001338TEST(pthread, pthread_cond_timedwait_timeout) {
1339 pthread_mutex_t mutex;
1340 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1341 pthread_cond_t cond;
1342 ASSERT_EQ(0, pthread_cond_init(&cond, nullptr));
1343 ASSERT_EQ(0, pthread_mutex_lock(&mutex));
1344 timespec ts;
Elliott Hughes0e714a52014-03-03 16:42:47 -08001345 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001346 ASSERT_EQ(ETIMEDOUT, pthread_cond_timedwait(&cond, &mutex, &ts));
1347 ts.tv_nsec = -1;
1348 ASSERT_EQ(EINVAL, pthread_cond_timedwait(&cond, &mutex, &ts));
1349 ts.tv_nsec = NS_PER_S;
1350 ASSERT_EQ(EINVAL, pthread_cond_timedwait(&cond, &mutex, &ts));
1351 ts.tv_nsec = NS_PER_S - 1;
1352 ts.tv_sec = -1;
1353 ASSERT_EQ(ETIMEDOUT, pthread_cond_timedwait(&cond, &mutex, &ts));
1354 ASSERT_EQ(0, pthread_mutex_unlock(&mutex));
Elliott Hughes0e714a52014-03-03 16:42:47 -08001355}
Elliott Hughes57b7a612014-08-25 17:26:50 -07001356
1357TEST(pthread, pthread_attr_getstack__main_thread) {
1358 // This test is only meaningful for the main thread, so make sure we're running on it!
1359 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1360
1361 // Get the main thread's attributes.
1362 pthread_attr_t attributes;
1363 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1364
1365 // Check that we correctly report that the main thread has no guard page.
1366 size_t guard_size;
1367 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
1368 ASSERT_EQ(0U, guard_size); // The main thread has no guard page.
1369
1370 // Get the stack base and the stack size (both ways).
1371 void* stack_base;
1372 size_t stack_size;
1373 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1374 size_t stack_size2;
1375 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1376
1377 // The two methods of asking for the stack size should agree.
1378 EXPECT_EQ(stack_size, stack_size2);
1379
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001380#if defined(__BIONIC__)
Elliott Hughes57b7a612014-08-25 17:26:50 -07001381 // What does /proc/self/maps' [stack] line say?
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001382 void* maps_stack_hi = NULL;
Elliott Hughes15dfd632015-09-22 16:40:14 -07001383 std::vector<map_record> maps;
1384 ASSERT_TRUE(Maps::parse_maps(&maps));
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07001385 for (const auto& map : maps) {
Elliott Hughes15dfd632015-09-22 16:40:14 -07001386 if (map.pathname == "[stack]") {
1387 maps_stack_hi = reinterpret_cast<void*>(map.addr_end);
Elliott Hughes57b7a612014-08-25 17:26:50 -07001388 break;
1389 }
1390 }
Elliott Hughes57b7a612014-08-25 17:26:50 -07001391
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001392 // The high address of the /proc/self/maps [stack] region should equal stack_base + stack_size.
1393 // Remember that the stack grows down (and is mapped in on demand), so the low address of the
1394 // region isn't very interesting.
1395 EXPECT_EQ(maps_stack_hi, reinterpret_cast<uint8_t*>(stack_base) + stack_size);
1396
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001397 // The stack size should correspond to RLIMIT_STACK.
Elliott Hughes57b7a612014-08-25 17:26:50 -07001398 rlimit rl;
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001399 ASSERT_EQ(0, getrlimit(RLIMIT_STACK, &rl));
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001400 uint64_t original_rlim_cur = rl.rlim_cur;
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001401 if (rl.rlim_cur == RLIM_INFINITY) {
1402 rl.rlim_cur = 8 * 1024 * 1024; // Bionic reports unlimited stacks as 8MiB.
1403 }
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001404 EXPECT_EQ(rl.rlim_cur, stack_size);
1405
Tom Cherryb8ab6182017-04-05 16:20:29 -07001406 auto guard = android::base::make_scope_guard([&rl, original_rlim_cur]() {
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001407 rl.rlim_cur = original_rlim_cur;
1408 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1409 });
1410
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001411 //
1412 // What if RLIMIT_STACK is smaller than the stack's current extent?
1413 //
Elliott Hughes57b7a612014-08-25 17:26:50 -07001414 rl.rlim_cur = rl.rlim_max = 1024; // 1KiB. We know the stack must be at least a page already.
1415 rl.rlim_max = RLIM_INFINITY;
1416 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1417
1418 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1419 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1420 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1421
1422 EXPECT_EQ(stack_size, stack_size2);
1423 ASSERT_EQ(1024U, stack_size);
1424
1425 //
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001426 // What if RLIMIT_STACK isn't a whole number of pages?
Elliott Hughes57b7a612014-08-25 17:26:50 -07001427 //
1428 rl.rlim_cur = rl.rlim_max = 6666; // Not a whole number of pages.
1429 rl.rlim_max = RLIM_INFINITY;
1430 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1431
1432 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1433 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1434 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1435
1436 EXPECT_EQ(stack_size, stack_size2);
1437 ASSERT_EQ(6666U, stack_size);
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001438#endif
Elliott Hughes57b7a612014-08-25 17:26:50 -07001439}
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001440
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001441struct GetStackSignalHandlerArg {
1442 volatile bool done;
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001443 void* signal_stack_base;
1444 size_t signal_stack_size;
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001445 void* main_stack_base;
1446 size_t main_stack_size;
1447};
1448
1449static GetStackSignalHandlerArg getstack_signal_handler_arg;
1450
1451static void getstack_signal_handler(int sig) {
1452 ASSERT_EQ(SIGUSR1, sig);
1453 // Use sleep() to make current thread be switched out by the kernel to provoke the error.
1454 sleep(1);
1455 pthread_attr_t attr;
1456 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1457 void* stack_base;
1458 size_t stack_size;
1459 ASSERT_EQ(0, pthread_attr_getstack(&attr, &stack_base, &stack_size));
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001460
1461 // Verify if the stack used by the signal handler is the alternate stack just registered.
1462 ASSERT_LE(getstack_signal_handler_arg.signal_stack_base, &attr);
1463 ASSERT_LT(static_cast<void*>(&attr),
1464 static_cast<char*>(getstack_signal_handler_arg.signal_stack_base) +
1465 getstack_signal_handler_arg.signal_stack_size);
1466
1467 // Verify if the main thread's stack got in the signal handler is correct.
1468 ASSERT_EQ(getstack_signal_handler_arg.main_stack_base, stack_base);
1469 ASSERT_LE(getstack_signal_handler_arg.main_stack_size, stack_size);
1470
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001471 getstack_signal_handler_arg.done = true;
1472}
1473
1474// The previous code obtained the main thread's stack by reading the entry in
1475// /proc/self/task/<pid>/maps that was labeled [stack]. Unfortunately, on x86/x86_64, the kernel
1476// relies on sp0 in task state segment(tss) to label the stack map with [stack]. If the kernel
1477// switches a process while the main thread is in an alternate stack, then the kernel will label
1478// the wrong map with [stack]. This test verifies that when the above situation happens, the main
1479// thread's stack is found correctly.
1480TEST(pthread, pthread_attr_getstack_in_signal_handler) {
Yabin Cui61e4d462016-03-07 17:44:58 -08001481 // This test is only meaningful for the main thread, so make sure we're running on it!
1482 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1483
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001484 const size_t sig_stack_size = 16 * 1024;
1485 void* sig_stack = mmap(NULL, sig_stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS,
1486 -1, 0);
1487 ASSERT_NE(MAP_FAILED, sig_stack);
1488 stack_t ss;
1489 ss.ss_sp = sig_stack;
1490 ss.ss_size = sig_stack_size;
1491 ss.ss_flags = 0;
1492 stack_t oss;
1493 ASSERT_EQ(0, sigaltstack(&ss, &oss));
1494
Yabin Cui61e4d462016-03-07 17:44:58 -08001495 pthread_attr_t attr;
1496 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1497 void* main_stack_base;
1498 size_t main_stack_size;
1499 ASSERT_EQ(0, pthread_attr_getstack(&attr, &main_stack_base, &main_stack_size));
1500
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001501 ScopedSignalHandler handler(SIGUSR1, getstack_signal_handler, SA_ONSTACK);
1502 getstack_signal_handler_arg.done = false;
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001503 getstack_signal_handler_arg.signal_stack_base = sig_stack;
1504 getstack_signal_handler_arg.signal_stack_size = sig_stack_size;
1505 getstack_signal_handler_arg.main_stack_base = main_stack_base;
1506 getstack_signal_handler_arg.main_stack_size = main_stack_size;
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001507 kill(getpid(), SIGUSR1);
1508 ASSERT_EQ(true, getstack_signal_handler_arg.done);
1509
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001510 ASSERT_EQ(0, sigaltstack(&oss, nullptr));
1511 ASSERT_EQ(0, munmap(sig_stack, sig_stack_size));
1512}
1513
Yabin Cui917d3902015-01-08 12:32:42 -08001514static void pthread_attr_getstack_18908062_helper(void*) {
1515 char local_variable;
1516 pthread_attr_t attributes;
1517 pthread_getattr_np(pthread_self(), &attributes);
1518 void* stack_base;
1519 size_t stack_size;
1520 pthread_attr_getstack(&attributes, &stack_base, &stack_size);
1521
1522 // Test whether &local_variable is in [stack_base, stack_base + stack_size).
1523 ASSERT_LE(reinterpret_cast<char*>(stack_base), &local_variable);
1524 ASSERT_LT(&local_variable, reinterpret_cast<char*>(stack_base) + stack_size);
1525}
1526
1527// Check whether something on stack is in the range of
1528// [stack_base, stack_base + stack_size). see b/18908062.
1529TEST(pthread, pthread_attr_getstack_18908062) {
1530 pthread_t t;
1531 ASSERT_EQ(0, pthread_create(&t, NULL,
1532 reinterpret_cast<void* (*)(void*)>(pthread_attr_getstack_18908062_helper),
1533 NULL));
Elliott Hughes8aecba72017-10-17 15:34:41 -07001534 ASSERT_EQ(0, pthread_join(t, NULL));
Yabin Cui917d3902015-01-08 12:32:42 -08001535}
1536
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001537#if defined(__BIONIC__)
Elliott Hughesf2083612015-11-11 13:32:28 -08001538static pthread_mutex_t pthread_gettid_np_mutex = PTHREAD_MUTEX_INITIALIZER;
1539
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001540static void* pthread_gettid_np_helper(void* arg) {
1541 *reinterpret_cast<pid_t*>(arg) = gettid();
Elliott Hughesf2083612015-11-11 13:32:28 -08001542
1543 // Wait for our parent to call pthread_gettid_np on us before exiting.
1544 pthread_mutex_lock(&pthread_gettid_np_mutex);
1545 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001546 return NULL;
1547}
1548#endif
1549
1550TEST(pthread, pthread_gettid_np) {
1551#if defined(__BIONIC__)
1552 ASSERT_EQ(gettid(), pthread_gettid_np(pthread_self()));
1553
Elliott Hughesf2083612015-11-11 13:32:28 -08001554 // Ensure the other thread doesn't exit until after we've called
1555 // pthread_gettid_np on it.
1556 pthread_mutex_lock(&pthread_gettid_np_mutex);
1557
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001558 pid_t t_gettid_result;
1559 pthread_t t;
1560 pthread_create(&t, NULL, pthread_gettid_np_helper, &t_gettid_result);
1561
1562 pid_t t_pthread_gettid_np_result = pthread_gettid_np(t);
1563
Elliott Hughesf2083612015-11-11 13:32:28 -08001564 // Release the other thread and wait for it to exit.
1565 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Elliott Hughes8aecba72017-10-17 15:34:41 -07001566 ASSERT_EQ(0, pthread_join(t, NULL));
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001567
1568 ASSERT_EQ(t_gettid_result, t_pthread_gettid_np_result);
1569#else
1570 GTEST_LOG_(INFO) << "This test does nothing.\n";
1571#endif
1572}
Elliott Hughes34c987a2014-09-22 16:01:26 -07001573
1574static size_t cleanup_counter = 0;
1575
Derek Xue41996952014-09-25 11:05:32 +01001576static void AbortCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001577 abort();
1578}
1579
Derek Xue41996952014-09-25 11:05:32 +01001580static void CountCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001581 ++cleanup_counter;
1582}
1583
Derek Xue41996952014-09-25 11:05:32 +01001584static void PthreadCleanupTester() {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001585 pthread_cleanup_push(CountCleanupRoutine, NULL);
1586 pthread_cleanup_push(CountCleanupRoutine, NULL);
1587 pthread_cleanup_push(AbortCleanupRoutine, NULL);
1588
1589 pthread_cleanup_pop(0); // Pop the abort without executing it.
1590 pthread_cleanup_pop(1); // Pop one count while executing it.
1591 ASSERT_EQ(1U, cleanup_counter);
1592 // Exit while the other count is still on the cleanup stack.
1593 pthread_exit(NULL);
1594
1595 // Calls to pthread_cleanup_pop/pthread_cleanup_push must always be balanced.
1596 pthread_cleanup_pop(0);
1597}
1598
Derek Xue41996952014-09-25 11:05:32 +01001599static void* PthreadCleanupStartRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001600 PthreadCleanupTester();
1601 return NULL;
1602}
1603
1604TEST(pthread, pthread_cleanup_push__pthread_cleanup_pop) {
1605 pthread_t t;
1606 ASSERT_EQ(0, pthread_create(&t, NULL, PthreadCleanupStartRoutine, NULL));
Elliott Hughes8aecba72017-10-17 15:34:41 -07001607 ASSERT_EQ(0, pthread_join(t, NULL));
Elliott Hughes34c987a2014-09-22 16:01:26 -07001608 ASSERT_EQ(2U, cleanup_counter);
1609}
Derek Xue41996952014-09-25 11:05:32 +01001610
1611TEST(pthread, PTHREAD_MUTEX_DEFAULT_is_PTHREAD_MUTEX_NORMAL) {
1612 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_DEFAULT);
1613}
1614
1615TEST(pthread, pthread_mutexattr_gettype) {
1616 pthread_mutexattr_t attr;
1617 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1618
1619 int attr_type;
1620
1621 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL));
1622 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1623 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, attr_type);
1624
1625 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK));
1626 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1627 ASSERT_EQ(PTHREAD_MUTEX_ERRORCHECK, attr_type);
1628
1629 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE));
1630 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1631 ASSERT_EQ(PTHREAD_MUTEX_RECURSIVE, attr_type);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001632
1633 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
1634}
1635
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001636TEST(pthread, pthread_mutexattr_protocol) {
1637 pthread_mutexattr_t attr;
1638 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1639
1640 int protocol;
1641 ASSERT_EQ(0, pthread_mutexattr_getprotocol(&attr, &protocol));
1642 ASSERT_EQ(PTHREAD_PRIO_NONE, protocol);
1643 for (size_t repeat = 0; repeat < 2; ++repeat) {
1644 for (int set_protocol : {PTHREAD_PRIO_NONE, PTHREAD_PRIO_INHERIT}) {
1645 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, set_protocol));
1646 ASSERT_EQ(0, pthread_mutexattr_getprotocol(&attr, &protocol));
1647 ASSERT_EQ(protocol, set_protocol);
1648 }
1649 }
1650}
1651
Yabin Cui17393b02015-03-21 15:08:25 -07001652struct PthreadMutex {
1653 pthread_mutex_t lock;
1654
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001655 explicit PthreadMutex(int mutex_type, int protocol = PTHREAD_PRIO_NONE) {
1656 init(mutex_type, protocol);
Yabin Cui17393b02015-03-21 15:08:25 -07001657 }
1658
1659 ~PthreadMutex() {
1660 destroy();
1661 }
1662
1663 private:
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001664 void init(int mutex_type, int protocol) {
Yabin Cui17393b02015-03-21 15:08:25 -07001665 pthread_mutexattr_t attr;
1666 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1667 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, mutex_type));
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001668 ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, protocol));
Yabin Cui17393b02015-03-21 15:08:25 -07001669 ASSERT_EQ(0, pthread_mutex_init(&lock, &attr));
1670 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
1671 }
1672
1673 void destroy() {
1674 ASSERT_EQ(0, pthread_mutex_destroy(&lock));
1675 }
1676
1677 DISALLOW_COPY_AND_ASSIGN(PthreadMutex);
1678};
Derek Xue41996952014-09-25 11:05:32 +01001679
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001680static void TestPthreadMutexLockNormal(int protocol) {
1681 PthreadMutex m(PTHREAD_MUTEX_NORMAL, protocol);
Derek Xue41996952014-09-25 11:05:32 +01001682
Yabin Cui17393b02015-03-21 15:08:25 -07001683 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1684 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08001685 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
1686 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
1687 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01001688}
1689
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001690static void TestPthreadMutexLockErrorCheck(int protocol) {
1691 PthreadMutex m(PTHREAD_MUTEX_ERRORCHECK, protocol);
Derek Xue41996952014-09-25 11:05:32 +01001692
Yabin Cui17393b02015-03-21 15:08:25 -07001693 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1694 ASSERT_EQ(EDEADLK, pthread_mutex_lock(&m.lock));
1695 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1696 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001697 if (protocol == PTHREAD_PRIO_NONE) {
1698 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
1699 } else {
1700 ASSERT_EQ(EDEADLK, pthread_mutex_trylock(&m.lock));
1701 }
Yabin Cui17393b02015-03-21 15:08:25 -07001702 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1703 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01001704}
1705
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001706static void TestPthreadMutexLockRecursive(int protocol) {
1707 PthreadMutex m(PTHREAD_MUTEX_RECURSIVE, protocol);
Derek Xue41996952014-09-25 11:05:32 +01001708
Yabin Cui17393b02015-03-21 15:08:25 -07001709 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1710 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1711 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1712 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1713 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08001714 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
1715 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07001716 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1717 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
1718}
1719
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001720TEST(pthread, pthread_mutex_lock_NORMAL) {
1721 TestPthreadMutexLockNormal(PTHREAD_PRIO_NONE);
1722}
1723
1724TEST(pthread, pthread_mutex_lock_ERRORCHECK) {
1725 TestPthreadMutexLockErrorCheck(PTHREAD_PRIO_NONE);
1726}
1727
1728TEST(pthread, pthread_mutex_lock_RECURSIVE) {
1729 TestPthreadMutexLockRecursive(PTHREAD_PRIO_NONE);
1730}
1731
1732TEST(pthread, pthread_mutex_lock_pi) {
1733#if defined(__BIONIC__) && !defined(__LP64__)
1734 GTEST_LOG_(INFO) << "PTHREAD_PRIO_INHERIT isn't supported in 32bit programs, skipping test";
1735 return;
1736#endif
1737 TestPthreadMutexLockNormal(PTHREAD_PRIO_INHERIT);
1738 TestPthreadMutexLockErrorCheck(PTHREAD_PRIO_INHERIT);
1739 TestPthreadMutexLockRecursive(PTHREAD_PRIO_INHERIT);
1740}
1741
Yabin Cui17393b02015-03-21 15:08:25 -07001742TEST(pthread, pthread_mutex_init_same_as_static_initializers) {
1743 pthread_mutex_t lock_normal = PTHREAD_MUTEX_INITIALIZER;
1744 PthreadMutex m1(PTHREAD_MUTEX_NORMAL);
1745 ASSERT_EQ(0, memcmp(&lock_normal, &m1.lock, sizeof(pthread_mutex_t)));
1746 pthread_mutex_destroy(&lock_normal);
1747
1748 pthread_mutex_t lock_errorcheck = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
1749 PthreadMutex m2(PTHREAD_MUTEX_ERRORCHECK);
1750 ASSERT_EQ(0, memcmp(&lock_errorcheck, &m2.lock, sizeof(pthread_mutex_t)));
1751 pthread_mutex_destroy(&lock_errorcheck);
1752
1753 pthread_mutex_t lock_recursive = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
1754 PthreadMutex m3(PTHREAD_MUTEX_RECURSIVE);
1755 ASSERT_EQ(0, memcmp(&lock_recursive, &m3.lock, sizeof(pthread_mutex_t)));
1756 ASSERT_EQ(0, pthread_mutex_destroy(&lock_recursive));
Derek Xue41996952014-09-25 11:05:32 +01001757}
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001758class MutexWakeupHelper {
1759 private:
Yabin Cui17393b02015-03-21 15:08:25 -07001760 PthreadMutex m;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001761 enum Progress {
1762 LOCK_INITIALIZED,
1763 LOCK_WAITING,
1764 LOCK_RELEASED,
1765 LOCK_ACCESSED
1766 };
1767 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -07001768 std::atomic<pid_t> tid;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001769
1770 static void thread_fn(MutexWakeupHelper* helper) {
Yabin Cuif7969852015-04-02 17:47:48 -07001771 helper->tid = gettid();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001772 ASSERT_EQ(LOCK_INITIALIZED, helper->progress);
1773 helper->progress = LOCK_WAITING;
1774
Yabin Cui17393b02015-03-21 15:08:25 -07001775 ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001776 ASSERT_EQ(LOCK_RELEASED, helper->progress);
Yabin Cui17393b02015-03-21 15:08:25 -07001777 ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001778
1779 helper->progress = LOCK_ACCESSED;
1780 }
1781
1782 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -07001783 explicit MutexWakeupHelper(int mutex_type) : m(mutex_type) {
Yabin Cui17393b02015-03-21 15:08:25 -07001784 }
1785
1786 void test() {
1787 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001788 progress = LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -07001789 tid = 0;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001790
1791 pthread_t thread;
1792 ASSERT_EQ(0, pthread_create(&thread, NULL,
1793 reinterpret_cast<void* (*)(void*)>(MutexWakeupHelper::thread_fn), this));
1794
Yabin Cuif7969852015-04-02 17:47:48 -07001795 WaitUntilThreadSleep(tid);
1796 ASSERT_EQ(LOCK_WAITING, progress);
1797
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001798 progress = LOCK_RELEASED;
Yabin Cui17393b02015-03-21 15:08:25 -07001799 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001800
1801 ASSERT_EQ(0, pthread_join(thread, NULL));
1802 ASSERT_EQ(LOCK_ACCESSED, progress);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001803 }
1804};
1805
1806TEST(pthread, pthread_mutex_NORMAL_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07001807 MutexWakeupHelper helper(PTHREAD_MUTEX_NORMAL);
1808 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001809}
1810
1811TEST(pthread, pthread_mutex_ERRORCHECK_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07001812 MutexWakeupHelper helper(PTHREAD_MUTEX_ERRORCHECK);
1813 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001814}
1815
1816TEST(pthread, pthread_mutex_RECURSIVE_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07001817 MutexWakeupHelper helper(PTHREAD_MUTEX_RECURSIVE);
1818 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001819}
1820
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001821static int GetThreadPriority(pid_t tid) {
1822 // sched_getparam() returns the static priority of a thread, which can't reflect a thread's
1823 // priority after priority inheritance. So read /proc/<pid>/stat to get the dynamic priority.
1824 std::string filename = android::base::StringPrintf("/proc/%d/stat", tid);
1825 std::string content;
1826 int result = INT_MAX;
1827 if (!android::base::ReadFileToString(filename, &content)) {
1828 return result;
1829 }
1830 std::vector<std::string> strs = android::base::Split(content, " ");
1831 if (strs.size() < 18) {
1832 return result;
1833 }
1834 if (!android::base::ParseInt(strs[17], &result)) {
1835 return INT_MAX;
1836 }
1837 return result;
1838}
1839
1840class PIMutexWakeupHelper {
1841private:
1842 PthreadMutex m;
1843 int protocol;
1844 enum Progress {
1845 LOCK_INITIALIZED,
1846 LOCK_CHILD_READY,
1847 LOCK_WAITING,
1848 LOCK_RELEASED,
1849 };
1850 std::atomic<Progress> progress;
1851 std::atomic<pid_t> main_tid;
1852 std::atomic<pid_t> child_tid;
1853 PthreadMutex start_thread_m;
1854
1855 static void thread_fn(PIMutexWakeupHelper* helper) {
1856 helper->child_tid = gettid();
1857 ASSERT_EQ(LOCK_INITIALIZED, helper->progress);
1858 ASSERT_EQ(0, setpriority(PRIO_PROCESS, gettid(), 1));
1859 ASSERT_EQ(21, GetThreadPriority(gettid()));
1860 ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock));
1861 helper->progress = LOCK_CHILD_READY;
1862 ASSERT_EQ(0, pthread_mutex_lock(&helper->start_thread_m.lock));
1863
1864 ASSERT_EQ(0, pthread_mutex_unlock(&helper->start_thread_m.lock));
1865 WaitUntilThreadSleep(helper->main_tid);
1866 ASSERT_EQ(LOCK_WAITING, helper->progress);
1867
1868 if (helper->protocol == PTHREAD_PRIO_INHERIT) {
1869 ASSERT_EQ(20, GetThreadPriority(gettid()));
1870 } else {
1871 ASSERT_EQ(21, GetThreadPriority(gettid()));
1872 }
1873 helper->progress = LOCK_RELEASED;
1874 ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock));
1875 }
1876
1877public:
1878 explicit PIMutexWakeupHelper(int mutex_type, int protocol)
1879 : m(mutex_type, protocol), protocol(protocol), start_thread_m(PTHREAD_MUTEX_NORMAL) {
1880 }
1881
1882 void test() {
1883 ASSERT_EQ(0, pthread_mutex_lock(&start_thread_m.lock));
1884 main_tid = gettid();
1885 ASSERT_EQ(20, GetThreadPriority(main_tid));
1886 progress = LOCK_INITIALIZED;
1887 child_tid = 0;
1888
1889 pthread_t thread;
1890 ASSERT_EQ(0, pthread_create(&thread, NULL,
1891 reinterpret_cast<void* (*)(void*)>(PIMutexWakeupHelper::thread_fn), this));
1892
1893 WaitUntilThreadSleep(child_tid);
1894 ASSERT_EQ(LOCK_CHILD_READY, progress);
1895 ASSERT_EQ(0, pthread_mutex_unlock(&start_thread_m.lock));
1896 progress = LOCK_WAITING;
1897 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1898
1899 ASSERT_EQ(LOCK_RELEASED, progress);
1900 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1901 ASSERT_EQ(0, pthread_join(thread, nullptr));
1902 }
1903};
1904
1905TEST(pthread, pthread_mutex_pi_wakeup) {
1906#if defined(__BIONIC__) && !defined(__LP64__)
1907 GTEST_LOG_(INFO) << "PTHREAD_PRIO_INHERIT isn't supported in 32bit programs, skipping test";
1908 return;
1909#endif
1910 for (int type : {PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_RECURSIVE, PTHREAD_MUTEX_ERRORCHECK}) {
1911 for (int protocol : {PTHREAD_PRIO_INHERIT}) {
1912 PIMutexWakeupHelper helper(type, protocol);
1913 helper.test();
1914 }
1915 }
1916}
1917
Yabin Cui140f3672015-02-03 10:32:00 -08001918TEST(pthread, pthread_mutex_owner_tid_limit) {
Yabin Cuie69c2452015-02-13 16:21:25 -08001919#if defined(__BIONIC__) && !defined(__LP64__)
Yabin Cui140f3672015-02-03 10:32:00 -08001920 FILE* fp = fopen("/proc/sys/kernel/pid_max", "r");
1921 ASSERT_TRUE(fp != NULL);
1922 long pid_max;
1923 ASSERT_EQ(1, fscanf(fp, "%ld", &pid_max));
1924 fclose(fp);
Yabin Cuie69c2452015-02-13 16:21:25 -08001925 // Bionic's pthread_mutex implementation on 32-bit devices uses 16 bits to represent owner tid.
Yabin Cui140f3672015-02-03 10:32:00 -08001926 ASSERT_LE(pid_max, 65536);
Yabin Cuie69c2452015-02-13 16:21:25 -08001927#else
1928 GTEST_LOG_(INFO) << "This test does nothing as 32-bit tid is supported by pthread_mutex.\n";
1929#endif
Yabin Cui140f3672015-02-03 10:32:00 -08001930}
Yabin Cuib5845722015-03-16 22:46:42 -07001931
Yabin Cuic9a659c2015-11-05 15:36:08 -08001932TEST(pthread, pthread_mutex_timedlock) {
1933 pthread_mutex_t m;
1934 ASSERT_EQ(0, pthread_mutex_init(&m, nullptr));
1935
1936 // If the mutex is already locked, pthread_mutex_timedlock should time out.
1937 ASSERT_EQ(0, pthread_mutex_lock(&m));
1938
1939 timespec ts;
1940 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1941 ASSERT_EQ(ETIMEDOUT, pthread_mutex_timedlock(&m, &ts));
1942 ts.tv_nsec = -1;
1943 ASSERT_EQ(EINVAL, pthread_mutex_timedlock(&m, &ts));
1944 ts.tv_nsec = NS_PER_S;
1945 ASSERT_EQ(EINVAL, pthread_mutex_timedlock(&m, &ts));
1946 ts.tv_nsec = NS_PER_S - 1;
1947 ts.tv_sec = -1;
1948 ASSERT_EQ(ETIMEDOUT, pthread_mutex_timedlock(&m, &ts));
1949
1950 // If the mutex is unlocked, pthread_mutex_timedlock should succeed.
1951 ASSERT_EQ(0, pthread_mutex_unlock(&m));
1952
1953 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1954 ts.tv_sec += 1;
1955 ASSERT_EQ(0, pthread_mutex_timedlock(&m, &ts));
1956
1957 ASSERT_EQ(0, pthread_mutex_unlock(&m));
1958 ASSERT_EQ(0, pthread_mutex_destroy(&m));
1959}
1960
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001961TEST(pthread, pthread_mutex_timedlock_pi) {
1962#if defined(__BIONIC__) && !defined(__LP64__)
1963 GTEST_LOG_(INFO) << "PTHREAD_PRIO_INHERIT isn't supported in 32bit programs, skipping test";
1964 return;
1965#endif
1966 PthreadMutex m(PTHREAD_MUTEX_NORMAL, PTHREAD_PRIO_INHERIT);
1967 timespec ts;
1968 clock_gettime(CLOCK_REALTIME, &ts);
1969 ts.tv_sec += 1;
1970 ASSERT_EQ(0, pthread_mutex_timedlock(&m.lock, &ts));
1971
1972 auto ThreadFn = [](void* arg) -> void* {
1973 PthreadMutex& m = *static_cast<PthreadMutex*>(arg);
1974 timespec ts;
1975 clock_gettime(CLOCK_REALTIME, &ts);
1976 ts.tv_sec += 1;
1977 intptr_t result = pthread_mutex_timedlock(&m.lock, &ts);
1978 return reinterpret_cast<void*>(result);
1979 };
1980
1981 pthread_t thread;
1982 ASSERT_EQ(0, pthread_create(&thread, NULL, ThreadFn, &m));
1983 void* result;
1984 ASSERT_EQ(0, pthread_join(thread, &result));
1985 ASSERT_EQ(ETIMEDOUT, reinterpret_cast<intptr_t>(result));
1986 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1987}
1988
Yabin Cuib5845722015-03-16 22:46:42 -07001989class StrictAlignmentAllocator {
1990 public:
1991 void* allocate(size_t size, size_t alignment) {
1992 char* p = new char[size + alignment * 2];
1993 allocated_array.push_back(p);
1994 while (!is_strict_aligned(p, alignment)) {
1995 ++p;
1996 }
1997 return p;
1998 }
1999
2000 ~StrictAlignmentAllocator() {
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07002001 for (const auto& p : allocated_array) {
2002 delete[] p;
Yabin Cuib5845722015-03-16 22:46:42 -07002003 }
2004 }
2005
2006 private:
2007 bool is_strict_aligned(char* p, size_t alignment) {
2008 return (reinterpret_cast<uintptr_t>(p) % (alignment * 2)) == alignment;
2009 }
2010
2011 std::vector<char*> allocated_array;
2012};
2013
2014TEST(pthread, pthread_types_allow_four_bytes_alignment) {
2015#if defined(__BIONIC__)
2016 // For binary compatibility with old version, we need to allow 4-byte aligned data for pthread types.
2017 StrictAlignmentAllocator allocator;
2018 pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(
2019 allocator.allocate(sizeof(pthread_mutex_t), 4));
2020 ASSERT_EQ(0, pthread_mutex_init(mutex, NULL));
2021 ASSERT_EQ(0, pthread_mutex_lock(mutex));
2022 ASSERT_EQ(0, pthread_mutex_unlock(mutex));
2023 ASSERT_EQ(0, pthread_mutex_destroy(mutex));
2024
2025 pthread_cond_t* cond = reinterpret_cast<pthread_cond_t*>(
2026 allocator.allocate(sizeof(pthread_cond_t), 4));
2027 ASSERT_EQ(0, pthread_cond_init(cond, NULL));
2028 ASSERT_EQ(0, pthread_cond_signal(cond));
2029 ASSERT_EQ(0, pthread_cond_broadcast(cond));
2030 ASSERT_EQ(0, pthread_cond_destroy(cond));
2031
2032 pthread_rwlock_t* rwlock = reinterpret_cast<pthread_rwlock_t*>(
2033 allocator.allocate(sizeof(pthread_rwlock_t), 4));
2034 ASSERT_EQ(0, pthread_rwlock_init(rwlock, NULL));
2035 ASSERT_EQ(0, pthread_rwlock_rdlock(rwlock));
2036 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
2037 ASSERT_EQ(0, pthread_rwlock_wrlock(rwlock));
2038 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
2039 ASSERT_EQ(0, pthread_rwlock_destroy(rwlock));
2040
2041#else
2042 GTEST_LOG_(INFO) << "This test tests bionic implementation details.";
2043#endif
2044}
Christopher Ferris60907c72015-06-09 18:46:15 -07002045
2046TEST(pthread, pthread_mutex_lock_null_32) {
2047#if defined(__BIONIC__) && !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -07002048 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return
2049 // EINVAL in that case: http://b/19995172.
2050 //
2051 // We decorate the public defintion with _Nonnull so that people recompiling
2052 // their code with get a warning and might fix their bug, but need to pass
2053 // NULL here to test that we remain compatible.
2054 pthread_mutex_t* null_value = nullptr;
2055 ASSERT_EQ(EINVAL, pthread_mutex_lock(null_value));
Christopher Ferris60907c72015-06-09 18:46:15 -07002056#else
2057 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 32 bit devices.";
2058#endif
2059}
2060
2061TEST(pthread, pthread_mutex_unlock_null_32) {
2062#if defined(__BIONIC__) && !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -07002063 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return
2064 // EINVAL in that case: http://b/19995172.
2065 //
2066 // We decorate the public defintion with _Nonnull so that people recompiling
2067 // their code with get a warning and might fix their bug, but need to pass
2068 // NULL here to test that we remain compatible.
2069 pthread_mutex_t* null_value = nullptr;
2070 ASSERT_EQ(EINVAL, pthread_mutex_unlock(null_value));
Christopher Ferris60907c72015-06-09 18:46:15 -07002071#else
2072 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 32 bit devices.";
2073#endif
2074}
2075
2076TEST_F(pthread_DeathTest, pthread_mutex_lock_null_64) {
2077#if defined(__BIONIC__) && defined(__LP64__)
2078 pthread_mutex_t* null_value = nullptr;
2079 ASSERT_EXIT(pthread_mutex_lock(null_value), testing::KilledBySignal(SIGSEGV), "");
2080#else
2081 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 64 bit devices.";
2082#endif
2083}
2084
2085TEST_F(pthread_DeathTest, pthread_mutex_unlock_null_64) {
2086#if defined(__BIONIC__) && defined(__LP64__)
2087 pthread_mutex_t* null_value = nullptr;
2088 ASSERT_EXIT(pthread_mutex_unlock(null_value), testing::KilledBySignal(SIGSEGV), "");
2089#else
2090 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 64 bit devices.";
2091#endif
2092}
Yabin Cui33ac04a2015-09-22 11:16:15 -07002093
2094extern _Unwind_Reason_Code FrameCounter(_Unwind_Context* ctx, void* arg);
2095
2096static volatile bool signal_handler_on_altstack_done;
2097
Josh Gao61db9ac2017-03-15 19:42:05 -07002098__attribute__((__noinline__))
2099static void signal_handler_backtrace() {
2100 // Check if we have enough stack space for unwinding.
2101 int count = 0;
2102 _Unwind_Backtrace(FrameCounter, &count);
2103 ASSERT_GT(count, 0);
2104}
2105
2106__attribute__((__noinline__))
2107static void signal_handler_logging() {
2108 // Check if we have enough stack space for logging.
2109 std::string s(2048, '*');
2110 GTEST_LOG_(INFO) << s;
2111 signal_handler_on_altstack_done = true;
2112}
2113
2114__attribute__((__noinline__))
2115static void signal_handler_snprintf() {
2116 // Check if we have enough stack space for snprintf to a PATH_MAX buffer, plus some extra.
2117 char buf[PATH_MAX + 2048];
2118 ASSERT_GT(snprintf(buf, sizeof(buf), "/proc/%d/status", getpid()), 0);
2119}
2120
Yabin Cui33ac04a2015-09-22 11:16:15 -07002121static void SignalHandlerOnAltStack(int signo, siginfo_t*, void*) {
2122 ASSERT_EQ(SIGUSR1, signo);
Josh Gao61db9ac2017-03-15 19:42:05 -07002123 signal_handler_backtrace();
2124 signal_handler_logging();
2125 signal_handler_snprintf();
Yabin Cui33ac04a2015-09-22 11:16:15 -07002126}
2127
Josh Gao415daa82017-03-06 17:45:33 -08002128TEST(pthread, big_enough_signal_stack) {
Yabin Cui33ac04a2015-09-22 11:16:15 -07002129 signal_handler_on_altstack_done = false;
2130 ScopedSignalHandler handler(SIGUSR1, SignalHandlerOnAltStack, SA_SIGINFO | SA_ONSTACK);
2131 kill(getpid(), SIGUSR1);
2132 ASSERT_TRUE(signal_handler_on_altstack_done);
2133}
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002134
2135TEST(pthread, pthread_barrierattr_smoke) {
2136 pthread_barrierattr_t attr;
2137 ASSERT_EQ(0, pthread_barrierattr_init(&attr));
2138 int pshared;
2139 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
2140 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
2141 ASSERT_EQ(0, pthread_barrierattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
2142 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
2143 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
2144 ASSERT_EQ(0, pthread_barrierattr_destroy(&attr));
2145}
2146
Yabin Cui81d27972016-03-22 13:45:55 -07002147struct BarrierTestHelperData {
2148 size_t thread_count;
2149 pthread_barrier_t barrier;
2150 std::atomic<int> finished_mask;
2151 std::atomic<int> serial_thread_count;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002152 size_t iteration_count;
Yabin Cui81d27972016-03-22 13:45:55 -07002153 std::atomic<size_t> finished_iteration_count;
2154
2155 BarrierTestHelperData(size_t thread_count, size_t iteration_count)
2156 : thread_count(thread_count), finished_mask(0), serial_thread_count(0),
2157 iteration_count(iteration_count), finished_iteration_count(0) {
2158 }
2159};
2160
2161struct BarrierTestHelperArg {
2162 int id;
2163 BarrierTestHelperData* data;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002164};
2165
2166static void BarrierTestHelper(BarrierTestHelperArg* arg) {
Yabin Cui81d27972016-03-22 13:45:55 -07002167 for (size_t i = 0; i < arg->data->iteration_count; ++i) {
2168 int result = pthread_barrier_wait(&arg->data->barrier);
2169 if (result == PTHREAD_BARRIER_SERIAL_THREAD) {
2170 arg->data->serial_thread_count++;
2171 } else {
2172 ASSERT_EQ(0, result);
2173 }
Yabin Cuid5c04c52017-05-02 12:57:39 -07002174 int mask = arg->data->finished_mask.fetch_or(1 << arg->id);
Yabin Cuiab4cddc2017-05-02 16:18:13 -07002175 mask |= 1 << arg->id;
Yabin Cuid5c04c52017-05-02 12:57:39 -07002176 if (mask == ((1 << arg->data->thread_count) - 1)) {
Yabin Cui81d27972016-03-22 13:45:55 -07002177 ASSERT_EQ(1, arg->data->serial_thread_count);
2178 arg->data->finished_iteration_count++;
2179 arg->data->finished_mask = 0;
2180 arg->data->serial_thread_count = 0;
2181 }
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002182 }
2183}
2184
2185TEST(pthread, pthread_barrier_smoke) {
2186 const size_t BARRIER_ITERATION_COUNT = 10;
2187 const size_t BARRIER_THREAD_COUNT = 10;
Yabin Cui81d27972016-03-22 13:45:55 -07002188 BarrierTestHelperData data(BARRIER_THREAD_COUNT, BARRIER_ITERATION_COUNT);
2189 ASSERT_EQ(0, pthread_barrier_init(&data.barrier, nullptr, data.thread_count));
2190 std::vector<pthread_t> threads(data.thread_count);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002191 std::vector<BarrierTestHelperArg> args(threads.size());
2192 for (size_t i = 0; i < threads.size(); ++i) {
Yabin Cui81d27972016-03-22 13:45:55 -07002193 args[i].id = i;
2194 args[i].data = &data;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002195 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
2196 reinterpret_cast<void* (*)(void*)>(BarrierTestHelper), &args[i]));
2197 }
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002198 for (size_t i = 0; i < threads.size(); ++i) {
2199 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
2200 }
Yabin Cui81d27972016-03-22 13:45:55 -07002201 ASSERT_EQ(data.iteration_count, data.finished_iteration_count);
2202 ASSERT_EQ(0, pthread_barrier_destroy(&data.barrier));
2203}
2204
2205struct BarrierDestroyTestArg {
2206 std::atomic<int> tid;
2207 pthread_barrier_t* barrier;
2208};
2209
2210static void BarrierDestroyTestHelper(BarrierDestroyTestArg* arg) {
2211 arg->tid = gettid();
2212 ASSERT_EQ(0, pthread_barrier_wait(arg->barrier));
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002213}
2214
2215TEST(pthread, pthread_barrier_destroy) {
2216 pthread_barrier_t barrier;
2217 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, 2));
2218 pthread_t thread;
Yabin Cui81d27972016-03-22 13:45:55 -07002219 BarrierDestroyTestArg arg;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002220 arg.tid = 0;
2221 arg.barrier = &barrier;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002222 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui81d27972016-03-22 13:45:55 -07002223 reinterpret_cast<void* (*)(void*)>(BarrierDestroyTestHelper), &arg));
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002224 WaitUntilThreadSleep(arg.tid);
2225 ASSERT_EQ(EBUSY, pthread_barrier_destroy(&barrier));
2226 ASSERT_EQ(PTHREAD_BARRIER_SERIAL_THREAD, pthread_barrier_wait(&barrier));
2227 // Verify if the barrier can be destroyed directly after pthread_barrier_wait().
2228 ASSERT_EQ(0, pthread_barrier_destroy(&barrier));
2229 ASSERT_EQ(0, pthread_join(thread, nullptr));
2230#if defined(__BIONIC__)
2231 ASSERT_EQ(EINVAL, pthread_barrier_destroy(&barrier));
2232#endif
2233}
2234
2235struct BarrierOrderingTestHelperArg {
2236 pthread_barrier_t* barrier;
2237 size_t* array;
2238 size_t array_length;
2239 size_t id;
2240};
2241
2242void BarrierOrderingTestHelper(BarrierOrderingTestHelperArg* arg) {
2243 const size_t ITERATION_COUNT = 10000;
2244 for (size_t i = 1; i <= ITERATION_COUNT; ++i) {
2245 arg->array[arg->id] = i;
Yabin Cuic9a659c2015-11-05 15:36:08 -08002246 int result = pthread_barrier_wait(arg->barrier);
2247 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002248 for (size_t j = 0; j < arg->array_length; ++j) {
2249 ASSERT_EQ(i, arg->array[j]);
2250 }
Yabin Cuic9a659c2015-11-05 15:36:08 -08002251 result = pthread_barrier_wait(arg->barrier);
2252 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002253 }
2254}
2255
2256TEST(pthread, pthread_barrier_check_ordering) {
2257 const size_t THREAD_COUNT = 4;
2258 pthread_barrier_t barrier;
2259 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, THREAD_COUNT));
2260 size_t array[THREAD_COUNT];
2261 std::vector<pthread_t> threads(THREAD_COUNT);
2262 std::vector<BarrierOrderingTestHelperArg> args(THREAD_COUNT);
2263 for (size_t i = 0; i < THREAD_COUNT; ++i) {
2264 args[i].barrier = &barrier;
2265 args[i].array = array;
2266 args[i].array_length = THREAD_COUNT;
2267 args[i].id = i;
2268 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
2269 reinterpret_cast<void* (*)(void*)>(BarrierOrderingTestHelper),
2270 &args[i]));
2271 }
2272 for (size_t i = 0; i < THREAD_COUNT; ++i) {
2273 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
2274 }
2275}
Yabin Cuife3a83a2015-11-17 16:03:18 -08002276
2277TEST(pthread, pthread_spinlock_smoke) {
2278 pthread_spinlock_t lock;
2279 ASSERT_EQ(0, pthread_spin_init(&lock, 0));
2280 ASSERT_EQ(0, pthread_spin_trylock(&lock));
2281 ASSERT_EQ(0, pthread_spin_unlock(&lock));
2282 ASSERT_EQ(0, pthread_spin_lock(&lock));
2283 ASSERT_EQ(EBUSY, pthread_spin_trylock(&lock));
2284 ASSERT_EQ(0, pthread_spin_unlock(&lock));
2285 ASSERT_EQ(0, pthread_spin_destroy(&lock));
2286}
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002287
Elliott Hughes8aecba72017-10-17 15:34:41 -07002288TEST(pthread, pthread_attr_getdetachstate__pthread_attr_setdetachstate) {
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002289 pthread_attr_t attr;
2290 ASSERT_EQ(0, pthread_attr_init(&attr));
2291
Elliott Hughes8aecba72017-10-17 15:34:41 -07002292 int state;
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002293 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002294 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2295 ASSERT_EQ(PTHREAD_CREATE_DETACHED, state);
2296
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002297 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002298 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2299 ASSERT_EQ(PTHREAD_CREATE_JOINABLE, state);
2300
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002301 ASSERT_EQ(EINVAL, pthread_attr_setdetachstate(&attr, 123));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002302 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2303 ASSERT_EQ(PTHREAD_CREATE_JOINABLE, state);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002304}
2305
2306TEST(pthread, pthread_create__mmap_failures) {
2307 pthread_attr_t attr;
2308 ASSERT_EQ(0, pthread_attr_init(&attr));
2309 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
2310
2311 const auto kPageSize = sysconf(_SC_PAGE_SIZE);
2312
Elliott Hughes57512982017-10-02 22:49:18 -07002313 // Use up all the VMAs. By default this is 64Ki (though some will already be in use).
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002314 std::vector<void*> pages;
Elliott Hughes57512982017-10-02 22:49:18 -07002315 pages.reserve(64 * 1024);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002316 int prot = PROT_NONE;
2317 while (true) {
2318 void* page = mmap(nullptr, kPageSize, prot, MAP_ANON|MAP_PRIVATE, -1, 0);
2319 if (page == MAP_FAILED) break;
2320 pages.push_back(page);
2321 prot = (prot == PROT_NONE) ? PROT_READ : PROT_NONE;
2322 }
2323
2324 // Try creating threads, freeing up a page each time we fail.
2325 size_t EAGAIN_count = 0;
2326 size_t i = 0;
2327 for (; i < pages.size(); ++i) {
2328 pthread_t t;
2329 int status = pthread_create(&t, &attr, IdFn, nullptr);
2330 if (status != EAGAIN) break;
2331 ++EAGAIN_count;
2332 ASSERT_EQ(0, munmap(pages[i], kPageSize));
2333 }
2334
2335 // Creating a thread uses at least six VMAs: the stack, the TLS, and a guard each side of both.
2336 // So we should have seen at least six failures.
2337 ASSERT_GE(EAGAIN_count, 6U);
2338
2339 for (; i < pages.size(); ++i) {
2340 ASSERT_EQ(0, munmap(pages[i], kPageSize));
2341 }
2342}
Elliott Hughesdff08ce2017-10-16 09:58:45 -07002343
2344TEST(pthread, pthread_setschedparam) {
2345 sched_param p = { .sched_priority = INT_MIN };
2346 ASSERT_EQ(EINVAL, pthread_setschedparam(pthread_self(), INT_MIN, &p));
2347}
2348
2349TEST(pthread, pthread_setschedprio) {
2350 ASSERT_EQ(EINVAL, pthread_setschedprio(pthread_self(), INT_MIN));
2351}
Elliott Hughes8aecba72017-10-17 15:34:41 -07002352
2353TEST(pthread, pthread_attr_getinheritsched__pthread_attr_setinheritsched) {
2354 pthread_attr_t attr;
2355 ASSERT_EQ(0, pthread_attr_init(&attr));
2356
2357 int state;
2358 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2359 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
2360 ASSERT_EQ(PTHREAD_INHERIT_SCHED, state);
2361
2362 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
2363 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
2364 ASSERT_EQ(PTHREAD_EXPLICIT_SCHED, state);
2365
2366 ASSERT_EQ(EINVAL, pthread_attr_setinheritsched(&attr, 123));
2367 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
2368 ASSERT_EQ(PTHREAD_EXPLICIT_SCHED, state);
2369}
2370
2371TEST(pthread, pthread_attr_setinheritsched__PTHREAD_INHERIT_SCHED__PTHREAD_EXPLICIT_SCHED) {
2372 pthread_attr_t attr;
2373 ASSERT_EQ(0, pthread_attr_init(&attr));
2374
2375 // If we set invalid scheduling attributes but choose to inherit, everything's fine...
2376 sched_param param = { .sched_priority = sched_get_priority_max(SCHED_FIFO) + 1 };
2377 ASSERT_EQ(0, pthread_attr_setschedparam(&attr, &param));
2378 ASSERT_EQ(0, pthread_attr_setschedpolicy(&attr, SCHED_FIFO));
2379 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2380
2381 pthread_t t;
2382 ASSERT_EQ(0, pthread_create(&t, &attr, IdFn, nullptr));
2383 ASSERT_EQ(0, pthread_join(t, nullptr));
2384
Elliott Hughes7a660662017-10-30 09:26:06 -07002385#if defined(__LP64__)
2386 // If we ask to use them, though, we'll see a failure...
Elliott Hughes8aecba72017-10-17 15:34:41 -07002387 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
2388 ASSERT_EQ(EINVAL, pthread_create(&t, &attr, IdFn, nullptr));
Elliott Hughes7a660662017-10-30 09:26:06 -07002389#else
2390 // For backwards compatibility with broken apps, we just ignore failures
2391 // to set scheduler attributes on LP32.
2392#endif
Elliott Hughes8aecba72017-10-17 15:34:41 -07002393}
2394
2395TEST(pthread, pthread_attr_setinheritsched_PTHREAD_INHERIT_SCHED_takes_effect) {
2396 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
2397 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO, &param);
2398 if (rc == EPERM) {
2399 GTEST_LOG_(INFO) << "pthread_setschedparam failed with EPERM, skipping test\n";
2400 return;
2401 }
2402 ASSERT_EQ(0, rc);
2403
2404 pthread_attr_t attr;
2405 ASSERT_EQ(0, pthread_attr_init(&attr));
2406 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2407
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002408 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07002409 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002410 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002411 int actual_policy;
2412 sched_param actual_param;
2413 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
2414 ASSERT_EQ(SCHED_FIFO, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002415 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07002416 ASSERT_EQ(0, pthread_join(t, nullptr));
2417}
2418
2419TEST(pthread, pthread_attr_setinheritsched_PTHREAD_EXPLICIT_SCHED_takes_effect) {
2420 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
2421 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO, &param);
2422 if (rc == EPERM) {
2423 GTEST_LOG_(INFO) << "pthread_setschedparam failed with EPERM, skipping test\n";
2424 return;
2425 }
2426 ASSERT_EQ(0, rc);
2427
2428 pthread_attr_t attr;
2429 ASSERT_EQ(0, pthread_attr_init(&attr));
2430 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
2431 ASSERT_EQ(0, pthread_attr_setschedpolicy(&attr, SCHED_OTHER));
2432
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002433 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07002434 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002435 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002436 int actual_policy;
2437 sched_param actual_param;
2438 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
2439 ASSERT_EQ(SCHED_OTHER, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002440 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07002441 ASSERT_EQ(0, pthread_join(t, nullptr));
2442}
2443
2444TEST(pthread, pthread_attr_setinheritsched__takes_effect_despite_SCHED_RESET_ON_FORK) {
2445 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
2446 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param);
2447 if (rc == EPERM) {
2448 GTEST_LOG_(INFO) << "pthread_setschedparam failed with EPERM, skipping test\n";
2449 return;
2450 }
2451 ASSERT_EQ(0, rc);
2452
2453 pthread_attr_t attr;
2454 ASSERT_EQ(0, pthread_attr_init(&attr));
2455 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2456
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002457 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07002458 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002459 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002460 int actual_policy;
2461 sched_param actual_param;
2462 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
2463 ASSERT_EQ(SCHED_FIFO | SCHED_RESET_ON_FORK, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002464 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07002465 ASSERT_EQ(0, pthread_join(t, nullptr));
2466}