blob: 46140bbc6b8110236b5a464169b2fadfd820b2f6 [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
Tom Cherryb8ab6182017-04-05 16:20:29 -070036#include <android-base/scopeguard.h>
37
Yabin Cuic9a659c2015-11-05 15:36:08 -080038#include "private/bionic_constants.h"
Yabin Cui17393b02015-03-21 15:08:25 -070039#include "private/bionic_macros.h"
Yabin Cui17393b02015-03-21 15:08:25 -070040#include "BionicDeathTest.h"
41#include "ScopedSignalHandler.h"
Elliott Hughes15dfd632015-09-22 16:40:14 -070042#include "utils.h"
43
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070044TEST(pthread, pthread_key_create) {
45 pthread_key_t key;
46 ASSERT_EQ(0, pthread_key_create(&key, NULL));
47 ASSERT_EQ(0, pthread_key_delete(key));
48 // Can't delete a key that's already been deleted.
49 ASSERT_EQ(EINVAL, pthread_key_delete(key));
50}
Elliott Hughes4d014e12012-09-07 16:47:54 -070051
Dan Albertc4bcc752014-09-30 11:48:24 -070052TEST(pthread, pthread_keys_max) {
Yabin Cui6c238f22014-12-11 20:50:41 -080053 // POSIX says PTHREAD_KEYS_MAX should be at least _POSIX_THREAD_KEYS_MAX.
54 ASSERT_GE(PTHREAD_KEYS_MAX, _POSIX_THREAD_KEYS_MAX);
Dan Albertc4bcc752014-09-30 11:48:24 -070055}
Elliott Hughes718a5b52014-01-28 17:02:03 -080056
Yabin Cui6c238f22014-12-11 20:50:41 -080057TEST(pthread, sysconf_SC_THREAD_KEYS_MAX_eq_PTHREAD_KEYS_MAX) {
Dan Albertc4bcc752014-09-30 11:48:24 -070058 int sysconf_max = sysconf(_SC_THREAD_KEYS_MAX);
Yabin Cui6c238f22014-12-11 20:50:41 -080059 ASSERT_EQ(sysconf_max, PTHREAD_KEYS_MAX);
Dan Albertc4bcc752014-09-30 11:48:24 -070060}
61
62TEST(pthread, pthread_key_many_distinct) {
Yabin Cui6c238f22014-12-11 20:50:41 -080063 // As gtest uses pthread keys, we can't allocate exactly PTHREAD_KEYS_MAX
64 // pthread keys, but We should be able to allocate at least this many keys.
65 int nkeys = PTHREAD_KEYS_MAX / 2;
Dan Albertc4bcc752014-09-30 11:48:24 -070066 std::vector<pthread_key_t> keys;
67
Tom Cherryb8ab6182017-04-05 16:20:29 -070068 auto scope_guard = android::base::make_scope_guard([&keys] {
Elliott Hughes0b2acdf2015-10-02 18:25:19 -070069 for (const auto& key : keys) {
Dan Albertc4bcc752014-09-30 11:48:24 -070070 EXPECT_EQ(0, pthread_key_delete(key));
71 }
72 });
73
74 for (int i = 0; i < nkeys; ++i) {
75 pthread_key_t key;
Elliott Hughes61706932015-03-31 10:56:58 -070076 // If this fails, it's likely that LIBC_PTHREAD_KEY_RESERVED_COUNT is wrong.
Dan Albertc4bcc752014-09-30 11:48:24 -070077 ASSERT_EQ(0, pthread_key_create(&key, NULL)) << i << " of " << nkeys;
78 keys.push_back(key);
79 ASSERT_EQ(0, pthread_setspecific(key, reinterpret_cast<void*>(i)));
80 }
81
82 for (int i = keys.size() - 1; i >= 0; --i) {
83 ASSERT_EQ(reinterpret_cast<void*>(i), pthread_getspecific(keys.back()));
84 pthread_key_t key = keys.back();
85 keys.pop_back();
86 ASSERT_EQ(0, pthread_key_delete(key));
87 }
88}
89
Yabin Cui6c238f22014-12-11 20:50:41 -080090TEST(pthread, pthread_key_not_exceed_PTHREAD_KEYS_MAX) {
Elliott Hughes44b53ad2013-02-11 20:18:47 +000091 std::vector<pthread_key_t> keys;
Dan Albertc4bcc752014-09-30 11:48:24 -070092 int rv = 0;
Yabin Cui6c238f22014-12-11 20:50:41 -080093
94 // Pthread keys are used by gtest, so PTHREAD_KEYS_MAX should
95 // be more than we are allowed to allocate now.
96 for (int i = 0; i < PTHREAD_KEYS_MAX; i++) {
Elliott Hughes44b53ad2013-02-11 20:18:47 +000097 pthread_key_t key;
Dan Albertc4bcc752014-09-30 11:48:24 -070098 rv = pthread_key_create(&key, NULL);
99 if (rv == EAGAIN) {
100 break;
101 }
102 EXPECT_EQ(0, rv);
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000103 keys.push_back(key);
104 }
105
Dan Albertc4bcc752014-09-30 11:48:24 -0700106 // Don't leak keys.
Elliott Hughes0b2acdf2015-10-02 18:25:19 -0700107 for (const auto& key : keys) {
Dan Albertc4bcc752014-09-30 11:48:24 -0700108 EXPECT_EQ(0, pthread_key_delete(key));
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000109 }
Dan Albertc4bcc752014-09-30 11:48:24 -0700110 keys.clear();
111
112 // We should have eventually reached the maximum number of keys and received
113 // EAGAIN.
114 ASSERT_EQ(EAGAIN, rv);
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000115}
116
Elliott Hughesebb770f2014-06-25 13:46:46 -0700117TEST(pthread, pthread_key_delete) {
118 void* expected = reinterpret_cast<void*>(1234);
119 pthread_key_t key;
120 ASSERT_EQ(0, pthread_key_create(&key, NULL));
121 ASSERT_EQ(0, pthread_setspecific(key, expected));
122 ASSERT_EQ(expected, pthread_getspecific(key));
123 ASSERT_EQ(0, pthread_key_delete(key));
124 // After deletion, pthread_getspecific returns NULL.
125 ASSERT_EQ(NULL, pthread_getspecific(key));
126 // And you can't use pthread_setspecific with the deleted key.
127 ASSERT_EQ(EINVAL, pthread_setspecific(key, expected));
128}
129
Elliott Hughes40a52172014-07-30 14:48:10 -0700130TEST(pthread, pthread_key_fork) {
131 void* expected = reinterpret_cast<void*>(1234);
132 pthread_key_t key;
133 ASSERT_EQ(0, pthread_key_create(&key, NULL));
134 ASSERT_EQ(0, pthread_setspecific(key, expected));
135 ASSERT_EQ(expected, pthread_getspecific(key));
136
137 pid_t pid = fork();
138 ASSERT_NE(-1, pid) << strerror(errno);
139
140 if (pid == 0) {
141 // The surviving thread inherits all the forking thread's TLS values...
142 ASSERT_EQ(expected, pthread_getspecific(key));
143 _exit(99);
144 }
145
Elliott Hughes33697a02016-01-26 13:04:57 -0800146 AssertChildExited(pid, 99);
Elliott Hughes40a52172014-07-30 14:48:10 -0700147
148 ASSERT_EQ(expected, pthread_getspecific(key));
Dan Albert1d53ae22014-09-02 15:24:26 -0700149 ASSERT_EQ(0, pthread_key_delete(key));
Elliott Hughes40a52172014-07-30 14:48:10 -0700150}
151
152static void* DirtyKeyFn(void* key) {
153 return pthread_getspecific(*reinterpret_cast<pthread_key_t*>(key));
154}
155
156TEST(pthread, pthread_key_dirty) {
157 pthread_key_t key;
158 ASSERT_EQ(0, pthread_key_create(&key, NULL));
159
Yabin Cuia36158a2015-11-16 21:06:16 -0800160 size_t stack_size = 640 * 1024;
Elliott Hughes40a52172014-07-30 14:48:10 -0700161 void* stack = mmap(NULL, stack_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
162 ASSERT_NE(MAP_FAILED, stack);
163 memset(stack, 0xff, stack_size);
164
165 pthread_attr_t attr;
166 ASSERT_EQ(0, pthread_attr_init(&attr));
167 ASSERT_EQ(0, pthread_attr_setstack(&attr, stack, stack_size));
168
169 pthread_t t;
170 ASSERT_EQ(0, pthread_create(&t, &attr, DirtyKeyFn, &key));
171
172 void* result;
173 ASSERT_EQ(0, pthread_join(t, &result));
174 ASSERT_EQ(nullptr, result); // Not ~0!
175
176 ASSERT_EQ(0, munmap(stack, stack_size));
Dan Albert1d53ae22014-09-02 15:24:26 -0700177 ASSERT_EQ(0, pthread_key_delete(key));
Elliott Hughes40a52172014-07-30 14:48:10 -0700178}
179
Yabin Cui5ddbb3f2015-03-05 20:35:32 -0800180TEST(pthread, static_pthread_key_used_before_creation) {
181#if defined(__BIONIC__)
182 // See http://b/19625804. The bug is about a static/global pthread key being used before creation.
183 // So here tests if the static/global default value 0 can be detected as invalid key.
184 static pthread_key_t key;
185 ASSERT_EQ(nullptr, pthread_getspecific(key));
186 ASSERT_EQ(EINVAL, pthread_setspecific(key, nullptr));
187 ASSERT_EQ(EINVAL, pthread_key_delete(key));
188#else
189 GTEST_LOG_(INFO) << "This test tests bionic pthread key implementation detail.\n";
190#endif
191}
192
Elliott Hughes4d014e12012-09-07 16:47:54 -0700193static void* IdFn(void* arg) {
194 return arg;
195}
196
Yabin Cui63481602014-12-01 17:41:04 -0800197class SpinFunctionHelper {
198 public:
199 SpinFunctionHelper() {
200 SpinFunctionHelper::spin_flag_ = true;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400201 }
Yabin Cui63481602014-12-01 17:41:04 -0800202 ~SpinFunctionHelper() {
203 UnSpin();
204 }
205 auto GetFunction() -> void* (*)(void*) {
206 return SpinFunctionHelper::SpinFn;
207 }
208
209 void UnSpin() {
210 SpinFunctionHelper::spin_flag_ = false;
211 }
212
213 private:
214 static void* SpinFn(void*) {
215 while (spin_flag_) {}
216 return NULL;
217 }
Yabin Cuia36158a2015-11-16 21:06:16 -0800218 static std::atomic<bool> spin_flag_;
Yabin Cui63481602014-12-01 17:41:04 -0800219};
220
221// It doesn't matter if spin_flag_ is used in several tests,
222// because it is always set to false after each test. Each thread
223// loops on spin_flag_ can find it becomes false at some time.
Yabin Cuia36158a2015-11-16 21:06:16 -0800224std::atomic<bool> SpinFunctionHelper::spin_flag_;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400225
Elliott Hughes4d014e12012-09-07 16:47:54 -0700226static void* JoinFn(void* arg) {
227 return reinterpret_cast<void*>(pthread_join(reinterpret_cast<pthread_t>(arg), NULL));
228}
229
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400230static void AssertDetached(pthread_t t, bool is_detached) {
231 pthread_attr_t attr;
232 ASSERT_EQ(0, pthread_getattr_np(t, &attr));
233 int detach_state;
234 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &detach_state));
235 pthread_attr_destroy(&attr);
236 ASSERT_EQ(is_detached, (detach_state == PTHREAD_CREATE_DETACHED));
237}
238
Elliott Hughes7484c212017-02-02 02:41:38 +0000239static void MakeDeadThread(pthread_t& t) {
240 ASSERT_EQ(0, pthread_create(&t, NULL, IdFn, NULL));
241 ASSERT_EQ(0, pthread_join(t, NULL));
242}
243
Elliott Hughes4d014e12012-09-07 16:47:54 -0700244TEST(pthread, pthread_create) {
245 void* expected_result = reinterpret_cast<void*>(123);
246 // Can we create a thread?
247 pthread_t t;
248 ASSERT_EQ(0, pthread_create(&t, NULL, IdFn, expected_result));
249 // If we join, do we get the expected value back?
250 void* result;
251 ASSERT_EQ(0, pthread_join(t, &result));
252 ASSERT_EQ(expected_result, result);
253}
254
Elliott Hughes3e898472013-02-12 16:40:24 +0000255TEST(pthread, pthread_create_EAGAIN) {
256 pthread_attr_t attributes;
257 ASSERT_EQ(0, pthread_attr_init(&attributes));
258 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, static_cast<size_t>(-1) & ~(getpagesize() - 1)));
259
260 pthread_t t;
261 ASSERT_EQ(EAGAIN, pthread_create(&t, &attributes, IdFn, NULL));
262}
263
Elliott Hughes4d014e12012-09-07 16:47:54 -0700264TEST(pthread, pthread_no_join_after_detach) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700265 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800266
Elliott Hughes4d014e12012-09-07 16:47:54 -0700267 pthread_t t1;
Elliott Hughes725b2a92016-03-23 11:20:47 -0700268 ASSERT_EQ(0, pthread_create(&t1, NULL, spin_helper.GetFunction(), NULL));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700269
270 // After a pthread_detach...
271 ASSERT_EQ(0, pthread_detach(t1));
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400272 AssertDetached(t1, true);
Elliott Hughes4d014e12012-09-07 16:47:54 -0700273
274 // ...pthread_join should fail.
Elliott Hughes34c987a2014-09-22 16:01:26 -0700275 ASSERT_EQ(EINVAL, pthread_join(t1, NULL));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700276}
277
278TEST(pthread, pthread_no_op_detach_after_join) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700279 SpinFunctionHelper spin_helper;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400280
Elliott Hughes4d014e12012-09-07 16:47:54 -0700281 pthread_t t1;
Elliott Hughes725b2a92016-03-23 11:20:47 -0700282 ASSERT_EQ(0, pthread_create(&t1, NULL, spin_helper.GetFunction(), NULL));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700283
284 // If thread 2 is already waiting to join thread 1...
285 pthread_t t2;
286 ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1)));
287
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400288 sleep(1); // (Give t2 a chance to call pthread_join.)
Elliott Hughes4d014e12012-09-07 16:47:54 -0700289
Yabin Cuibbb04322015-03-19 15:19:25 -0700290#if defined(__BIONIC__)
291 ASSERT_EQ(EINVAL, pthread_detach(t1));
292#else
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400293 ASSERT_EQ(0, pthread_detach(t1));
Yabin Cuibbb04322015-03-19 15:19:25 -0700294#endif
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400295 AssertDetached(t1, false);
296
Elliott Hughes725b2a92016-03-23 11:20:47 -0700297 spin_helper.UnSpin();
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400298
299 // ...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 -0700300 void* join_result;
301 ASSERT_EQ(0, pthread_join(t2, &join_result));
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700302 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700303}
Elliott Hughes14f19592012-10-29 10:19:44 -0700304
305TEST(pthread, pthread_join_self) {
Elliott Hughes34c987a2014-09-22 16:01:26 -0700306 ASSERT_EQ(EDEADLK, pthread_join(pthread_self(), NULL));
Elliott Hughes14f19592012-10-29 10:19:44 -0700307}
Elliott Hughes4f251be2012-11-01 16:33:29 -0700308
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800309struct TestBug37410 {
310 pthread_t main_thread;
311 pthread_mutex_t mutex;
Elliott Hughes4f251be2012-11-01 16:33:29 -0700312
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800313 static void main() {
314 TestBug37410 data;
315 data.main_thread = pthread_self();
316 ASSERT_EQ(0, pthread_mutex_init(&data.mutex, NULL));
317 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
318
319 pthread_t t;
320 ASSERT_EQ(0, pthread_create(&t, NULL, TestBug37410::thread_fn, reinterpret_cast<void*>(&data)));
321
322 // Wait for the thread to be running...
323 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
324 ASSERT_EQ(0, pthread_mutex_unlock(&data.mutex));
325
326 // ...and exit.
327 pthread_exit(NULL);
328 }
329
330 private:
331 static void* thread_fn(void* arg) {
332 TestBug37410* data = reinterpret_cast<TestBug37410*>(arg);
333
334 // Let the main thread know we're running.
335 pthread_mutex_unlock(&data->mutex);
336
337 // And wait for the main thread to exit.
338 pthread_join(data->main_thread, NULL);
339
340 return NULL;
341 }
342};
Elliott Hughes4f251be2012-11-01 16:33:29 -0700343
Elliott Hughes7fd803c2013-02-14 16:33:52 -0800344// Even though this isn't really a death test, we have to say "DeathTest" here so gtest knows to
345// run this test (which exits normally) in its own process.
Yabin Cui9df70402014-11-05 18:01:01 -0800346
347class pthread_DeathTest : public BionicDeathTest {};
348
349TEST_F(pthread_DeathTest, pthread_bug_37410) {
Elliott Hughes4f251be2012-11-01 16:33:29 -0700350 // http://code.google.com/p/android/issues/detail?id=37410
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800351 ASSERT_EXIT(TestBug37410::main(), ::testing::ExitedWithCode(0), "");
Elliott Hughes4f251be2012-11-01 16:33:29 -0700352}
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800353
354static void* SignalHandlerFn(void* arg) {
355 sigset_t wait_set;
356 sigfillset(&wait_set);
357 return reinterpret_cast<void*>(sigwait(&wait_set, reinterpret_cast<int*>(arg)));
358}
359
360TEST(pthread, pthread_sigmask) {
Elliott Hughes19e62322013-10-15 11:23:57 -0700361 // Check that SIGUSR1 isn't blocked.
362 sigset_t original_set;
363 sigemptyset(&original_set);
364 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, NULL, &original_set));
365 ASSERT_FALSE(sigismember(&original_set, SIGUSR1));
366
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800367 // Block SIGUSR1.
368 sigset_t set;
369 sigemptyset(&set);
370 sigaddset(&set, SIGUSR1);
371 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, &set, NULL));
372
Elliott Hughes19e62322013-10-15 11:23:57 -0700373 // Check that SIGUSR1 is blocked.
374 sigset_t final_set;
375 sigemptyset(&final_set);
376 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, NULL, &final_set));
377 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
378 // ...and that sigprocmask agrees with pthread_sigmask.
379 sigemptyset(&final_set);
380 ASSERT_EQ(0, sigprocmask(SIG_BLOCK, NULL, &final_set));
381 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
382
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800383 // Spawn a thread that calls sigwait and tells us what it received.
384 pthread_t signal_thread;
385 int received_signal = -1;
386 ASSERT_EQ(0, pthread_create(&signal_thread, NULL, SignalHandlerFn, &received_signal));
387
388 // Send that thread SIGUSR1.
389 pthread_kill(signal_thread, SIGUSR1);
390
391 // See what it got.
392 void* join_result;
393 ASSERT_EQ(0, pthread_join(signal_thread, &join_result));
394 ASSERT_EQ(SIGUSR1, received_signal);
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700395 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
Elliott Hughes19e62322013-10-15 11:23:57 -0700396
397 // Restore the original signal mask.
398 ASSERT_EQ(0, pthread_sigmask(SIG_SETMASK, &original_set, NULL));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800399}
Elliott Hughes5e3fc432013-02-11 16:36:48 -0800400
Elliott Hughes725b2a92016-03-23 11:20:47 -0700401static void test_pthread_setname_np__pthread_getname_np(pthread_t t) {
402 ASSERT_EQ(0, pthread_setname_np(t, "short"));
403 char name[32];
404 ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name)));
405 ASSERT_STREQ("short", name);
406
Elliott Hughesd1aea302015-04-25 10:05:24 -0700407 // The limit is 15 characters --- the kernel's buffer is 16, but includes a NUL.
Elliott Hughes725b2a92016-03-23 11:20:47 -0700408 ASSERT_EQ(0, pthread_setname_np(t, "123456789012345"));
409 ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name)));
410 ASSERT_STREQ("123456789012345", name);
411
412 ASSERT_EQ(ERANGE, pthread_setname_np(t, "1234567890123456"));
413
414 // The passed-in buffer should be at least 16 bytes.
415 ASSERT_EQ(0, pthread_getname_np(t, name, 16));
416 ASSERT_EQ(ERANGE, pthread_getname_np(t, name, 15));
Elliott Hughes3e898472013-02-12 16:40:24 +0000417}
418
Elliott Hughes725b2a92016-03-23 11:20:47 -0700419TEST(pthread, pthread_setname_np__pthread_getname_np__self) {
420 test_pthread_setname_np__pthread_getname_np(pthread_self());
Elliott Hughes3e898472013-02-12 16:40:24 +0000421}
422
Elliott Hughes725b2a92016-03-23 11:20:47 -0700423TEST(pthread, pthread_setname_np__pthread_getname_np__other) {
424 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800425
Elliott Hughes725b2a92016-03-23 11:20:47 -0700426 pthread_t t;
Elliott Hughes4d098ca2016-04-11 12:43:05 -0700427 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
428 test_pthread_setname_np__pthread_getname_np(t);
429 spin_helper.UnSpin();
430 ASSERT_EQ(0, pthread_join(t, nullptr));
431}
432
433// http://b/28051133: a kernel misfeature means that you can't change the
434// name of another thread if you've set PR_SET_DUMPABLE to 0.
435TEST(pthread, pthread_setname_np__pthread_getname_np__other_PR_SET_DUMPABLE) {
436 ASSERT_EQ(0, prctl(PR_SET_DUMPABLE, 0)) << strerror(errno);
437
438 SpinFunctionHelper spin_helper;
439
440 pthread_t t;
441 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
Elliott Hughes725b2a92016-03-23 11:20:47 -0700442 test_pthread_setname_np__pthread_getname_np(t);
443 spin_helper.UnSpin();
444 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes3e898472013-02-12 16:40:24 +0000445}
446
Elliott Hughes11859d42017-02-13 17:59:29 -0800447TEST_F(pthread_DeathTest, pthread_setname_np__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000448 pthread_t dead_thread;
449 MakeDeadThread(dead_thread);
450
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800451 EXPECT_DEATH(pthread_setname_np(dead_thread, "short 3"), "invalid pthread_t");
452}
453
454TEST_F(pthread_DeathTest, pthread_setname_np__null_thread) {
455 pthread_t null_thread = 0;
456 EXPECT_EQ(ENOENT, pthread_setname_np(null_thread, "short 3"));
Elliott Hughes11859d42017-02-13 17:59:29 -0800457}
458
459TEST_F(pthread_DeathTest, pthread_getname_np__no_such_thread) {
460 pthread_t dead_thread;
461 MakeDeadThread(dead_thread);
462
Elliott Hughesbcb15292017-02-07 21:05:30 +0000463 char name[64];
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800464 EXPECT_DEATH(pthread_getname_np(dead_thread, name, sizeof(name)), "invalid pthread_t");
465}
466
467TEST_F(pthread_DeathTest, pthread_getname_np__null_thread) {
468 pthread_t null_thread = 0;
469
470 char name[64];
471 EXPECT_EQ(ENOENT, pthread_getname_np(null_thread, name, sizeof(name)));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000472}
473
Elliott Hughes9d23e042013-02-15 19:21:51 -0800474TEST(pthread, pthread_kill__0) {
475 // Signal 0 just tests that the thread exists, so it's safe to call on ourselves.
476 ASSERT_EQ(0, pthread_kill(pthread_self(), 0));
477}
478
479TEST(pthread, pthread_kill__invalid_signal) {
480 ASSERT_EQ(EINVAL, pthread_kill(pthread_self(), -1));
481}
482
Elliott Hughesfae89fc2013-02-21 11:22:23 -0800483static void pthread_kill__in_signal_handler_helper(int signal_number) {
484 static int count = 0;
485 ASSERT_EQ(SIGALRM, signal_number);
486 if (++count == 1) {
487 // Can we call pthread_kill from a signal handler?
488 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
489 }
490}
491
492TEST(pthread, pthread_kill__in_signal_handler) {
Elliott Hughes4b558f52014-03-04 15:58:02 -0800493 ScopedSignalHandler ssh(SIGALRM, pthread_kill__in_signal_handler_helper);
Elliott Hughesfae89fc2013-02-21 11:22:23 -0800494 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
495}
496
Elliott Hughes11859d42017-02-13 17:59:29 -0800497TEST_F(pthread_DeathTest, pthread_detach__no_such_thread) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000498 pthread_t dead_thread;
499 MakeDeadThread(dead_thread);
500
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800501 EXPECT_DEATH(pthread_detach(dead_thread), "invalid pthread_t");
502}
503
504TEST_F(pthread_DeathTest, pthread_detach__null_thread) {
505 pthread_t null_thread = 0;
506 EXPECT_EQ(ESRCH, pthread_detach(null_thread));
Elliott Hughes7484c212017-02-02 02:41:38 +0000507}
508
Jeff Hao9b06cc32013-08-15 14:51:16 -0700509TEST(pthread, pthread_getcpuclockid__clock_gettime) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700510 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800511
Jeff Hao9b06cc32013-08-15 14:51:16 -0700512 pthread_t t;
Elliott Hughes725b2a92016-03-23 11:20:47 -0700513 ASSERT_EQ(0, pthread_create(&t, NULL, spin_helper.GetFunction(), NULL));
Jeff Hao9b06cc32013-08-15 14:51:16 -0700514
515 clockid_t c;
516 ASSERT_EQ(0, pthread_getcpuclockid(t, &c));
517 timespec ts;
518 ASSERT_EQ(0, clock_gettime(c, &ts));
Elliott Hughes725b2a92016-03-23 11:20:47 -0700519 spin_helper.UnSpin();
Yabin Cuia36158a2015-11-16 21:06:16 -0800520 ASSERT_EQ(0, pthread_join(t, nullptr));
Jeff Hao9b06cc32013-08-15 14:51:16 -0700521}
522
Elliott Hughes11859d42017-02-13 17:59:29 -0800523TEST_F(pthread_DeathTest, pthread_getcpuclockid__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000524 pthread_t dead_thread;
525 MakeDeadThread(dead_thread);
526
527 clockid_t c;
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800528 EXPECT_DEATH(pthread_getcpuclockid(dead_thread, &c), "invalid pthread_t");
529}
530
531TEST_F(pthread_DeathTest, pthread_getcpuclockid__null_thread) {
532 pthread_t null_thread = 0;
533 clockid_t c;
534 EXPECT_EQ(ESRCH, pthread_getcpuclockid(null_thread, &c));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000535}
536
Elliott Hughes11859d42017-02-13 17:59:29 -0800537TEST_F(pthread_DeathTest, pthread_getschedparam__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000538 pthread_t dead_thread;
539 MakeDeadThread(dead_thread);
540
541 int policy;
542 sched_param param;
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800543 EXPECT_DEATH(pthread_getschedparam(dead_thread, &policy, &param), "invalid pthread_t");
544}
545
546TEST_F(pthread_DeathTest, pthread_getschedparam__null_thread) {
547 pthread_t null_thread = 0;
548 int policy;
549 sched_param param;
550 EXPECT_EQ(ESRCH, pthread_getschedparam(null_thread, &policy, &param));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000551}
552
Elliott Hughes11859d42017-02-13 17:59:29 -0800553TEST_F(pthread_DeathTest, pthread_setschedparam__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000554 pthread_t dead_thread;
555 MakeDeadThread(dead_thread);
556
557 int policy = 0;
558 sched_param param;
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800559 EXPECT_DEATH(pthread_setschedparam(dead_thread, policy, &param), "invalid pthread_t");
560}
561
562TEST_F(pthread_DeathTest, pthread_setschedparam__null_thread) {
563 pthread_t null_thread = 0;
564 int policy = 0;
565 sched_param param;
566 EXPECT_EQ(ESRCH, pthread_setschedparam(null_thread, policy, &param));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000567}
568
Elliott Hughes11859d42017-02-13 17:59:29 -0800569TEST_F(pthread_DeathTest, pthread_join__no_such_thread) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000570 pthread_t dead_thread;
571 MakeDeadThread(dead_thread);
572
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800573 EXPECT_DEATH(pthread_join(dead_thread, NULL), "invalid pthread_t");
574}
575
576TEST_F(pthread_DeathTest, pthread_join__null_thread) {
577 pthread_t null_thread = 0;
578 EXPECT_EQ(ESRCH, pthread_join(null_thread, NULL));
Elliott Hughes7484c212017-02-02 02:41:38 +0000579}
580
Elliott Hughes11859d42017-02-13 17:59:29 -0800581TEST_F(pthread_DeathTest, pthread_kill__no_such_thread) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000582 pthread_t dead_thread;
583 MakeDeadThread(dead_thread);
584
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800585 EXPECT_DEATH(pthread_kill(dead_thread, 0), "invalid pthread_t");
586}
587
588TEST_F(pthread_DeathTest, pthread_kill__null_thread) {
589 pthread_t null_thread = 0;
590 EXPECT_EQ(ESRCH, pthread_kill(null_thread, 0));
Elliott Hughes7484c212017-02-02 02:41:38 +0000591}
592
msg5550f020d12013-06-06 14:59:28 -0400593TEST(pthread, pthread_join__multijoin) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700594 SpinFunctionHelper spin_helper;
msg5550f020d12013-06-06 14:59:28 -0400595
596 pthread_t t1;
Elliott Hughes725b2a92016-03-23 11:20:47 -0700597 ASSERT_EQ(0, pthread_create(&t1, NULL, spin_helper.GetFunction(), NULL));
msg5550f020d12013-06-06 14:59:28 -0400598
599 pthread_t t2;
600 ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1)));
601
602 sleep(1); // (Give t2 a chance to call pthread_join.)
603
604 // Multiple joins to the same thread should fail.
605 ASSERT_EQ(EINVAL, pthread_join(t1, NULL));
606
Elliott Hughes725b2a92016-03-23 11:20:47 -0700607 spin_helper.UnSpin();
msg5550f020d12013-06-06 14:59:28 -0400608
609 // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes).
610 void* join_result;
611 ASSERT_EQ(0, pthread_join(t2, &join_result));
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700612 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
msg5550f020d12013-06-06 14:59:28 -0400613}
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700614
Elliott Hughes70b24b12013-11-15 11:51:07 -0800615TEST(pthread, pthread_join__race) {
616 // http://b/11693195 --- pthread_join could return before the thread had actually exited.
617 // If the joiner unmapped the thread's stack, that could lead to SIGSEGV in the thread.
618 for (size_t i = 0; i < 1024; ++i) {
Yabin Cuia36158a2015-11-16 21:06:16 -0800619 size_t stack_size = 640*1024;
Elliott Hughes70b24b12013-11-15 11:51:07 -0800620 void* stack = mmap(NULL, stack_size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
621
622 pthread_attr_t a;
623 pthread_attr_init(&a);
624 pthread_attr_setstack(&a, stack, stack_size);
625
626 pthread_t t;
627 ASSERT_EQ(0, pthread_create(&t, &a, IdFn, NULL));
628 ASSERT_EQ(0, pthread_join(t, NULL));
629 ASSERT_EQ(0, munmap(stack, stack_size));
630 }
631}
632
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700633static void* GetActualGuardSizeFn(void* arg) {
634 pthread_attr_t attributes;
635 pthread_getattr_np(pthread_self(), &attributes);
636 pthread_attr_getguardsize(&attributes, reinterpret_cast<size_t*>(arg));
637 return NULL;
638}
639
640static size_t GetActualGuardSize(const pthread_attr_t& attributes) {
641 size_t result;
642 pthread_t t;
643 pthread_create(&t, &attributes, GetActualGuardSizeFn, &result);
Elliott Hughes34c987a2014-09-22 16:01:26 -0700644 pthread_join(t, NULL);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700645 return result;
646}
647
648static void* GetActualStackSizeFn(void* arg) {
649 pthread_attr_t attributes;
650 pthread_getattr_np(pthread_self(), &attributes);
651 pthread_attr_getstacksize(&attributes, reinterpret_cast<size_t*>(arg));
652 return NULL;
653}
654
655static size_t GetActualStackSize(const pthread_attr_t& attributes) {
656 size_t result;
657 pthread_t t;
658 pthread_create(&t, &attributes, GetActualStackSizeFn, &result);
Elliott Hughes34c987a2014-09-22 16:01:26 -0700659 pthread_join(t, NULL);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700660 return result;
661}
662
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700663TEST(pthread, pthread_attr_setguardsize_tiny) {
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700664 pthread_attr_t attributes;
665 ASSERT_EQ(0, pthread_attr_init(&attributes));
666
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700667 // No such thing as too small: will be rounded up to one page by pthread_create.
668 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 128));
669 size_t guard_size;
670 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
671 ASSERT_EQ(128U, guard_size);
672 ASSERT_EQ(4096U, GetActualGuardSize(attributes));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700673}
674
675TEST(pthread, pthread_attr_setguardsize_reasonable) {
676 pthread_attr_t attributes;
677 ASSERT_EQ(0, pthread_attr_init(&attributes));
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700678
679 // Large enough and a multiple of the page size.
680 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700681 size_t guard_size;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700682 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
683 ASSERT_EQ(32*1024U, guard_size);
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700684 ASSERT_EQ(32*1024U, GetActualGuardSize(attributes));
685}
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700686
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700687TEST(pthread, pthread_attr_setguardsize_needs_rounding) {
688 pthread_attr_t attributes;
689 ASSERT_EQ(0, pthread_attr_init(&attributes));
690
691 // Large enough but not a multiple of the page size.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700692 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024 + 1));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700693 size_t guard_size;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700694 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
695 ASSERT_EQ(32*1024U + 1, guard_size);
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700696 ASSERT_EQ(36*1024U, GetActualGuardSize(attributes));
697}
698
699TEST(pthread, pthread_attr_setguardsize_enormous) {
700 pthread_attr_t attributes;
701 ASSERT_EQ(0, pthread_attr_init(&attributes));
702
703 // Larger than the stack itself. (Historically we mistakenly carved
704 // the guard out of the stack itself, rather than adding it after the
705 // end.)
706 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024*1024));
707 size_t guard_size;
708 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
709 ASSERT_EQ(32*1024*1024U, guard_size);
710 ASSERT_EQ(32*1024*1024U, GetActualGuardSize(attributes));
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700711}
712
713TEST(pthread, pthread_attr_setstacksize) {
714 pthread_attr_t attributes;
715 ASSERT_EQ(0, pthread_attr_init(&attributes));
716
717 // Get the default stack size.
718 size_t default_stack_size;
719 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &default_stack_size));
720
721 // Too small.
722 ASSERT_EQ(EINVAL, pthread_attr_setstacksize(&attributes, 128));
723 size_t stack_size;
724 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
725 ASSERT_EQ(default_stack_size, stack_size);
726 ASSERT_GE(GetActualStackSize(attributes), default_stack_size);
727
Yabin Cui917d3902015-01-08 12:32:42 -0800728 // Large enough and a multiple of the page size; may be rounded up by pthread_create.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700729 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024));
730 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
731 ASSERT_EQ(32*1024U, stack_size);
Yabin Cui917d3902015-01-08 12:32:42 -0800732 ASSERT_GE(GetActualStackSize(attributes), 32*1024U);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700733
Yabin Cui917d3902015-01-08 12:32:42 -0800734 // Large enough but not aligned; will be rounded up by pthread_create.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700735 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024 + 1));
736 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
737 ASSERT_EQ(32*1024U + 1, stack_size);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800738#if defined(__BIONIC__)
Yabin Cui917d3902015-01-08 12:32:42 -0800739 ASSERT_GT(GetActualStackSize(attributes), 32*1024U + 1);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800740#else // __BIONIC__
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700741 // glibc rounds down, in violation of POSIX. They document this in their BUGS section.
742 ASSERT_EQ(GetActualStackSize(attributes), 32*1024U);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800743#endif // __BIONIC__
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700744}
Elliott Hughesc3f11402013-10-30 14:40:09 -0700745
Yabin Cui76615da2015-03-17 14:22:09 -0700746TEST(pthread, pthread_rwlockattr_smoke) {
747 pthread_rwlockattr_t attr;
748 ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
749
750 int pshared_value_array[] = {PTHREAD_PROCESS_PRIVATE, PTHREAD_PROCESS_SHARED};
751 for (size_t i = 0; i < sizeof(pshared_value_array) / sizeof(pshared_value_array[0]); ++i) {
752 ASSERT_EQ(0, pthread_rwlockattr_setpshared(&attr, pshared_value_array[i]));
753 int pshared;
754 ASSERT_EQ(0, pthread_rwlockattr_getpshared(&attr, &pshared));
755 ASSERT_EQ(pshared_value_array[i], pshared);
756 }
757
758 int kind_array[] = {PTHREAD_RWLOCK_PREFER_READER_NP,
759 PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP};
760 for (size_t i = 0; i < sizeof(kind_array) / sizeof(kind_array[0]); ++i) {
761 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_array[i]));
762 int kind;
763 ASSERT_EQ(0, pthread_rwlockattr_getkind_np(&attr, &kind));
764 ASSERT_EQ(kind_array[i], kind);
765 }
766
767 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
768}
769
770TEST(pthread, pthread_rwlock_init_same_as_PTHREAD_RWLOCK_INITIALIZER) {
771 pthread_rwlock_t lock1 = PTHREAD_RWLOCK_INITIALIZER;
772 pthread_rwlock_t lock2;
773 ASSERT_EQ(0, pthread_rwlock_init(&lock2, NULL));
774 ASSERT_EQ(0, memcmp(&lock1, &lock2, sizeof(lock1)));
775}
776
Elliott Hughesc3f11402013-10-30 14:40:09 -0700777TEST(pthread, pthread_rwlock_smoke) {
778 pthread_rwlock_t l;
779 ASSERT_EQ(0, pthread_rwlock_init(&l, NULL));
780
Calin Juravle76f352e2014-05-19 13:41:10 +0100781 // Single read lock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700782 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
783 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
784
Calin Juravle76f352e2014-05-19 13:41:10 +0100785 // Multiple read lock
786 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
787 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
788 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
789 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
790
791 // Write lock
Calin Juravle92687e42014-05-22 19:21:22 +0100792 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
793 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100794
795 // Try writer lock
796 ASSERT_EQ(0, pthread_rwlock_trywrlock(&l));
797 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
798 ASSERT_EQ(EBUSY, pthread_rwlock_tryrdlock(&l));
799 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
800
801 // Try reader lock
802 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
803 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
804 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
805 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
806 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
807
808 // Try writer lock after unlock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700809 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
810 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
811
Calin Juravle76f352e2014-05-19 13:41:10 +0100812 // EDEADLK in "read after write"
813 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
814 ASSERT_EQ(EDEADLK, pthread_rwlock_rdlock(&l));
815 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
816
817 // EDEADLK in "write after write"
818 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
819 ASSERT_EQ(EDEADLK, pthread_rwlock_wrlock(&l));
820 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100821
Elliott Hughesc3f11402013-10-30 14:40:09 -0700822 ASSERT_EQ(0, pthread_rwlock_destroy(&l));
823}
824
Yabin Cui08ee8d22015-02-11 17:04:36 -0800825struct RwlockWakeupHelperArg {
826 pthread_rwlock_t lock;
827 enum Progress {
828 LOCK_INITIALIZED,
829 LOCK_WAITING,
830 LOCK_RELEASED,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800831 LOCK_ACCESSED,
832 LOCK_TIMEDOUT,
Yabin Cui08ee8d22015-02-11 17:04:36 -0800833 };
834 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -0700835 std::atomic<pid_t> tid;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800836 std::function<int (pthread_rwlock_t*)> trylock_function;
837 std::function<int (pthread_rwlock_t*)> lock_function;
838 std::function<int (pthread_rwlock_t*, const timespec*)> timed_lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800839};
840
Yabin Cuic9a659c2015-11-05 15:36:08 -0800841static void pthread_rwlock_wakeup_helper(RwlockWakeupHelperArg* arg) {
Yabin Cuif7969852015-04-02 17:47:48 -0700842 arg->tid = gettid();
Yabin Cui08ee8d22015-02-11 17:04:36 -0800843 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
844 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
845
Yabin Cuic9a659c2015-11-05 15:36:08 -0800846 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
847 ASSERT_EQ(0, arg->lock_function(&arg->lock));
Yabin Cui08ee8d22015-02-11 17:04:36 -0800848 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_RELEASED, arg->progress);
849 ASSERT_EQ(0, pthread_rwlock_unlock(&arg->lock));
850
851 arg->progress = RwlockWakeupHelperArg::LOCK_ACCESSED;
852}
853
Yabin Cuic9a659c2015-11-05 15:36:08 -0800854static void test_pthread_rwlock_reader_wakeup_writer(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -0800855 RwlockWakeupHelperArg wakeup_arg;
856 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, NULL));
857 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
858 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -0700859 wakeup_arg.tid = 0;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800860 wakeup_arg.trylock_function = pthread_rwlock_trywrlock;
861 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800862
863 pthread_t thread;
864 ASSERT_EQ(0, pthread_create(&thread, NULL,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800865 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -0700866 WaitUntilThreadSleep(wakeup_arg.tid);
867 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
868
Yabin Cui08ee8d22015-02-11 17:04:36 -0800869 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
870 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
871
872 ASSERT_EQ(0, pthread_join(thread, NULL));
873 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
874 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
875}
876
Yabin Cuic9a659c2015-11-05 15:36:08 -0800877TEST(pthread, pthread_rwlock_reader_wakeup_writer) {
878 test_pthread_rwlock_reader_wakeup_writer(pthread_rwlock_wrlock);
Yabin Cui08ee8d22015-02-11 17:04:36 -0800879}
880
Yabin Cuic9a659c2015-11-05 15:36:08 -0800881TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait) {
882 timespec ts;
883 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
884 ts.tv_sec += 1;
885 test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) {
886 return pthread_rwlock_timedwrlock(lock, &ts);
887 });
888}
889
890static void test_pthread_rwlock_writer_wakeup_reader(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -0800891 RwlockWakeupHelperArg wakeup_arg;
892 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, NULL));
893 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
894 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -0700895 wakeup_arg.tid = 0;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800896 wakeup_arg.trylock_function = pthread_rwlock_tryrdlock;
897 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800898
899 pthread_t thread;
900 ASSERT_EQ(0, pthread_create(&thread, NULL,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800901 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -0700902 WaitUntilThreadSleep(wakeup_arg.tid);
903 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
904
Yabin Cui08ee8d22015-02-11 17:04:36 -0800905 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
906 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
907
908 ASSERT_EQ(0, pthread_join(thread, NULL));
909 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
910 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
911}
912
Yabin Cuic9a659c2015-11-05 15:36:08 -0800913TEST(pthread, pthread_rwlock_writer_wakeup_reader) {
914 test_pthread_rwlock_writer_wakeup_reader(pthread_rwlock_rdlock);
915}
916
917TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait) {
918 timespec ts;
919 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
920 ts.tv_sec += 1;
921 test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) {
922 return pthread_rwlock_timedrdlock(lock, &ts);
923 });
924}
925
926static void pthread_rwlock_wakeup_timeout_helper(RwlockWakeupHelperArg* arg) {
927 arg->tid = gettid();
928 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
929 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
930
931 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
932
933 timespec ts;
934 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
935 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
936 ts.tv_nsec = -1;
937 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
938 ts.tv_nsec = NS_PER_S;
939 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
940 ts.tv_nsec = NS_PER_S - 1;
941 ts.tv_sec = -1;
942 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
943 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
944 ts.tv_sec += 1;
945 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
946 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, arg->progress);
947 arg->progress = RwlockWakeupHelperArg::LOCK_TIMEDOUT;
948}
949
950TEST(pthread, pthread_rwlock_timedrdlock_timeout) {
951 RwlockWakeupHelperArg wakeup_arg;
952 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
953 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
954 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
955 wakeup_arg.tid = 0;
956 wakeup_arg.trylock_function = pthread_rwlock_tryrdlock;
957 wakeup_arg.timed_lock_function = pthread_rwlock_timedrdlock;
958
959 pthread_t thread;
960 ASSERT_EQ(0, pthread_create(&thread, nullptr,
961 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
962 WaitUntilThreadSleep(wakeup_arg.tid);
963 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
964
965 ASSERT_EQ(0, pthread_join(thread, nullptr));
966 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
967 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
968 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
969}
970
971TEST(pthread, pthread_rwlock_timedwrlock_timeout) {
972 RwlockWakeupHelperArg wakeup_arg;
973 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
974 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
975 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
976 wakeup_arg.tid = 0;
977 wakeup_arg.trylock_function = pthread_rwlock_trywrlock;
978 wakeup_arg.timed_lock_function = pthread_rwlock_timedwrlock;
979
980 pthread_t thread;
981 ASSERT_EQ(0, pthread_create(&thread, nullptr,
982 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
983 WaitUntilThreadSleep(wakeup_arg.tid);
984 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
985
986 ASSERT_EQ(0, pthread_join(thread, nullptr));
987 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
988 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
989 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
990}
991
Yabin Cui76615da2015-03-17 14:22:09 -0700992class RwlockKindTestHelper {
993 private:
994 struct ThreadArg {
995 RwlockKindTestHelper* helper;
996 std::atomic<pid_t>& tid;
997
998 ThreadArg(RwlockKindTestHelper* helper, std::atomic<pid_t>& tid)
999 : helper(helper), tid(tid) { }
1000 };
1001
1002 public:
1003 pthread_rwlock_t lock;
1004
1005 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -07001006 explicit RwlockKindTestHelper(int kind_type) {
Yabin Cui76615da2015-03-17 14:22:09 -07001007 InitRwlock(kind_type);
1008 }
1009
1010 ~RwlockKindTestHelper() {
1011 DestroyRwlock();
1012 }
1013
1014 void CreateWriterThread(pthread_t& thread, std::atomic<pid_t>& tid) {
1015 tid = 0;
1016 ThreadArg* arg = new ThreadArg(this, tid);
1017 ASSERT_EQ(0, pthread_create(&thread, NULL,
1018 reinterpret_cast<void* (*)(void*)>(WriterThreadFn), arg));
1019 }
1020
1021 void CreateReaderThread(pthread_t& thread, std::atomic<pid_t>& tid) {
1022 tid = 0;
1023 ThreadArg* arg = new ThreadArg(this, tid);
1024 ASSERT_EQ(0, pthread_create(&thread, NULL,
1025 reinterpret_cast<void* (*)(void*)>(ReaderThreadFn), arg));
1026 }
1027
1028 private:
1029 void InitRwlock(int kind_type) {
1030 pthread_rwlockattr_t attr;
1031 ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
1032 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_type));
1033 ASSERT_EQ(0, pthread_rwlock_init(&lock, &attr));
1034 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
1035 }
1036
1037 void DestroyRwlock() {
1038 ASSERT_EQ(0, pthread_rwlock_destroy(&lock));
1039 }
1040
1041 static void WriterThreadFn(ThreadArg* arg) {
1042 arg->tid = gettid();
1043
1044 RwlockKindTestHelper* helper = arg->helper;
1045 ASSERT_EQ(0, pthread_rwlock_wrlock(&helper->lock));
1046 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
1047 delete arg;
1048 }
1049
1050 static void ReaderThreadFn(ThreadArg* arg) {
1051 arg->tid = gettid();
1052
1053 RwlockKindTestHelper* helper = arg->helper;
1054 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper->lock));
1055 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
1056 delete arg;
1057 }
1058};
1059
1060TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_READER_NP) {
1061 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_READER_NP);
1062 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
1063
1064 pthread_t writer_thread;
1065 std::atomic<pid_t> writer_tid;
1066 helper.CreateWriterThread(writer_thread, writer_tid);
1067 WaitUntilThreadSleep(writer_tid);
1068
1069 pthread_t reader_thread;
1070 std::atomic<pid_t> reader_tid;
1071 helper.CreateReaderThread(reader_thread, reader_tid);
1072 ASSERT_EQ(0, pthread_join(reader_thread, NULL));
1073
1074 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
1075 ASSERT_EQ(0, pthread_join(writer_thread, NULL));
1076}
1077
1078TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP) {
1079 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
1080 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
1081
1082 pthread_t writer_thread;
1083 std::atomic<pid_t> writer_tid;
1084 helper.CreateWriterThread(writer_thread, writer_tid);
1085 WaitUntilThreadSleep(writer_tid);
1086
1087 pthread_t reader_thread;
1088 std::atomic<pid_t> reader_tid;
1089 helper.CreateReaderThread(reader_thread, reader_tid);
1090 WaitUntilThreadSleep(reader_tid);
1091
1092 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
1093 ASSERT_EQ(0, pthread_join(writer_thread, NULL));
1094 ASSERT_EQ(0, pthread_join(reader_thread, NULL));
1095}
1096
Elliott Hughes1728b232014-05-14 10:02:03 -07001097static int g_once_fn_call_count = 0;
Elliott Hughesc3f11402013-10-30 14:40:09 -07001098static void OnceFn() {
Elliott Hughes1728b232014-05-14 10:02:03 -07001099 ++g_once_fn_call_count;
Elliott Hughesc3f11402013-10-30 14:40:09 -07001100}
1101
1102TEST(pthread, pthread_once_smoke) {
1103 pthread_once_t once_control = PTHREAD_ONCE_INIT;
1104 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
1105 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
Elliott Hughes1728b232014-05-14 10:02:03 -07001106 ASSERT_EQ(1, g_once_fn_call_count);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001107}
1108
Elliott Hughes3694ec62014-05-14 11:46:08 -07001109static std::string pthread_once_1934122_result = "";
1110
1111static void Routine2() {
1112 pthread_once_1934122_result += "2";
1113}
1114
1115static void Routine1() {
1116 pthread_once_t once_control_2 = PTHREAD_ONCE_INIT;
1117 pthread_once_1934122_result += "1";
1118 pthread_once(&once_control_2, &Routine2);
1119}
1120
1121TEST(pthread, pthread_once_1934122) {
1122 // Very old versions of Android couldn't call pthread_once from a
1123 // pthread_once init routine. http://b/1934122.
1124 pthread_once_t once_control_1 = PTHREAD_ONCE_INIT;
1125 ASSERT_EQ(0, pthread_once(&once_control_1, &Routine1));
1126 ASSERT_EQ("12", pthread_once_1934122_result);
1127}
1128
Elliott Hughes1728b232014-05-14 10:02:03 -07001129static int g_atfork_prepare_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001130static void AtForkPrepare1() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 1; }
1131static void AtForkPrepare2() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -07001132static int g_atfork_parent_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001133static void AtForkParent1() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 1; }
1134static void AtForkParent2() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -07001135static int g_atfork_child_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001136static void AtForkChild1() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 1; }
1137static void AtForkChild2() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 2; }
Elliott Hughesc3f11402013-10-30 14:40:09 -07001138
Dmitriy Ivanov00e37812014-11-20 16:53:47 -08001139TEST(pthread, pthread_atfork_smoke) {
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001140 ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1));
1141 ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2));
Elliott Hughesc3f11402013-10-30 14:40:09 -07001142
Elliott Hughes33697a02016-01-26 13:04:57 -08001143 pid_t pid = fork();
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001144 ASSERT_NE(-1, pid) << strerror(errno);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001145
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001146 // Child and parent calls are made in the order they were registered.
1147 if (pid == 0) {
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001148 ASSERT_EQ(12, g_atfork_child_calls);
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001149 _exit(0);
1150 }
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001151 ASSERT_EQ(12, g_atfork_parent_calls);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001152
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001153 // Prepare calls are made in the reverse order.
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001154 ASSERT_EQ(21, g_atfork_prepare_calls);
Elliott Hughes33697a02016-01-26 13:04:57 -08001155 AssertChildExited(pid, 0);
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001156}
1157
Elliott Hughesc3f11402013-10-30 14:40:09 -07001158TEST(pthread, pthread_attr_getscope) {
1159 pthread_attr_t attr;
1160 ASSERT_EQ(0, pthread_attr_init(&attr));
1161
1162 int scope;
1163 ASSERT_EQ(0, pthread_attr_getscope(&attr, &scope));
1164 ASSERT_EQ(PTHREAD_SCOPE_SYSTEM, scope);
1165}
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001166
1167TEST(pthread, pthread_condattr_init) {
1168 pthread_condattr_t attr;
1169 pthread_condattr_init(&attr);
1170
1171 clockid_t clock;
1172 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1173 ASSERT_EQ(CLOCK_REALTIME, clock);
1174
1175 int pshared;
1176 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1177 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
1178}
1179
1180TEST(pthread, pthread_condattr_setclock) {
1181 pthread_condattr_t attr;
1182 pthread_condattr_init(&attr);
1183
1184 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_REALTIME));
1185 clockid_t clock;
1186 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1187 ASSERT_EQ(CLOCK_REALTIME, clock);
1188
1189 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1190 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1191 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1192
1193 ASSERT_EQ(EINVAL, pthread_condattr_setclock(&attr, CLOCK_PROCESS_CPUTIME_ID));
1194}
1195
1196TEST(pthread, pthread_cond_broadcast__preserves_condattr_flags) {
Yabin Cui32651b82015-03-13 20:30:00 -07001197#if defined(__BIONIC__)
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001198 pthread_condattr_t attr;
1199 pthread_condattr_init(&attr);
1200
1201 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1202 ASSERT_EQ(0, pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
1203
1204 pthread_cond_t cond_var;
1205 ASSERT_EQ(0, pthread_cond_init(&cond_var, &attr));
1206
1207 ASSERT_EQ(0, pthread_cond_signal(&cond_var));
1208 ASSERT_EQ(0, pthread_cond_broadcast(&cond_var));
1209
Yabin Cui32651b82015-03-13 20:30:00 -07001210 attr = static_cast<pthread_condattr_t>(*reinterpret_cast<uint32_t*>(cond_var.__private));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001211 clockid_t clock;
1212 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1213 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1214 int pshared;
1215 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1216 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
Yabin Cui32651b82015-03-13 20:30:00 -07001217#else // !defined(__BIONIC__)
1218 GTEST_LOG_(INFO) << "This tests a bionic implementation detail.\n";
1219#endif // !defined(__BIONIC__)
1220}
1221
1222class pthread_CondWakeupTest : public ::testing::Test {
1223 protected:
1224 pthread_mutex_t mutex;
1225 pthread_cond_t cond;
1226
1227 enum Progress {
1228 INITIALIZED,
1229 WAITING,
1230 SIGNALED,
1231 FINISHED,
1232 };
1233 std::atomic<Progress> progress;
1234 pthread_t thread;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001235 std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function;
Yabin Cui32651b82015-03-13 20:30:00 -07001236
1237 protected:
Yabin Cuic9a659c2015-11-05 15:36:08 -08001238 void SetUp() override {
1239 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1240 }
1241
1242 void InitCond(clockid_t clock=CLOCK_REALTIME) {
1243 pthread_condattr_t attr;
1244 ASSERT_EQ(0, pthread_condattr_init(&attr));
1245 ASSERT_EQ(0, pthread_condattr_setclock(&attr, clock));
1246 ASSERT_EQ(0, pthread_cond_init(&cond, &attr));
1247 ASSERT_EQ(0, pthread_condattr_destroy(&attr));
1248 }
1249
1250 void StartWaitingThread(std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function) {
Yabin Cui32651b82015-03-13 20:30:00 -07001251 progress = INITIALIZED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001252 this->wait_function = wait_function;
1253 ASSERT_EQ(0, pthread_create(&thread, NULL, reinterpret_cast<void* (*)(void*)>(WaitThreadFn), this));
1254 while (progress != WAITING) {
Yabin Cui32651b82015-03-13 20:30:00 -07001255 usleep(5000);
1256 }
1257 usleep(5000);
1258 }
1259
Yabin Cuic9a659c2015-11-05 15:36:08 -08001260 void TearDown() override {
1261 ASSERT_EQ(0, pthread_join(thread, nullptr));
1262 ASSERT_EQ(FINISHED, progress);
1263 ASSERT_EQ(0, pthread_cond_destroy(&cond));
1264 ASSERT_EQ(0, pthread_mutex_destroy(&mutex));
1265 }
1266
Yabin Cui32651b82015-03-13 20:30:00 -07001267 private:
1268 static void WaitThreadFn(pthread_CondWakeupTest* test) {
1269 ASSERT_EQ(0, pthread_mutex_lock(&test->mutex));
1270 test->progress = WAITING;
1271 while (test->progress == WAITING) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001272 ASSERT_EQ(0, test->wait_function(&test->cond, &test->mutex));
Yabin Cui32651b82015-03-13 20:30:00 -07001273 }
1274 ASSERT_EQ(SIGNALED, test->progress);
1275 test->progress = FINISHED;
1276 ASSERT_EQ(0, pthread_mutex_unlock(&test->mutex));
1277 }
1278};
1279
Yabin Cuic9a659c2015-11-05 15:36:08 -08001280TEST_F(pthread_CondWakeupTest, signal_wait) {
1281 InitCond();
1282 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1283 return pthread_cond_wait(cond, mutex);
1284 });
Yabin Cui32651b82015-03-13 20:30:00 -07001285 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001286 ASSERT_EQ(0, pthread_cond_signal(&cond));
Yabin Cui32651b82015-03-13 20:30:00 -07001287}
1288
Yabin Cuic9a659c2015-11-05 15:36:08 -08001289TEST_F(pthread_CondWakeupTest, broadcast_wait) {
1290 InitCond();
1291 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1292 return pthread_cond_wait(cond, mutex);
1293 });
Yabin Cui32651b82015-03-13 20:30:00 -07001294 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001295 ASSERT_EQ(0, pthread_cond_broadcast(&cond));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001296}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001297
Yabin Cuic9a659c2015-11-05 15:36:08 -08001298TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_REALTIME) {
1299 InitCond(CLOCK_REALTIME);
Elliott Hughes0e714a52014-03-03 16:42:47 -08001300 timespec ts;
1301 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001302 ts.tv_sec += 1;
1303 StartWaitingThread([&](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1304 return pthread_cond_timedwait(cond, mutex, &ts);
1305 });
1306 progress = SIGNALED;
1307 ASSERT_EQ(0, pthread_cond_signal(&cond));
1308}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001309
Yabin Cuic9a659c2015-11-05 15:36:08 -08001310TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC) {
1311 InitCond(CLOCK_MONOTONIC);
1312 timespec ts;
1313 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1314 ts.tv_sec += 1;
1315 StartWaitingThread([&](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1316 return pthread_cond_timedwait(cond, mutex, &ts);
1317 });
1318 progress = SIGNALED;
1319 ASSERT_EQ(0, pthread_cond_signal(&cond));
1320}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001321
Yabin Cuic9a659c2015-11-05 15:36:08 -08001322TEST(pthread, pthread_cond_timedwait_timeout) {
1323 pthread_mutex_t mutex;
1324 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1325 pthread_cond_t cond;
1326 ASSERT_EQ(0, pthread_cond_init(&cond, nullptr));
1327 ASSERT_EQ(0, pthread_mutex_lock(&mutex));
1328 timespec ts;
Elliott Hughes0e714a52014-03-03 16:42:47 -08001329 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001330 ASSERT_EQ(ETIMEDOUT, pthread_cond_timedwait(&cond, &mutex, &ts));
1331 ts.tv_nsec = -1;
1332 ASSERT_EQ(EINVAL, pthread_cond_timedwait(&cond, &mutex, &ts));
1333 ts.tv_nsec = NS_PER_S;
1334 ASSERT_EQ(EINVAL, pthread_cond_timedwait(&cond, &mutex, &ts));
1335 ts.tv_nsec = NS_PER_S - 1;
1336 ts.tv_sec = -1;
1337 ASSERT_EQ(ETIMEDOUT, pthread_cond_timedwait(&cond, &mutex, &ts));
1338 ASSERT_EQ(0, pthread_mutex_unlock(&mutex));
Elliott Hughes0e714a52014-03-03 16:42:47 -08001339}
Elliott Hughes57b7a612014-08-25 17:26:50 -07001340
1341TEST(pthread, pthread_attr_getstack__main_thread) {
1342 // This test is only meaningful for the main thread, so make sure we're running on it!
1343 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1344
1345 // Get the main thread's attributes.
1346 pthread_attr_t attributes;
1347 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1348
1349 // Check that we correctly report that the main thread has no guard page.
1350 size_t guard_size;
1351 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
1352 ASSERT_EQ(0U, guard_size); // The main thread has no guard page.
1353
1354 // Get the stack base and the stack size (both ways).
1355 void* stack_base;
1356 size_t stack_size;
1357 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1358 size_t stack_size2;
1359 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1360
1361 // The two methods of asking for the stack size should agree.
1362 EXPECT_EQ(stack_size, stack_size2);
1363
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001364#if defined(__BIONIC__)
Elliott Hughes57b7a612014-08-25 17:26:50 -07001365 // What does /proc/self/maps' [stack] line say?
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001366 void* maps_stack_hi = NULL;
Elliott Hughes15dfd632015-09-22 16:40:14 -07001367 std::vector<map_record> maps;
1368 ASSERT_TRUE(Maps::parse_maps(&maps));
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07001369 for (const auto& map : maps) {
Elliott Hughes15dfd632015-09-22 16:40:14 -07001370 if (map.pathname == "[stack]") {
1371 maps_stack_hi = reinterpret_cast<void*>(map.addr_end);
Elliott Hughes57b7a612014-08-25 17:26:50 -07001372 break;
1373 }
1374 }
Elliott Hughes57b7a612014-08-25 17:26:50 -07001375
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001376 // The high address of the /proc/self/maps [stack] region should equal stack_base + stack_size.
1377 // Remember that the stack grows down (and is mapped in on demand), so the low address of the
1378 // region isn't very interesting.
1379 EXPECT_EQ(maps_stack_hi, reinterpret_cast<uint8_t*>(stack_base) + stack_size);
1380
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001381 // The stack size should correspond to RLIMIT_STACK.
Elliott Hughes57b7a612014-08-25 17:26:50 -07001382 rlimit rl;
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001383 ASSERT_EQ(0, getrlimit(RLIMIT_STACK, &rl));
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001384 uint64_t original_rlim_cur = rl.rlim_cur;
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001385 if (rl.rlim_cur == RLIM_INFINITY) {
1386 rl.rlim_cur = 8 * 1024 * 1024; // Bionic reports unlimited stacks as 8MiB.
1387 }
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001388 EXPECT_EQ(rl.rlim_cur, stack_size);
1389
Tom Cherryb8ab6182017-04-05 16:20:29 -07001390 auto guard = android::base::make_scope_guard([&rl, original_rlim_cur]() {
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001391 rl.rlim_cur = original_rlim_cur;
1392 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1393 });
1394
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001395 //
1396 // What if RLIMIT_STACK is smaller than the stack's current extent?
1397 //
Elliott Hughes57b7a612014-08-25 17:26:50 -07001398 rl.rlim_cur = rl.rlim_max = 1024; // 1KiB. We know the stack must be at least a page already.
1399 rl.rlim_max = RLIM_INFINITY;
1400 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1401
1402 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1403 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1404 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1405
1406 EXPECT_EQ(stack_size, stack_size2);
1407 ASSERT_EQ(1024U, stack_size);
1408
1409 //
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001410 // What if RLIMIT_STACK isn't a whole number of pages?
Elliott Hughes57b7a612014-08-25 17:26:50 -07001411 //
1412 rl.rlim_cur = rl.rlim_max = 6666; // Not a whole number of pages.
1413 rl.rlim_max = RLIM_INFINITY;
1414 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1415
1416 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1417 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1418 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1419
1420 EXPECT_EQ(stack_size, stack_size2);
1421 ASSERT_EQ(6666U, stack_size);
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001422#endif
Elliott Hughes57b7a612014-08-25 17:26:50 -07001423}
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001424
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001425struct GetStackSignalHandlerArg {
1426 volatile bool done;
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001427 void* signal_stack_base;
1428 size_t signal_stack_size;
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001429 void* main_stack_base;
1430 size_t main_stack_size;
1431};
1432
1433static GetStackSignalHandlerArg getstack_signal_handler_arg;
1434
1435static void getstack_signal_handler(int sig) {
1436 ASSERT_EQ(SIGUSR1, sig);
1437 // Use sleep() to make current thread be switched out by the kernel to provoke the error.
1438 sleep(1);
1439 pthread_attr_t attr;
1440 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1441 void* stack_base;
1442 size_t stack_size;
1443 ASSERT_EQ(0, pthread_attr_getstack(&attr, &stack_base, &stack_size));
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001444
1445 // Verify if the stack used by the signal handler is the alternate stack just registered.
1446 ASSERT_LE(getstack_signal_handler_arg.signal_stack_base, &attr);
1447 ASSERT_LT(static_cast<void*>(&attr),
1448 static_cast<char*>(getstack_signal_handler_arg.signal_stack_base) +
1449 getstack_signal_handler_arg.signal_stack_size);
1450
1451 // Verify if the main thread's stack got in the signal handler is correct.
1452 ASSERT_EQ(getstack_signal_handler_arg.main_stack_base, stack_base);
1453 ASSERT_LE(getstack_signal_handler_arg.main_stack_size, stack_size);
1454
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001455 getstack_signal_handler_arg.done = true;
1456}
1457
1458// The previous code obtained the main thread's stack by reading the entry in
1459// /proc/self/task/<pid>/maps that was labeled [stack]. Unfortunately, on x86/x86_64, the kernel
1460// relies on sp0 in task state segment(tss) to label the stack map with [stack]. If the kernel
1461// switches a process while the main thread is in an alternate stack, then the kernel will label
1462// the wrong map with [stack]. This test verifies that when the above situation happens, the main
1463// thread's stack is found correctly.
1464TEST(pthread, pthread_attr_getstack_in_signal_handler) {
Yabin Cui61e4d462016-03-07 17:44:58 -08001465 // This test is only meaningful for the main thread, so make sure we're running on it!
1466 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1467
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001468 const size_t sig_stack_size = 16 * 1024;
1469 void* sig_stack = mmap(NULL, sig_stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS,
1470 -1, 0);
1471 ASSERT_NE(MAP_FAILED, sig_stack);
1472 stack_t ss;
1473 ss.ss_sp = sig_stack;
1474 ss.ss_size = sig_stack_size;
1475 ss.ss_flags = 0;
1476 stack_t oss;
1477 ASSERT_EQ(0, sigaltstack(&ss, &oss));
1478
Yabin Cui61e4d462016-03-07 17:44:58 -08001479 pthread_attr_t attr;
1480 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1481 void* main_stack_base;
1482 size_t main_stack_size;
1483 ASSERT_EQ(0, pthread_attr_getstack(&attr, &main_stack_base, &main_stack_size));
1484
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001485 ScopedSignalHandler handler(SIGUSR1, getstack_signal_handler, SA_ONSTACK);
1486 getstack_signal_handler_arg.done = false;
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001487 getstack_signal_handler_arg.signal_stack_base = sig_stack;
1488 getstack_signal_handler_arg.signal_stack_size = sig_stack_size;
1489 getstack_signal_handler_arg.main_stack_base = main_stack_base;
1490 getstack_signal_handler_arg.main_stack_size = main_stack_size;
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001491 kill(getpid(), SIGUSR1);
1492 ASSERT_EQ(true, getstack_signal_handler_arg.done);
1493
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001494 ASSERT_EQ(0, sigaltstack(&oss, nullptr));
1495 ASSERT_EQ(0, munmap(sig_stack, sig_stack_size));
1496}
1497
Yabin Cui917d3902015-01-08 12:32:42 -08001498static void pthread_attr_getstack_18908062_helper(void*) {
1499 char local_variable;
1500 pthread_attr_t attributes;
1501 pthread_getattr_np(pthread_self(), &attributes);
1502 void* stack_base;
1503 size_t stack_size;
1504 pthread_attr_getstack(&attributes, &stack_base, &stack_size);
1505
1506 // Test whether &local_variable is in [stack_base, stack_base + stack_size).
1507 ASSERT_LE(reinterpret_cast<char*>(stack_base), &local_variable);
1508 ASSERT_LT(&local_variable, reinterpret_cast<char*>(stack_base) + stack_size);
1509}
1510
1511// Check whether something on stack is in the range of
1512// [stack_base, stack_base + stack_size). see b/18908062.
1513TEST(pthread, pthread_attr_getstack_18908062) {
1514 pthread_t t;
1515 ASSERT_EQ(0, pthread_create(&t, NULL,
1516 reinterpret_cast<void* (*)(void*)>(pthread_attr_getstack_18908062_helper),
1517 NULL));
1518 pthread_join(t, NULL);
1519}
1520
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001521#if defined(__BIONIC__)
Elliott Hughesf2083612015-11-11 13:32:28 -08001522static pthread_mutex_t pthread_gettid_np_mutex = PTHREAD_MUTEX_INITIALIZER;
1523
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001524static void* pthread_gettid_np_helper(void* arg) {
1525 *reinterpret_cast<pid_t*>(arg) = gettid();
Elliott Hughesf2083612015-11-11 13:32:28 -08001526
1527 // Wait for our parent to call pthread_gettid_np on us before exiting.
1528 pthread_mutex_lock(&pthread_gettid_np_mutex);
1529 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001530 return NULL;
1531}
1532#endif
1533
1534TEST(pthread, pthread_gettid_np) {
1535#if defined(__BIONIC__)
1536 ASSERT_EQ(gettid(), pthread_gettid_np(pthread_self()));
1537
Elliott Hughesf2083612015-11-11 13:32:28 -08001538 // Ensure the other thread doesn't exit until after we've called
1539 // pthread_gettid_np on it.
1540 pthread_mutex_lock(&pthread_gettid_np_mutex);
1541
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001542 pid_t t_gettid_result;
1543 pthread_t t;
1544 pthread_create(&t, NULL, pthread_gettid_np_helper, &t_gettid_result);
1545
1546 pid_t t_pthread_gettid_np_result = pthread_gettid_np(t);
1547
Elliott Hughesf2083612015-11-11 13:32:28 -08001548 // Release the other thread and wait for it to exit.
1549 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Elliott Hughes34c987a2014-09-22 16:01:26 -07001550 pthread_join(t, NULL);
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001551
1552 ASSERT_EQ(t_gettid_result, t_pthread_gettid_np_result);
1553#else
1554 GTEST_LOG_(INFO) << "This test does nothing.\n";
1555#endif
1556}
Elliott Hughes34c987a2014-09-22 16:01:26 -07001557
1558static size_t cleanup_counter = 0;
1559
Derek Xue41996952014-09-25 11:05:32 +01001560static void AbortCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001561 abort();
1562}
1563
Derek Xue41996952014-09-25 11:05:32 +01001564static void CountCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001565 ++cleanup_counter;
1566}
1567
Derek Xue41996952014-09-25 11:05:32 +01001568static void PthreadCleanupTester() {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001569 pthread_cleanup_push(CountCleanupRoutine, NULL);
1570 pthread_cleanup_push(CountCleanupRoutine, NULL);
1571 pthread_cleanup_push(AbortCleanupRoutine, NULL);
1572
1573 pthread_cleanup_pop(0); // Pop the abort without executing it.
1574 pthread_cleanup_pop(1); // Pop one count while executing it.
1575 ASSERT_EQ(1U, cleanup_counter);
1576 // Exit while the other count is still on the cleanup stack.
1577 pthread_exit(NULL);
1578
1579 // Calls to pthread_cleanup_pop/pthread_cleanup_push must always be balanced.
1580 pthread_cleanup_pop(0);
1581}
1582
Derek Xue41996952014-09-25 11:05:32 +01001583static void* PthreadCleanupStartRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001584 PthreadCleanupTester();
1585 return NULL;
1586}
1587
1588TEST(pthread, pthread_cleanup_push__pthread_cleanup_pop) {
1589 pthread_t t;
1590 ASSERT_EQ(0, pthread_create(&t, NULL, PthreadCleanupStartRoutine, NULL));
1591 pthread_join(t, NULL);
1592 ASSERT_EQ(2U, cleanup_counter);
1593}
Derek Xue41996952014-09-25 11:05:32 +01001594
1595TEST(pthread, PTHREAD_MUTEX_DEFAULT_is_PTHREAD_MUTEX_NORMAL) {
1596 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_DEFAULT);
1597}
1598
1599TEST(pthread, pthread_mutexattr_gettype) {
1600 pthread_mutexattr_t attr;
1601 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1602
1603 int attr_type;
1604
1605 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL));
1606 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1607 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, attr_type);
1608
1609 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK));
1610 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1611 ASSERT_EQ(PTHREAD_MUTEX_ERRORCHECK, attr_type);
1612
1613 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE));
1614 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1615 ASSERT_EQ(PTHREAD_MUTEX_RECURSIVE, attr_type);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001616
1617 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
1618}
1619
Yabin Cui17393b02015-03-21 15:08:25 -07001620struct PthreadMutex {
1621 pthread_mutex_t lock;
1622
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -07001623 explicit PthreadMutex(int mutex_type) {
Yabin Cui17393b02015-03-21 15:08:25 -07001624 init(mutex_type);
1625 }
1626
1627 ~PthreadMutex() {
1628 destroy();
1629 }
1630
1631 private:
1632 void init(int mutex_type) {
1633 pthread_mutexattr_t attr;
1634 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1635 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, mutex_type));
1636 ASSERT_EQ(0, pthread_mutex_init(&lock, &attr));
1637 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
1638 }
1639
1640 void destroy() {
1641 ASSERT_EQ(0, pthread_mutex_destroy(&lock));
1642 }
1643
1644 DISALLOW_COPY_AND_ASSIGN(PthreadMutex);
1645};
Derek Xue41996952014-09-25 11:05:32 +01001646
1647TEST(pthread, pthread_mutex_lock_NORMAL) {
Yabin Cui17393b02015-03-21 15:08:25 -07001648 PthreadMutex m(PTHREAD_MUTEX_NORMAL);
Derek Xue41996952014-09-25 11:05:32 +01001649
Yabin Cui17393b02015-03-21 15:08:25 -07001650 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1651 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08001652 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
1653 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
1654 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01001655}
1656
1657TEST(pthread, pthread_mutex_lock_ERRORCHECK) {
Yabin Cui17393b02015-03-21 15:08:25 -07001658 PthreadMutex m(PTHREAD_MUTEX_ERRORCHECK);
Derek Xue41996952014-09-25 11:05:32 +01001659
Yabin Cui17393b02015-03-21 15:08:25 -07001660 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1661 ASSERT_EQ(EDEADLK, pthread_mutex_lock(&m.lock));
1662 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1663 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
1664 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
1665 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1666 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01001667}
1668
1669TEST(pthread, pthread_mutex_lock_RECURSIVE) {
Yabin Cui17393b02015-03-21 15:08:25 -07001670 PthreadMutex m(PTHREAD_MUTEX_RECURSIVE);
Derek Xue41996952014-09-25 11:05:32 +01001671
Yabin Cui17393b02015-03-21 15:08:25 -07001672 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1673 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1674 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1675 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1676 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08001677 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
1678 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07001679 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1680 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
1681}
1682
1683TEST(pthread, pthread_mutex_init_same_as_static_initializers) {
1684 pthread_mutex_t lock_normal = PTHREAD_MUTEX_INITIALIZER;
1685 PthreadMutex m1(PTHREAD_MUTEX_NORMAL);
1686 ASSERT_EQ(0, memcmp(&lock_normal, &m1.lock, sizeof(pthread_mutex_t)));
1687 pthread_mutex_destroy(&lock_normal);
1688
1689 pthread_mutex_t lock_errorcheck = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
1690 PthreadMutex m2(PTHREAD_MUTEX_ERRORCHECK);
1691 ASSERT_EQ(0, memcmp(&lock_errorcheck, &m2.lock, sizeof(pthread_mutex_t)));
1692 pthread_mutex_destroy(&lock_errorcheck);
1693
1694 pthread_mutex_t lock_recursive = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
1695 PthreadMutex m3(PTHREAD_MUTEX_RECURSIVE);
1696 ASSERT_EQ(0, memcmp(&lock_recursive, &m3.lock, sizeof(pthread_mutex_t)));
1697 ASSERT_EQ(0, pthread_mutex_destroy(&lock_recursive));
Derek Xue41996952014-09-25 11:05:32 +01001698}
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001699class MutexWakeupHelper {
1700 private:
Yabin Cui17393b02015-03-21 15:08:25 -07001701 PthreadMutex m;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001702 enum Progress {
1703 LOCK_INITIALIZED,
1704 LOCK_WAITING,
1705 LOCK_RELEASED,
1706 LOCK_ACCESSED
1707 };
1708 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -07001709 std::atomic<pid_t> tid;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001710
1711 static void thread_fn(MutexWakeupHelper* helper) {
Yabin Cuif7969852015-04-02 17:47:48 -07001712 helper->tid = gettid();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001713 ASSERT_EQ(LOCK_INITIALIZED, helper->progress);
1714 helper->progress = LOCK_WAITING;
1715
Yabin Cui17393b02015-03-21 15:08:25 -07001716 ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001717 ASSERT_EQ(LOCK_RELEASED, helper->progress);
Yabin Cui17393b02015-03-21 15:08:25 -07001718 ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001719
1720 helper->progress = LOCK_ACCESSED;
1721 }
1722
1723 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -07001724 explicit MutexWakeupHelper(int mutex_type) : m(mutex_type) {
Yabin Cui17393b02015-03-21 15:08:25 -07001725 }
1726
1727 void test() {
1728 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001729 progress = LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -07001730 tid = 0;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001731
1732 pthread_t thread;
1733 ASSERT_EQ(0, pthread_create(&thread, NULL,
1734 reinterpret_cast<void* (*)(void*)>(MutexWakeupHelper::thread_fn), this));
1735
Yabin Cuif7969852015-04-02 17:47:48 -07001736 WaitUntilThreadSleep(tid);
1737 ASSERT_EQ(LOCK_WAITING, progress);
1738
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001739 progress = LOCK_RELEASED;
Yabin Cui17393b02015-03-21 15:08:25 -07001740 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001741
1742 ASSERT_EQ(0, pthread_join(thread, NULL));
1743 ASSERT_EQ(LOCK_ACCESSED, progress);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001744 }
1745};
1746
1747TEST(pthread, pthread_mutex_NORMAL_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07001748 MutexWakeupHelper helper(PTHREAD_MUTEX_NORMAL);
1749 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001750}
1751
1752TEST(pthread, pthread_mutex_ERRORCHECK_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07001753 MutexWakeupHelper helper(PTHREAD_MUTEX_ERRORCHECK);
1754 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001755}
1756
1757TEST(pthread, pthread_mutex_RECURSIVE_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07001758 MutexWakeupHelper helper(PTHREAD_MUTEX_RECURSIVE);
1759 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001760}
1761
Yabin Cui140f3672015-02-03 10:32:00 -08001762TEST(pthread, pthread_mutex_owner_tid_limit) {
Yabin Cuie69c2452015-02-13 16:21:25 -08001763#if defined(__BIONIC__) && !defined(__LP64__)
Yabin Cui140f3672015-02-03 10:32:00 -08001764 FILE* fp = fopen("/proc/sys/kernel/pid_max", "r");
1765 ASSERT_TRUE(fp != NULL);
1766 long pid_max;
1767 ASSERT_EQ(1, fscanf(fp, "%ld", &pid_max));
1768 fclose(fp);
Yabin Cuie69c2452015-02-13 16:21:25 -08001769 // Bionic's pthread_mutex implementation on 32-bit devices uses 16 bits to represent owner tid.
Yabin Cui140f3672015-02-03 10:32:00 -08001770 ASSERT_LE(pid_max, 65536);
Yabin Cuie69c2452015-02-13 16:21:25 -08001771#else
1772 GTEST_LOG_(INFO) << "This test does nothing as 32-bit tid is supported by pthread_mutex.\n";
1773#endif
Yabin Cui140f3672015-02-03 10:32:00 -08001774}
Yabin Cuib5845722015-03-16 22:46:42 -07001775
Yabin Cuic9a659c2015-11-05 15:36:08 -08001776TEST(pthread, pthread_mutex_timedlock) {
1777 pthread_mutex_t m;
1778 ASSERT_EQ(0, pthread_mutex_init(&m, nullptr));
1779
1780 // If the mutex is already locked, pthread_mutex_timedlock should time out.
1781 ASSERT_EQ(0, pthread_mutex_lock(&m));
1782
1783 timespec ts;
1784 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1785 ASSERT_EQ(ETIMEDOUT, pthread_mutex_timedlock(&m, &ts));
1786 ts.tv_nsec = -1;
1787 ASSERT_EQ(EINVAL, pthread_mutex_timedlock(&m, &ts));
1788 ts.tv_nsec = NS_PER_S;
1789 ASSERT_EQ(EINVAL, pthread_mutex_timedlock(&m, &ts));
1790 ts.tv_nsec = NS_PER_S - 1;
1791 ts.tv_sec = -1;
1792 ASSERT_EQ(ETIMEDOUT, pthread_mutex_timedlock(&m, &ts));
1793
1794 // If the mutex is unlocked, pthread_mutex_timedlock should succeed.
1795 ASSERT_EQ(0, pthread_mutex_unlock(&m));
1796
1797 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1798 ts.tv_sec += 1;
1799 ASSERT_EQ(0, pthread_mutex_timedlock(&m, &ts));
1800
1801 ASSERT_EQ(0, pthread_mutex_unlock(&m));
1802 ASSERT_EQ(0, pthread_mutex_destroy(&m));
1803}
1804
Yabin Cuib5845722015-03-16 22:46:42 -07001805class StrictAlignmentAllocator {
1806 public:
1807 void* allocate(size_t size, size_t alignment) {
1808 char* p = new char[size + alignment * 2];
1809 allocated_array.push_back(p);
1810 while (!is_strict_aligned(p, alignment)) {
1811 ++p;
1812 }
1813 return p;
1814 }
1815
1816 ~StrictAlignmentAllocator() {
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07001817 for (const auto& p : allocated_array) {
1818 delete[] p;
Yabin Cuib5845722015-03-16 22:46:42 -07001819 }
1820 }
1821
1822 private:
1823 bool is_strict_aligned(char* p, size_t alignment) {
1824 return (reinterpret_cast<uintptr_t>(p) % (alignment * 2)) == alignment;
1825 }
1826
1827 std::vector<char*> allocated_array;
1828};
1829
1830TEST(pthread, pthread_types_allow_four_bytes_alignment) {
1831#if defined(__BIONIC__)
1832 // For binary compatibility with old version, we need to allow 4-byte aligned data for pthread types.
1833 StrictAlignmentAllocator allocator;
1834 pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(
1835 allocator.allocate(sizeof(pthread_mutex_t), 4));
1836 ASSERT_EQ(0, pthread_mutex_init(mutex, NULL));
1837 ASSERT_EQ(0, pthread_mutex_lock(mutex));
1838 ASSERT_EQ(0, pthread_mutex_unlock(mutex));
1839 ASSERT_EQ(0, pthread_mutex_destroy(mutex));
1840
1841 pthread_cond_t* cond = reinterpret_cast<pthread_cond_t*>(
1842 allocator.allocate(sizeof(pthread_cond_t), 4));
1843 ASSERT_EQ(0, pthread_cond_init(cond, NULL));
1844 ASSERT_EQ(0, pthread_cond_signal(cond));
1845 ASSERT_EQ(0, pthread_cond_broadcast(cond));
1846 ASSERT_EQ(0, pthread_cond_destroy(cond));
1847
1848 pthread_rwlock_t* rwlock = reinterpret_cast<pthread_rwlock_t*>(
1849 allocator.allocate(sizeof(pthread_rwlock_t), 4));
1850 ASSERT_EQ(0, pthread_rwlock_init(rwlock, NULL));
1851 ASSERT_EQ(0, pthread_rwlock_rdlock(rwlock));
1852 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
1853 ASSERT_EQ(0, pthread_rwlock_wrlock(rwlock));
1854 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
1855 ASSERT_EQ(0, pthread_rwlock_destroy(rwlock));
1856
1857#else
1858 GTEST_LOG_(INFO) << "This test tests bionic implementation details.";
1859#endif
1860}
Christopher Ferris60907c72015-06-09 18:46:15 -07001861
1862TEST(pthread, pthread_mutex_lock_null_32) {
1863#if defined(__BIONIC__) && !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -07001864 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return
1865 // EINVAL in that case: http://b/19995172.
1866 //
1867 // We decorate the public defintion with _Nonnull so that people recompiling
1868 // their code with get a warning and might fix their bug, but need to pass
1869 // NULL here to test that we remain compatible.
1870 pthread_mutex_t* null_value = nullptr;
1871 ASSERT_EQ(EINVAL, pthread_mutex_lock(null_value));
Christopher Ferris60907c72015-06-09 18:46:15 -07001872#else
1873 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 32 bit devices.";
1874#endif
1875}
1876
1877TEST(pthread, pthread_mutex_unlock_null_32) {
1878#if defined(__BIONIC__) && !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -07001879 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return
1880 // EINVAL in that case: http://b/19995172.
1881 //
1882 // We decorate the public defintion with _Nonnull so that people recompiling
1883 // their code with get a warning and might fix their bug, but need to pass
1884 // NULL here to test that we remain compatible.
1885 pthread_mutex_t* null_value = nullptr;
1886 ASSERT_EQ(EINVAL, pthread_mutex_unlock(null_value));
Christopher Ferris60907c72015-06-09 18:46:15 -07001887#else
1888 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 32 bit devices.";
1889#endif
1890}
1891
1892TEST_F(pthread_DeathTest, pthread_mutex_lock_null_64) {
1893#if defined(__BIONIC__) && defined(__LP64__)
1894 pthread_mutex_t* null_value = nullptr;
1895 ASSERT_EXIT(pthread_mutex_lock(null_value), testing::KilledBySignal(SIGSEGV), "");
1896#else
1897 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 64 bit devices.";
1898#endif
1899}
1900
1901TEST_F(pthread_DeathTest, pthread_mutex_unlock_null_64) {
1902#if defined(__BIONIC__) && defined(__LP64__)
1903 pthread_mutex_t* null_value = nullptr;
1904 ASSERT_EXIT(pthread_mutex_unlock(null_value), testing::KilledBySignal(SIGSEGV), "");
1905#else
1906 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 64 bit devices.";
1907#endif
1908}
Yabin Cui33ac04a2015-09-22 11:16:15 -07001909
1910extern _Unwind_Reason_Code FrameCounter(_Unwind_Context* ctx, void* arg);
1911
1912static volatile bool signal_handler_on_altstack_done;
1913
Josh Gao61db9ac2017-03-15 19:42:05 -07001914__attribute__((__noinline__))
1915static void signal_handler_backtrace() {
1916 // Check if we have enough stack space for unwinding.
1917 int count = 0;
1918 _Unwind_Backtrace(FrameCounter, &count);
1919 ASSERT_GT(count, 0);
1920}
1921
1922__attribute__((__noinline__))
1923static void signal_handler_logging() {
1924 // Check if we have enough stack space for logging.
1925 std::string s(2048, '*');
1926 GTEST_LOG_(INFO) << s;
1927 signal_handler_on_altstack_done = true;
1928}
1929
1930__attribute__((__noinline__))
1931static void signal_handler_snprintf() {
1932 // Check if we have enough stack space for snprintf to a PATH_MAX buffer, plus some extra.
1933 char buf[PATH_MAX + 2048];
1934 ASSERT_GT(snprintf(buf, sizeof(buf), "/proc/%d/status", getpid()), 0);
1935}
1936
Yabin Cui33ac04a2015-09-22 11:16:15 -07001937static void SignalHandlerOnAltStack(int signo, siginfo_t*, void*) {
1938 ASSERT_EQ(SIGUSR1, signo);
Josh Gao61db9ac2017-03-15 19:42:05 -07001939 signal_handler_backtrace();
1940 signal_handler_logging();
1941 signal_handler_snprintf();
Yabin Cui33ac04a2015-09-22 11:16:15 -07001942}
1943
Josh Gao415daa82017-03-06 17:45:33 -08001944TEST(pthread, big_enough_signal_stack) {
Yabin Cui33ac04a2015-09-22 11:16:15 -07001945 signal_handler_on_altstack_done = false;
1946 ScopedSignalHandler handler(SIGUSR1, SignalHandlerOnAltStack, SA_SIGINFO | SA_ONSTACK);
1947 kill(getpid(), SIGUSR1);
1948 ASSERT_TRUE(signal_handler_on_altstack_done);
1949}
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001950
1951TEST(pthread, pthread_barrierattr_smoke) {
1952 pthread_barrierattr_t attr;
1953 ASSERT_EQ(0, pthread_barrierattr_init(&attr));
1954 int pshared;
1955 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
1956 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
1957 ASSERT_EQ(0, pthread_barrierattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
1958 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
1959 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
1960 ASSERT_EQ(0, pthread_barrierattr_destroy(&attr));
1961}
1962
Yabin Cui81d27972016-03-22 13:45:55 -07001963struct BarrierTestHelperData {
1964 size_t thread_count;
1965 pthread_barrier_t barrier;
1966 std::atomic<int> finished_mask;
1967 std::atomic<int> serial_thread_count;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001968 size_t iteration_count;
Yabin Cui81d27972016-03-22 13:45:55 -07001969 std::atomic<size_t> finished_iteration_count;
1970
1971 BarrierTestHelperData(size_t thread_count, size_t iteration_count)
1972 : thread_count(thread_count), finished_mask(0), serial_thread_count(0),
1973 iteration_count(iteration_count), finished_iteration_count(0) {
1974 }
1975};
1976
1977struct BarrierTestHelperArg {
1978 int id;
1979 BarrierTestHelperData* data;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001980};
1981
1982static void BarrierTestHelper(BarrierTestHelperArg* arg) {
Yabin Cui81d27972016-03-22 13:45:55 -07001983 for (size_t i = 0; i < arg->data->iteration_count; ++i) {
1984 int result = pthread_barrier_wait(&arg->data->barrier);
1985 if (result == PTHREAD_BARRIER_SERIAL_THREAD) {
1986 arg->data->serial_thread_count++;
1987 } else {
1988 ASSERT_EQ(0, result);
1989 }
Yabin Cuid5c04c52017-05-02 12:57:39 -07001990 int mask = arg->data->finished_mask.fetch_or(1 << arg->id);
Yabin Cuiab4cddc2017-05-02 16:18:13 -07001991 mask |= 1 << arg->id;
Yabin Cuid5c04c52017-05-02 12:57:39 -07001992 if (mask == ((1 << arg->data->thread_count) - 1)) {
Yabin Cui81d27972016-03-22 13:45:55 -07001993 ASSERT_EQ(1, arg->data->serial_thread_count);
1994 arg->data->finished_iteration_count++;
1995 arg->data->finished_mask = 0;
1996 arg->data->serial_thread_count = 0;
1997 }
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001998 }
1999}
2000
2001TEST(pthread, pthread_barrier_smoke) {
2002 const size_t BARRIER_ITERATION_COUNT = 10;
2003 const size_t BARRIER_THREAD_COUNT = 10;
Yabin Cui81d27972016-03-22 13:45:55 -07002004 BarrierTestHelperData data(BARRIER_THREAD_COUNT, BARRIER_ITERATION_COUNT);
2005 ASSERT_EQ(0, pthread_barrier_init(&data.barrier, nullptr, data.thread_count));
2006 std::vector<pthread_t> threads(data.thread_count);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002007 std::vector<BarrierTestHelperArg> args(threads.size());
2008 for (size_t i = 0; i < threads.size(); ++i) {
Yabin Cui81d27972016-03-22 13:45:55 -07002009 args[i].id = i;
2010 args[i].data = &data;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002011 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
2012 reinterpret_cast<void* (*)(void*)>(BarrierTestHelper), &args[i]));
2013 }
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002014 for (size_t i = 0; i < threads.size(); ++i) {
2015 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
2016 }
Yabin Cui81d27972016-03-22 13:45:55 -07002017 ASSERT_EQ(data.iteration_count, data.finished_iteration_count);
2018 ASSERT_EQ(0, pthread_barrier_destroy(&data.barrier));
2019}
2020
2021struct BarrierDestroyTestArg {
2022 std::atomic<int> tid;
2023 pthread_barrier_t* barrier;
2024};
2025
2026static void BarrierDestroyTestHelper(BarrierDestroyTestArg* arg) {
2027 arg->tid = gettid();
2028 ASSERT_EQ(0, pthread_barrier_wait(arg->barrier));
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002029}
2030
2031TEST(pthread, pthread_barrier_destroy) {
2032 pthread_barrier_t barrier;
2033 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, 2));
2034 pthread_t thread;
Yabin Cui81d27972016-03-22 13:45:55 -07002035 BarrierDestroyTestArg arg;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002036 arg.tid = 0;
2037 arg.barrier = &barrier;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002038 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui81d27972016-03-22 13:45:55 -07002039 reinterpret_cast<void* (*)(void*)>(BarrierDestroyTestHelper), &arg));
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002040 WaitUntilThreadSleep(arg.tid);
2041 ASSERT_EQ(EBUSY, pthread_barrier_destroy(&barrier));
2042 ASSERT_EQ(PTHREAD_BARRIER_SERIAL_THREAD, pthread_barrier_wait(&barrier));
2043 // Verify if the barrier can be destroyed directly after pthread_barrier_wait().
2044 ASSERT_EQ(0, pthread_barrier_destroy(&barrier));
2045 ASSERT_EQ(0, pthread_join(thread, nullptr));
2046#if defined(__BIONIC__)
2047 ASSERT_EQ(EINVAL, pthread_barrier_destroy(&barrier));
2048#endif
2049}
2050
2051struct BarrierOrderingTestHelperArg {
2052 pthread_barrier_t* barrier;
2053 size_t* array;
2054 size_t array_length;
2055 size_t id;
2056};
2057
2058void BarrierOrderingTestHelper(BarrierOrderingTestHelperArg* arg) {
2059 const size_t ITERATION_COUNT = 10000;
2060 for (size_t i = 1; i <= ITERATION_COUNT; ++i) {
2061 arg->array[arg->id] = i;
Yabin Cuic9a659c2015-11-05 15:36:08 -08002062 int result = pthread_barrier_wait(arg->barrier);
2063 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002064 for (size_t j = 0; j < arg->array_length; ++j) {
2065 ASSERT_EQ(i, arg->array[j]);
2066 }
Yabin Cuic9a659c2015-11-05 15:36:08 -08002067 result = pthread_barrier_wait(arg->barrier);
2068 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002069 }
2070}
2071
2072TEST(pthread, pthread_barrier_check_ordering) {
2073 const size_t THREAD_COUNT = 4;
2074 pthread_barrier_t barrier;
2075 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, THREAD_COUNT));
2076 size_t array[THREAD_COUNT];
2077 std::vector<pthread_t> threads(THREAD_COUNT);
2078 std::vector<BarrierOrderingTestHelperArg> args(THREAD_COUNT);
2079 for (size_t i = 0; i < THREAD_COUNT; ++i) {
2080 args[i].barrier = &barrier;
2081 args[i].array = array;
2082 args[i].array_length = THREAD_COUNT;
2083 args[i].id = i;
2084 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
2085 reinterpret_cast<void* (*)(void*)>(BarrierOrderingTestHelper),
2086 &args[i]));
2087 }
2088 for (size_t i = 0; i < THREAD_COUNT; ++i) {
2089 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
2090 }
2091}
Yabin Cuife3a83a2015-11-17 16:03:18 -08002092
2093TEST(pthread, pthread_spinlock_smoke) {
2094 pthread_spinlock_t lock;
2095 ASSERT_EQ(0, pthread_spin_init(&lock, 0));
2096 ASSERT_EQ(0, pthread_spin_trylock(&lock));
2097 ASSERT_EQ(0, pthread_spin_unlock(&lock));
2098 ASSERT_EQ(0, pthread_spin_lock(&lock));
2099 ASSERT_EQ(EBUSY, pthread_spin_trylock(&lock));
2100 ASSERT_EQ(0, pthread_spin_unlock(&lock));
2101 ASSERT_EQ(0, pthread_spin_destroy(&lock));
2102}
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002103
2104TEST(pthread, pthread_attr_setdetachstate) {
2105 pthread_attr_t attr;
2106 ASSERT_EQ(0, pthread_attr_init(&attr));
2107
2108 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
2109 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
2110 ASSERT_EQ(EINVAL, pthread_attr_setdetachstate(&attr, 123));
2111}
2112
2113TEST(pthread, pthread_create__mmap_failures) {
2114 pthread_attr_t attr;
2115 ASSERT_EQ(0, pthread_attr_init(&attr));
2116 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
2117
2118 const auto kPageSize = sysconf(_SC_PAGE_SIZE);
2119
2120 // Use up all the VMAs. By default this is 64Ki.
2121 std::vector<void*> pages;
2122 int prot = PROT_NONE;
2123 while (true) {
2124 void* page = mmap(nullptr, kPageSize, prot, MAP_ANON|MAP_PRIVATE, -1, 0);
2125 if (page == MAP_FAILED) break;
2126 pages.push_back(page);
2127 prot = (prot == PROT_NONE) ? PROT_READ : PROT_NONE;
2128 }
2129
2130 // Try creating threads, freeing up a page each time we fail.
2131 size_t EAGAIN_count = 0;
2132 size_t i = 0;
2133 for (; i < pages.size(); ++i) {
2134 pthread_t t;
2135 int status = pthread_create(&t, &attr, IdFn, nullptr);
2136 if (status != EAGAIN) break;
2137 ++EAGAIN_count;
2138 ASSERT_EQ(0, munmap(pages[i], kPageSize));
2139 }
2140
2141 // Creating a thread uses at least six VMAs: the stack, the TLS, and a guard each side of both.
2142 // So we should have seen at least six failures.
2143 ASSERT_GE(EAGAIN_count, 6U);
2144
2145 for (; i < pages.size(); ++i) {
2146 ASSERT_EQ(0, munmap(pages[i], kPageSize));
2147 }
2148}