blob: e0350f2ce2bbd29da4cb54abc2a43969fe79b831 [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 Hughes4d014e12012-09-07 16:47:54 -0700238TEST(pthread, pthread_create) {
239 void* expected_result = reinterpret_cast<void*>(123);
240 // Can we create a thread?
241 pthread_t t;
242 ASSERT_EQ(0, pthread_create(&t, NULL, IdFn, expected_result));
243 // If we join, do we get the expected value back?
244 void* result;
245 ASSERT_EQ(0, pthread_join(t, &result));
246 ASSERT_EQ(expected_result, result);
247}
248
Elliott Hughes3e898472013-02-12 16:40:24 +0000249TEST(pthread, pthread_create_EAGAIN) {
250 pthread_attr_t attributes;
251 ASSERT_EQ(0, pthread_attr_init(&attributes));
252 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, static_cast<size_t>(-1) & ~(getpagesize() - 1)));
253
254 pthread_t t;
255 ASSERT_EQ(EAGAIN, pthread_create(&t, &attributes, IdFn, NULL));
256}
257
Elliott Hughes4d014e12012-09-07 16:47:54 -0700258TEST(pthread, pthread_no_join_after_detach) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700259 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800260
Elliott Hughes4d014e12012-09-07 16:47:54 -0700261 pthread_t t1;
Elliott Hughes725b2a92016-03-23 11:20:47 -0700262 ASSERT_EQ(0, pthread_create(&t1, NULL, spin_helper.GetFunction(), NULL));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700263
264 // After a pthread_detach...
265 ASSERT_EQ(0, pthread_detach(t1));
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400266 AssertDetached(t1, true);
Elliott Hughes4d014e12012-09-07 16:47:54 -0700267
268 // ...pthread_join should fail.
Elliott Hughes34c987a2014-09-22 16:01:26 -0700269 ASSERT_EQ(EINVAL, pthread_join(t1, NULL));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700270}
271
272TEST(pthread, pthread_no_op_detach_after_join) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700273 SpinFunctionHelper spin_helper;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400274
Elliott Hughes4d014e12012-09-07 16:47:54 -0700275 pthread_t t1;
Elliott Hughes725b2a92016-03-23 11:20:47 -0700276 ASSERT_EQ(0, pthread_create(&t1, NULL, spin_helper.GetFunction(), NULL));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700277
278 // If thread 2 is already waiting to join thread 1...
279 pthread_t t2;
280 ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1)));
281
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400282 sleep(1); // (Give t2 a chance to call pthread_join.)
Elliott Hughes4d014e12012-09-07 16:47:54 -0700283
Yabin Cuibbb04322015-03-19 15:19:25 -0700284#if defined(__BIONIC__)
285 ASSERT_EQ(EINVAL, pthread_detach(t1));
286#else
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400287 ASSERT_EQ(0, pthread_detach(t1));
Yabin Cuibbb04322015-03-19 15:19:25 -0700288#endif
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400289 AssertDetached(t1, false);
290
Elliott Hughes725b2a92016-03-23 11:20:47 -0700291 spin_helper.UnSpin();
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400292
293 // ...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 -0700294 void* join_result;
295 ASSERT_EQ(0, pthread_join(t2, &join_result));
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700296 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700297}
Elliott Hughes14f19592012-10-29 10:19:44 -0700298
299TEST(pthread, pthread_join_self) {
Elliott Hughes34c987a2014-09-22 16:01:26 -0700300 ASSERT_EQ(EDEADLK, pthread_join(pthread_self(), NULL));
Elliott Hughes14f19592012-10-29 10:19:44 -0700301}
Elliott Hughes4f251be2012-11-01 16:33:29 -0700302
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800303struct TestBug37410 {
304 pthread_t main_thread;
305 pthread_mutex_t mutex;
Elliott Hughes4f251be2012-11-01 16:33:29 -0700306
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800307 static void main() {
308 TestBug37410 data;
309 data.main_thread = pthread_self();
310 ASSERT_EQ(0, pthread_mutex_init(&data.mutex, NULL));
311 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
312
313 pthread_t t;
314 ASSERT_EQ(0, pthread_create(&t, NULL, TestBug37410::thread_fn, reinterpret_cast<void*>(&data)));
315
316 // Wait for the thread to be running...
317 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
318 ASSERT_EQ(0, pthread_mutex_unlock(&data.mutex));
319
320 // ...and exit.
321 pthread_exit(NULL);
322 }
323
324 private:
325 static void* thread_fn(void* arg) {
326 TestBug37410* data = reinterpret_cast<TestBug37410*>(arg);
327
328 // Let the main thread know we're running.
329 pthread_mutex_unlock(&data->mutex);
330
331 // And wait for the main thread to exit.
332 pthread_join(data->main_thread, NULL);
333
334 return NULL;
335 }
336};
Elliott Hughes4f251be2012-11-01 16:33:29 -0700337
Elliott Hughes7fd803c2013-02-14 16:33:52 -0800338// Even though this isn't really a death test, we have to say "DeathTest" here so gtest knows to
339// run this test (which exits normally) in its own process.
Yabin Cui9df70402014-11-05 18:01:01 -0800340
341class pthread_DeathTest : public BionicDeathTest {};
342
343TEST_F(pthread_DeathTest, pthread_bug_37410) {
Elliott Hughes4f251be2012-11-01 16:33:29 -0700344 // http://code.google.com/p/android/issues/detail?id=37410
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800345 ASSERT_EXIT(TestBug37410::main(), ::testing::ExitedWithCode(0), "");
Elliott Hughes4f251be2012-11-01 16:33:29 -0700346}
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800347
348static void* SignalHandlerFn(void* arg) {
349 sigset_t wait_set;
350 sigfillset(&wait_set);
351 return reinterpret_cast<void*>(sigwait(&wait_set, reinterpret_cast<int*>(arg)));
352}
353
354TEST(pthread, pthread_sigmask) {
Elliott Hughes19e62322013-10-15 11:23:57 -0700355 // Check that SIGUSR1 isn't blocked.
356 sigset_t original_set;
357 sigemptyset(&original_set);
358 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, NULL, &original_set));
359 ASSERT_FALSE(sigismember(&original_set, SIGUSR1));
360
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800361 // Block SIGUSR1.
362 sigset_t set;
363 sigemptyset(&set);
364 sigaddset(&set, SIGUSR1);
365 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, &set, NULL));
366
Elliott Hughes19e62322013-10-15 11:23:57 -0700367 // Check that SIGUSR1 is blocked.
368 sigset_t final_set;
369 sigemptyset(&final_set);
370 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, NULL, &final_set));
371 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
372 // ...and that sigprocmask agrees with pthread_sigmask.
373 sigemptyset(&final_set);
374 ASSERT_EQ(0, sigprocmask(SIG_BLOCK, NULL, &final_set));
375 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
376
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800377 // Spawn a thread that calls sigwait and tells us what it received.
378 pthread_t signal_thread;
379 int received_signal = -1;
380 ASSERT_EQ(0, pthread_create(&signal_thread, NULL, SignalHandlerFn, &received_signal));
381
382 // Send that thread SIGUSR1.
383 pthread_kill(signal_thread, SIGUSR1);
384
385 // See what it got.
386 void* join_result;
387 ASSERT_EQ(0, pthread_join(signal_thread, &join_result));
388 ASSERT_EQ(SIGUSR1, received_signal);
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700389 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
Elliott Hughes19e62322013-10-15 11:23:57 -0700390
391 // Restore the original signal mask.
392 ASSERT_EQ(0, pthread_sigmask(SIG_SETMASK, &original_set, NULL));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800393}
Elliott Hughes5e3fc432013-02-11 16:36:48 -0800394
Elliott Hughes725b2a92016-03-23 11:20:47 -0700395static void test_pthread_setname_np__pthread_getname_np(pthread_t t) {
396 ASSERT_EQ(0, pthread_setname_np(t, "short"));
397 char name[32];
398 ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name)));
399 ASSERT_STREQ("short", name);
400
Elliott Hughesd1aea302015-04-25 10:05:24 -0700401 // The limit is 15 characters --- the kernel's buffer is 16, but includes a NUL.
Elliott Hughes725b2a92016-03-23 11:20:47 -0700402 ASSERT_EQ(0, pthread_setname_np(t, "123456789012345"));
403 ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name)));
404 ASSERT_STREQ("123456789012345", name);
405
406 ASSERT_EQ(ERANGE, pthread_setname_np(t, "1234567890123456"));
407
408 // The passed-in buffer should be at least 16 bytes.
409 ASSERT_EQ(0, pthread_getname_np(t, name, 16));
410 ASSERT_EQ(ERANGE, pthread_getname_np(t, name, 15));
Elliott Hughes3e898472013-02-12 16:40:24 +0000411}
412
Elliott Hughes725b2a92016-03-23 11:20:47 -0700413TEST(pthread, pthread_setname_np__pthread_getname_np__self) {
414 test_pthread_setname_np__pthread_getname_np(pthread_self());
Elliott Hughes3e898472013-02-12 16:40:24 +0000415}
416
Elliott Hughes725b2a92016-03-23 11:20:47 -0700417TEST(pthread, pthread_setname_np__pthread_getname_np__other) {
418 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800419
Elliott Hughes725b2a92016-03-23 11:20:47 -0700420 pthread_t t;
Elliott Hughes4d098ca2016-04-11 12:43:05 -0700421 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
422 test_pthread_setname_np__pthread_getname_np(t);
423 spin_helper.UnSpin();
424 ASSERT_EQ(0, pthread_join(t, nullptr));
425}
426
427// http://b/28051133: a kernel misfeature means that you can't change the
428// name of another thread if you've set PR_SET_DUMPABLE to 0.
429TEST(pthread, pthread_setname_np__pthread_getname_np__other_PR_SET_DUMPABLE) {
430 ASSERT_EQ(0, prctl(PR_SET_DUMPABLE, 0)) << strerror(errno);
431
432 SpinFunctionHelper spin_helper;
433
434 pthread_t t;
435 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
Elliott Hughes725b2a92016-03-23 11:20:47 -0700436 test_pthread_setname_np__pthread_getname_np(t);
437 spin_helper.UnSpin();
438 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes3e898472013-02-12 16:40:24 +0000439}
440
Elliott Hughes9d23e042013-02-15 19:21:51 -0800441TEST(pthread, pthread_kill__0) {
442 // Signal 0 just tests that the thread exists, so it's safe to call on ourselves.
443 ASSERT_EQ(0, pthread_kill(pthread_self(), 0));
444}
445
446TEST(pthread, pthread_kill__invalid_signal) {
447 ASSERT_EQ(EINVAL, pthread_kill(pthread_self(), -1));
448}
449
Elliott Hughesfae89fc2013-02-21 11:22:23 -0800450static void pthread_kill__in_signal_handler_helper(int signal_number) {
451 static int count = 0;
452 ASSERT_EQ(SIGALRM, signal_number);
453 if (++count == 1) {
454 // Can we call pthread_kill from a signal handler?
455 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
456 }
457}
458
459TEST(pthread, pthread_kill__in_signal_handler) {
Elliott Hughes4b558f52014-03-04 15:58:02 -0800460 ScopedSignalHandler ssh(SIGALRM, pthread_kill__in_signal_handler_helper);
Elliott Hughesfae89fc2013-02-21 11:22:23 -0800461 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
462}
463
Jeff Hao9b06cc32013-08-15 14:51:16 -0700464TEST(pthread, pthread_getcpuclockid__clock_gettime) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700465 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800466
Jeff Hao9b06cc32013-08-15 14:51:16 -0700467 pthread_t t;
Elliott Hughes725b2a92016-03-23 11:20:47 -0700468 ASSERT_EQ(0, pthread_create(&t, NULL, spin_helper.GetFunction(), NULL));
Jeff Hao9b06cc32013-08-15 14:51:16 -0700469
470 clockid_t c;
471 ASSERT_EQ(0, pthread_getcpuclockid(t, &c));
472 timespec ts;
473 ASSERT_EQ(0, clock_gettime(c, &ts));
Elliott Hughes725b2a92016-03-23 11:20:47 -0700474 spin_helper.UnSpin();
Yabin Cuia36158a2015-11-16 21:06:16 -0800475 ASSERT_EQ(0, pthread_join(t, nullptr));
Jeff Hao9b06cc32013-08-15 14:51:16 -0700476}
477
msg5550f020d12013-06-06 14:59:28 -0400478TEST(pthread, pthread_join__multijoin) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700479 SpinFunctionHelper spin_helper;
msg5550f020d12013-06-06 14:59:28 -0400480
481 pthread_t t1;
Elliott Hughes725b2a92016-03-23 11:20:47 -0700482 ASSERT_EQ(0, pthread_create(&t1, NULL, spin_helper.GetFunction(), NULL));
msg5550f020d12013-06-06 14:59:28 -0400483
484 pthread_t t2;
485 ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1)));
486
487 sleep(1); // (Give t2 a chance to call pthread_join.)
488
489 // Multiple joins to the same thread should fail.
490 ASSERT_EQ(EINVAL, pthread_join(t1, NULL));
491
Elliott Hughes725b2a92016-03-23 11:20:47 -0700492 spin_helper.UnSpin();
msg5550f020d12013-06-06 14:59:28 -0400493
494 // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes).
495 void* join_result;
496 ASSERT_EQ(0, pthread_join(t2, &join_result));
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700497 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
msg5550f020d12013-06-06 14:59:28 -0400498}
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700499
Elliott Hughes70b24b12013-11-15 11:51:07 -0800500TEST(pthread, pthread_join__race) {
501 // http://b/11693195 --- pthread_join could return before the thread had actually exited.
502 // If the joiner unmapped the thread's stack, that could lead to SIGSEGV in the thread.
503 for (size_t i = 0; i < 1024; ++i) {
Yabin Cuia36158a2015-11-16 21:06:16 -0800504 size_t stack_size = 640*1024;
Elliott Hughes70b24b12013-11-15 11:51:07 -0800505 void* stack = mmap(NULL, stack_size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
506
507 pthread_attr_t a;
508 pthread_attr_init(&a);
509 pthread_attr_setstack(&a, stack, stack_size);
510
511 pthread_t t;
512 ASSERT_EQ(0, pthread_create(&t, &a, IdFn, NULL));
513 ASSERT_EQ(0, pthread_join(t, NULL));
514 ASSERT_EQ(0, munmap(stack, stack_size));
515 }
516}
517
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700518static void* GetActualGuardSizeFn(void* arg) {
519 pthread_attr_t attributes;
520 pthread_getattr_np(pthread_self(), &attributes);
521 pthread_attr_getguardsize(&attributes, reinterpret_cast<size_t*>(arg));
522 return NULL;
523}
524
525static size_t GetActualGuardSize(const pthread_attr_t& attributes) {
526 size_t result;
527 pthread_t t;
528 pthread_create(&t, &attributes, GetActualGuardSizeFn, &result);
Elliott Hughes34c987a2014-09-22 16:01:26 -0700529 pthread_join(t, NULL);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700530 return result;
531}
532
533static void* GetActualStackSizeFn(void* arg) {
534 pthread_attr_t attributes;
535 pthread_getattr_np(pthread_self(), &attributes);
536 pthread_attr_getstacksize(&attributes, reinterpret_cast<size_t*>(arg));
537 return NULL;
538}
539
540static size_t GetActualStackSize(const pthread_attr_t& attributes) {
541 size_t result;
542 pthread_t t;
543 pthread_create(&t, &attributes, GetActualStackSizeFn, &result);
Elliott Hughes34c987a2014-09-22 16:01:26 -0700544 pthread_join(t, NULL);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700545 return result;
546}
547
548TEST(pthread, pthread_attr_setguardsize) {
549 pthread_attr_t attributes;
550 ASSERT_EQ(0, pthread_attr_init(&attributes));
551
552 // Get the default guard size.
553 size_t default_guard_size;
554 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &default_guard_size));
555
556 // No such thing as too small: will be rounded up to one page by pthread_create.
557 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 128));
558 size_t guard_size;
559 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
560 ASSERT_EQ(128U, guard_size);
561 ASSERT_EQ(4096U, GetActualGuardSize(attributes));
562
563 // Large enough and a multiple of the page size.
564 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024));
565 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
566 ASSERT_EQ(32*1024U, guard_size);
567
568 // Large enough but not a multiple of the page size; will be rounded up by pthread_create.
569 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024 + 1));
570 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
571 ASSERT_EQ(32*1024U + 1, guard_size);
572}
573
574TEST(pthread, pthread_attr_setstacksize) {
575 pthread_attr_t attributes;
576 ASSERT_EQ(0, pthread_attr_init(&attributes));
577
578 // Get the default stack size.
579 size_t default_stack_size;
580 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &default_stack_size));
581
582 // Too small.
583 ASSERT_EQ(EINVAL, pthread_attr_setstacksize(&attributes, 128));
584 size_t stack_size;
585 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
586 ASSERT_EQ(default_stack_size, stack_size);
587 ASSERT_GE(GetActualStackSize(attributes), default_stack_size);
588
Yabin Cui917d3902015-01-08 12:32:42 -0800589 // Large enough and a multiple of the page size; may be rounded up by pthread_create.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700590 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024));
591 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
592 ASSERT_EQ(32*1024U, stack_size);
Yabin Cui917d3902015-01-08 12:32:42 -0800593 ASSERT_GE(GetActualStackSize(attributes), 32*1024U);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700594
Yabin Cui917d3902015-01-08 12:32:42 -0800595 // Large enough but not aligned; will be rounded up by pthread_create.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700596 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024 + 1));
597 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
598 ASSERT_EQ(32*1024U + 1, stack_size);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800599#if defined(__BIONIC__)
Yabin Cui917d3902015-01-08 12:32:42 -0800600 ASSERT_GT(GetActualStackSize(attributes), 32*1024U + 1);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800601#else // __BIONIC__
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700602 // glibc rounds down, in violation of POSIX. They document this in their BUGS section.
603 ASSERT_EQ(GetActualStackSize(attributes), 32*1024U);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800604#endif // __BIONIC__
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700605}
Elliott Hughesc3f11402013-10-30 14:40:09 -0700606
Yabin Cui76615da2015-03-17 14:22:09 -0700607TEST(pthread, pthread_rwlockattr_smoke) {
608 pthread_rwlockattr_t attr;
609 ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
610
611 int pshared_value_array[] = {PTHREAD_PROCESS_PRIVATE, PTHREAD_PROCESS_SHARED};
612 for (size_t i = 0; i < sizeof(pshared_value_array) / sizeof(pshared_value_array[0]); ++i) {
613 ASSERT_EQ(0, pthread_rwlockattr_setpshared(&attr, pshared_value_array[i]));
614 int pshared;
615 ASSERT_EQ(0, pthread_rwlockattr_getpshared(&attr, &pshared));
616 ASSERT_EQ(pshared_value_array[i], pshared);
617 }
618
619 int kind_array[] = {PTHREAD_RWLOCK_PREFER_READER_NP,
620 PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP};
621 for (size_t i = 0; i < sizeof(kind_array) / sizeof(kind_array[0]); ++i) {
622 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_array[i]));
623 int kind;
624 ASSERT_EQ(0, pthread_rwlockattr_getkind_np(&attr, &kind));
625 ASSERT_EQ(kind_array[i], kind);
626 }
627
628 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
629}
630
631TEST(pthread, pthread_rwlock_init_same_as_PTHREAD_RWLOCK_INITIALIZER) {
632 pthread_rwlock_t lock1 = PTHREAD_RWLOCK_INITIALIZER;
633 pthread_rwlock_t lock2;
634 ASSERT_EQ(0, pthread_rwlock_init(&lock2, NULL));
635 ASSERT_EQ(0, memcmp(&lock1, &lock2, sizeof(lock1)));
636}
637
Elliott Hughesc3f11402013-10-30 14:40:09 -0700638TEST(pthread, pthread_rwlock_smoke) {
639 pthread_rwlock_t l;
640 ASSERT_EQ(0, pthread_rwlock_init(&l, NULL));
641
Calin Juravle76f352e2014-05-19 13:41:10 +0100642 // Single read lock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700643 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
644 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
645
Calin Juravle76f352e2014-05-19 13:41:10 +0100646 // Multiple read lock
647 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
648 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
649 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
650 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
651
652 // Write lock
Calin Juravle92687e42014-05-22 19:21:22 +0100653 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
654 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100655
656 // Try writer lock
657 ASSERT_EQ(0, pthread_rwlock_trywrlock(&l));
658 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
659 ASSERT_EQ(EBUSY, pthread_rwlock_tryrdlock(&l));
660 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
661
662 // Try reader lock
663 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
664 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
665 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
666 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
667 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
668
669 // Try writer lock after unlock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700670 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
671 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
672
Calin Juravle76f352e2014-05-19 13:41:10 +0100673 // EDEADLK in "read after write"
674 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
675 ASSERT_EQ(EDEADLK, pthread_rwlock_rdlock(&l));
676 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
677
678 // EDEADLK in "write after write"
679 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
680 ASSERT_EQ(EDEADLK, pthread_rwlock_wrlock(&l));
681 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100682
Elliott Hughesc3f11402013-10-30 14:40:09 -0700683 ASSERT_EQ(0, pthread_rwlock_destroy(&l));
684}
685
Yabin Cui08ee8d22015-02-11 17:04:36 -0800686struct RwlockWakeupHelperArg {
687 pthread_rwlock_t lock;
688 enum Progress {
689 LOCK_INITIALIZED,
690 LOCK_WAITING,
691 LOCK_RELEASED,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800692 LOCK_ACCESSED,
693 LOCK_TIMEDOUT,
Yabin Cui08ee8d22015-02-11 17:04:36 -0800694 };
695 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -0700696 std::atomic<pid_t> tid;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800697 std::function<int (pthread_rwlock_t*)> trylock_function;
698 std::function<int (pthread_rwlock_t*)> lock_function;
699 std::function<int (pthread_rwlock_t*, const timespec*)> timed_lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800700};
701
Yabin Cuic9a659c2015-11-05 15:36:08 -0800702static void pthread_rwlock_wakeup_helper(RwlockWakeupHelperArg* arg) {
Yabin Cuif7969852015-04-02 17:47:48 -0700703 arg->tid = gettid();
Yabin Cui08ee8d22015-02-11 17:04:36 -0800704 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
705 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
706
Yabin Cuic9a659c2015-11-05 15:36:08 -0800707 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
708 ASSERT_EQ(0, arg->lock_function(&arg->lock));
Yabin Cui08ee8d22015-02-11 17:04:36 -0800709 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_RELEASED, arg->progress);
710 ASSERT_EQ(0, pthread_rwlock_unlock(&arg->lock));
711
712 arg->progress = RwlockWakeupHelperArg::LOCK_ACCESSED;
713}
714
Yabin Cuic9a659c2015-11-05 15:36:08 -0800715static void test_pthread_rwlock_reader_wakeup_writer(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -0800716 RwlockWakeupHelperArg wakeup_arg;
717 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, NULL));
718 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
719 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -0700720 wakeup_arg.tid = 0;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800721 wakeup_arg.trylock_function = pthread_rwlock_trywrlock;
722 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800723
724 pthread_t thread;
725 ASSERT_EQ(0, pthread_create(&thread, NULL,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800726 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -0700727 WaitUntilThreadSleep(wakeup_arg.tid);
728 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
729
Yabin Cui08ee8d22015-02-11 17:04:36 -0800730 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
731 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
732
733 ASSERT_EQ(0, pthread_join(thread, NULL));
734 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
735 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
736}
737
Yabin Cuic9a659c2015-11-05 15:36:08 -0800738TEST(pthread, pthread_rwlock_reader_wakeup_writer) {
739 test_pthread_rwlock_reader_wakeup_writer(pthread_rwlock_wrlock);
Yabin Cui08ee8d22015-02-11 17:04:36 -0800740}
741
Yabin Cuic9a659c2015-11-05 15:36:08 -0800742TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait) {
743 timespec ts;
744 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
745 ts.tv_sec += 1;
746 test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) {
747 return pthread_rwlock_timedwrlock(lock, &ts);
748 });
749}
750
751static void test_pthread_rwlock_writer_wakeup_reader(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -0800752 RwlockWakeupHelperArg wakeup_arg;
753 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, NULL));
754 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
755 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -0700756 wakeup_arg.tid = 0;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800757 wakeup_arg.trylock_function = pthread_rwlock_tryrdlock;
758 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800759
760 pthread_t thread;
761 ASSERT_EQ(0, pthread_create(&thread, NULL,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800762 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -0700763 WaitUntilThreadSleep(wakeup_arg.tid);
764 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
765
Yabin Cui08ee8d22015-02-11 17:04:36 -0800766 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
767 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
768
769 ASSERT_EQ(0, pthread_join(thread, NULL));
770 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
771 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
772}
773
Yabin Cuic9a659c2015-11-05 15:36:08 -0800774TEST(pthread, pthread_rwlock_writer_wakeup_reader) {
775 test_pthread_rwlock_writer_wakeup_reader(pthread_rwlock_rdlock);
776}
777
778TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait) {
779 timespec ts;
780 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
781 ts.tv_sec += 1;
782 test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) {
783 return pthread_rwlock_timedrdlock(lock, &ts);
784 });
785}
786
787static void pthread_rwlock_wakeup_timeout_helper(RwlockWakeupHelperArg* arg) {
788 arg->tid = gettid();
789 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
790 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
791
792 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
793
794 timespec ts;
795 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
796 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
797 ts.tv_nsec = -1;
798 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
799 ts.tv_nsec = NS_PER_S;
800 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
801 ts.tv_nsec = NS_PER_S - 1;
802 ts.tv_sec = -1;
803 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
804 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
805 ts.tv_sec += 1;
806 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
807 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, arg->progress);
808 arg->progress = RwlockWakeupHelperArg::LOCK_TIMEDOUT;
809}
810
811TEST(pthread, pthread_rwlock_timedrdlock_timeout) {
812 RwlockWakeupHelperArg wakeup_arg;
813 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
814 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
815 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
816 wakeup_arg.tid = 0;
817 wakeup_arg.trylock_function = pthread_rwlock_tryrdlock;
818 wakeup_arg.timed_lock_function = pthread_rwlock_timedrdlock;
819
820 pthread_t thread;
821 ASSERT_EQ(0, pthread_create(&thread, nullptr,
822 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
823 WaitUntilThreadSleep(wakeup_arg.tid);
824 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
825
826 ASSERT_EQ(0, pthread_join(thread, nullptr));
827 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
828 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
829 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
830}
831
832TEST(pthread, pthread_rwlock_timedwrlock_timeout) {
833 RwlockWakeupHelperArg wakeup_arg;
834 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
835 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
836 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
837 wakeup_arg.tid = 0;
838 wakeup_arg.trylock_function = pthread_rwlock_trywrlock;
839 wakeup_arg.timed_lock_function = pthread_rwlock_timedwrlock;
840
841 pthread_t thread;
842 ASSERT_EQ(0, pthread_create(&thread, nullptr,
843 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
844 WaitUntilThreadSleep(wakeup_arg.tid);
845 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
846
847 ASSERT_EQ(0, pthread_join(thread, nullptr));
848 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
849 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
850 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
851}
852
Yabin Cui76615da2015-03-17 14:22:09 -0700853class RwlockKindTestHelper {
854 private:
855 struct ThreadArg {
856 RwlockKindTestHelper* helper;
857 std::atomic<pid_t>& tid;
858
859 ThreadArg(RwlockKindTestHelper* helper, std::atomic<pid_t>& tid)
860 : helper(helper), tid(tid) { }
861 };
862
863 public:
864 pthread_rwlock_t lock;
865
866 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -0700867 explicit RwlockKindTestHelper(int kind_type) {
Yabin Cui76615da2015-03-17 14:22:09 -0700868 InitRwlock(kind_type);
869 }
870
871 ~RwlockKindTestHelper() {
872 DestroyRwlock();
873 }
874
875 void CreateWriterThread(pthread_t& thread, std::atomic<pid_t>& tid) {
876 tid = 0;
877 ThreadArg* arg = new ThreadArg(this, tid);
878 ASSERT_EQ(0, pthread_create(&thread, NULL,
879 reinterpret_cast<void* (*)(void*)>(WriterThreadFn), arg));
880 }
881
882 void CreateReaderThread(pthread_t& thread, std::atomic<pid_t>& tid) {
883 tid = 0;
884 ThreadArg* arg = new ThreadArg(this, tid);
885 ASSERT_EQ(0, pthread_create(&thread, NULL,
886 reinterpret_cast<void* (*)(void*)>(ReaderThreadFn), arg));
887 }
888
889 private:
890 void InitRwlock(int kind_type) {
891 pthread_rwlockattr_t attr;
892 ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
893 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_type));
894 ASSERT_EQ(0, pthread_rwlock_init(&lock, &attr));
895 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
896 }
897
898 void DestroyRwlock() {
899 ASSERT_EQ(0, pthread_rwlock_destroy(&lock));
900 }
901
902 static void WriterThreadFn(ThreadArg* arg) {
903 arg->tid = gettid();
904
905 RwlockKindTestHelper* helper = arg->helper;
906 ASSERT_EQ(0, pthread_rwlock_wrlock(&helper->lock));
907 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
908 delete arg;
909 }
910
911 static void ReaderThreadFn(ThreadArg* arg) {
912 arg->tid = gettid();
913
914 RwlockKindTestHelper* helper = arg->helper;
915 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper->lock));
916 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
917 delete arg;
918 }
919};
920
921TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_READER_NP) {
922 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_READER_NP);
923 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
924
925 pthread_t writer_thread;
926 std::atomic<pid_t> writer_tid;
927 helper.CreateWriterThread(writer_thread, writer_tid);
928 WaitUntilThreadSleep(writer_tid);
929
930 pthread_t reader_thread;
931 std::atomic<pid_t> reader_tid;
932 helper.CreateReaderThread(reader_thread, reader_tid);
933 ASSERT_EQ(0, pthread_join(reader_thread, NULL));
934
935 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
936 ASSERT_EQ(0, pthread_join(writer_thread, NULL));
937}
938
939TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP) {
940 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
941 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
942
943 pthread_t writer_thread;
944 std::atomic<pid_t> writer_tid;
945 helper.CreateWriterThread(writer_thread, writer_tid);
946 WaitUntilThreadSleep(writer_tid);
947
948 pthread_t reader_thread;
949 std::atomic<pid_t> reader_tid;
950 helper.CreateReaderThread(reader_thread, reader_tid);
951 WaitUntilThreadSleep(reader_tid);
952
953 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
954 ASSERT_EQ(0, pthread_join(writer_thread, NULL));
955 ASSERT_EQ(0, pthread_join(reader_thread, NULL));
956}
957
Elliott Hughes1728b232014-05-14 10:02:03 -0700958static int g_once_fn_call_count = 0;
Elliott Hughesc3f11402013-10-30 14:40:09 -0700959static void OnceFn() {
Elliott Hughes1728b232014-05-14 10:02:03 -0700960 ++g_once_fn_call_count;
Elliott Hughesc3f11402013-10-30 14:40:09 -0700961}
962
963TEST(pthread, pthread_once_smoke) {
964 pthread_once_t once_control = PTHREAD_ONCE_INIT;
965 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
966 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
Elliott Hughes1728b232014-05-14 10:02:03 -0700967 ASSERT_EQ(1, g_once_fn_call_count);
Elliott Hughesc3f11402013-10-30 14:40:09 -0700968}
969
Elliott Hughes3694ec62014-05-14 11:46:08 -0700970static std::string pthread_once_1934122_result = "";
971
972static void Routine2() {
973 pthread_once_1934122_result += "2";
974}
975
976static void Routine1() {
977 pthread_once_t once_control_2 = PTHREAD_ONCE_INIT;
978 pthread_once_1934122_result += "1";
979 pthread_once(&once_control_2, &Routine2);
980}
981
982TEST(pthread, pthread_once_1934122) {
983 // Very old versions of Android couldn't call pthread_once from a
984 // pthread_once init routine. http://b/1934122.
985 pthread_once_t once_control_1 = PTHREAD_ONCE_INIT;
986 ASSERT_EQ(0, pthread_once(&once_control_1, &Routine1));
987 ASSERT_EQ("12", pthread_once_1934122_result);
988}
989
Elliott Hughes1728b232014-05-14 10:02:03 -0700990static int g_atfork_prepare_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -0800991static void AtForkPrepare1() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 1; }
992static void AtForkPrepare2() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -0700993static int g_atfork_parent_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -0800994static void AtForkParent1() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 1; }
995static void AtForkParent2() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -0700996static int g_atfork_child_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -0800997static void AtForkChild1() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 1; }
998static void AtForkChild2() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 2; }
Elliott Hughesc3f11402013-10-30 14:40:09 -0700999
Dmitriy Ivanov00e37812014-11-20 16:53:47 -08001000TEST(pthread, pthread_atfork_smoke) {
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001001 ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1));
1002 ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2));
Elliott Hughesc3f11402013-10-30 14:40:09 -07001003
Elliott Hughes33697a02016-01-26 13:04:57 -08001004 pid_t pid = fork();
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001005 ASSERT_NE(-1, pid) << strerror(errno);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001006
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001007 // Child and parent calls are made in the order they were registered.
1008 if (pid == 0) {
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001009 ASSERT_EQ(12, g_atfork_child_calls);
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001010 _exit(0);
1011 }
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001012 ASSERT_EQ(12, g_atfork_parent_calls);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001013
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001014 // Prepare calls are made in the reverse order.
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001015 ASSERT_EQ(21, g_atfork_prepare_calls);
Elliott Hughes33697a02016-01-26 13:04:57 -08001016 AssertChildExited(pid, 0);
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001017}
1018
Elliott Hughesc3f11402013-10-30 14:40:09 -07001019TEST(pthread, pthread_attr_getscope) {
1020 pthread_attr_t attr;
1021 ASSERT_EQ(0, pthread_attr_init(&attr));
1022
1023 int scope;
1024 ASSERT_EQ(0, pthread_attr_getscope(&attr, &scope));
1025 ASSERT_EQ(PTHREAD_SCOPE_SYSTEM, scope);
1026}
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001027
1028TEST(pthread, pthread_condattr_init) {
1029 pthread_condattr_t attr;
1030 pthread_condattr_init(&attr);
1031
1032 clockid_t clock;
1033 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1034 ASSERT_EQ(CLOCK_REALTIME, clock);
1035
1036 int pshared;
1037 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1038 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
1039}
1040
1041TEST(pthread, pthread_condattr_setclock) {
1042 pthread_condattr_t attr;
1043 pthread_condattr_init(&attr);
1044
1045 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_REALTIME));
1046 clockid_t clock;
1047 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1048 ASSERT_EQ(CLOCK_REALTIME, clock);
1049
1050 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1051 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1052 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1053
1054 ASSERT_EQ(EINVAL, pthread_condattr_setclock(&attr, CLOCK_PROCESS_CPUTIME_ID));
1055}
1056
1057TEST(pthread, pthread_cond_broadcast__preserves_condattr_flags) {
Yabin Cui32651b82015-03-13 20:30:00 -07001058#if defined(__BIONIC__)
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001059 pthread_condattr_t attr;
1060 pthread_condattr_init(&attr);
1061
1062 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1063 ASSERT_EQ(0, pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
1064
1065 pthread_cond_t cond_var;
1066 ASSERT_EQ(0, pthread_cond_init(&cond_var, &attr));
1067
1068 ASSERT_EQ(0, pthread_cond_signal(&cond_var));
1069 ASSERT_EQ(0, pthread_cond_broadcast(&cond_var));
1070
Yabin Cui32651b82015-03-13 20:30:00 -07001071 attr = static_cast<pthread_condattr_t>(*reinterpret_cast<uint32_t*>(cond_var.__private));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001072 clockid_t clock;
1073 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1074 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1075 int pshared;
1076 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1077 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
Yabin Cui32651b82015-03-13 20:30:00 -07001078#else // !defined(__BIONIC__)
1079 GTEST_LOG_(INFO) << "This tests a bionic implementation detail.\n";
1080#endif // !defined(__BIONIC__)
1081}
1082
1083class pthread_CondWakeupTest : public ::testing::Test {
1084 protected:
1085 pthread_mutex_t mutex;
1086 pthread_cond_t cond;
1087
1088 enum Progress {
1089 INITIALIZED,
1090 WAITING,
1091 SIGNALED,
1092 FINISHED,
1093 };
1094 std::atomic<Progress> progress;
1095 pthread_t thread;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001096 std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function;
Yabin Cui32651b82015-03-13 20:30:00 -07001097
1098 protected:
Yabin Cuic9a659c2015-11-05 15:36:08 -08001099 void SetUp() override {
1100 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1101 }
1102
1103 void InitCond(clockid_t clock=CLOCK_REALTIME) {
1104 pthread_condattr_t attr;
1105 ASSERT_EQ(0, pthread_condattr_init(&attr));
1106 ASSERT_EQ(0, pthread_condattr_setclock(&attr, clock));
1107 ASSERT_EQ(0, pthread_cond_init(&cond, &attr));
1108 ASSERT_EQ(0, pthread_condattr_destroy(&attr));
1109 }
1110
1111 void StartWaitingThread(std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function) {
Yabin Cui32651b82015-03-13 20:30:00 -07001112 progress = INITIALIZED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001113 this->wait_function = wait_function;
1114 ASSERT_EQ(0, pthread_create(&thread, NULL, reinterpret_cast<void* (*)(void*)>(WaitThreadFn), this));
1115 while (progress != WAITING) {
Yabin Cui32651b82015-03-13 20:30:00 -07001116 usleep(5000);
1117 }
1118 usleep(5000);
1119 }
1120
Yabin Cuic9a659c2015-11-05 15:36:08 -08001121 void TearDown() override {
1122 ASSERT_EQ(0, pthread_join(thread, nullptr));
1123 ASSERT_EQ(FINISHED, progress);
1124 ASSERT_EQ(0, pthread_cond_destroy(&cond));
1125 ASSERT_EQ(0, pthread_mutex_destroy(&mutex));
1126 }
1127
Yabin Cui32651b82015-03-13 20:30:00 -07001128 private:
1129 static void WaitThreadFn(pthread_CondWakeupTest* test) {
1130 ASSERT_EQ(0, pthread_mutex_lock(&test->mutex));
1131 test->progress = WAITING;
1132 while (test->progress == WAITING) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001133 ASSERT_EQ(0, test->wait_function(&test->cond, &test->mutex));
Yabin Cui32651b82015-03-13 20:30:00 -07001134 }
1135 ASSERT_EQ(SIGNALED, test->progress);
1136 test->progress = FINISHED;
1137 ASSERT_EQ(0, pthread_mutex_unlock(&test->mutex));
1138 }
1139};
1140
Yabin Cuic9a659c2015-11-05 15:36:08 -08001141TEST_F(pthread_CondWakeupTest, signal_wait) {
1142 InitCond();
1143 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1144 return pthread_cond_wait(cond, mutex);
1145 });
Yabin Cui32651b82015-03-13 20:30:00 -07001146 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001147 ASSERT_EQ(0, pthread_cond_signal(&cond));
Yabin Cui32651b82015-03-13 20:30:00 -07001148}
1149
Yabin Cuic9a659c2015-11-05 15:36:08 -08001150TEST_F(pthread_CondWakeupTest, broadcast_wait) {
1151 InitCond();
1152 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1153 return pthread_cond_wait(cond, mutex);
1154 });
Yabin Cui32651b82015-03-13 20:30:00 -07001155 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001156 ASSERT_EQ(0, pthread_cond_broadcast(&cond));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001157}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001158
Yabin Cuic9a659c2015-11-05 15:36:08 -08001159TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_REALTIME) {
1160 InitCond(CLOCK_REALTIME);
Elliott Hughes0e714a52014-03-03 16:42:47 -08001161 timespec ts;
1162 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001163 ts.tv_sec += 1;
1164 StartWaitingThread([&](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1165 return pthread_cond_timedwait(cond, mutex, &ts);
1166 });
1167 progress = SIGNALED;
1168 ASSERT_EQ(0, pthread_cond_signal(&cond));
1169}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001170
Yabin Cuic9a659c2015-11-05 15:36:08 -08001171TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC) {
1172 InitCond(CLOCK_MONOTONIC);
1173 timespec ts;
1174 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1175 ts.tv_sec += 1;
1176 StartWaitingThread([&](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1177 return pthread_cond_timedwait(cond, mutex, &ts);
1178 });
1179 progress = SIGNALED;
1180 ASSERT_EQ(0, pthread_cond_signal(&cond));
1181}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001182
Yabin Cuic9a659c2015-11-05 15:36:08 -08001183TEST(pthread, pthread_cond_timedwait_timeout) {
1184 pthread_mutex_t mutex;
1185 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1186 pthread_cond_t cond;
1187 ASSERT_EQ(0, pthread_cond_init(&cond, nullptr));
1188 ASSERT_EQ(0, pthread_mutex_lock(&mutex));
1189 timespec ts;
Elliott Hughes0e714a52014-03-03 16:42:47 -08001190 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001191 ASSERT_EQ(ETIMEDOUT, pthread_cond_timedwait(&cond, &mutex, &ts));
1192 ts.tv_nsec = -1;
1193 ASSERT_EQ(EINVAL, pthread_cond_timedwait(&cond, &mutex, &ts));
1194 ts.tv_nsec = NS_PER_S;
1195 ASSERT_EQ(EINVAL, pthread_cond_timedwait(&cond, &mutex, &ts));
1196 ts.tv_nsec = NS_PER_S - 1;
1197 ts.tv_sec = -1;
1198 ASSERT_EQ(ETIMEDOUT, pthread_cond_timedwait(&cond, &mutex, &ts));
1199 ASSERT_EQ(0, pthread_mutex_unlock(&mutex));
Elliott Hughes0e714a52014-03-03 16:42:47 -08001200}
Elliott Hughes57b7a612014-08-25 17:26:50 -07001201
1202TEST(pthread, pthread_attr_getstack__main_thread) {
1203 // This test is only meaningful for the main thread, so make sure we're running on it!
1204 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1205
1206 // Get the main thread's attributes.
1207 pthread_attr_t attributes;
1208 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1209
1210 // Check that we correctly report that the main thread has no guard page.
1211 size_t guard_size;
1212 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
1213 ASSERT_EQ(0U, guard_size); // The main thread has no guard page.
1214
1215 // Get the stack base and the stack size (both ways).
1216 void* stack_base;
1217 size_t stack_size;
1218 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1219 size_t stack_size2;
1220 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1221
1222 // The two methods of asking for the stack size should agree.
1223 EXPECT_EQ(stack_size, stack_size2);
1224
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001225#if defined(__BIONIC__)
Elliott Hughes57b7a612014-08-25 17:26:50 -07001226 // What does /proc/self/maps' [stack] line say?
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001227 void* maps_stack_hi = NULL;
Elliott Hughes15dfd632015-09-22 16:40:14 -07001228 std::vector<map_record> maps;
1229 ASSERT_TRUE(Maps::parse_maps(&maps));
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07001230 for (const auto& map : maps) {
Elliott Hughes15dfd632015-09-22 16:40:14 -07001231 if (map.pathname == "[stack]") {
1232 maps_stack_hi = reinterpret_cast<void*>(map.addr_end);
Elliott Hughes57b7a612014-08-25 17:26:50 -07001233 break;
1234 }
1235 }
Elliott Hughes57b7a612014-08-25 17:26:50 -07001236
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001237 // The high address of the /proc/self/maps [stack] region should equal stack_base + stack_size.
1238 // Remember that the stack grows down (and is mapped in on demand), so the low address of the
1239 // region isn't very interesting.
1240 EXPECT_EQ(maps_stack_hi, reinterpret_cast<uint8_t*>(stack_base) + stack_size);
1241
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001242 // The stack size should correspond to RLIMIT_STACK.
Elliott Hughes57b7a612014-08-25 17:26:50 -07001243 rlimit rl;
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001244 ASSERT_EQ(0, getrlimit(RLIMIT_STACK, &rl));
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001245 uint64_t original_rlim_cur = rl.rlim_cur;
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001246 if (rl.rlim_cur == RLIM_INFINITY) {
1247 rl.rlim_cur = 8 * 1024 * 1024; // Bionic reports unlimited stacks as 8MiB.
1248 }
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001249 EXPECT_EQ(rl.rlim_cur, stack_size);
1250
Dmitriy Ivanovd9ff7222014-09-08 16:22:22 -07001251 auto guard = make_scope_guard([&rl, original_rlim_cur]() {
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001252 rl.rlim_cur = original_rlim_cur;
1253 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1254 });
1255
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001256 //
1257 // What if RLIMIT_STACK is smaller than the stack's current extent?
1258 //
Elliott Hughes57b7a612014-08-25 17:26:50 -07001259 rl.rlim_cur = rl.rlim_max = 1024; // 1KiB. We know the stack must be at least a page already.
1260 rl.rlim_max = RLIM_INFINITY;
1261 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1262
1263 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1264 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1265 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1266
1267 EXPECT_EQ(stack_size, stack_size2);
1268 ASSERT_EQ(1024U, stack_size);
1269
1270 //
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001271 // What if RLIMIT_STACK isn't a whole number of pages?
Elliott Hughes57b7a612014-08-25 17:26:50 -07001272 //
1273 rl.rlim_cur = rl.rlim_max = 6666; // Not a whole number of pages.
1274 rl.rlim_max = RLIM_INFINITY;
1275 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1276
1277 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1278 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1279 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1280
1281 EXPECT_EQ(stack_size, stack_size2);
1282 ASSERT_EQ(6666U, stack_size);
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001283#endif
Elliott Hughes57b7a612014-08-25 17:26:50 -07001284}
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001285
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001286struct GetStackSignalHandlerArg {
1287 volatile bool done;
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001288 void* signal_stack_base;
1289 size_t signal_stack_size;
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001290 void* main_stack_base;
1291 size_t main_stack_size;
1292};
1293
1294static GetStackSignalHandlerArg getstack_signal_handler_arg;
1295
1296static void getstack_signal_handler(int sig) {
1297 ASSERT_EQ(SIGUSR1, sig);
1298 // Use sleep() to make current thread be switched out by the kernel to provoke the error.
1299 sleep(1);
1300 pthread_attr_t attr;
1301 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1302 void* stack_base;
1303 size_t stack_size;
1304 ASSERT_EQ(0, pthread_attr_getstack(&attr, &stack_base, &stack_size));
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001305
1306 // Verify if the stack used by the signal handler is the alternate stack just registered.
1307 ASSERT_LE(getstack_signal_handler_arg.signal_stack_base, &attr);
1308 ASSERT_LT(static_cast<void*>(&attr),
1309 static_cast<char*>(getstack_signal_handler_arg.signal_stack_base) +
1310 getstack_signal_handler_arg.signal_stack_size);
1311
1312 // Verify if the main thread's stack got in the signal handler is correct.
1313 ASSERT_EQ(getstack_signal_handler_arg.main_stack_base, stack_base);
1314 ASSERT_LE(getstack_signal_handler_arg.main_stack_size, stack_size);
1315
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001316 getstack_signal_handler_arg.done = true;
1317}
1318
1319// The previous code obtained the main thread's stack by reading the entry in
1320// /proc/self/task/<pid>/maps that was labeled [stack]. Unfortunately, on x86/x86_64, the kernel
1321// relies on sp0 in task state segment(tss) to label the stack map with [stack]. If the kernel
1322// switches a process while the main thread is in an alternate stack, then the kernel will label
1323// the wrong map with [stack]. This test verifies that when the above situation happens, the main
1324// thread's stack is found correctly.
1325TEST(pthread, pthread_attr_getstack_in_signal_handler) {
Yabin Cui61e4d462016-03-07 17:44:58 -08001326 // This test is only meaningful for the main thread, so make sure we're running on it!
1327 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1328
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001329 const size_t sig_stack_size = 16 * 1024;
1330 void* sig_stack = mmap(NULL, sig_stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS,
1331 -1, 0);
1332 ASSERT_NE(MAP_FAILED, sig_stack);
1333 stack_t ss;
1334 ss.ss_sp = sig_stack;
1335 ss.ss_size = sig_stack_size;
1336 ss.ss_flags = 0;
1337 stack_t oss;
1338 ASSERT_EQ(0, sigaltstack(&ss, &oss));
1339
Yabin Cui61e4d462016-03-07 17:44:58 -08001340 pthread_attr_t attr;
1341 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1342 void* main_stack_base;
1343 size_t main_stack_size;
1344 ASSERT_EQ(0, pthread_attr_getstack(&attr, &main_stack_base, &main_stack_size));
1345
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001346 ScopedSignalHandler handler(SIGUSR1, getstack_signal_handler, SA_ONSTACK);
1347 getstack_signal_handler_arg.done = false;
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001348 getstack_signal_handler_arg.signal_stack_base = sig_stack;
1349 getstack_signal_handler_arg.signal_stack_size = sig_stack_size;
1350 getstack_signal_handler_arg.main_stack_base = main_stack_base;
1351 getstack_signal_handler_arg.main_stack_size = main_stack_size;
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001352 kill(getpid(), SIGUSR1);
1353 ASSERT_EQ(true, getstack_signal_handler_arg.done);
1354
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001355 ASSERT_EQ(0, sigaltstack(&oss, nullptr));
1356 ASSERT_EQ(0, munmap(sig_stack, sig_stack_size));
1357}
1358
Yabin Cui917d3902015-01-08 12:32:42 -08001359static void pthread_attr_getstack_18908062_helper(void*) {
1360 char local_variable;
1361 pthread_attr_t attributes;
1362 pthread_getattr_np(pthread_self(), &attributes);
1363 void* stack_base;
1364 size_t stack_size;
1365 pthread_attr_getstack(&attributes, &stack_base, &stack_size);
1366
1367 // Test whether &local_variable is in [stack_base, stack_base + stack_size).
1368 ASSERT_LE(reinterpret_cast<char*>(stack_base), &local_variable);
1369 ASSERT_LT(&local_variable, reinterpret_cast<char*>(stack_base) + stack_size);
1370}
1371
1372// Check whether something on stack is in the range of
1373// [stack_base, stack_base + stack_size). see b/18908062.
1374TEST(pthread, pthread_attr_getstack_18908062) {
1375 pthread_t t;
1376 ASSERT_EQ(0, pthread_create(&t, NULL,
1377 reinterpret_cast<void* (*)(void*)>(pthread_attr_getstack_18908062_helper),
1378 NULL));
1379 pthread_join(t, NULL);
1380}
1381
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001382#if defined(__BIONIC__)
Elliott Hughesf2083612015-11-11 13:32:28 -08001383static pthread_mutex_t pthread_gettid_np_mutex = PTHREAD_MUTEX_INITIALIZER;
1384
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001385static void* pthread_gettid_np_helper(void* arg) {
1386 *reinterpret_cast<pid_t*>(arg) = gettid();
Elliott Hughesf2083612015-11-11 13:32:28 -08001387
1388 // Wait for our parent to call pthread_gettid_np on us before exiting.
1389 pthread_mutex_lock(&pthread_gettid_np_mutex);
1390 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001391 return NULL;
1392}
1393#endif
1394
1395TEST(pthread, pthread_gettid_np) {
1396#if defined(__BIONIC__)
1397 ASSERT_EQ(gettid(), pthread_gettid_np(pthread_self()));
1398
Elliott Hughesf2083612015-11-11 13:32:28 -08001399 // Ensure the other thread doesn't exit until after we've called
1400 // pthread_gettid_np on it.
1401 pthread_mutex_lock(&pthread_gettid_np_mutex);
1402
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001403 pid_t t_gettid_result;
1404 pthread_t t;
1405 pthread_create(&t, NULL, pthread_gettid_np_helper, &t_gettid_result);
1406
1407 pid_t t_pthread_gettid_np_result = pthread_gettid_np(t);
1408
Elliott Hughesf2083612015-11-11 13:32:28 -08001409 // Release the other thread and wait for it to exit.
1410 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Elliott Hughes34c987a2014-09-22 16:01:26 -07001411 pthread_join(t, NULL);
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001412
1413 ASSERT_EQ(t_gettid_result, t_pthread_gettid_np_result);
1414#else
1415 GTEST_LOG_(INFO) << "This test does nothing.\n";
1416#endif
1417}
Elliott Hughes34c987a2014-09-22 16:01:26 -07001418
1419static size_t cleanup_counter = 0;
1420
Derek Xue41996952014-09-25 11:05:32 +01001421static void AbortCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001422 abort();
1423}
1424
Derek Xue41996952014-09-25 11:05:32 +01001425static void CountCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001426 ++cleanup_counter;
1427}
1428
Derek Xue41996952014-09-25 11:05:32 +01001429static void PthreadCleanupTester() {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001430 pthread_cleanup_push(CountCleanupRoutine, NULL);
1431 pthread_cleanup_push(CountCleanupRoutine, NULL);
1432 pthread_cleanup_push(AbortCleanupRoutine, NULL);
1433
1434 pthread_cleanup_pop(0); // Pop the abort without executing it.
1435 pthread_cleanup_pop(1); // Pop one count while executing it.
1436 ASSERT_EQ(1U, cleanup_counter);
1437 // Exit while the other count is still on the cleanup stack.
1438 pthread_exit(NULL);
1439
1440 // Calls to pthread_cleanup_pop/pthread_cleanup_push must always be balanced.
1441 pthread_cleanup_pop(0);
1442}
1443
Derek Xue41996952014-09-25 11:05:32 +01001444static void* PthreadCleanupStartRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001445 PthreadCleanupTester();
1446 return NULL;
1447}
1448
1449TEST(pthread, pthread_cleanup_push__pthread_cleanup_pop) {
1450 pthread_t t;
1451 ASSERT_EQ(0, pthread_create(&t, NULL, PthreadCleanupStartRoutine, NULL));
1452 pthread_join(t, NULL);
1453 ASSERT_EQ(2U, cleanup_counter);
1454}
Derek Xue41996952014-09-25 11:05:32 +01001455
1456TEST(pthread, PTHREAD_MUTEX_DEFAULT_is_PTHREAD_MUTEX_NORMAL) {
1457 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_DEFAULT);
1458}
1459
1460TEST(pthread, pthread_mutexattr_gettype) {
1461 pthread_mutexattr_t attr;
1462 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1463
1464 int attr_type;
1465
1466 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL));
1467 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1468 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, attr_type);
1469
1470 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK));
1471 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1472 ASSERT_EQ(PTHREAD_MUTEX_ERRORCHECK, attr_type);
1473
1474 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE));
1475 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1476 ASSERT_EQ(PTHREAD_MUTEX_RECURSIVE, attr_type);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001477
1478 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
1479}
1480
Yabin Cui17393b02015-03-21 15:08:25 -07001481struct PthreadMutex {
1482 pthread_mutex_t lock;
1483
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -07001484 explicit PthreadMutex(int mutex_type) {
Yabin Cui17393b02015-03-21 15:08:25 -07001485 init(mutex_type);
1486 }
1487
1488 ~PthreadMutex() {
1489 destroy();
1490 }
1491
1492 private:
1493 void init(int mutex_type) {
1494 pthread_mutexattr_t attr;
1495 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1496 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, mutex_type));
1497 ASSERT_EQ(0, pthread_mutex_init(&lock, &attr));
1498 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
1499 }
1500
1501 void destroy() {
1502 ASSERT_EQ(0, pthread_mutex_destroy(&lock));
1503 }
1504
1505 DISALLOW_COPY_AND_ASSIGN(PthreadMutex);
1506};
Derek Xue41996952014-09-25 11:05:32 +01001507
1508TEST(pthread, pthread_mutex_lock_NORMAL) {
Yabin Cui17393b02015-03-21 15:08:25 -07001509 PthreadMutex m(PTHREAD_MUTEX_NORMAL);
Derek Xue41996952014-09-25 11:05:32 +01001510
Yabin Cui17393b02015-03-21 15:08:25 -07001511 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1512 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08001513 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
1514 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
1515 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01001516}
1517
1518TEST(pthread, pthread_mutex_lock_ERRORCHECK) {
Yabin Cui17393b02015-03-21 15:08:25 -07001519 PthreadMutex m(PTHREAD_MUTEX_ERRORCHECK);
Derek Xue41996952014-09-25 11:05:32 +01001520
Yabin Cui17393b02015-03-21 15:08:25 -07001521 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1522 ASSERT_EQ(EDEADLK, pthread_mutex_lock(&m.lock));
1523 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1524 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
1525 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
1526 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1527 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01001528}
1529
1530TEST(pthread, pthread_mutex_lock_RECURSIVE) {
Yabin Cui17393b02015-03-21 15:08:25 -07001531 PthreadMutex m(PTHREAD_MUTEX_RECURSIVE);
Derek Xue41996952014-09-25 11:05:32 +01001532
Yabin Cui17393b02015-03-21 15:08:25 -07001533 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1534 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1535 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1536 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1537 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08001538 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
1539 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07001540 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1541 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
1542}
1543
1544TEST(pthread, pthread_mutex_init_same_as_static_initializers) {
1545 pthread_mutex_t lock_normal = PTHREAD_MUTEX_INITIALIZER;
1546 PthreadMutex m1(PTHREAD_MUTEX_NORMAL);
1547 ASSERT_EQ(0, memcmp(&lock_normal, &m1.lock, sizeof(pthread_mutex_t)));
1548 pthread_mutex_destroy(&lock_normal);
1549
1550 pthread_mutex_t lock_errorcheck = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
1551 PthreadMutex m2(PTHREAD_MUTEX_ERRORCHECK);
1552 ASSERT_EQ(0, memcmp(&lock_errorcheck, &m2.lock, sizeof(pthread_mutex_t)));
1553 pthread_mutex_destroy(&lock_errorcheck);
1554
1555 pthread_mutex_t lock_recursive = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
1556 PthreadMutex m3(PTHREAD_MUTEX_RECURSIVE);
1557 ASSERT_EQ(0, memcmp(&lock_recursive, &m3.lock, sizeof(pthread_mutex_t)));
1558 ASSERT_EQ(0, pthread_mutex_destroy(&lock_recursive));
Derek Xue41996952014-09-25 11:05:32 +01001559}
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001560class MutexWakeupHelper {
1561 private:
Yabin Cui17393b02015-03-21 15:08:25 -07001562 PthreadMutex m;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001563 enum Progress {
1564 LOCK_INITIALIZED,
1565 LOCK_WAITING,
1566 LOCK_RELEASED,
1567 LOCK_ACCESSED
1568 };
1569 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -07001570 std::atomic<pid_t> tid;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001571
1572 static void thread_fn(MutexWakeupHelper* helper) {
Yabin Cuif7969852015-04-02 17:47:48 -07001573 helper->tid = gettid();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001574 ASSERT_EQ(LOCK_INITIALIZED, helper->progress);
1575 helper->progress = LOCK_WAITING;
1576
Yabin Cui17393b02015-03-21 15:08:25 -07001577 ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001578 ASSERT_EQ(LOCK_RELEASED, helper->progress);
Yabin Cui17393b02015-03-21 15:08:25 -07001579 ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001580
1581 helper->progress = LOCK_ACCESSED;
1582 }
1583
1584 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -07001585 explicit MutexWakeupHelper(int mutex_type) : m(mutex_type) {
Yabin Cui17393b02015-03-21 15:08:25 -07001586 }
1587
1588 void test() {
1589 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001590 progress = LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -07001591 tid = 0;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001592
1593 pthread_t thread;
1594 ASSERT_EQ(0, pthread_create(&thread, NULL,
1595 reinterpret_cast<void* (*)(void*)>(MutexWakeupHelper::thread_fn), this));
1596
Yabin Cuif7969852015-04-02 17:47:48 -07001597 WaitUntilThreadSleep(tid);
1598 ASSERT_EQ(LOCK_WAITING, progress);
1599
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001600 progress = LOCK_RELEASED;
Yabin Cui17393b02015-03-21 15:08:25 -07001601 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001602
1603 ASSERT_EQ(0, pthread_join(thread, NULL));
1604 ASSERT_EQ(LOCK_ACCESSED, progress);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001605 }
1606};
1607
1608TEST(pthread, pthread_mutex_NORMAL_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07001609 MutexWakeupHelper helper(PTHREAD_MUTEX_NORMAL);
1610 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001611}
1612
1613TEST(pthread, pthread_mutex_ERRORCHECK_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07001614 MutexWakeupHelper helper(PTHREAD_MUTEX_ERRORCHECK);
1615 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001616}
1617
1618TEST(pthread, pthread_mutex_RECURSIVE_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07001619 MutexWakeupHelper helper(PTHREAD_MUTEX_RECURSIVE);
1620 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001621}
1622
Yabin Cui140f3672015-02-03 10:32:00 -08001623TEST(pthread, pthread_mutex_owner_tid_limit) {
Yabin Cuie69c2452015-02-13 16:21:25 -08001624#if defined(__BIONIC__) && !defined(__LP64__)
Yabin Cui140f3672015-02-03 10:32:00 -08001625 FILE* fp = fopen("/proc/sys/kernel/pid_max", "r");
1626 ASSERT_TRUE(fp != NULL);
1627 long pid_max;
1628 ASSERT_EQ(1, fscanf(fp, "%ld", &pid_max));
1629 fclose(fp);
Yabin Cuie69c2452015-02-13 16:21:25 -08001630 // Bionic's pthread_mutex implementation on 32-bit devices uses 16 bits to represent owner tid.
Yabin Cui140f3672015-02-03 10:32:00 -08001631 ASSERT_LE(pid_max, 65536);
Yabin Cuie69c2452015-02-13 16:21:25 -08001632#else
1633 GTEST_LOG_(INFO) << "This test does nothing as 32-bit tid is supported by pthread_mutex.\n";
1634#endif
Yabin Cui140f3672015-02-03 10:32:00 -08001635}
Yabin Cuib5845722015-03-16 22:46:42 -07001636
Yabin Cuic9a659c2015-11-05 15:36:08 -08001637TEST(pthread, pthread_mutex_timedlock) {
1638 pthread_mutex_t m;
1639 ASSERT_EQ(0, pthread_mutex_init(&m, nullptr));
1640
1641 // If the mutex is already locked, pthread_mutex_timedlock should time out.
1642 ASSERT_EQ(0, pthread_mutex_lock(&m));
1643
1644 timespec ts;
1645 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1646 ASSERT_EQ(ETIMEDOUT, pthread_mutex_timedlock(&m, &ts));
1647 ts.tv_nsec = -1;
1648 ASSERT_EQ(EINVAL, pthread_mutex_timedlock(&m, &ts));
1649 ts.tv_nsec = NS_PER_S;
1650 ASSERT_EQ(EINVAL, pthread_mutex_timedlock(&m, &ts));
1651 ts.tv_nsec = NS_PER_S - 1;
1652 ts.tv_sec = -1;
1653 ASSERT_EQ(ETIMEDOUT, pthread_mutex_timedlock(&m, &ts));
1654
1655 // If the mutex is unlocked, pthread_mutex_timedlock should succeed.
1656 ASSERT_EQ(0, pthread_mutex_unlock(&m));
1657
1658 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1659 ts.tv_sec += 1;
1660 ASSERT_EQ(0, pthread_mutex_timedlock(&m, &ts));
1661
1662 ASSERT_EQ(0, pthread_mutex_unlock(&m));
1663 ASSERT_EQ(0, pthread_mutex_destroy(&m));
1664}
1665
Yabin Cuib5845722015-03-16 22:46:42 -07001666class StrictAlignmentAllocator {
1667 public:
1668 void* allocate(size_t size, size_t alignment) {
1669 char* p = new char[size + alignment * 2];
1670 allocated_array.push_back(p);
1671 while (!is_strict_aligned(p, alignment)) {
1672 ++p;
1673 }
1674 return p;
1675 }
1676
1677 ~StrictAlignmentAllocator() {
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07001678 for (const auto& p : allocated_array) {
1679 delete[] p;
Yabin Cuib5845722015-03-16 22:46:42 -07001680 }
1681 }
1682
1683 private:
1684 bool is_strict_aligned(char* p, size_t alignment) {
1685 return (reinterpret_cast<uintptr_t>(p) % (alignment * 2)) == alignment;
1686 }
1687
1688 std::vector<char*> allocated_array;
1689};
1690
1691TEST(pthread, pthread_types_allow_four_bytes_alignment) {
1692#if defined(__BIONIC__)
1693 // For binary compatibility with old version, we need to allow 4-byte aligned data for pthread types.
1694 StrictAlignmentAllocator allocator;
1695 pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(
1696 allocator.allocate(sizeof(pthread_mutex_t), 4));
1697 ASSERT_EQ(0, pthread_mutex_init(mutex, NULL));
1698 ASSERT_EQ(0, pthread_mutex_lock(mutex));
1699 ASSERT_EQ(0, pthread_mutex_unlock(mutex));
1700 ASSERT_EQ(0, pthread_mutex_destroy(mutex));
1701
1702 pthread_cond_t* cond = reinterpret_cast<pthread_cond_t*>(
1703 allocator.allocate(sizeof(pthread_cond_t), 4));
1704 ASSERT_EQ(0, pthread_cond_init(cond, NULL));
1705 ASSERT_EQ(0, pthread_cond_signal(cond));
1706 ASSERT_EQ(0, pthread_cond_broadcast(cond));
1707 ASSERT_EQ(0, pthread_cond_destroy(cond));
1708
1709 pthread_rwlock_t* rwlock = reinterpret_cast<pthread_rwlock_t*>(
1710 allocator.allocate(sizeof(pthread_rwlock_t), 4));
1711 ASSERT_EQ(0, pthread_rwlock_init(rwlock, NULL));
1712 ASSERT_EQ(0, pthread_rwlock_rdlock(rwlock));
1713 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
1714 ASSERT_EQ(0, pthread_rwlock_wrlock(rwlock));
1715 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
1716 ASSERT_EQ(0, pthread_rwlock_destroy(rwlock));
1717
1718#else
1719 GTEST_LOG_(INFO) << "This test tests bionic implementation details.";
1720#endif
1721}
Christopher Ferris60907c72015-06-09 18:46:15 -07001722
1723TEST(pthread, pthread_mutex_lock_null_32) {
1724#if defined(__BIONIC__) && !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -07001725 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return
1726 // EINVAL in that case: http://b/19995172.
1727 //
1728 // We decorate the public defintion with _Nonnull so that people recompiling
1729 // their code with get a warning and might fix their bug, but need to pass
1730 // NULL here to test that we remain compatible.
1731 pthread_mutex_t* null_value = nullptr;
1732 ASSERT_EQ(EINVAL, pthread_mutex_lock(null_value));
Christopher Ferris60907c72015-06-09 18:46:15 -07001733#else
1734 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 32 bit devices.";
1735#endif
1736}
1737
1738TEST(pthread, pthread_mutex_unlock_null_32) {
1739#if defined(__BIONIC__) && !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -07001740 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return
1741 // EINVAL in that case: http://b/19995172.
1742 //
1743 // We decorate the public defintion with _Nonnull so that people recompiling
1744 // their code with get a warning and might fix their bug, but need to pass
1745 // NULL here to test that we remain compatible.
1746 pthread_mutex_t* null_value = nullptr;
1747 ASSERT_EQ(EINVAL, pthread_mutex_unlock(null_value));
Christopher Ferris60907c72015-06-09 18:46:15 -07001748#else
1749 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 32 bit devices.";
1750#endif
1751}
1752
1753TEST_F(pthread_DeathTest, pthread_mutex_lock_null_64) {
1754#if defined(__BIONIC__) && defined(__LP64__)
1755 pthread_mutex_t* null_value = nullptr;
1756 ASSERT_EXIT(pthread_mutex_lock(null_value), testing::KilledBySignal(SIGSEGV), "");
1757#else
1758 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 64 bit devices.";
1759#endif
1760}
1761
1762TEST_F(pthread_DeathTest, pthread_mutex_unlock_null_64) {
1763#if defined(__BIONIC__) && defined(__LP64__)
1764 pthread_mutex_t* null_value = nullptr;
1765 ASSERT_EXIT(pthread_mutex_unlock(null_value), testing::KilledBySignal(SIGSEGV), "");
1766#else
1767 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 64 bit devices.";
1768#endif
1769}
Yabin Cui33ac04a2015-09-22 11:16:15 -07001770
1771extern _Unwind_Reason_Code FrameCounter(_Unwind_Context* ctx, void* arg);
1772
1773static volatile bool signal_handler_on_altstack_done;
1774
1775static void SignalHandlerOnAltStack(int signo, siginfo_t*, void*) {
1776 ASSERT_EQ(SIGUSR1, signo);
1777 // Check if we have enough stack space for unwinding.
1778 int count = 0;
1779 _Unwind_Backtrace(FrameCounter, &count);
1780 ASSERT_GT(count, 0);
1781 // Check if we have enough stack space for logging.
1782 std::string s(2048, '*');
1783 GTEST_LOG_(INFO) << s;
1784 signal_handler_on_altstack_done = true;
1785}
1786
1787TEST(pthread, big_enough_signal_stack_for_64bit_arch) {
1788 signal_handler_on_altstack_done = false;
1789 ScopedSignalHandler handler(SIGUSR1, SignalHandlerOnAltStack, SA_SIGINFO | SA_ONSTACK);
1790 kill(getpid(), SIGUSR1);
1791 ASSERT_TRUE(signal_handler_on_altstack_done);
1792}
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001793
1794TEST(pthread, pthread_barrierattr_smoke) {
1795 pthread_barrierattr_t attr;
1796 ASSERT_EQ(0, pthread_barrierattr_init(&attr));
1797 int pshared;
1798 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
1799 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
1800 ASSERT_EQ(0, pthread_barrierattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
1801 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
1802 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
1803 ASSERT_EQ(0, pthread_barrierattr_destroy(&attr));
1804}
1805
Yabin Cui81d27972016-03-22 13:45:55 -07001806struct BarrierTestHelperData {
1807 size_t thread_count;
1808 pthread_barrier_t barrier;
1809 std::atomic<int> finished_mask;
1810 std::atomic<int> serial_thread_count;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001811 size_t iteration_count;
Yabin Cui81d27972016-03-22 13:45:55 -07001812 std::atomic<size_t> finished_iteration_count;
1813
1814 BarrierTestHelperData(size_t thread_count, size_t iteration_count)
1815 : thread_count(thread_count), finished_mask(0), serial_thread_count(0),
1816 iteration_count(iteration_count), finished_iteration_count(0) {
1817 }
1818};
1819
1820struct BarrierTestHelperArg {
1821 int id;
1822 BarrierTestHelperData* data;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001823};
1824
1825static void BarrierTestHelper(BarrierTestHelperArg* arg) {
Yabin Cui81d27972016-03-22 13:45:55 -07001826 for (size_t i = 0; i < arg->data->iteration_count; ++i) {
1827 int result = pthread_barrier_wait(&arg->data->barrier);
1828 if (result == PTHREAD_BARRIER_SERIAL_THREAD) {
1829 arg->data->serial_thread_count++;
1830 } else {
1831 ASSERT_EQ(0, result);
1832 }
1833 arg->data->finished_mask |= (1 << arg->id);
1834 if (arg->data->finished_mask == ((1 << arg->data->thread_count) - 1)) {
1835 ASSERT_EQ(1, arg->data->serial_thread_count);
1836 arg->data->finished_iteration_count++;
1837 arg->data->finished_mask = 0;
1838 arg->data->serial_thread_count = 0;
1839 }
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001840 }
1841}
1842
1843TEST(pthread, pthread_barrier_smoke) {
1844 const size_t BARRIER_ITERATION_COUNT = 10;
1845 const size_t BARRIER_THREAD_COUNT = 10;
Yabin Cui81d27972016-03-22 13:45:55 -07001846 BarrierTestHelperData data(BARRIER_THREAD_COUNT, BARRIER_ITERATION_COUNT);
1847 ASSERT_EQ(0, pthread_barrier_init(&data.barrier, nullptr, data.thread_count));
1848 std::vector<pthread_t> threads(data.thread_count);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001849 std::vector<BarrierTestHelperArg> args(threads.size());
1850 for (size_t i = 0; i < threads.size(); ++i) {
Yabin Cui81d27972016-03-22 13:45:55 -07001851 args[i].id = i;
1852 args[i].data = &data;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001853 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
1854 reinterpret_cast<void* (*)(void*)>(BarrierTestHelper), &args[i]));
1855 }
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001856 for (size_t i = 0; i < threads.size(); ++i) {
1857 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
1858 }
Yabin Cui81d27972016-03-22 13:45:55 -07001859 ASSERT_EQ(data.iteration_count, data.finished_iteration_count);
1860 ASSERT_EQ(0, pthread_barrier_destroy(&data.barrier));
1861}
1862
1863struct BarrierDestroyTestArg {
1864 std::atomic<int> tid;
1865 pthread_barrier_t* barrier;
1866};
1867
1868static void BarrierDestroyTestHelper(BarrierDestroyTestArg* arg) {
1869 arg->tid = gettid();
1870 ASSERT_EQ(0, pthread_barrier_wait(arg->barrier));
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001871}
1872
1873TEST(pthread, pthread_barrier_destroy) {
1874 pthread_barrier_t barrier;
1875 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, 2));
1876 pthread_t thread;
Yabin Cui81d27972016-03-22 13:45:55 -07001877 BarrierDestroyTestArg arg;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001878 arg.tid = 0;
1879 arg.barrier = &barrier;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001880 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui81d27972016-03-22 13:45:55 -07001881 reinterpret_cast<void* (*)(void*)>(BarrierDestroyTestHelper), &arg));
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001882 WaitUntilThreadSleep(arg.tid);
1883 ASSERT_EQ(EBUSY, pthread_barrier_destroy(&barrier));
1884 ASSERT_EQ(PTHREAD_BARRIER_SERIAL_THREAD, pthread_barrier_wait(&barrier));
1885 // Verify if the barrier can be destroyed directly after pthread_barrier_wait().
1886 ASSERT_EQ(0, pthread_barrier_destroy(&barrier));
1887 ASSERT_EQ(0, pthread_join(thread, nullptr));
1888#if defined(__BIONIC__)
1889 ASSERT_EQ(EINVAL, pthread_barrier_destroy(&barrier));
1890#endif
1891}
1892
1893struct BarrierOrderingTestHelperArg {
1894 pthread_barrier_t* barrier;
1895 size_t* array;
1896 size_t array_length;
1897 size_t id;
1898};
1899
1900void BarrierOrderingTestHelper(BarrierOrderingTestHelperArg* arg) {
1901 const size_t ITERATION_COUNT = 10000;
1902 for (size_t i = 1; i <= ITERATION_COUNT; ++i) {
1903 arg->array[arg->id] = i;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001904 int result = pthread_barrier_wait(arg->barrier);
1905 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001906 for (size_t j = 0; j < arg->array_length; ++j) {
1907 ASSERT_EQ(i, arg->array[j]);
1908 }
Yabin Cuic9a659c2015-11-05 15:36:08 -08001909 result = pthread_barrier_wait(arg->barrier);
1910 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001911 }
1912}
1913
1914TEST(pthread, pthread_barrier_check_ordering) {
1915 const size_t THREAD_COUNT = 4;
1916 pthread_barrier_t barrier;
1917 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, THREAD_COUNT));
1918 size_t array[THREAD_COUNT];
1919 std::vector<pthread_t> threads(THREAD_COUNT);
1920 std::vector<BarrierOrderingTestHelperArg> args(THREAD_COUNT);
1921 for (size_t i = 0; i < THREAD_COUNT; ++i) {
1922 args[i].barrier = &barrier;
1923 args[i].array = array;
1924 args[i].array_length = THREAD_COUNT;
1925 args[i].id = i;
1926 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
1927 reinterpret_cast<void* (*)(void*)>(BarrierOrderingTestHelper),
1928 &args[i]));
1929 }
1930 for (size_t i = 0; i < THREAD_COUNT; ++i) {
1931 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
1932 }
1933}
Yabin Cuife3a83a2015-11-17 16:03:18 -08001934
1935TEST(pthread, pthread_spinlock_smoke) {
1936 pthread_spinlock_t lock;
1937 ASSERT_EQ(0, pthread_spin_init(&lock, 0));
1938 ASSERT_EQ(0, pthread_spin_trylock(&lock));
1939 ASSERT_EQ(0, pthread_spin_unlock(&lock));
1940 ASSERT_EQ(0, pthread_spin_lock(&lock));
1941 ASSERT_EQ(EBUSY, pthread_spin_trylock(&lock));
1942 ASSERT_EQ(0, pthread_spin_unlock(&lock));
1943 ASSERT_EQ(0, pthread_spin_destroy(&lock));
1944}