blob: 8345a47f9bf21c5424d55fe793fc094cb5ee6186 [file] [log] [blame]
Elliott Hughesbfeab1b2012-09-05 17:47:37 -07001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <gtest/gtest.h>
18
19#include <errno.h>
Elliott Hughes5b9310e2013-10-02 16:59:05 -070020#include <inttypes.h>
Elliott Hughesb95cf0d2013-07-15 14:51:07 -070021#include <limits.h>
Elliott Hughes04620a32014-03-07 17:59:05 -080022#include <malloc.h>
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070023#include <pthread.h>
Christopher Ferrisf04935c2013-12-20 18:43:21 -080024#include <signal.h>
Yabin Cui140f3672015-02-03 10:32:00 -080025#include <stdio.h>
Elliott Hughes70b24b12013-11-15 11:51:07 -080026#include <sys/mman.h>
Elliott Hughes4d098ca2016-04-11 12:43:05 -070027#include <sys/prctl.h>
Elliott Hughes57b7a612014-08-25 17:26:50 -070028#include <sys/syscall.h>
Narayan Kamath51e6cb32014-03-03 15:38:51 +000029#include <time.h>
Elliott Hughes4d014e12012-09-07 16:47:54 -070030#include <unistd.h>
Yabin Cui33ac04a2015-09-22 11:16:15 -070031#include <unwind.h>
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070032
Yabin Cui08ee8d22015-02-11 17:04:36 -080033#include <atomic>
Yabin Cuib5845722015-03-16 22:46:42 -070034#include <vector>
Yabin Cui08ee8d22015-02-11 17:04:36 -080035
Yabin Cuic9a659c2015-11-05 15:36:08 -080036#include "private/bionic_constants.h"
Yabin Cui17393b02015-03-21 15:08:25 -070037#include "private/bionic_macros.h"
38#include "private/ScopeGuard.h"
39#include "BionicDeathTest.h"
40#include "ScopedSignalHandler.h"
Elliott Hughes15dfd632015-09-22 16:40:14 -070041#include "utils.h"
42
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070043TEST(pthread, pthread_key_create) {
44 pthread_key_t key;
45 ASSERT_EQ(0, pthread_key_create(&key, NULL));
46 ASSERT_EQ(0, pthread_key_delete(key));
47 // Can't delete a key that's already been deleted.
48 ASSERT_EQ(EINVAL, pthread_key_delete(key));
49}
Elliott Hughes4d014e12012-09-07 16:47:54 -070050
Dan Albertc4bcc752014-09-30 11:48:24 -070051TEST(pthread, pthread_keys_max) {
Yabin Cui6c238f22014-12-11 20:50:41 -080052 // POSIX says PTHREAD_KEYS_MAX should be at least _POSIX_THREAD_KEYS_MAX.
53 ASSERT_GE(PTHREAD_KEYS_MAX, _POSIX_THREAD_KEYS_MAX);
Dan Albertc4bcc752014-09-30 11:48:24 -070054}
Elliott Hughes718a5b52014-01-28 17:02:03 -080055
Yabin Cui6c238f22014-12-11 20:50:41 -080056TEST(pthread, sysconf_SC_THREAD_KEYS_MAX_eq_PTHREAD_KEYS_MAX) {
Dan Albertc4bcc752014-09-30 11:48:24 -070057 int sysconf_max = sysconf(_SC_THREAD_KEYS_MAX);
Yabin Cui6c238f22014-12-11 20:50:41 -080058 ASSERT_EQ(sysconf_max, PTHREAD_KEYS_MAX);
Dan Albertc4bcc752014-09-30 11:48:24 -070059}
60
61TEST(pthread, pthread_key_many_distinct) {
Yabin Cui6c238f22014-12-11 20:50:41 -080062 // As gtest uses pthread keys, we can't allocate exactly PTHREAD_KEYS_MAX
63 // pthread keys, but We should be able to allocate at least this many keys.
64 int nkeys = PTHREAD_KEYS_MAX / 2;
Dan Albertc4bcc752014-09-30 11:48:24 -070065 std::vector<pthread_key_t> keys;
66
67 auto scope_guard = make_scope_guard([&keys]{
Elliott Hughes0b2acdf2015-10-02 18:25:19 -070068 for (const auto& key : keys) {
Dan Albertc4bcc752014-09-30 11:48:24 -070069 EXPECT_EQ(0, pthread_key_delete(key));
70 }
71 });
72
73 for (int i = 0; i < nkeys; ++i) {
74 pthread_key_t key;
Elliott Hughes61706932015-03-31 10:56:58 -070075 // If this fails, it's likely that LIBC_PTHREAD_KEY_RESERVED_COUNT is wrong.
Dan Albertc4bcc752014-09-30 11:48:24 -070076 ASSERT_EQ(0, pthread_key_create(&key, NULL)) << i << " of " << nkeys;
77 keys.push_back(key);
78 ASSERT_EQ(0, pthread_setspecific(key, reinterpret_cast<void*>(i)));
79 }
80
81 for (int i = keys.size() - 1; i >= 0; --i) {
82 ASSERT_EQ(reinterpret_cast<void*>(i), pthread_getspecific(keys.back()));
83 pthread_key_t key = keys.back();
84 keys.pop_back();
85 ASSERT_EQ(0, pthread_key_delete(key));
86 }
87}
88
Yabin Cui6c238f22014-12-11 20:50:41 -080089TEST(pthread, pthread_key_not_exceed_PTHREAD_KEYS_MAX) {
Elliott Hughes44b53ad2013-02-11 20:18:47 +000090 std::vector<pthread_key_t> keys;
Dan Albertc4bcc752014-09-30 11:48:24 -070091 int rv = 0;
Yabin Cui6c238f22014-12-11 20:50:41 -080092
93 // Pthread keys are used by gtest, so PTHREAD_KEYS_MAX should
94 // be more than we are allowed to allocate now.
95 for (int i = 0; i < PTHREAD_KEYS_MAX; i++) {
Elliott Hughes44b53ad2013-02-11 20:18:47 +000096 pthread_key_t key;
Dan Albertc4bcc752014-09-30 11:48:24 -070097 rv = pthread_key_create(&key, NULL);
98 if (rv == EAGAIN) {
99 break;
100 }
101 EXPECT_EQ(0, rv);
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000102 keys.push_back(key);
103 }
104
Dan Albertc4bcc752014-09-30 11:48:24 -0700105 // Don't leak keys.
Elliott Hughes0b2acdf2015-10-02 18:25:19 -0700106 for (const auto& key : keys) {
Dan Albertc4bcc752014-09-30 11:48:24 -0700107 EXPECT_EQ(0, pthread_key_delete(key));
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000108 }
Dan Albertc4bcc752014-09-30 11:48:24 -0700109 keys.clear();
110
111 // We should have eventually reached the maximum number of keys and received
112 // EAGAIN.
113 ASSERT_EQ(EAGAIN, rv);
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000114}
115
Elliott Hughesebb770f2014-06-25 13:46:46 -0700116TEST(pthread, pthread_key_delete) {
117 void* expected = reinterpret_cast<void*>(1234);
118 pthread_key_t key;
119 ASSERT_EQ(0, pthread_key_create(&key, NULL));
120 ASSERT_EQ(0, pthread_setspecific(key, expected));
121 ASSERT_EQ(expected, pthread_getspecific(key));
122 ASSERT_EQ(0, pthread_key_delete(key));
123 // After deletion, pthread_getspecific returns NULL.
124 ASSERT_EQ(NULL, pthread_getspecific(key));
125 // And you can't use pthread_setspecific with the deleted key.
126 ASSERT_EQ(EINVAL, pthread_setspecific(key, expected));
127}
128
Elliott Hughes40a52172014-07-30 14:48:10 -0700129TEST(pthread, pthread_key_fork) {
130 void* expected = reinterpret_cast<void*>(1234);
131 pthread_key_t key;
132 ASSERT_EQ(0, pthread_key_create(&key, NULL));
133 ASSERT_EQ(0, pthread_setspecific(key, expected));
134 ASSERT_EQ(expected, pthread_getspecific(key));
135
136 pid_t pid = fork();
137 ASSERT_NE(-1, pid) << strerror(errno);
138
139 if (pid == 0) {
140 // The surviving thread inherits all the forking thread's TLS values...
141 ASSERT_EQ(expected, pthread_getspecific(key));
142 _exit(99);
143 }
144
Elliott Hughes33697a02016-01-26 13:04:57 -0800145 AssertChildExited(pid, 99);
Elliott Hughes40a52172014-07-30 14:48:10 -0700146
147 ASSERT_EQ(expected, pthread_getspecific(key));
Dan Albert1d53ae22014-09-02 15:24:26 -0700148 ASSERT_EQ(0, pthread_key_delete(key));
Elliott Hughes40a52172014-07-30 14:48:10 -0700149}
150
151static void* DirtyKeyFn(void* key) {
152 return pthread_getspecific(*reinterpret_cast<pthread_key_t*>(key));
153}
154
155TEST(pthread, pthread_key_dirty) {
156 pthread_key_t key;
157 ASSERT_EQ(0, pthread_key_create(&key, NULL));
158
Yabin Cuia36158a2015-11-16 21:06:16 -0800159 size_t stack_size = 640 * 1024;
Elliott Hughes40a52172014-07-30 14:48:10 -0700160 void* stack = mmap(NULL, stack_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
161 ASSERT_NE(MAP_FAILED, stack);
162 memset(stack, 0xff, stack_size);
163
164 pthread_attr_t attr;
165 ASSERT_EQ(0, pthread_attr_init(&attr));
166 ASSERT_EQ(0, pthread_attr_setstack(&attr, stack, stack_size));
167
168 pthread_t t;
169 ASSERT_EQ(0, pthread_create(&t, &attr, DirtyKeyFn, &key));
170
171 void* result;
172 ASSERT_EQ(0, pthread_join(t, &result));
173 ASSERT_EQ(nullptr, result); // Not ~0!
174
175 ASSERT_EQ(0, munmap(stack, stack_size));
Dan Albert1d53ae22014-09-02 15:24:26 -0700176 ASSERT_EQ(0, pthread_key_delete(key));
Elliott Hughes40a52172014-07-30 14:48:10 -0700177}
178
Yabin Cui5ddbb3f2015-03-05 20:35:32 -0800179TEST(pthread, static_pthread_key_used_before_creation) {
180#if defined(__BIONIC__)
181 // See http://b/19625804. The bug is about a static/global pthread key being used before creation.
182 // So here tests if the static/global default value 0 can be detected as invalid key.
183 static pthread_key_t key;
184 ASSERT_EQ(nullptr, pthread_getspecific(key));
185 ASSERT_EQ(EINVAL, pthread_setspecific(key, nullptr));
186 ASSERT_EQ(EINVAL, pthread_key_delete(key));
187#else
188 GTEST_LOG_(INFO) << "This test tests bionic pthread key implementation detail.\n";
189#endif
190}
191
Elliott Hughes4d014e12012-09-07 16:47:54 -0700192static void* IdFn(void* arg) {
193 return arg;
194}
195
Yabin Cui63481602014-12-01 17:41:04 -0800196class SpinFunctionHelper {
197 public:
198 SpinFunctionHelper() {
199 SpinFunctionHelper::spin_flag_ = true;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400200 }
Yabin Cui63481602014-12-01 17:41:04 -0800201 ~SpinFunctionHelper() {
202 UnSpin();
203 }
204 auto GetFunction() -> void* (*)(void*) {
205 return SpinFunctionHelper::SpinFn;
206 }
207
208 void UnSpin() {
209 SpinFunctionHelper::spin_flag_ = false;
210 }
211
212 private:
213 static void* SpinFn(void*) {
214 while (spin_flag_) {}
215 return NULL;
216 }
Yabin Cuia36158a2015-11-16 21:06:16 -0800217 static std::atomic<bool> spin_flag_;
Yabin Cui63481602014-12-01 17:41:04 -0800218};
219
220// It doesn't matter if spin_flag_ is used in several tests,
221// because it is always set to false after each test. Each thread
222// loops on spin_flag_ can find it becomes false at some time.
Yabin Cuia36158a2015-11-16 21:06:16 -0800223std::atomic<bool> SpinFunctionHelper::spin_flag_;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400224
Elliott Hughes4d014e12012-09-07 16:47:54 -0700225static void* JoinFn(void* arg) {
226 return reinterpret_cast<void*>(pthread_join(reinterpret_cast<pthread_t>(arg), NULL));
227}
228
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400229static void AssertDetached(pthread_t t, bool is_detached) {
230 pthread_attr_t attr;
231 ASSERT_EQ(0, pthread_getattr_np(t, &attr));
232 int detach_state;
233 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &detach_state));
234 pthread_attr_destroy(&attr);
235 ASSERT_EQ(is_detached, (detach_state == PTHREAD_CREATE_DETACHED));
236}
237
Elliott Hughes7484c212017-02-02 02:41:38 +0000238static void MakeDeadThread(pthread_t& t) {
239 ASSERT_EQ(0, pthread_create(&t, NULL, IdFn, NULL));
240 ASSERT_EQ(0, pthread_join(t, NULL));
241}
242
Elliott Hughes4d014e12012-09-07 16:47:54 -0700243TEST(pthread, pthread_create) {
244 void* expected_result = reinterpret_cast<void*>(123);
245 // Can we create a thread?
246 pthread_t t;
247 ASSERT_EQ(0, pthread_create(&t, NULL, IdFn, expected_result));
248 // If we join, do we get the expected value back?
249 void* result;
250 ASSERT_EQ(0, pthread_join(t, &result));
251 ASSERT_EQ(expected_result, result);
252}
253
Elliott Hughes3e898472013-02-12 16:40:24 +0000254TEST(pthread, pthread_create_EAGAIN) {
255 pthread_attr_t attributes;
256 ASSERT_EQ(0, pthread_attr_init(&attributes));
257 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, static_cast<size_t>(-1) & ~(getpagesize() - 1)));
258
259 pthread_t t;
260 ASSERT_EQ(EAGAIN, pthread_create(&t, &attributes, IdFn, NULL));
261}
262
Elliott Hughes4d014e12012-09-07 16:47:54 -0700263TEST(pthread, pthread_no_join_after_detach) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700264 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800265
Elliott Hughes4d014e12012-09-07 16:47:54 -0700266 pthread_t t1;
Elliott Hughes725b2a92016-03-23 11:20:47 -0700267 ASSERT_EQ(0, pthread_create(&t1, NULL, spin_helper.GetFunction(), NULL));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700268
269 // After a pthread_detach...
270 ASSERT_EQ(0, pthread_detach(t1));
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400271 AssertDetached(t1, true);
Elliott Hughes4d014e12012-09-07 16:47:54 -0700272
273 // ...pthread_join should fail.
Elliott Hughes34c987a2014-09-22 16:01:26 -0700274 ASSERT_EQ(EINVAL, pthread_join(t1, NULL));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700275}
276
277TEST(pthread, pthread_no_op_detach_after_join) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700278 SpinFunctionHelper spin_helper;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400279
Elliott Hughes4d014e12012-09-07 16:47:54 -0700280 pthread_t t1;
Elliott Hughes725b2a92016-03-23 11:20:47 -0700281 ASSERT_EQ(0, pthread_create(&t1, NULL, spin_helper.GetFunction(), NULL));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700282
283 // If thread 2 is already waiting to join thread 1...
284 pthread_t t2;
285 ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1)));
286
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400287 sleep(1); // (Give t2 a chance to call pthread_join.)
Elliott Hughes4d014e12012-09-07 16:47:54 -0700288
Yabin Cuibbb04322015-03-19 15:19:25 -0700289#if defined(__BIONIC__)
290 ASSERT_EQ(EINVAL, pthread_detach(t1));
291#else
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400292 ASSERT_EQ(0, pthread_detach(t1));
Yabin Cuibbb04322015-03-19 15:19:25 -0700293#endif
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400294 AssertDetached(t1, false);
295
Elliott Hughes725b2a92016-03-23 11:20:47 -0700296 spin_helper.UnSpin();
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400297
298 // ...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 -0700299 void* join_result;
300 ASSERT_EQ(0, pthread_join(t2, &join_result));
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700301 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700302}
Elliott Hughes14f19592012-10-29 10:19:44 -0700303
304TEST(pthread, pthread_join_self) {
Elliott Hughes34c987a2014-09-22 16:01:26 -0700305 ASSERT_EQ(EDEADLK, pthread_join(pthread_self(), NULL));
Elliott Hughes14f19592012-10-29 10:19:44 -0700306}
Elliott Hughes4f251be2012-11-01 16:33:29 -0700307
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800308struct TestBug37410 {
309 pthread_t main_thread;
310 pthread_mutex_t mutex;
Elliott Hughes4f251be2012-11-01 16:33:29 -0700311
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800312 static void main() {
313 TestBug37410 data;
314 data.main_thread = pthread_self();
315 ASSERT_EQ(0, pthread_mutex_init(&data.mutex, NULL));
316 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
317
318 pthread_t t;
319 ASSERT_EQ(0, pthread_create(&t, NULL, TestBug37410::thread_fn, reinterpret_cast<void*>(&data)));
320
321 // Wait for the thread to be running...
322 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
323 ASSERT_EQ(0, pthread_mutex_unlock(&data.mutex));
324
325 // ...and exit.
326 pthread_exit(NULL);
327 }
328
329 private:
330 static void* thread_fn(void* arg) {
331 TestBug37410* data = reinterpret_cast<TestBug37410*>(arg);
332
333 // Let the main thread know we're running.
334 pthread_mutex_unlock(&data->mutex);
335
336 // And wait for the main thread to exit.
337 pthread_join(data->main_thread, NULL);
338
339 return NULL;
340 }
341};
Elliott Hughes4f251be2012-11-01 16:33:29 -0700342
Elliott Hughes7fd803c2013-02-14 16:33:52 -0800343// Even though this isn't really a death test, we have to say "DeathTest" here so gtest knows to
344// run this test (which exits normally) in its own process.
Yabin Cui9df70402014-11-05 18:01:01 -0800345
346class pthread_DeathTest : public BionicDeathTest {};
347
348TEST_F(pthread_DeathTest, pthread_bug_37410) {
Elliott Hughes4f251be2012-11-01 16:33:29 -0700349 // http://code.google.com/p/android/issues/detail?id=37410
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800350 ASSERT_EXIT(TestBug37410::main(), ::testing::ExitedWithCode(0), "");
Elliott Hughes4f251be2012-11-01 16:33:29 -0700351}
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800352
353static void* SignalHandlerFn(void* arg) {
354 sigset_t wait_set;
355 sigfillset(&wait_set);
356 return reinterpret_cast<void*>(sigwait(&wait_set, reinterpret_cast<int*>(arg)));
357}
358
359TEST(pthread, pthread_sigmask) {
Elliott Hughes19e62322013-10-15 11:23:57 -0700360 // Check that SIGUSR1 isn't blocked.
361 sigset_t original_set;
362 sigemptyset(&original_set);
363 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, NULL, &original_set));
364 ASSERT_FALSE(sigismember(&original_set, SIGUSR1));
365
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800366 // Block SIGUSR1.
367 sigset_t set;
368 sigemptyset(&set);
369 sigaddset(&set, SIGUSR1);
370 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, &set, NULL));
371
Elliott Hughes19e62322013-10-15 11:23:57 -0700372 // Check that SIGUSR1 is blocked.
373 sigset_t final_set;
374 sigemptyset(&final_set);
375 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, NULL, &final_set));
376 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
377 // ...and that sigprocmask agrees with pthread_sigmask.
378 sigemptyset(&final_set);
379 ASSERT_EQ(0, sigprocmask(SIG_BLOCK, NULL, &final_set));
380 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
381
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800382 // Spawn a thread that calls sigwait and tells us what it received.
383 pthread_t signal_thread;
384 int received_signal = -1;
385 ASSERT_EQ(0, pthread_create(&signal_thread, NULL, SignalHandlerFn, &received_signal));
386
387 // Send that thread SIGUSR1.
388 pthread_kill(signal_thread, SIGUSR1);
389
390 // See what it got.
391 void* join_result;
392 ASSERT_EQ(0, pthread_join(signal_thread, &join_result));
393 ASSERT_EQ(SIGUSR1, received_signal);
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700394 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
Elliott Hughes19e62322013-10-15 11:23:57 -0700395
396 // Restore the original signal mask.
397 ASSERT_EQ(0, pthread_sigmask(SIG_SETMASK, &original_set, NULL));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800398}
Elliott Hughes5e3fc432013-02-11 16:36:48 -0800399
Elliott Hughes725b2a92016-03-23 11:20:47 -0700400static void test_pthread_setname_np__pthread_getname_np(pthread_t t) {
401 ASSERT_EQ(0, pthread_setname_np(t, "short"));
402 char name[32];
403 ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name)));
404 ASSERT_STREQ("short", name);
405
Elliott Hughesd1aea302015-04-25 10:05:24 -0700406 // The limit is 15 characters --- the kernel's buffer is 16, but includes a NUL.
Elliott Hughes725b2a92016-03-23 11:20:47 -0700407 ASSERT_EQ(0, pthread_setname_np(t, "123456789012345"));
408 ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name)));
409 ASSERT_STREQ("123456789012345", name);
410
411 ASSERT_EQ(ERANGE, pthread_setname_np(t, "1234567890123456"));
412
413 // The passed-in buffer should be at least 16 bytes.
414 ASSERT_EQ(0, pthread_getname_np(t, name, 16));
415 ASSERT_EQ(ERANGE, pthread_getname_np(t, name, 15));
Elliott Hughes3e898472013-02-12 16:40:24 +0000416}
417
Elliott Hughes725b2a92016-03-23 11:20:47 -0700418TEST(pthread, pthread_setname_np__pthread_getname_np__self) {
419 test_pthread_setname_np__pthread_getname_np(pthread_self());
Elliott Hughes3e898472013-02-12 16:40:24 +0000420}
421
Elliott Hughes725b2a92016-03-23 11:20:47 -0700422TEST(pthread, pthread_setname_np__pthread_getname_np__other) {
423 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800424
Elliott Hughes725b2a92016-03-23 11:20:47 -0700425 pthread_t t;
Elliott Hughes4d098ca2016-04-11 12:43:05 -0700426 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
427 test_pthread_setname_np__pthread_getname_np(t);
428 spin_helper.UnSpin();
429 ASSERT_EQ(0, pthread_join(t, nullptr));
430}
431
432// http://b/28051133: a kernel misfeature means that you can't change the
433// name of another thread if you've set PR_SET_DUMPABLE to 0.
434TEST(pthread, pthread_setname_np__pthread_getname_np__other_PR_SET_DUMPABLE) {
435 ASSERT_EQ(0, prctl(PR_SET_DUMPABLE, 0)) << strerror(errno);
436
437 SpinFunctionHelper spin_helper;
438
439 pthread_t t;
440 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
Elliott Hughes725b2a92016-03-23 11:20:47 -0700441 test_pthread_setname_np__pthread_getname_np(t);
442 spin_helper.UnSpin();
443 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes3e898472013-02-12 16:40:24 +0000444}
445
Elliott Hughes9d23e042013-02-15 19:21:51 -0800446TEST(pthread, pthread_kill__0) {
447 // Signal 0 just tests that the thread exists, so it's safe to call on ourselves.
448 ASSERT_EQ(0, pthread_kill(pthread_self(), 0));
449}
450
451TEST(pthread, pthread_kill__invalid_signal) {
452 ASSERT_EQ(EINVAL, pthread_kill(pthread_self(), -1));
453}
454
Elliott Hughesfae89fc2013-02-21 11:22:23 -0800455static void pthread_kill__in_signal_handler_helper(int signal_number) {
456 static int count = 0;
457 ASSERT_EQ(SIGALRM, signal_number);
458 if (++count == 1) {
459 // Can we call pthread_kill from a signal handler?
460 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
461 }
462}
463
464TEST(pthread, pthread_kill__in_signal_handler) {
Elliott Hughes4b558f52014-03-04 15:58:02 -0800465 ScopedSignalHandler ssh(SIGALRM, pthread_kill__in_signal_handler_helper);
Elliott Hughesfae89fc2013-02-21 11:22:23 -0800466 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
467}
468
Elliott Hughes7484c212017-02-02 02:41:38 +0000469TEST(pthread, pthread_detach__no_such_thread) {
470 pthread_t dead_thread;
471 MakeDeadThread(dead_thread);
472
473 ASSERT_EQ(ESRCH, pthread_detach(dead_thread));
474}
475
Jeff Hao9b06cc32013-08-15 14:51:16 -0700476TEST(pthread, pthread_getcpuclockid__clock_gettime) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700477 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800478
Jeff Hao9b06cc32013-08-15 14:51:16 -0700479 pthread_t t;
Elliott Hughes725b2a92016-03-23 11:20:47 -0700480 ASSERT_EQ(0, pthread_create(&t, NULL, spin_helper.GetFunction(), NULL));
Jeff Hao9b06cc32013-08-15 14:51:16 -0700481
482 clockid_t c;
483 ASSERT_EQ(0, pthread_getcpuclockid(t, &c));
484 timespec ts;
485 ASSERT_EQ(0, clock_gettime(c, &ts));
Elliott Hughes725b2a92016-03-23 11:20:47 -0700486 spin_helper.UnSpin();
Yabin Cuia36158a2015-11-16 21:06:16 -0800487 ASSERT_EQ(0, pthread_join(t, nullptr));
Jeff Hao9b06cc32013-08-15 14:51:16 -0700488}
489
Elliott Hughes7484c212017-02-02 02:41:38 +0000490TEST(pthread, pthread_join__no_such_thread) {
491 pthread_t dead_thread;
492 MakeDeadThread(dead_thread);
493
494 ASSERT_EQ(ESRCH, pthread_join(dead_thread, NULL));
495}
496
497TEST(pthread, pthread_kill__no_such_thread) {
498 pthread_t dead_thread;
499 MakeDeadThread(dead_thread);
500
501 ASSERT_EQ(ESRCH, pthread_kill(dead_thread, 0));
502}
503
msg5550f020d12013-06-06 14:59:28 -0400504TEST(pthread, pthread_join__multijoin) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700505 SpinFunctionHelper spin_helper;
msg5550f020d12013-06-06 14:59:28 -0400506
507 pthread_t t1;
Elliott Hughes725b2a92016-03-23 11:20:47 -0700508 ASSERT_EQ(0, pthread_create(&t1, NULL, spin_helper.GetFunction(), NULL));
msg5550f020d12013-06-06 14:59:28 -0400509
510 pthread_t t2;
511 ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1)));
512
513 sleep(1); // (Give t2 a chance to call pthread_join.)
514
515 // Multiple joins to the same thread should fail.
516 ASSERT_EQ(EINVAL, pthread_join(t1, NULL));
517
Elliott Hughes725b2a92016-03-23 11:20:47 -0700518 spin_helper.UnSpin();
msg5550f020d12013-06-06 14:59:28 -0400519
520 // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes).
521 void* join_result;
522 ASSERT_EQ(0, pthread_join(t2, &join_result));
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700523 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
msg5550f020d12013-06-06 14:59:28 -0400524}
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700525
Elliott Hughes70b24b12013-11-15 11:51:07 -0800526TEST(pthread, pthread_join__race) {
527 // http://b/11693195 --- pthread_join could return before the thread had actually exited.
528 // If the joiner unmapped the thread's stack, that could lead to SIGSEGV in the thread.
529 for (size_t i = 0; i < 1024; ++i) {
Yabin Cuia36158a2015-11-16 21:06:16 -0800530 size_t stack_size = 640*1024;
Elliott Hughes70b24b12013-11-15 11:51:07 -0800531 void* stack = mmap(NULL, stack_size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
532
533 pthread_attr_t a;
534 pthread_attr_init(&a);
535 pthread_attr_setstack(&a, stack, stack_size);
536
537 pthread_t t;
538 ASSERT_EQ(0, pthread_create(&t, &a, IdFn, NULL));
539 ASSERT_EQ(0, pthread_join(t, NULL));
540 ASSERT_EQ(0, munmap(stack, stack_size));
541 }
542}
543
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700544static void* GetActualGuardSizeFn(void* arg) {
545 pthread_attr_t attributes;
546 pthread_getattr_np(pthread_self(), &attributes);
547 pthread_attr_getguardsize(&attributes, reinterpret_cast<size_t*>(arg));
548 return NULL;
549}
550
551static size_t GetActualGuardSize(const pthread_attr_t& attributes) {
552 size_t result;
553 pthread_t t;
554 pthread_create(&t, &attributes, GetActualGuardSizeFn, &result);
Elliott Hughes34c987a2014-09-22 16:01:26 -0700555 pthread_join(t, NULL);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700556 return result;
557}
558
559static void* GetActualStackSizeFn(void* arg) {
560 pthread_attr_t attributes;
561 pthread_getattr_np(pthread_self(), &attributes);
562 pthread_attr_getstacksize(&attributes, reinterpret_cast<size_t*>(arg));
563 return NULL;
564}
565
566static size_t GetActualStackSize(const pthread_attr_t& attributes) {
567 size_t result;
568 pthread_t t;
569 pthread_create(&t, &attributes, GetActualStackSizeFn, &result);
Elliott Hughes34c987a2014-09-22 16:01:26 -0700570 pthread_join(t, NULL);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700571 return result;
572}
573
574TEST(pthread, pthread_attr_setguardsize) {
575 pthread_attr_t attributes;
576 ASSERT_EQ(0, pthread_attr_init(&attributes));
577
578 // Get the default guard size.
579 size_t default_guard_size;
580 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &default_guard_size));
581
582 // No such thing as too small: will be rounded up to one page by pthread_create.
583 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 128));
584 size_t guard_size;
585 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
586 ASSERT_EQ(128U, guard_size);
587 ASSERT_EQ(4096U, GetActualGuardSize(attributes));
588
589 // Large enough and a multiple of the page size.
590 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024));
591 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
592 ASSERT_EQ(32*1024U, guard_size);
593
594 // Large enough but not a multiple of the page size; will be rounded up by pthread_create.
595 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024 + 1));
596 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
597 ASSERT_EQ(32*1024U + 1, guard_size);
598}
599
600TEST(pthread, pthread_attr_setstacksize) {
601 pthread_attr_t attributes;
602 ASSERT_EQ(0, pthread_attr_init(&attributes));
603
604 // Get the default stack size.
605 size_t default_stack_size;
606 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &default_stack_size));
607
608 // Too small.
609 ASSERT_EQ(EINVAL, pthread_attr_setstacksize(&attributes, 128));
610 size_t stack_size;
611 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
612 ASSERT_EQ(default_stack_size, stack_size);
613 ASSERT_GE(GetActualStackSize(attributes), default_stack_size);
614
Yabin Cui917d3902015-01-08 12:32:42 -0800615 // Large enough and a multiple of the page size; may be rounded up by pthread_create.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700616 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024));
617 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
618 ASSERT_EQ(32*1024U, stack_size);
Yabin Cui917d3902015-01-08 12:32:42 -0800619 ASSERT_GE(GetActualStackSize(attributes), 32*1024U);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700620
Yabin Cui917d3902015-01-08 12:32:42 -0800621 // Large enough but not aligned; will be rounded up by pthread_create.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700622 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024 + 1));
623 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
624 ASSERT_EQ(32*1024U + 1, stack_size);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800625#if defined(__BIONIC__)
Yabin Cui917d3902015-01-08 12:32:42 -0800626 ASSERT_GT(GetActualStackSize(attributes), 32*1024U + 1);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800627#else // __BIONIC__
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700628 // glibc rounds down, in violation of POSIX. They document this in their BUGS section.
629 ASSERT_EQ(GetActualStackSize(attributes), 32*1024U);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800630#endif // __BIONIC__
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700631}
Elliott Hughesc3f11402013-10-30 14:40:09 -0700632
Yabin Cui76615da2015-03-17 14:22:09 -0700633TEST(pthread, pthread_rwlockattr_smoke) {
634 pthread_rwlockattr_t attr;
635 ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
636
637 int pshared_value_array[] = {PTHREAD_PROCESS_PRIVATE, PTHREAD_PROCESS_SHARED};
638 for (size_t i = 0; i < sizeof(pshared_value_array) / sizeof(pshared_value_array[0]); ++i) {
639 ASSERT_EQ(0, pthread_rwlockattr_setpshared(&attr, pshared_value_array[i]));
640 int pshared;
641 ASSERT_EQ(0, pthread_rwlockattr_getpshared(&attr, &pshared));
642 ASSERT_EQ(pshared_value_array[i], pshared);
643 }
644
645 int kind_array[] = {PTHREAD_RWLOCK_PREFER_READER_NP,
646 PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP};
647 for (size_t i = 0; i < sizeof(kind_array) / sizeof(kind_array[0]); ++i) {
648 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_array[i]));
649 int kind;
650 ASSERT_EQ(0, pthread_rwlockattr_getkind_np(&attr, &kind));
651 ASSERT_EQ(kind_array[i], kind);
652 }
653
654 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
655}
656
657TEST(pthread, pthread_rwlock_init_same_as_PTHREAD_RWLOCK_INITIALIZER) {
658 pthread_rwlock_t lock1 = PTHREAD_RWLOCK_INITIALIZER;
659 pthread_rwlock_t lock2;
660 ASSERT_EQ(0, pthread_rwlock_init(&lock2, NULL));
661 ASSERT_EQ(0, memcmp(&lock1, &lock2, sizeof(lock1)));
662}
663
Elliott Hughesc3f11402013-10-30 14:40:09 -0700664TEST(pthread, pthread_rwlock_smoke) {
665 pthread_rwlock_t l;
666 ASSERT_EQ(0, pthread_rwlock_init(&l, NULL));
667
Calin Juravle76f352e2014-05-19 13:41:10 +0100668 // Single read lock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700669 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
670 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
671
Calin Juravle76f352e2014-05-19 13:41:10 +0100672 // Multiple read lock
673 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
674 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
675 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
676 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
677
678 // Write lock
Calin Juravle92687e42014-05-22 19:21:22 +0100679 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
680 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100681
682 // Try writer lock
683 ASSERT_EQ(0, pthread_rwlock_trywrlock(&l));
684 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
685 ASSERT_EQ(EBUSY, pthread_rwlock_tryrdlock(&l));
686 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
687
688 // Try reader lock
689 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
690 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
691 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
692 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
693 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
694
695 // Try writer lock after unlock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700696 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
697 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
698
Calin Juravle76f352e2014-05-19 13:41:10 +0100699 // EDEADLK in "read after write"
700 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
701 ASSERT_EQ(EDEADLK, pthread_rwlock_rdlock(&l));
702 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
703
704 // EDEADLK in "write after write"
705 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
706 ASSERT_EQ(EDEADLK, pthread_rwlock_wrlock(&l));
707 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100708
Elliott Hughesc3f11402013-10-30 14:40:09 -0700709 ASSERT_EQ(0, pthread_rwlock_destroy(&l));
710}
711
Yabin Cui08ee8d22015-02-11 17:04:36 -0800712struct RwlockWakeupHelperArg {
713 pthread_rwlock_t lock;
714 enum Progress {
715 LOCK_INITIALIZED,
716 LOCK_WAITING,
717 LOCK_RELEASED,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800718 LOCK_ACCESSED,
719 LOCK_TIMEDOUT,
Yabin Cui08ee8d22015-02-11 17:04:36 -0800720 };
721 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -0700722 std::atomic<pid_t> tid;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800723 std::function<int (pthread_rwlock_t*)> trylock_function;
724 std::function<int (pthread_rwlock_t*)> lock_function;
725 std::function<int (pthread_rwlock_t*, const timespec*)> timed_lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800726};
727
Yabin Cuic9a659c2015-11-05 15:36:08 -0800728static void pthread_rwlock_wakeup_helper(RwlockWakeupHelperArg* arg) {
Yabin Cuif7969852015-04-02 17:47:48 -0700729 arg->tid = gettid();
Yabin Cui08ee8d22015-02-11 17:04:36 -0800730 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
731 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
732
Yabin Cuic9a659c2015-11-05 15:36:08 -0800733 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
734 ASSERT_EQ(0, arg->lock_function(&arg->lock));
Yabin Cui08ee8d22015-02-11 17:04:36 -0800735 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_RELEASED, arg->progress);
736 ASSERT_EQ(0, pthread_rwlock_unlock(&arg->lock));
737
738 arg->progress = RwlockWakeupHelperArg::LOCK_ACCESSED;
739}
740
Yabin Cuic9a659c2015-11-05 15:36:08 -0800741static void test_pthread_rwlock_reader_wakeup_writer(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -0800742 RwlockWakeupHelperArg wakeup_arg;
743 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, NULL));
744 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
745 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -0700746 wakeup_arg.tid = 0;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800747 wakeup_arg.trylock_function = pthread_rwlock_trywrlock;
748 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800749
750 pthread_t thread;
751 ASSERT_EQ(0, pthread_create(&thread, NULL,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800752 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -0700753 WaitUntilThreadSleep(wakeup_arg.tid);
754 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
755
Yabin Cui08ee8d22015-02-11 17:04:36 -0800756 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
757 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
758
759 ASSERT_EQ(0, pthread_join(thread, NULL));
760 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
761 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
762}
763
Yabin Cuic9a659c2015-11-05 15:36:08 -0800764TEST(pthread, pthread_rwlock_reader_wakeup_writer) {
765 test_pthread_rwlock_reader_wakeup_writer(pthread_rwlock_wrlock);
Yabin Cui08ee8d22015-02-11 17:04:36 -0800766}
767
Yabin Cuic9a659c2015-11-05 15:36:08 -0800768TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait) {
769 timespec ts;
770 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
771 ts.tv_sec += 1;
772 test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) {
773 return pthread_rwlock_timedwrlock(lock, &ts);
774 });
775}
776
777static void test_pthread_rwlock_writer_wakeup_reader(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -0800778 RwlockWakeupHelperArg wakeup_arg;
779 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, NULL));
780 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
781 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -0700782 wakeup_arg.tid = 0;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800783 wakeup_arg.trylock_function = pthread_rwlock_tryrdlock;
784 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800785
786 pthread_t thread;
787 ASSERT_EQ(0, pthread_create(&thread, NULL,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800788 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -0700789 WaitUntilThreadSleep(wakeup_arg.tid);
790 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
791
Yabin Cui08ee8d22015-02-11 17:04:36 -0800792 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
793 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
794
795 ASSERT_EQ(0, pthread_join(thread, NULL));
796 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
797 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
798}
799
Yabin Cuic9a659c2015-11-05 15:36:08 -0800800TEST(pthread, pthread_rwlock_writer_wakeup_reader) {
801 test_pthread_rwlock_writer_wakeup_reader(pthread_rwlock_rdlock);
802}
803
804TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait) {
805 timespec ts;
806 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
807 ts.tv_sec += 1;
808 test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) {
809 return pthread_rwlock_timedrdlock(lock, &ts);
810 });
811}
812
813static void pthread_rwlock_wakeup_timeout_helper(RwlockWakeupHelperArg* arg) {
814 arg->tid = gettid();
815 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
816 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
817
818 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
819
820 timespec ts;
821 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
822 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
823 ts.tv_nsec = -1;
824 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
825 ts.tv_nsec = NS_PER_S;
826 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
827 ts.tv_nsec = NS_PER_S - 1;
828 ts.tv_sec = -1;
829 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
830 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
831 ts.tv_sec += 1;
832 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
833 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, arg->progress);
834 arg->progress = RwlockWakeupHelperArg::LOCK_TIMEDOUT;
835}
836
837TEST(pthread, pthread_rwlock_timedrdlock_timeout) {
838 RwlockWakeupHelperArg wakeup_arg;
839 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
840 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
841 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
842 wakeup_arg.tid = 0;
843 wakeup_arg.trylock_function = pthread_rwlock_tryrdlock;
844 wakeup_arg.timed_lock_function = pthread_rwlock_timedrdlock;
845
846 pthread_t thread;
847 ASSERT_EQ(0, pthread_create(&thread, nullptr,
848 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
849 WaitUntilThreadSleep(wakeup_arg.tid);
850 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
851
852 ASSERT_EQ(0, pthread_join(thread, nullptr));
853 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
854 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
855 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
856}
857
858TEST(pthread, pthread_rwlock_timedwrlock_timeout) {
859 RwlockWakeupHelperArg wakeup_arg;
860 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
861 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
862 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
863 wakeup_arg.tid = 0;
864 wakeup_arg.trylock_function = pthread_rwlock_trywrlock;
865 wakeup_arg.timed_lock_function = pthread_rwlock_timedwrlock;
866
867 pthread_t thread;
868 ASSERT_EQ(0, pthread_create(&thread, nullptr,
869 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
870 WaitUntilThreadSleep(wakeup_arg.tid);
871 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
872
873 ASSERT_EQ(0, pthread_join(thread, nullptr));
874 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
875 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
876 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
877}
878
Yabin Cui76615da2015-03-17 14:22:09 -0700879class RwlockKindTestHelper {
880 private:
881 struct ThreadArg {
882 RwlockKindTestHelper* helper;
883 std::atomic<pid_t>& tid;
884
885 ThreadArg(RwlockKindTestHelper* helper, std::atomic<pid_t>& tid)
886 : helper(helper), tid(tid) { }
887 };
888
889 public:
890 pthread_rwlock_t lock;
891
892 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -0700893 explicit RwlockKindTestHelper(int kind_type) {
Yabin Cui76615da2015-03-17 14:22:09 -0700894 InitRwlock(kind_type);
895 }
896
897 ~RwlockKindTestHelper() {
898 DestroyRwlock();
899 }
900
901 void CreateWriterThread(pthread_t& thread, std::atomic<pid_t>& tid) {
902 tid = 0;
903 ThreadArg* arg = new ThreadArg(this, tid);
904 ASSERT_EQ(0, pthread_create(&thread, NULL,
905 reinterpret_cast<void* (*)(void*)>(WriterThreadFn), arg));
906 }
907
908 void CreateReaderThread(pthread_t& thread, std::atomic<pid_t>& tid) {
909 tid = 0;
910 ThreadArg* arg = new ThreadArg(this, tid);
911 ASSERT_EQ(0, pthread_create(&thread, NULL,
912 reinterpret_cast<void* (*)(void*)>(ReaderThreadFn), arg));
913 }
914
915 private:
916 void InitRwlock(int kind_type) {
917 pthread_rwlockattr_t attr;
918 ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
919 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_type));
920 ASSERT_EQ(0, pthread_rwlock_init(&lock, &attr));
921 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
922 }
923
924 void DestroyRwlock() {
925 ASSERT_EQ(0, pthread_rwlock_destroy(&lock));
926 }
927
928 static void WriterThreadFn(ThreadArg* arg) {
929 arg->tid = gettid();
930
931 RwlockKindTestHelper* helper = arg->helper;
932 ASSERT_EQ(0, pthread_rwlock_wrlock(&helper->lock));
933 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
934 delete arg;
935 }
936
937 static void ReaderThreadFn(ThreadArg* arg) {
938 arg->tid = gettid();
939
940 RwlockKindTestHelper* helper = arg->helper;
941 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper->lock));
942 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
943 delete arg;
944 }
945};
946
947TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_READER_NP) {
948 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_READER_NP);
949 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
950
951 pthread_t writer_thread;
952 std::atomic<pid_t> writer_tid;
953 helper.CreateWriterThread(writer_thread, writer_tid);
954 WaitUntilThreadSleep(writer_tid);
955
956 pthread_t reader_thread;
957 std::atomic<pid_t> reader_tid;
958 helper.CreateReaderThread(reader_thread, reader_tid);
959 ASSERT_EQ(0, pthread_join(reader_thread, NULL));
960
961 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
962 ASSERT_EQ(0, pthread_join(writer_thread, NULL));
963}
964
965TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP) {
966 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
967 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
968
969 pthread_t writer_thread;
970 std::atomic<pid_t> writer_tid;
971 helper.CreateWriterThread(writer_thread, writer_tid);
972 WaitUntilThreadSleep(writer_tid);
973
974 pthread_t reader_thread;
975 std::atomic<pid_t> reader_tid;
976 helper.CreateReaderThread(reader_thread, reader_tid);
977 WaitUntilThreadSleep(reader_tid);
978
979 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
980 ASSERT_EQ(0, pthread_join(writer_thread, NULL));
981 ASSERT_EQ(0, pthread_join(reader_thread, NULL));
982}
983
Elliott Hughes1728b232014-05-14 10:02:03 -0700984static int g_once_fn_call_count = 0;
Elliott Hughesc3f11402013-10-30 14:40:09 -0700985static void OnceFn() {
Elliott Hughes1728b232014-05-14 10:02:03 -0700986 ++g_once_fn_call_count;
Elliott Hughesc3f11402013-10-30 14:40:09 -0700987}
988
989TEST(pthread, pthread_once_smoke) {
990 pthread_once_t once_control = PTHREAD_ONCE_INIT;
991 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
992 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
Elliott Hughes1728b232014-05-14 10:02:03 -0700993 ASSERT_EQ(1, g_once_fn_call_count);
Elliott Hughesc3f11402013-10-30 14:40:09 -0700994}
995
Elliott Hughes3694ec62014-05-14 11:46:08 -0700996static std::string pthread_once_1934122_result = "";
997
998static void Routine2() {
999 pthread_once_1934122_result += "2";
1000}
1001
1002static void Routine1() {
1003 pthread_once_t once_control_2 = PTHREAD_ONCE_INIT;
1004 pthread_once_1934122_result += "1";
1005 pthread_once(&once_control_2, &Routine2);
1006}
1007
1008TEST(pthread, pthread_once_1934122) {
1009 // Very old versions of Android couldn't call pthread_once from a
1010 // pthread_once init routine. http://b/1934122.
1011 pthread_once_t once_control_1 = PTHREAD_ONCE_INIT;
1012 ASSERT_EQ(0, pthread_once(&once_control_1, &Routine1));
1013 ASSERT_EQ("12", pthread_once_1934122_result);
1014}
1015
Elliott Hughes1728b232014-05-14 10:02:03 -07001016static int g_atfork_prepare_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001017static void AtForkPrepare1() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 1; }
1018static void AtForkPrepare2() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -07001019static int g_atfork_parent_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001020static void AtForkParent1() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 1; }
1021static void AtForkParent2() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -07001022static int g_atfork_child_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001023static void AtForkChild1() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 1; }
1024static void AtForkChild2() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 2; }
Elliott Hughesc3f11402013-10-30 14:40:09 -07001025
Dmitriy Ivanov00e37812014-11-20 16:53:47 -08001026TEST(pthread, pthread_atfork_smoke) {
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001027 ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1));
1028 ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2));
Elliott Hughesc3f11402013-10-30 14:40:09 -07001029
Elliott Hughes33697a02016-01-26 13:04:57 -08001030 pid_t pid = fork();
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001031 ASSERT_NE(-1, pid) << strerror(errno);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001032
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001033 // Child and parent calls are made in the order they were registered.
1034 if (pid == 0) {
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001035 ASSERT_EQ(12, g_atfork_child_calls);
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001036 _exit(0);
1037 }
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001038 ASSERT_EQ(12, g_atfork_parent_calls);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001039
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001040 // Prepare calls are made in the reverse order.
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001041 ASSERT_EQ(21, g_atfork_prepare_calls);
Elliott Hughes33697a02016-01-26 13:04:57 -08001042 AssertChildExited(pid, 0);
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001043}
1044
Elliott Hughesc3f11402013-10-30 14:40:09 -07001045TEST(pthread, pthread_attr_getscope) {
1046 pthread_attr_t attr;
1047 ASSERT_EQ(0, pthread_attr_init(&attr));
1048
1049 int scope;
1050 ASSERT_EQ(0, pthread_attr_getscope(&attr, &scope));
1051 ASSERT_EQ(PTHREAD_SCOPE_SYSTEM, scope);
1052}
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001053
1054TEST(pthread, pthread_condattr_init) {
1055 pthread_condattr_t attr;
1056 pthread_condattr_init(&attr);
1057
1058 clockid_t clock;
1059 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1060 ASSERT_EQ(CLOCK_REALTIME, clock);
1061
1062 int pshared;
1063 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1064 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
1065}
1066
1067TEST(pthread, pthread_condattr_setclock) {
1068 pthread_condattr_t attr;
1069 pthread_condattr_init(&attr);
1070
1071 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_REALTIME));
1072 clockid_t clock;
1073 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1074 ASSERT_EQ(CLOCK_REALTIME, clock);
1075
1076 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1077 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1078 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1079
1080 ASSERT_EQ(EINVAL, pthread_condattr_setclock(&attr, CLOCK_PROCESS_CPUTIME_ID));
1081}
1082
1083TEST(pthread, pthread_cond_broadcast__preserves_condattr_flags) {
Yabin Cui32651b82015-03-13 20:30:00 -07001084#if defined(__BIONIC__)
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001085 pthread_condattr_t attr;
1086 pthread_condattr_init(&attr);
1087
1088 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1089 ASSERT_EQ(0, pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
1090
1091 pthread_cond_t cond_var;
1092 ASSERT_EQ(0, pthread_cond_init(&cond_var, &attr));
1093
1094 ASSERT_EQ(0, pthread_cond_signal(&cond_var));
1095 ASSERT_EQ(0, pthread_cond_broadcast(&cond_var));
1096
Yabin Cui32651b82015-03-13 20:30:00 -07001097 attr = static_cast<pthread_condattr_t>(*reinterpret_cast<uint32_t*>(cond_var.__private));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001098 clockid_t clock;
1099 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1100 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1101 int pshared;
1102 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1103 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
Yabin Cui32651b82015-03-13 20:30:00 -07001104#else // !defined(__BIONIC__)
1105 GTEST_LOG_(INFO) << "This tests a bionic implementation detail.\n";
1106#endif // !defined(__BIONIC__)
1107}
1108
1109class pthread_CondWakeupTest : public ::testing::Test {
1110 protected:
1111 pthread_mutex_t mutex;
1112 pthread_cond_t cond;
1113
1114 enum Progress {
1115 INITIALIZED,
1116 WAITING,
1117 SIGNALED,
1118 FINISHED,
1119 };
1120 std::atomic<Progress> progress;
1121 pthread_t thread;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001122 std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function;
Yabin Cui32651b82015-03-13 20:30:00 -07001123
1124 protected:
Yabin Cuic9a659c2015-11-05 15:36:08 -08001125 void SetUp() override {
1126 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1127 }
1128
1129 void InitCond(clockid_t clock=CLOCK_REALTIME) {
1130 pthread_condattr_t attr;
1131 ASSERT_EQ(0, pthread_condattr_init(&attr));
1132 ASSERT_EQ(0, pthread_condattr_setclock(&attr, clock));
1133 ASSERT_EQ(0, pthread_cond_init(&cond, &attr));
1134 ASSERT_EQ(0, pthread_condattr_destroy(&attr));
1135 }
1136
1137 void StartWaitingThread(std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function) {
Yabin Cui32651b82015-03-13 20:30:00 -07001138 progress = INITIALIZED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001139 this->wait_function = wait_function;
1140 ASSERT_EQ(0, pthread_create(&thread, NULL, reinterpret_cast<void* (*)(void*)>(WaitThreadFn), this));
1141 while (progress != WAITING) {
Yabin Cui32651b82015-03-13 20:30:00 -07001142 usleep(5000);
1143 }
1144 usleep(5000);
1145 }
1146
Yabin Cuic9a659c2015-11-05 15:36:08 -08001147 void TearDown() override {
1148 ASSERT_EQ(0, pthread_join(thread, nullptr));
1149 ASSERT_EQ(FINISHED, progress);
1150 ASSERT_EQ(0, pthread_cond_destroy(&cond));
1151 ASSERT_EQ(0, pthread_mutex_destroy(&mutex));
1152 }
1153
Yabin Cui32651b82015-03-13 20:30:00 -07001154 private:
1155 static void WaitThreadFn(pthread_CondWakeupTest* test) {
1156 ASSERT_EQ(0, pthread_mutex_lock(&test->mutex));
1157 test->progress = WAITING;
1158 while (test->progress == WAITING) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001159 ASSERT_EQ(0, test->wait_function(&test->cond, &test->mutex));
Yabin Cui32651b82015-03-13 20:30:00 -07001160 }
1161 ASSERT_EQ(SIGNALED, test->progress);
1162 test->progress = FINISHED;
1163 ASSERT_EQ(0, pthread_mutex_unlock(&test->mutex));
1164 }
1165};
1166
Yabin Cuic9a659c2015-11-05 15:36:08 -08001167TEST_F(pthread_CondWakeupTest, signal_wait) {
1168 InitCond();
1169 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1170 return pthread_cond_wait(cond, mutex);
1171 });
Yabin Cui32651b82015-03-13 20:30:00 -07001172 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001173 ASSERT_EQ(0, pthread_cond_signal(&cond));
Yabin Cui32651b82015-03-13 20:30:00 -07001174}
1175
Yabin Cuic9a659c2015-11-05 15:36:08 -08001176TEST_F(pthread_CondWakeupTest, broadcast_wait) {
1177 InitCond();
1178 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1179 return pthread_cond_wait(cond, mutex);
1180 });
Yabin Cui32651b82015-03-13 20:30:00 -07001181 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001182 ASSERT_EQ(0, pthread_cond_broadcast(&cond));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001183}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001184
Yabin Cuic9a659c2015-11-05 15:36:08 -08001185TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_REALTIME) {
1186 InitCond(CLOCK_REALTIME);
Elliott Hughes0e714a52014-03-03 16:42:47 -08001187 timespec ts;
1188 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001189 ts.tv_sec += 1;
1190 StartWaitingThread([&](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1191 return pthread_cond_timedwait(cond, mutex, &ts);
1192 });
1193 progress = SIGNALED;
1194 ASSERT_EQ(0, pthread_cond_signal(&cond));
1195}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001196
Yabin Cuic9a659c2015-11-05 15:36:08 -08001197TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC) {
1198 InitCond(CLOCK_MONOTONIC);
1199 timespec ts;
1200 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1201 ts.tv_sec += 1;
1202 StartWaitingThread([&](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1203 return pthread_cond_timedwait(cond, mutex, &ts);
1204 });
1205 progress = SIGNALED;
1206 ASSERT_EQ(0, pthread_cond_signal(&cond));
1207}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001208
Yabin Cuic9a659c2015-11-05 15:36:08 -08001209TEST(pthread, pthread_cond_timedwait_timeout) {
1210 pthread_mutex_t mutex;
1211 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1212 pthread_cond_t cond;
1213 ASSERT_EQ(0, pthread_cond_init(&cond, nullptr));
1214 ASSERT_EQ(0, pthread_mutex_lock(&mutex));
1215 timespec ts;
Elliott Hughes0e714a52014-03-03 16:42:47 -08001216 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001217 ASSERT_EQ(ETIMEDOUT, pthread_cond_timedwait(&cond, &mutex, &ts));
1218 ts.tv_nsec = -1;
1219 ASSERT_EQ(EINVAL, pthread_cond_timedwait(&cond, &mutex, &ts));
1220 ts.tv_nsec = NS_PER_S;
1221 ASSERT_EQ(EINVAL, pthread_cond_timedwait(&cond, &mutex, &ts));
1222 ts.tv_nsec = NS_PER_S - 1;
1223 ts.tv_sec = -1;
1224 ASSERT_EQ(ETIMEDOUT, pthread_cond_timedwait(&cond, &mutex, &ts));
1225 ASSERT_EQ(0, pthread_mutex_unlock(&mutex));
Elliott Hughes0e714a52014-03-03 16:42:47 -08001226}
Elliott Hughes57b7a612014-08-25 17:26:50 -07001227
1228TEST(pthread, pthread_attr_getstack__main_thread) {
1229 // This test is only meaningful for the main thread, so make sure we're running on it!
1230 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1231
1232 // Get the main thread's attributes.
1233 pthread_attr_t attributes;
1234 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1235
1236 // Check that we correctly report that the main thread has no guard page.
1237 size_t guard_size;
1238 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
1239 ASSERT_EQ(0U, guard_size); // The main thread has no guard page.
1240
1241 // Get the stack base and the stack size (both ways).
1242 void* stack_base;
1243 size_t stack_size;
1244 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1245 size_t stack_size2;
1246 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1247
1248 // The two methods of asking for the stack size should agree.
1249 EXPECT_EQ(stack_size, stack_size2);
1250
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001251#if defined(__BIONIC__)
Elliott Hughes57b7a612014-08-25 17:26:50 -07001252 // What does /proc/self/maps' [stack] line say?
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001253 void* maps_stack_hi = NULL;
Elliott Hughes15dfd632015-09-22 16:40:14 -07001254 std::vector<map_record> maps;
1255 ASSERT_TRUE(Maps::parse_maps(&maps));
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07001256 for (const auto& map : maps) {
Elliott Hughes15dfd632015-09-22 16:40:14 -07001257 if (map.pathname == "[stack]") {
1258 maps_stack_hi = reinterpret_cast<void*>(map.addr_end);
Elliott Hughes57b7a612014-08-25 17:26:50 -07001259 break;
1260 }
1261 }
Elliott Hughes57b7a612014-08-25 17:26:50 -07001262
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001263 // The high address of the /proc/self/maps [stack] region should equal stack_base + stack_size.
1264 // Remember that the stack grows down (and is mapped in on demand), so the low address of the
1265 // region isn't very interesting.
1266 EXPECT_EQ(maps_stack_hi, reinterpret_cast<uint8_t*>(stack_base) + stack_size);
1267
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001268 // The stack size should correspond to RLIMIT_STACK.
Elliott Hughes57b7a612014-08-25 17:26:50 -07001269 rlimit rl;
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001270 ASSERT_EQ(0, getrlimit(RLIMIT_STACK, &rl));
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001271 uint64_t original_rlim_cur = rl.rlim_cur;
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001272 if (rl.rlim_cur == RLIM_INFINITY) {
1273 rl.rlim_cur = 8 * 1024 * 1024; // Bionic reports unlimited stacks as 8MiB.
1274 }
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001275 EXPECT_EQ(rl.rlim_cur, stack_size);
1276
Dmitriy Ivanovd9ff7222014-09-08 16:22:22 -07001277 auto guard = make_scope_guard([&rl, original_rlim_cur]() {
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001278 rl.rlim_cur = original_rlim_cur;
1279 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1280 });
1281
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001282 //
1283 // What if RLIMIT_STACK is smaller than the stack's current extent?
1284 //
Elliott Hughes57b7a612014-08-25 17:26:50 -07001285 rl.rlim_cur = rl.rlim_max = 1024; // 1KiB. We know the stack must be at least a page already.
1286 rl.rlim_max = RLIM_INFINITY;
1287 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1288
1289 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1290 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1291 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1292
1293 EXPECT_EQ(stack_size, stack_size2);
1294 ASSERT_EQ(1024U, stack_size);
1295
1296 //
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001297 // What if RLIMIT_STACK isn't a whole number of pages?
Elliott Hughes57b7a612014-08-25 17:26:50 -07001298 //
1299 rl.rlim_cur = rl.rlim_max = 6666; // Not a whole number of pages.
1300 rl.rlim_max = RLIM_INFINITY;
1301 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1302
1303 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1304 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1305 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1306
1307 EXPECT_EQ(stack_size, stack_size2);
1308 ASSERT_EQ(6666U, stack_size);
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001309#endif
Elliott Hughes57b7a612014-08-25 17:26:50 -07001310}
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001311
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001312struct GetStackSignalHandlerArg {
1313 volatile bool done;
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001314 void* signal_stack_base;
1315 size_t signal_stack_size;
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001316 void* main_stack_base;
1317 size_t main_stack_size;
1318};
1319
1320static GetStackSignalHandlerArg getstack_signal_handler_arg;
1321
1322static void getstack_signal_handler(int sig) {
1323 ASSERT_EQ(SIGUSR1, sig);
1324 // Use sleep() to make current thread be switched out by the kernel to provoke the error.
1325 sleep(1);
1326 pthread_attr_t attr;
1327 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1328 void* stack_base;
1329 size_t stack_size;
1330 ASSERT_EQ(0, pthread_attr_getstack(&attr, &stack_base, &stack_size));
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001331
1332 // Verify if the stack used by the signal handler is the alternate stack just registered.
1333 ASSERT_LE(getstack_signal_handler_arg.signal_stack_base, &attr);
1334 ASSERT_LT(static_cast<void*>(&attr),
1335 static_cast<char*>(getstack_signal_handler_arg.signal_stack_base) +
1336 getstack_signal_handler_arg.signal_stack_size);
1337
1338 // Verify if the main thread's stack got in the signal handler is correct.
1339 ASSERT_EQ(getstack_signal_handler_arg.main_stack_base, stack_base);
1340 ASSERT_LE(getstack_signal_handler_arg.main_stack_size, stack_size);
1341
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001342 getstack_signal_handler_arg.done = true;
1343}
1344
1345// The previous code obtained the main thread's stack by reading the entry in
1346// /proc/self/task/<pid>/maps that was labeled [stack]. Unfortunately, on x86/x86_64, the kernel
1347// relies on sp0 in task state segment(tss) to label the stack map with [stack]. If the kernel
1348// switches a process while the main thread is in an alternate stack, then the kernel will label
1349// the wrong map with [stack]. This test verifies that when the above situation happens, the main
1350// thread's stack is found correctly.
1351TEST(pthread, pthread_attr_getstack_in_signal_handler) {
Yabin Cui61e4d462016-03-07 17:44:58 -08001352 // This test is only meaningful for the main thread, so make sure we're running on it!
1353 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1354
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001355 const size_t sig_stack_size = 16 * 1024;
1356 void* sig_stack = mmap(NULL, sig_stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS,
1357 -1, 0);
1358 ASSERT_NE(MAP_FAILED, sig_stack);
1359 stack_t ss;
1360 ss.ss_sp = sig_stack;
1361 ss.ss_size = sig_stack_size;
1362 ss.ss_flags = 0;
1363 stack_t oss;
1364 ASSERT_EQ(0, sigaltstack(&ss, &oss));
1365
Yabin Cui61e4d462016-03-07 17:44:58 -08001366 pthread_attr_t attr;
1367 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1368 void* main_stack_base;
1369 size_t main_stack_size;
1370 ASSERT_EQ(0, pthread_attr_getstack(&attr, &main_stack_base, &main_stack_size));
1371
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001372 ScopedSignalHandler handler(SIGUSR1, getstack_signal_handler, SA_ONSTACK);
1373 getstack_signal_handler_arg.done = false;
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001374 getstack_signal_handler_arg.signal_stack_base = sig_stack;
1375 getstack_signal_handler_arg.signal_stack_size = sig_stack_size;
1376 getstack_signal_handler_arg.main_stack_base = main_stack_base;
1377 getstack_signal_handler_arg.main_stack_size = main_stack_size;
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001378 kill(getpid(), SIGUSR1);
1379 ASSERT_EQ(true, getstack_signal_handler_arg.done);
1380
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001381 ASSERT_EQ(0, sigaltstack(&oss, nullptr));
1382 ASSERT_EQ(0, munmap(sig_stack, sig_stack_size));
1383}
1384
Yabin Cui917d3902015-01-08 12:32:42 -08001385static void pthread_attr_getstack_18908062_helper(void*) {
1386 char local_variable;
1387 pthread_attr_t attributes;
1388 pthread_getattr_np(pthread_self(), &attributes);
1389 void* stack_base;
1390 size_t stack_size;
1391 pthread_attr_getstack(&attributes, &stack_base, &stack_size);
1392
1393 // Test whether &local_variable is in [stack_base, stack_base + stack_size).
1394 ASSERT_LE(reinterpret_cast<char*>(stack_base), &local_variable);
1395 ASSERT_LT(&local_variable, reinterpret_cast<char*>(stack_base) + stack_size);
1396}
1397
1398// Check whether something on stack is in the range of
1399// [stack_base, stack_base + stack_size). see b/18908062.
1400TEST(pthread, pthread_attr_getstack_18908062) {
1401 pthread_t t;
1402 ASSERT_EQ(0, pthread_create(&t, NULL,
1403 reinterpret_cast<void* (*)(void*)>(pthread_attr_getstack_18908062_helper),
1404 NULL));
1405 pthread_join(t, NULL);
1406}
1407
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001408#if defined(__BIONIC__)
Elliott Hughesf2083612015-11-11 13:32:28 -08001409static pthread_mutex_t pthread_gettid_np_mutex = PTHREAD_MUTEX_INITIALIZER;
1410
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001411static void* pthread_gettid_np_helper(void* arg) {
1412 *reinterpret_cast<pid_t*>(arg) = gettid();
Elliott Hughesf2083612015-11-11 13:32:28 -08001413
1414 // Wait for our parent to call pthread_gettid_np on us before exiting.
1415 pthread_mutex_lock(&pthread_gettid_np_mutex);
1416 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001417 return NULL;
1418}
1419#endif
1420
1421TEST(pthread, pthread_gettid_np) {
1422#if defined(__BIONIC__)
1423 ASSERT_EQ(gettid(), pthread_gettid_np(pthread_self()));
1424
Elliott Hughesf2083612015-11-11 13:32:28 -08001425 // Ensure the other thread doesn't exit until after we've called
1426 // pthread_gettid_np on it.
1427 pthread_mutex_lock(&pthread_gettid_np_mutex);
1428
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001429 pid_t t_gettid_result;
1430 pthread_t t;
1431 pthread_create(&t, NULL, pthread_gettid_np_helper, &t_gettid_result);
1432
1433 pid_t t_pthread_gettid_np_result = pthread_gettid_np(t);
1434
Elliott Hughesf2083612015-11-11 13:32:28 -08001435 // Release the other thread and wait for it to exit.
1436 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Elliott Hughes34c987a2014-09-22 16:01:26 -07001437 pthread_join(t, NULL);
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001438
1439 ASSERT_EQ(t_gettid_result, t_pthread_gettid_np_result);
1440#else
1441 GTEST_LOG_(INFO) << "This test does nothing.\n";
1442#endif
1443}
Elliott Hughes34c987a2014-09-22 16:01:26 -07001444
1445static size_t cleanup_counter = 0;
1446
Derek Xue41996952014-09-25 11:05:32 +01001447static void AbortCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001448 abort();
1449}
1450
Derek Xue41996952014-09-25 11:05:32 +01001451static void CountCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001452 ++cleanup_counter;
1453}
1454
Derek Xue41996952014-09-25 11:05:32 +01001455static void PthreadCleanupTester() {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001456 pthread_cleanup_push(CountCleanupRoutine, NULL);
1457 pthread_cleanup_push(CountCleanupRoutine, NULL);
1458 pthread_cleanup_push(AbortCleanupRoutine, NULL);
1459
1460 pthread_cleanup_pop(0); // Pop the abort without executing it.
1461 pthread_cleanup_pop(1); // Pop one count while executing it.
1462 ASSERT_EQ(1U, cleanup_counter);
1463 // Exit while the other count is still on the cleanup stack.
1464 pthread_exit(NULL);
1465
1466 // Calls to pthread_cleanup_pop/pthread_cleanup_push must always be balanced.
1467 pthread_cleanup_pop(0);
1468}
1469
Derek Xue41996952014-09-25 11:05:32 +01001470static void* PthreadCleanupStartRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001471 PthreadCleanupTester();
1472 return NULL;
1473}
1474
1475TEST(pthread, pthread_cleanup_push__pthread_cleanup_pop) {
1476 pthread_t t;
1477 ASSERT_EQ(0, pthread_create(&t, NULL, PthreadCleanupStartRoutine, NULL));
1478 pthread_join(t, NULL);
1479 ASSERT_EQ(2U, cleanup_counter);
1480}
Derek Xue41996952014-09-25 11:05:32 +01001481
1482TEST(pthread, PTHREAD_MUTEX_DEFAULT_is_PTHREAD_MUTEX_NORMAL) {
1483 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_DEFAULT);
1484}
1485
1486TEST(pthread, pthread_mutexattr_gettype) {
1487 pthread_mutexattr_t attr;
1488 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1489
1490 int attr_type;
1491
1492 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL));
1493 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1494 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, attr_type);
1495
1496 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK));
1497 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1498 ASSERT_EQ(PTHREAD_MUTEX_ERRORCHECK, attr_type);
1499
1500 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE));
1501 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1502 ASSERT_EQ(PTHREAD_MUTEX_RECURSIVE, attr_type);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001503
1504 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
1505}
1506
Yabin Cui17393b02015-03-21 15:08:25 -07001507struct PthreadMutex {
1508 pthread_mutex_t lock;
1509
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -07001510 explicit PthreadMutex(int mutex_type) {
Yabin Cui17393b02015-03-21 15:08:25 -07001511 init(mutex_type);
1512 }
1513
1514 ~PthreadMutex() {
1515 destroy();
1516 }
1517
1518 private:
1519 void init(int mutex_type) {
1520 pthread_mutexattr_t attr;
1521 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1522 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, mutex_type));
1523 ASSERT_EQ(0, pthread_mutex_init(&lock, &attr));
1524 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
1525 }
1526
1527 void destroy() {
1528 ASSERT_EQ(0, pthread_mutex_destroy(&lock));
1529 }
1530
1531 DISALLOW_COPY_AND_ASSIGN(PthreadMutex);
1532};
Derek Xue41996952014-09-25 11:05:32 +01001533
1534TEST(pthread, pthread_mutex_lock_NORMAL) {
Yabin Cui17393b02015-03-21 15:08:25 -07001535 PthreadMutex m(PTHREAD_MUTEX_NORMAL);
Derek Xue41996952014-09-25 11:05:32 +01001536
Yabin Cui17393b02015-03-21 15:08:25 -07001537 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1538 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08001539 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
1540 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
1541 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01001542}
1543
1544TEST(pthread, pthread_mutex_lock_ERRORCHECK) {
Yabin Cui17393b02015-03-21 15:08:25 -07001545 PthreadMutex m(PTHREAD_MUTEX_ERRORCHECK);
Derek Xue41996952014-09-25 11:05:32 +01001546
Yabin Cui17393b02015-03-21 15:08:25 -07001547 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1548 ASSERT_EQ(EDEADLK, pthread_mutex_lock(&m.lock));
1549 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1550 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
1551 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
1552 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1553 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01001554}
1555
1556TEST(pthread, pthread_mutex_lock_RECURSIVE) {
Yabin Cui17393b02015-03-21 15:08:25 -07001557 PthreadMutex m(PTHREAD_MUTEX_RECURSIVE);
Derek Xue41996952014-09-25 11:05:32 +01001558
Yabin Cui17393b02015-03-21 15:08:25 -07001559 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1560 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1561 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1562 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1563 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08001564 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
1565 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07001566 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1567 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
1568}
1569
1570TEST(pthread, pthread_mutex_init_same_as_static_initializers) {
1571 pthread_mutex_t lock_normal = PTHREAD_MUTEX_INITIALIZER;
1572 PthreadMutex m1(PTHREAD_MUTEX_NORMAL);
1573 ASSERT_EQ(0, memcmp(&lock_normal, &m1.lock, sizeof(pthread_mutex_t)));
1574 pthread_mutex_destroy(&lock_normal);
1575
1576 pthread_mutex_t lock_errorcheck = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
1577 PthreadMutex m2(PTHREAD_MUTEX_ERRORCHECK);
1578 ASSERT_EQ(0, memcmp(&lock_errorcheck, &m2.lock, sizeof(pthread_mutex_t)));
1579 pthread_mutex_destroy(&lock_errorcheck);
1580
1581 pthread_mutex_t lock_recursive = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
1582 PthreadMutex m3(PTHREAD_MUTEX_RECURSIVE);
1583 ASSERT_EQ(0, memcmp(&lock_recursive, &m3.lock, sizeof(pthread_mutex_t)));
1584 ASSERT_EQ(0, pthread_mutex_destroy(&lock_recursive));
Derek Xue41996952014-09-25 11:05:32 +01001585}
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001586class MutexWakeupHelper {
1587 private:
Yabin Cui17393b02015-03-21 15:08:25 -07001588 PthreadMutex m;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001589 enum Progress {
1590 LOCK_INITIALIZED,
1591 LOCK_WAITING,
1592 LOCK_RELEASED,
1593 LOCK_ACCESSED
1594 };
1595 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -07001596 std::atomic<pid_t> tid;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001597
1598 static void thread_fn(MutexWakeupHelper* helper) {
Yabin Cuif7969852015-04-02 17:47:48 -07001599 helper->tid = gettid();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001600 ASSERT_EQ(LOCK_INITIALIZED, helper->progress);
1601 helper->progress = LOCK_WAITING;
1602
Yabin Cui17393b02015-03-21 15:08:25 -07001603 ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001604 ASSERT_EQ(LOCK_RELEASED, helper->progress);
Yabin Cui17393b02015-03-21 15:08:25 -07001605 ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001606
1607 helper->progress = LOCK_ACCESSED;
1608 }
1609
1610 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -07001611 explicit MutexWakeupHelper(int mutex_type) : m(mutex_type) {
Yabin Cui17393b02015-03-21 15:08:25 -07001612 }
1613
1614 void test() {
1615 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001616 progress = LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -07001617 tid = 0;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001618
1619 pthread_t thread;
1620 ASSERT_EQ(0, pthread_create(&thread, NULL,
1621 reinterpret_cast<void* (*)(void*)>(MutexWakeupHelper::thread_fn), this));
1622
Yabin Cuif7969852015-04-02 17:47:48 -07001623 WaitUntilThreadSleep(tid);
1624 ASSERT_EQ(LOCK_WAITING, progress);
1625
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001626 progress = LOCK_RELEASED;
Yabin Cui17393b02015-03-21 15:08:25 -07001627 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001628
1629 ASSERT_EQ(0, pthread_join(thread, NULL));
1630 ASSERT_EQ(LOCK_ACCESSED, progress);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001631 }
1632};
1633
1634TEST(pthread, pthread_mutex_NORMAL_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07001635 MutexWakeupHelper helper(PTHREAD_MUTEX_NORMAL);
1636 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001637}
1638
1639TEST(pthread, pthread_mutex_ERRORCHECK_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07001640 MutexWakeupHelper helper(PTHREAD_MUTEX_ERRORCHECK);
1641 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001642}
1643
1644TEST(pthread, pthread_mutex_RECURSIVE_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07001645 MutexWakeupHelper helper(PTHREAD_MUTEX_RECURSIVE);
1646 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001647}
1648
Yabin Cui140f3672015-02-03 10:32:00 -08001649TEST(pthread, pthread_mutex_owner_tid_limit) {
Yabin Cuie69c2452015-02-13 16:21:25 -08001650#if defined(__BIONIC__) && !defined(__LP64__)
Yabin Cui140f3672015-02-03 10:32:00 -08001651 FILE* fp = fopen("/proc/sys/kernel/pid_max", "r");
1652 ASSERT_TRUE(fp != NULL);
1653 long pid_max;
1654 ASSERT_EQ(1, fscanf(fp, "%ld", &pid_max));
1655 fclose(fp);
Yabin Cuie69c2452015-02-13 16:21:25 -08001656 // Bionic's pthread_mutex implementation on 32-bit devices uses 16 bits to represent owner tid.
Yabin Cui140f3672015-02-03 10:32:00 -08001657 ASSERT_LE(pid_max, 65536);
Yabin Cuie69c2452015-02-13 16:21:25 -08001658#else
1659 GTEST_LOG_(INFO) << "This test does nothing as 32-bit tid is supported by pthread_mutex.\n";
1660#endif
Yabin Cui140f3672015-02-03 10:32:00 -08001661}
Yabin Cuib5845722015-03-16 22:46:42 -07001662
Yabin Cuic9a659c2015-11-05 15:36:08 -08001663TEST(pthread, pthread_mutex_timedlock) {
1664 pthread_mutex_t m;
1665 ASSERT_EQ(0, pthread_mutex_init(&m, nullptr));
1666
1667 // If the mutex is already locked, pthread_mutex_timedlock should time out.
1668 ASSERT_EQ(0, pthread_mutex_lock(&m));
1669
1670 timespec ts;
1671 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1672 ASSERT_EQ(ETIMEDOUT, pthread_mutex_timedlock(&m, &ts));
1673 ts.tv_nsec = -1;
1674 ASSERT_EQ(EINVAL, pthread_mutex_timedlock(&m, &ts));
1675 ts.tv_nsec = NS_PER_S;
1676 ASSERT_EQ(EINVAL, pthread_mutex_timedlock(&m, &ts));
1677 ts.tv_nsec = NS_PER_S - 1;
1678 ts.tv_sec = -1;
1679 ASSERT_EQ(ETIMEDOUT, pthread_mutex_timedlock(&m, &ts));
1680
1681 // If the mutex is unlocked, pthread_mutex_timedlock should succeed.
1682 ASSERT_EQ(0, pthread_mutex_unlock(&m));
1683
1684 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1685 ts.tv_sec += 1;
1686 ASSERT_EQ(0, pthread_mutex_timedlock(&m, &ts));
1687
1688 ASSERT_EQ(0, pthread_mutex_unlock(&m));
1689 ASSERT_EQ(0, pthread_mutex_destroy(&m));
1690}
1691
Yabin Cuib5845722015-03-16 22:46:42 -07001692class StrictAlignmentAllocator {
1693 public:
1694 void* allocate(size_t size, size_t alignment) {
1695 char* p = new char[size + alignment * 2];
1696 allocated_array.push_back(p);
1697 while (!is_strict_aligned(p, alignment)) {
1698 ++p;
1699 }
1700 return p;
1701 }
1702
1703 ~StrictAlignmentAllocator() {
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07001704 for (const auto& p : allocated_array) {
1705 delete[] p;
Yabin Cuib5845722015-03-16 22:46:42 -07001706 }
1707 }
1708
1709 private:
1710 bool is_strict_aligned(char* p, size_t alignment) {
1711 return (reinterpret_cast<uintptr_t>(p) % (alignment * 2)) == alignment;
1712 }
1713
1714 std::vector<char*> allocated_array;
1715};
1716
1717TEST(pthread, pthread_types_allow_four_bytes_alignment) {
1718#if defined(__BIONIC__)
1719 // For binary compatibility with old version, we need to allow 4-byte aligned data for pthread types.
1720 StrictAlignmentAllocator allocator;
1721 pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(
1722 allocator.allocate(sizeof(pthread_mutex_t), 4));
1723 ASSERT_EQ(0, pthread_mutex_init(mutex, NULL));
1724 ASSERT_EQ(0, pthread_mutex_lock(mutex));
1725 ASSERT_EQ(0, pthread_mutex_unlock(mutex));
1726 ASSERT_EQ(0, pthread_mutex_destroy(mutex));
1727
1728 pthread_cond_t* cond = reinterpret_cast<pthread_cond_t*>(
1729 allocator.allocate(sizeof(pthread_cond_t), 4));
1730 ASSERT_EQ(0, pthread_cond_init(cond, NULL));
1731 ASSERT_EQ(0, pthread_cond_signal(cond));
1732 ASSERT_EQ(0, pthread_cond_broadcast(cond));
1733 ASSERT_EQ(0, pthread_cond_destroy(cond));
1734
1735 pthread_rwlock_t* rwlock = reinterpret_cast<pthread_rwlock_t*>(
1736 allocator.allocate(sizeof(pthread_rwlock_t), 4));
1737 ASSERT_EQ(0, pthread_rwlock_init(rwlock, NULL));
1738 ASSERT_EQ(0, pthread_rwlock_rdlock(rwlock));
1739 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
1740 ASSERT_EQ(0, pthread_rwlock_wrlock(rwlock));
1741 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
1742 ASSERT_EQ(0, pthread_rwlock_destroy(rwlock));
1743
1744#else
1745 GTEST_LOG_(INFO) << "This test tests bionic implementation details.";
1746#endif
1747}
Christopher Ferris60907c72015-06-09 18:46:15 -07001748
1749TEST(pthread, pthread_mutex_lock_null_32) {
1750#if defined(__BIONIC__) && !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -07001751 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return
1752 // EINVAL in that case: http://b/19995172.
1753 //
1754 // We decorate the public defintion with _Nonnull so that people recompiling
1755 // their code with get a warning and might fix their bug, but need to pass
1756 // NULL here to test that we remain compatible.
1757 pthread_mutex_t* null_value = nullptr;
1758 ASSERT_EQ(EINVAL, pthread_mutex_lock(null_value));
Christopher Ferris60907c72015-06-09 18:46:15 -07001759#else
1760 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 32 bit devices.";
1761#endif
1762}
1763
1764TEST(pthread, pthread_mutex_unlock_null_32) {
1765#if defined(__BIONIC__) && !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -07001766 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return
1767 // EINVAL in that case: http://b/19995172.
1768 //
1769 // We decorate the public defintion with _Nonnull so that people recompiling
1770 // their code with get a warning and might fix their bug, but need to pass
1771 // NULL here to test that we remain compatible.
1772 pthread_mutex_t* null_value = nullptr;
1773 ASSERT_EQ(EINVAL, pthread_mutex_unlock(null_value));
Christopher Ferris60907c72015-06-09 18:46:15 -07001774#else
1775 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 32 bit devices.";
1776#endif
1777}
1778
1779TEST_F(pthread_DeathTest, pthread_mutex_lock_null_64) {
1780#if defined(__BIONIC__) && defined(__LP64__)
1781 pthread_mutex_t* null_value = nullptr;
1782 ASSERT_EXIT(pthread_mutex_lock(null_value), testing::KilledBySignal(SIGSEGV), "");
1783#else
1784 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 64 bit devices.";
1785#endif
1786}
1787
1788TEST_F(pthread_DeathTest, pthread_mutex_unlock_null_64) {
1789#if defined(__BIONIC__) && defined(__LP64__)
1790 pthread_mutex_t* null_value = nullptr;
1791 ASSERT_EXIT(pthread_mutex_unlock(null_value), testing::KilledBySignal(SIGSEGV), "");
1792#else
1793 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 64 bit devices.";
1794#endif
1795}
Yabin Cui33ac04a2015-09-22 11:16:15 -07001796
1797extern _Unwind_Reason_Code FrameCounter(_Unwind_Context* ctx, void* arg);
1798
1799static volatile bool signal_handler_on_altstack_done;
1800
1801static void SignalHandlerOnAltStack(int signo, siginfo_t*, void*) {
1802 ASSERT_EQ(SIGUSR1, signo);
1803 // Check if we have enough stack space for unwinding.
1804 int count = 0;
1805 _Unwind_Backtrace(FrameCounter, &count);
1806 ASSERT_GT(count, 0);
1807 // Check if we have enough stack space for logging.
1808 std::string s(2048, '*');
1809 GTEST_LOG_(INFO) << s;
1810 signal_handler_on_altstack_done = true;
1811}
1812
1813TEST(pthread, big_enough_signal_stack_for_64bit_arch) {
1814 signal_handler_on_altstack_done = false;
1815 ScopedSignalHandler handler(SIGUSR1, SignalHandlerOnAltStack, SA_SIGINFO | SA_ONSTACK);
1816 kill(getpid(), SIGUSR1);
1817 ASSERT_TRUE(signal_handler_on_altstack_done);
1818}
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001819
1820TEST(pthread, pthread_barrierattr_smoke) {
1821 pthread_barrierattr_t attr;
1822 ASSERT_EQ(0, pthread_barrierattr_init(&attr));
1823 int pshared;
1824 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
1825 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
1826 ASSERT_EQ(0, pthread_barrierattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
1827 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
1828 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
1829 ASSERT_EQ(0, pthread_barrierattr_destroy(&attr));
1830}
1831
Yabin Cui81d27972016-03-22 13:45:55 -07001832struct BarrierTestHelperData {
1833 size_t thread_count;
1834 pthread_barrier_t barrier;
1835 std::atomic<int> finished_mask;
1836 std::atomic<int> serial_thread_count;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001837 size_t iteration_count;
Yabin Cui81d27972016-03-22 13:45:55 -07001838 std::atomic<size_t> finished_iteration_count;
1839
1840 BarrierTestHelperData(size_t thread_count, size_t iteration_count)
1841 : thread_count(thread_count), finished_mask(0), serial_thread_count(0),
1842 iteration_count(iteration_count), finished_iteration_count(0) {
1843 }
1844};
1845
1846struct BarrierTestHelperArg {
1847 int id;
1848 BarrierTestHelperData* data;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001849};
1850
1851static void BarrierTestHelper(BarrierTestHelperArg* arg) {
Yabin Cui81d27972016-03-22 13:45:55 -07001852 for (size_t i = 0; i < arg->data->iteration_count; ++i) {
1853 int result = pthread_barrier_wait(&arg->data->barrier);
1854 if (result == PTHREAD_BARRIER_SERIAL_THREAD) {
1855 arg->data->serial_thread_count++;
1856 } else {
1857 ASSERT_EQ(0, result);
1858 }
1859 arg->data->finished_mask |= (1 << arg->id);
1860 if (arg->data->finished_mask == ((1 << arg->data->thread_count) - 1)) {
1861 ASSERT_EQ(1, arg->data->serial_thread_count);
1862 arg->data->finished_iteration_count++;
1863 arg->data->finished_mask = 0;
1864 arg->data->serial_thread_count = 0;
1865 }
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001866 }
1867}
1868
1869TEST(pthread, pthread_barrier_smoke) {
1870 const size_t BARRIER_ITERATION_COUNT = 10;
1871 const size_t BARRIER_THREAD_COUNT = 10;
Yabin Cui81d27972016-03-22 13:45:55 -07001872 BarrierTestHelperData data(BARRIER_THREAD_COUNT, BARRIER_ITERATION_COUNT);
1873 ASSERT_EQ(0, pthread_barrier_init(&data.barrier, nullptr, data.thread_count));
1874 std::vector<pthread_t> threads(data.thread_count);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001875 std::vector<BarrierTestHelperArg> args(threads.size());
1876 for (size_t i = 0; i < threads.size(); ++i) {
Yabin Cui81d27972016-03-22 13:45:55 -07001877 args[i].id = i;
1878 args[i].data = &data;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001879 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
1880 reinterpret_cast<void* (*)(void*)>(BarrierTestHelper), &args[i]));
1881 }
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001882 for (size_t i = 0; i < threads.size(); ++i) {
1883 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
1884 }
Yabin Cui81d27972016-03-22 13:45:55 -07001885 ASSERT_EQ(data.iteration_count, data.finished_iteration_count);
1886 ASSERT_EQ(0, pthread_barrier_destroy(&data.barrier));
1887}
1888
1889struct BarrierDestroyTestArg {
1890 std::atomic<int> tid;
1891 pthread_barrier_t* barrier;
1892};
1893
1894static void BarrierDestroyTestHelper(BarrierDestroyTestArg* arg) {
1895 arg->tid = gettid();
1896 ASSERT_EQ(0, pthread_barrier_wait(arg->barrier));
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001897}
1898
1899TEST(pthread, pthread_barrier_destroy) {
1900 pthread_barrier_t barrier;
1901 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, 2));
1902 pthread_t thread;
Yabin Cui81d27972016-03-22 13:45:55 -07001903 BarrierDestroyTestArg arg;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001904 arg.tid = 0;
1905 arg.barrier = &barrier;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001906 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui81d27972016-03-22 13:45:55 -07001907 reinterpret_cast<void* (*)(void*)>(BarrierDestroyTestHelper), &arg));
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001908 WaitUntilThreadSleep(arg.tid);
1909 ASSERT_EQ(EBUSY, pthread_barrier_destroy(&barrier));
1910 ASSERT_EQ(PTHREAD_BARRIER_SERIAL_THREAD, pthread_barrier_wait(&barrier));
1911 // Verify if the barrier can be destroyed directly after pthread_barrier_wait().
1912 ASSERT_EQ(0, pthread_barrier_destroy(&barrier));
1913 ASSERT_EQ(0, pthread_join(thread, nullptr));
1914#if defined(__BIONIC__)
1915 ASSERT_EQ(EINVAL, pthread_barrier_destroy(&barrier));
1916#endif
1917}
1918
1919struct BarrierOrderingTestHelperArg {
1920 pthread_barrier_t* barrier;
1921 size_t* array;
1922 size_t array_length;
1923 size_t id;
1924};
1925
1926void BarrierOrderingTestHelper(BarrierOrderingTestHelperArg* arg) {
1927 const size_t ITERATION_COUNT = 10000;
1928 for (size_t i = 1; i <= ITERATION_COUNT; ++i) {
1929 arg->array[arg->id] = i;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001930 int result = pthread_barrier_wait(arg->barrier);
1931 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001932 for (size_t j = 0; j < arg->array_length; ++j) {
1933 ASSERT_EQ(i, arg->array[j]);
1934 }
Yabin Cuic9a659c2015-11-05 15:36:08 -08001935 result = pthread_barrier_wait(arg->barrier);
1936 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001937 }
1938}
1939
1940TEST(pthread, pthread_barrier_check_ordering) {
1941 const size_t THREAD_COUNT = 4;
1942 pthread_barrier_t barrier;
1943 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, THREAD_COUNT));
1944 size_t array[THREAD_COUNT];
1945 std::vector<pthread_t> threads(THREAD_COUNT);
1946 std::vector<BarrierOrderingTestHelperArg> args(THREAD_COUNT);
1947 for (size_t i = 0; i < THREAD_COUNT; ++i) {
1948 args[i].barrier = &barrier;
1949 args[i].array = array;
1950 args[i].array_length = THREAD_COUNT;
1951 args[i].id = i;
1952 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
1953 reinterpret_cast<void* (*)(void*)>(BarrierOrderingTestHelper),
1954 &args[i]));
1955 }
1956 for (size_t i = 0; i < THREAD_COUNT; ++i) {
1957 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
1958 }
1959}
Yabin Cuife3a83a2015-11-17 16:03:18 -08001960
1961TEST(pthread, pthread_spinlock_smoke) {
1962 pthread_spinlock_t lock;
1963 ASSERT_EQ(0, pthread_spin_init(&lock, 0));
1964 ASSERT_EQ(0, pthread_spin_trylock(&lock));
1965 ASSERT_EQ(0, pthread_spin_unlock(&lock));
1966 ASSERT_EQ(0, pthread_spin_lock(&lock));
1967 ASSERT_EQ(EBUSY, pthread_spin_trylock(&lock));
1968 ASSERT_EQ(0, pthread_spin_unlock(&lock));
1969 ASSERT_EQ(0, pthread_spin_destroy(&lock));
1970}