blob: d11ea3f7bdd1eb6ab8b1277fb39ac15469768c42 [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 Hughes57b7a612014-08-25 17:26:50 -070027#include <sys/syscall.h>
Narayan Kamath51e6cb32014-03-03 15:38:51 +000028#include <time.h>
Elliott Hughes4d014e12012-09-07 16:47:54 -070029#include <unistd.h>
Yabin Cui33ac04a2015-09-22 11:16:15 -070030#include <unwind.h>
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070031
Yabin Cui08ee8d22015-02-11 17:04:36 -080032#include <atomic>
Yabin Cuib5845722015-03-16 22:46:42 -070033#include <vector>
Yabin Cui08ee8d22015-02-11 17:04:36 -080034
Yabin Cuic9a659c2015-11-05 15:36:08 -080035#include "private/bionic_constants.h"
Yabin Cui17393b02015-03-21 15:08:25 -070036#include "private/bionic_macros.h"
37#include "private/ScopeGuard.h"
38#include "BionicDeathTest.h"
39#include "ScopedSignalHandler.h"
Elliott Hughes15dfd632015-09-22 16:40:14 -070040#include "utils.h"
41
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070042TEST(pthread, pthread_key_create) {
43 pthread_key_t key;
44 ASSERT_EQ(0, pthread_key_create(&key, NULL));
45 ASSERT_EQ(0, pthread_key_delete(key));
46 // Can't delete a key that's already been deleted.
47 ASSERT_EQ(EINVAL, pthread_key_delete(key));
48}
Elliott Hughes4d014e12012-09-07 16:47:54 -070049
Dan Albertc4bcc752014-09-30 11:48:24 -070050TEST(pthread, pthread_keys_max) {
Yabin Cui6c238f22014-12-11 20:50:41 -080051 // POSIX says PTHREAD_KEYS_MAX should be at least _POSIX_THREAD_KEYS_MAX.
52 ASSERT_GE(PTHREAD_KEYS_MAX, _POSIX_THREAD_KEYS_MAX);
Dan Albertc4bcc752014-09-30 11:48:24 -070053}
Elliott Hughes718a5b52014-01-28 17:02:03 -080054
Yabin Cui6c238f22014-12-11 20:50:41 -080055TEST(pthread, sysconf_SC_THREAD_KEYS_MAX_eq_PTHREAD_KEYS_MAX) {
Dan Albertc4bcc752014-09-30 11:48:24 -070056 int sysconf_max = sysconf(_SC_THREAD_KEYS_MAX);
Yabin Cui6c238f22014-12-11 20:50:41 -080057 ASSERT_EQ(sysconf_max, PTHREAD_KEYS_MAX);
Dan Albertc4bcc752014-09-30 11:48:24 -070058}
59
60TEST(pthread, pthread_key_many_distinct) {
Yabin Cui6c238f22014-12-11 20:50:41 -080061 // As gtest uses pthread keys, we can't allocate exactly PTHREAD_KEYS_MAX
62 // pthread keys, but We should be able to allocate at least this many keys.
63 int nkeys = PTHREAD_KEYS_MAX / 2;
Dan Albertc4bcc752014-09-30 11:48:24 -070064 std::vector<pthread_key_t> keys;
65
66 auto scope_guard = make_scope_guard([&keys]{
Elliott Hughes0b2acdf2015-10-02 18:25:19 -070067 for (const auto& key : keys) {
Dan Albertc4bcc752014-09-30 11:48:24 -070068 EXPECT_EQ(0, pthread_key_delete(key));
69 }
70 });
71
72 for (int i = 0; i < nkeys; ++i) {
73 pthread_key_t key;
Elliott Hughes61706932015-03-31 10:56:58 -070074 // If this fails, it's likely that LIBC_PTHREAD_KEY_RESERVED_COUNT is wrong.
Dan Albertc4bcc752014-09-30 11:48:24 -070075 ASSERT_EQ(0, pthread_key_create(&key, NULL)) << i << " of " << nkeys;
76 keys.push_back(key);
77 ASSERT_EQ(0, pthread_setspecific(key, reinterpret_cast<void*>(i)));
78 }
79
80 for (int i = keys.size() - 1; i >= 0; --i) {
81 ASSERT_EQ(reinterpret_cast<void*>(i), pthread_getspecific(keys.back()));
82 pthread_key_t key = keys.back();
83 keys.pop_back();
84 ASSERT_EQ(0, pthread_key_delete(key));
85 }
86}
87
Yabin Cui6c238f22014-12-11 20:50:41 -080088TEST(pthread, pthread_key_not_exceed_PTHREAD_KEYS_MAX) {
Elliott Hughes44b53ad2013-02-11 20:18:47 +000089 std::vector<pthread_key_t> keys;
Dan Albertc4bcc752014-09-30 11:48:24 -070090 int rv = 0;
Yabin Cui6c238f22014-12-11 20:50:41 -080091
92 // Pthread keys are used by gtest, so PTHREAD_KEYS_MAX should
93 // be more than we are allowed to allocate now.
94 for (int i = 0; i < PTHREAD_KEYS_MAX; i++) {
Elliott Hughes44b53ad2013-02-11 20:18:47 +000095 pthread_key_t key;
Dan Albertc4bcc752014-09-30 11:48:24 -070096 rv = pthread_key_create(&key, NULL);
97 if (rv == EAGAIN) {
98 break;
99 }
100 EXPECT_EQ(0, rv);
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000101 keys.push_back(key);
102 }
103
Dan Albertc4bcc752014-09-30 11:48:24 -0700104 // Don't leak keys.
Elliott Hughes0b2acdf2015-10-02 18:25:19 -0700105 for (const auto& key : keys) {
Dan Albertc4bcc752014-09-30 11:48:24 -0700106 EXPECT_EQ(0, pthread_key_delete(key));
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000107 }
Dan Albertc4bcc752014-09-30 11:48:24 -0700108 keys.clear();
109
110 // We should have eventually reached the maximum number of keys and received
111 // EAGAIN.
112 ASSERT_EQ(EAGAIN, rv);
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000113}
114
Elliott Hughesebb770f2014-06-25 13:46:46 -0700115TEST(pthread, pthread_key_delete) {
116 void* expected = reinterpret_cast<void*>(1234);
117 pthread_key_t key;
118 ASSERT_EQ(0, pthread_key_create(&key, NULL));
119 ASSERT_EQ(0, pthread_setspecific(key, expected));
120 ASSERT_EQ(expected, pthread_getspecific(key));
121 ASSERT_EQ(0, pthread_key_delete(key));
122 // After deletion, pthread_getspecific returns NULL.
123 ASSERT_EQ(NULL, pthread_getspecific(key));
124 // And you can't use pthread_setspecific with the deleted key.
125 ASSERT_EQ(EINVAL, pthread_setspecific(key, expected));
126}
127
Elliott Hughes40a52172014-07-30 14:48:10 -0700128TEST(pthread, pthread_key_fork) {
129 void* expected = reinterpret_cast<void*>(1234);
130 pthread_key_t key;
131 ASSERT_EQ(0, pthread_key_create(&key, NULL));
132 ASSERT_EQ(0, pthread_setspecific(key, expected));
133 ASSERT_EQ(expected, pthread_getspecific(key));
134
135 pid_t pid = fork();
136 ASSERT_NE(-1, pid) << strerror(errno);
137
138 if (pid == 0) {
139 // The surviving thread inherits all the forking thread's TLS values...
140 ASSERT_EQ(expected, pthread_getspecific(key));
141 _exit(99);
142 }
143
Elliott Hughes33697a02016-01-26 13:04:57 -0800144 AssertChildExited(pid, 99);
Elliott Hughes40a52172014-07-30 14:48:10 -0700145
146 ASSERT_EQ(expected, pthread_getspecific(key));
Dan Albert1d53ae22014-09-02 15:24:26 -0700147 ASSERT_EQ(0, pthread_key_delete(key));
Elliott Hughes40a52172014-07-30 14:48:10 -0700148}
149
150static void* DirtyKeyFn(void* key) {
151 return pthread_getspecific(*reinterpret_cast<pthread_key_t*>(key));
152}
153
154TEST(pthread, pthread_key_dirty) {
155 pthread_key_t key;
156 ASSERT_EQ(0, pthread_key_create(&key, NULL));
157
Yabin Cuia36158a2015-11-16 21:06:16 -0800158 size_t stack_size = 640 * 1024;
Elliott Hughes40a52172014-07-30 14:48:10 -0700159 void* stack = mmap(NULL, stack_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
160 ASSERT_NE(MAP_FAILED, stack);
161 memset(stack, 0xff, stack_size);
162
163 pthread_attr_t attr;
164 ASSERT_EQ(0, pthread_attr_init(&attr));
165 ASSERT_EQ(0, pthread_attr_setstack(&attr, stack, stack_size));
166
167 pthread_t t;
168 ASSERT_EQ(0, pthread_create(&t, &attr, DirtyKeyFn, &key));
169
170 void* result;
171 ASSERT_EQ(0, pthread_join(t, &result));
172 ASSERT_EQ(nullptr, result); // Not ~0!
173
174 ASSERT_EQ(0, munmap(stack, stack_size));
Dan Albert1d53ae22014-09-02 15:24:26 -0700175 ASSERT_EQ(0, pthread_key_delete(key));
Elliott Hughes40a52172014-07-30 14:48:10 -0700176}
177
Yabin Cui5ddbb3f2015-03-05 20:35:32 -0800178TEST(pthread, static_pthread_key_used_before_creation) {
179#if defined(__BIONIC__)
180 // See http://b/19625804. The bug is about a static/global pthread key being used before creation.
181 // So here tests if the static/global default value 0 can be detected as invalid key.
182 static pthread_key_t key;
183 ASSERT_EQ(nullptr, pthread_getspecific(key));
184 ASSERT_EQ(EINVAL, pthread_setspecific(key, nullptr));
185 ASSERT_EQ(EINVAL, pthread_key_delete(key));
186#else
187 GTEST_LOG_(INFO) << "This test tests bionic pthread key implementation detail.\n";
188#endif
189}
190
Elliott Hughes4d014e12012-09-07 16:47:54 -0700191static void* IdFn(void* arg) {
192 return arg;
193}
194
Yabin Cui63481602014-12-01 17:41:04 -0800195class SpinFunctionHelper {
196 public:
197 SpinFunctionHelper() {
198 SpinFunctionHelper::spin_flag_ = true;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400199 }
Yabin Cui63481602014-12-01 17:41:04 -0800200 ~SpinFunctionHelper() {
201 UnSpin();
202 }
203 auto GetFunction() -> void* (*)(void*) {
204 return SpinFunctionHelper::SpinFn;
205 }
206
207 void UnSpin() {
208 SpinFunctionHelper::spin_flag_ = false;
209 }
210
211 private:
212 static void* SpinFn(void*) {
213 while (spin_flag_) {}
214 return NULL;
215 }
Yabin Cuia36158a2015-11-16 21:06:16 -0800216 static std::atomic<bool> spin_flag_;
Yabin Cui63481602014-12-01 17:41:04 -0800217};
218
219// It doesn't matter if spin_flag_ is used in several tests,
220// because it is always set to false after each test. Each thread
221// loops on spin_flag_ can find it becomes false at some time.
Yabin Cuia36158a2015-11-16 21:06:16 -0800222std::atomic<bool> SpinFunctionHelper::spin_flag_;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400223
Elliott Hughes4d014e12012-09-07 16:47:54 -0700224static void* JoinFn(void* arg) {
225 return reinterpret_cast<void*>(pthread_join(reinterpret_cast<pthread_t>(arg), NULL));
226}
227
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400228static void AssertDetached(pthread_t t, bool is_detached) {
229 pthread_attr_t attr;
230 ASSERT_EQ(0, pthread_getattr_np(t, &attr));
231 int detach_state;
232 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &detach_state));
233 pthread_attr_destroy(&attr);
234 ASSERT_EQ(is_detached, (detach_state == PTHREAD_CREATE_DETACHED));
235}
236
Elliott Hughes9d23e042013-02-15 19:21:51 -0800237static void MakeDeadThread(pthread_t& t) {
238 ASSERT_EQ(0, pthread_create(&t, NULL, IdFn, NULL));
Elliott Hughes34c987a2014-09-22 16:01:26 -0700239 ASSERT_EQ(0, pthread_join(t, NULL));
Elliott Hughes9d23e042013-02-15 19:21:51 -0800240}
241
Elliott Hughes4d014e12012-09-07 16:47:54 -0700242TEST(pthread, pthread_create) {
243 void* expected_result = reinterpret_cast<void*>(123);
244 // Can we create a thread?
245 pthread_t t;
246 ASSERT_EQ(0, pthread_create(&t, NULL, IdFn, expected_result));
247 // If we join, do we get the expected value back?
248 void* result;
249 ASSERT_EQ(0, pthread_join(t, &result));
250 ASSERT_EQ(expected_result, result);
251}
252
Elliott Hughes3e898472013-02-12 16:40:24 +0000253TEST(pthread, pthread_create_EAGAIN) {
254 pthread_attr_t attributes;
255 ASSERT_EQ(0, pthread_attr_init(&attributes));
256 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, static_cast<size_t>(-1) & ~(getpagesize() - 1)));
257
258 pthread_t t;
259 ASSERT_EQ(EAGAIN, pthread_create(&t, &attributes, IdFn, NULL));
260}
261
Elliott Hughes4d014e12012-09-07 16:47:54 -0700262TEST(pthread, pthread_no_join_after_detach) {
Yabin Cui63481602014-12-01 17:41:04 -0800263 SpinFunctionHelper spinhelper;
264
Elliott Hughes4d014e12012-09-07 16:47:54 -0700265 pthread_t t1;
Yabin Cui63481602014-12-01 17:41:04 -0800266 ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700267
268 // After a pthread_detach...
269 ASSERT_EQ(0, pthread_detach(t1));
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400270 AssertDetached(t1, true);
Elliott Hughes4d014e12012-09-07 16:47:54 -0700271
272 // ...pthread_join should fail.
Elliott Hughes34c987a2014-09-22 16:01:26 -0700273 ASSERT_EQ(EINVAL, pthread_join(t1, NULL));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700274}
275
276TEST(pthread, pthread_no_op_detach_after_join) {
Yabin Cui63481602014-12-01 17:41:04 -0800277 SpinFunctionHelper spinhelper;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400278
Elliott Hughes4d014e12012-09-07 16:47:54 -0700279 pthread_t t1;
Yabin Cui63481602014-12-01 17:41:04 -0800280 ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700281
282 // If thread 2 is already waiting to join thread 1...
283 pthread_t t2;
284 ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1)));
285
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400286 sleep(1); // (Give t2 a chance to call pthread_join.)
Elliott Hughes4d014e12012-09-07 16:47:54 -0700287
Yabin Cuibbb04322015-03-19 15:19:25 -0700288#if defined(__BIONIC__)
289 ASSERT_EQ(EINVAL, pthread_detach(t1));
290#else
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400291 ASSERT_EQ(0, pthread_detach(t1));
Yabin Cuibbb04322015-03-19 15:19:25 -0700292#endif
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400293 AssertDetached(t1, false);
294
Yabin Cui63481602014-12-01 17:41:04 -0800295 spinhelper.UnSpin();
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400296
297 // ...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 -0700298 void* join_result;
299 ASSERT_EQ(0, pthread_join(t2, &join_result));
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700300 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700301}
Elliott Hughes14f19592012-10-29 10:19:44 -0700302
303TEST(pthread, pthread_join_self) {
Elliott Hughes34c987a2014-09-22 16:01:26 -0700304 ASSERT_EQ(EDEADLK, pthread_join(pthread_self(), NULL));
Elliott Hughes14f19592012-10-29 10:19:44 -0700305}
Elliott Hughes4f251be2012-11-01 16:33:29 -0700306
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800307struct TestBug37410 {
308 pthread_t main_thread;
309 pthread_mutex_t mutex;
Elliott Hughes4f251be2012-11-01 16:33:29 -0700310
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800311 static void main() {
312 TestBug37410 data;
313 data.main_thread = pthread_self();
314 ASSERT_EQ(0, pthread_mutex_init(&data.mutex, NULL));
315 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
316
317 pthread_t t;
318 ASSERT_EQ(0, pthread_create(&t, NULL, TestBug37410::thread_fn, reinterpret_cast<void*>(&data)));
319
320 // Wait for the thread to be running...
321 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
322 ASSERT_EQ(0, pthread_mutex_unlock(&data.mutex));
323
324 // ...and exit.
325 pthread_exit(NULL);
326 }
327
328 private:
329 static void* thread_fn(void* arg) {
330 TestBug37410* data = reinterpret_cast<TestBug37410*>(arg);
331
332 // Let the main thread know we're running.
333 pthread_mutex_unlock(&data->mutex);
334
335 // And wait for the main thread to exit.
336 pthread_join(data->main_thread, NULL);
337
338 return NULL;
339 }
340};
Elliott Hughes4f251be2012-11-01 16:33:29 -0700341
Elliott Hughes7fd803c2013-02-14 16:33:52 -0800342// Even though this isn't really a death test, we have to say "DeathTest" here so gtest knows to
343// run this test (which exits normally) in its own process.
Yabin Cui9df70402014-11-05 18:01:01 -0800344
345class pthread_DeathTest : public BionicDeathTest {};
346
347TEST_F(pthread_DeathTest, pthread_bug_37410) {
Elliott Hughes4f251be2012-11-01 16:33:29 -0700348 // http://code.google.com/p/android/issues/detail?id=37410
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800349 ASSERT_EXIT(TestBug37410::main(), ::testing::ExitedWithCode(0), "");
Elliott Hughes4f251be2012-11-01 16:33:29 -0700350}
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800351
352static void* SignalHandlerFn(void* arg) {
353 sigset_t wait_set;
354 sigfillset(&wait_set);
355 return reinterpret_cast<void*>(sigwait(&wait_set, reinterpret_cast<int*>(arg)));
356}
357
358TEST(pthread, pthread_sigmask) {
Elliott Hughes19e62322013-10-15 11:23:57 -0700359 // Check that SIGUSR1 isn't blocked.
360 sigset_t original_set;
361 sigemptyset(&original_set);
362 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, NULL, &original_set));
363 ASSERT_FALSE(sigismember(&original_set, SIGUSR1));
364
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800365 // Block SIGUSR1.
366 sigset_t set;
367 sigemptyset(&set);
368 sigaddset(&set, SIGUSR1);
369 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, &set, NULL));
370
Elliott Hughes19e62322013-10-15 11:23:57 -0700371 // Check that SIGUSR1 is blocked.
372 sigset_t final_set;
373 sigemptyset(&final_set);
374 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, NULL, &final_set));
375 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
376 // ...and that sigprocmask agrees with pthread_sigmask.
377 sigemptyset(&final_set);
378 ASSERT_EQ(0, sigprocmask(SIG_BLOCK, NULL, &final_set));
379 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
380
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800381 // Spawn a thread that calls sigwait and tells us what it received.
382 pthread_t signal_thread;
383 int received_signal = -1;
384 ASSERT_EQ(0, pthread_create(&signal_thread, NULL, SignalHandlerFn, &received_signal));
385
386 // Send that thread SIGUSR1.
387 pthread_kill(signal_thread, SIGUSR1);
388
389 // See what it got.
390 void* join_result;
391 ASSERT_EQ(0, pthread_join(signal_thread, &join_result));
392 ASSERT_EQ(SIGUSR1, received_signal);
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700393 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
Elliott Hughes19e62322013-10-15 11:23:57 -0700394
395 // Restore the original signal mask.
396 ASSERT_EQ(0, pthread_sigmask(SIG_SETMASK, &original_set, NULL));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800397}
Elliott Hughes5e3fc432013-02-11 16:36:48 -0800398
Elliott Hughes3e898472013-02-12 16:40:24 +0000399TEST(pthread, pthread_setname_np__too_long) {
Elliott Hughesd1aea302015-04-25 10:05:24 -0700400 // The limit is 15 characters --- the kernel's buffer is 16, but includes a NUL.
401 ASSERT_EQ(0, pthread_setname_np(pthread_self(), "123456789012345"));
402 ASSERT_EQ(ERANGE, pthread_setname_np(pthread_self(), "1234567890123456"));
Elliott Hughes3e898472013-02-12 16:40:24 +0000403}
404
405TEST(pthread, pthread_setname_np__self) {
406 ASSERT_EQ(0, pthread_setname_np(pthread_self(), "short 1"));
407}
408
409TEST(pthread, pthread_setname_np__other) {
Yabin Cui63481602014-12-01 17:41:04 -0800410 SpinFunctionHelper spinhelper;
411
Elliott Hughesed29e852014-10-27 12:01:51 -0700412 pthread_t t1;
Yabin Cui63481602014-12-01 17:41:04 -0800413 ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL));
Elliott Hughesed29e852014-10-27 12:01:51 -0700414 ASSERT_EQ(0, pthread_setname_np(t1, "short 2"));
Yabin Cuia36158a2015-11-16 21:06:16 -0800415 spinhelper.UnSpin();
416 ASSERT_EQ(0, pthread_join(t1, nullptr));
Elliott Hughes3e898472013-02-12 16:40:24 +0000417}
418
Yabin Cui220b99b2015-03-26 18:13:07 +0000419TEST(pthread, pthread_setname_np__no_such_thread) {
Elliott Hughes9d23e042013-02-15 19:21:51 -0800420 pthread_t dead_thread;
421 MakeDeadThread(dead_thread);
Elliott Hughes3e898472013-02-12 16:40:24 +0000422
423 // Call pthread_setname_np after thread has already exited.
Elliott Hughes68d98d82014-11-12 21:03:26 -0800424 ASSERT_EQ(ENOENT, pthread_setname_np(dead_thread, "short 3"));
Elliott Hughes3e898472013-02-12 16:40:24 +0000425}
Elliott Hughes9d23e042013-02-15 19:21:51 -0800426
427TEST(pthread, pthread_kill__0) {
428 // Signal 0 just tests that the thread exists, so it's safe to call on ourselves.
429 ASSERT_EQ(0, pthread_kill(pthread_self(), 0));
430}
431
432TEST(pthread, pthread_kill__invalid_signal) {
433 ASSERT_EQ(EINVAL, pthread_kill(pthread_self(), -1));
434}
435
Elliott Hughesfae89fc2013-02-21 11:22:23 -0800436static void pthread_kill__in_signal_handler_helper(int signal_number) {
437 static int count = 0;
438 ASSERT_EQ(SIGALRM, signal_number);
439 if (++count == 1) {
440 // Can we call pthread_kill from a signal handler?
441 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
442 }
443}
444
445TEST(pthread, pthread_kill__in_signal_handler) {
Elliott Hughes4b558f52014-03-04 15:58:02 -0800446 ScopedSignalHandler ssh(SIGALRM, pthread_kill__in_signal_handler_helper);
Elliott Hughesfae89fc2013-02-21 11:22:23 -0800447 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
448}
449
Yabin Cui220b99b2015-03-26 18:13:07 +0000450TEST(pthread, pthread_detach__no_such_thread) {
Elliott Hughes9d23e042013-02-15 19:21:51 -0800451 pthread_t dead_thread;
452 MakeDeadThread(dead_thread);
453
454 ASSERT_EQ(ESRCH, pthread_detach(dead_thread));
455}
456
Jeff Hao9b06cc32013-08-15 14:51:16 -0700457TEST(pthread, pthread_getcpuclockid__clock_gettime) {
Yabin Cui63481602014-12-01 17:41:04 -0800458 SpinFunctionHelper spinhelper;
459
Jeff Hao9b06cc32013-08-15 14:51:16 -0700460 pthread_t t;
Yabin Cui63481602014-12-01 17:41:04 -0800461 ASSERT_EQ(0, pthread_create(&t, NULL, spinhelper.GetFunction(), NULL));
Jeff Hao9b06cc32013-08-15 14:51:16 -0700462
463 clockid_t c;
464 ASSERT_EQ(0, pthread_getcpuclockid(t, &c));
465 timespec ts;
466 ASSERT_EQ(0, clock_gettime(c, &ts));
Yabin Cuia36158a2015-11-16 21:06:16 -0800467 spinhelper.UnSpin();
468 ASSERT_EQ(0, pthread_join(t, nullptr));
Jeff Hao9b06cc32013-08-15 14:51:16 -0700469}
470
Yabin Cui220b99b2015-03-26 18:13:07 +0000471TEST(pthread, pthread_getcpuclockid__no_such_thread) {
Elliott Hughes9d23e042013-02-15 19:21:51 -0800472 pthread_t dead_thread;
473 MakeDeadThread(dead_thread);
474
475 clockid_t c;
476 ASSERT_EQ(ESRCH, pthread_getcpuclockid(dead_thread, &c));
477}
478
Yabin Cui220b99b2015-03-26 18:13:07 +0000479TEST(pthread, pthread_getschedparam__no_such_thread) {
Elliott Hughes9d23e042013-02-15 19:21:51 -0800480 pthread_t dead_thread;
481 MakeDeadThread(dead_thread);
482
483 int policy;
484 sched_param param;
485 ASSERT_EQ(ESRCH, pthread_getschedparam(dead_thread, &policy, &param));
486}
487
Yabin Cui220b99b2015-03-26 18:13:07 +0000488TEST(pthread, pthread_setschedparam__no_such_thread) {
Elliott Hughes9d23e042013-02-15 19:21:51 -0800489 pthread_t dead_thread;
490 MakeDeadThread(dead_thread);
491
492 int policy = 0;
493 sched_param param;
494 ASSERT_EQ(ESRCH, pthread_setschedparam(dead_thread, policy, &param));
495}
496
Yabin Cui220b99b2015-03-26 18:13:07 +0000497TEST(pthread, pthread_join__no_such_thread) {
Elliott Hughes9d23e042013-02-15 19:21:51 -0800498 pthread_t dead_thread;
499 MakeDeadThread(dead_thread);
500
Elliott Hughes34c987a2014-09-22 16:01:26 -0700501 ASSERT_EQ(ESRCH, pthread_join(dead_thread, NULL));
Elliott Hughes9d23e042013-02-15 19:21:51 -0800502}
503
Yabin Cui220b99b2015-03-26 18:13:07 +0000504TEST(pthread, pthread_kill__no_such_thread) {
Elliott Hughes9d23e042013-02-15 19:21:51 -0800505 pthread_t dead_thread;
506 MakeDeadThread(dead_thread);
507
508 ASSERT_EQ(ESRCH, pthread_kill(dead_thread, 0));
509}
msg5550f020d12013-06-06 14:59:28 -0400510
511TEST(pthread, pthread_join__multijoin) {
Yabin Cui63481602014-12-01 17:41:04 -0800512 SpinFunctionHelper spinhelper;
msg5550f020d12013-06-06 14:59:28 -0400513
514 pthread_t t1;
Yabin Cui63481602014-12-01 17:41:04 -0800515 ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL));
msg5550f020d12013-06-06 14:59:28 -0400516
517 pthread_t t2;
518 ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1)));
519
520 sleep(1); // (Give t2 a chance to call pthread_join.)
521
522 // Multiple joins to the same thread should fail.
523 ASSERT_EQ(EINVAL, pthread_join(t1, NULL));
524
Yabin Cui63481602014-12-01 17:41:04 -0800525 spinhelper.UnSpin();
msg5550f020d12013-06-06 14:59:28 -0400526
527 // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes).
528 void* join_result;
529 ASSERT_EQ(0, pthread_join(t2, &join_result));
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700530 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
msg5550f020d12013-06-06 14:59:28 -0400531}
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700532
Elliott Hughes70b24b12013-11-15 11:51:07 -0800533TEST(pthread, pthread_join__race) {
534 // http://b/11693195 --- pthread_join could return before the thread had actually exited.
535 // If the joiner unmapped the thread's stack, that could lead to SIGSEGV in the thread.
536 for (size_t i = 0; i < 1024; ++i) {
Yabin Cuia36158a2015-11-16 21:06:16 -0800537 size_t stack_size = 640*1024;
Elliott Hughes70b24b12013-11-15 11:51:07 -0800538 void* stack = mmap(NULL, stack_size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
539
540 pthread_attr_t a;
541 pthread_attr_init(&a);
542 pthread_attr_setstack(&a, stack, stack_size);
543
544 pthread_t t;
545 ASSERT_EQ(0, pthread_create(&t, &a, IdFn, NULL));
546 ASSERT_EQ(0, pthread_join(t, NULL));
547 ASSERT_EQ(0, munmap(stack, stack_size));
548 }
549}
550
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700551static void* GetActualGuardSizeFn(void* arg) {
552 pthread_attr_t attributes;
553 pthread_getattr_np(pthread_self(), &attributes);
554 pthread_attr_getguardsize(&attributes, reinterpret_cast<size_t*>(arg));
555 return NULL;
556}
557
558static size_t GetActualGuardSize(const pthread_attr_t& attributes) {
559 size_t result;
560 pthread_t t;
561 pthread_create(&t, &attributes, GetActualGuardSizeFn, &result);
Elliott Hughes34c987a2014-09-22 16:01:26 -0700562 pthread_join(t, NULL);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700563 return result;
564}
565
566static void* GetActualStackSizeFn(void* arg) {
567 pthread_attr_t attributes;
568 pthread_getattr_np(pthread_self(), &attributes);
569 pthread_attr_getstacksize(&attributes, reinterpret_cast<size_t*>(arg));
570 return NULL;
571}
572
573static size_t GetActualStackSize(const pthread_attr_t& attributes) {
574 size_t result;
575 pthread_t t;
576 pthread_create(&t, &attributes, GetActualStackSizeFn, &result);
Elliott Hughes34c987a2014-09-22 16:01:26 -0700577 pthread_join(t, NULL);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700578 return result;
579}
580
581TEST(pthread, pthread_attr_setguardsize) {
582 pthread_attr_t attributes;
583 ASSERT_EQ(0, pthread_attr_init(&attributes));
584
585 // Get the default guard size.
586 size_t default_guard_size;
587 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &default_guard_size));
588
589 // No such thing as too small: will be rounded up to one page by pthread_create.
590 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 128));
591 size_t guard_size;
592 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
593 ASSERT_EQ(128U, guard_size);
594 ASSERT_EQ(4096U, GetActualGuardSize(attributes));
595
596 // Large enough and a multiple of the page size.
597 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024));
598 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
599 ASSERT_EQ(32*1024U, guard_size);
600
601 // Large enough but not a multiple of the page size; will be rounded up by pthread_create.
602 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024 + 1));
603 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
604 ASSERT_EQ(32*1024U + 1, guard_size);
605}
606
607TEST(pthread, pthread_attr_setstacksize) {
608 pthread_attr_t attributes;
609 ASSERT_EQ(0, pthread_attr_init(&attributes));
610
611 // Get the default stack size.
612 size_t default_stack_size;
613 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &default_stack_size));
614
615 // Too small.
616 ASSERT_EQ(EINVAL, pthread_attr_setstacksize(&attributes, 128));
617 size_t stack_size;
618 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
619 ASSERT_EQ(default_stack_size, stack_size);
620 ASSERT_GE(GetActualStackSize(attributes), default_stack_size);
621
Yabin Cui917d3902015-01-08 12:32:42 -0800622 // Large enough and a multiple of the page size; may be rounded up by pthread_create.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700623 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024));
624 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
625 ASSERT_EQ(32*1024U, stack_size);
Yabin Cui917d3902015-01-08 12:32:42 -0800626 ASSERT_GE(GetActualStackSize(attributes), 32*1024U);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700627
Yabin Cui917d3902015-01-08 12:32:42 -0800628 // Large enough but not aligned; will be rounded up by pthread_create.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700629 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024 + 1));
630 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
631 ASSERT_EQ(32*1024U + 1, stack_size);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800632#if defined(__BIONIC__)
Yabin Cui917d3902015-01-08 12:32:42 -0800633 ASSERT_GT(GetActualStackSize(attributes), 32*1024U + 1);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800634#else // __BIONIC__
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700635 // glibc rounds down, in violation of POSIX. They document this in their BUGS section.
636 ASSERT_EQ(GetActualStackSize(attributes), 32*1024U);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800637#endif // __BIONIC__
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700638}
Elliott Hughesc3f11402013-10-30 14:40:09 -0700639
Yabin Cui76615da2015-03-17 14:22:09 -0700640TEST(pthread, pthread_rwlockattr_smoke) {
641 pthread_rwlockattr_t attr;
642 ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
643
644 int pshared_value_array[] = {PTHREAD_PROCESS_PRIVATE, PTHREAD_PROCESS_SHARED};
645 for (size_t i = 0; i < sizeof(pshared_value_array) / sizeof(pshared_value_array[0]); ++i) {
646 ASSERT_EQ(0, pthread_rwlockattr_setpshared(&attr, pshared_value_array[i]));
647 int pshared;
648 ASSERT_EQ(0, pthread_rwlockattr_getpshared(&attr, &pshared));
649 ASSERT_EQ(pshared_value_array[i], pshared);
650 }
651
652 int kind_array[] = {PTHREAD_RWLOCK_PREFER_READER_NP,
653 PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP};
654 for (size_t i = 0; i < sizeof(kind_array) / sizeof(kind_array[0]); ++i) {
655 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_array[i]));
656 int kind;
657 ASSERT_EQ(0, pthread_rwlockattr_getkind_np(&attr, &kind));
658 ASSERT_EQ(kind_array[i], kind);
659 }
660
661 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
662}
663
664TEST(pthread, pthread_rwlock_init_same_as_PTHREAD_RWLOCK_INITIALIZER) {
665 pthread_rwlock_t lock1 = PTHREAD_RWLOCK_INITIALIZER;
666 pthread_rwlock_t lock2;
667 ASSERT_EQ(0, pthread_rwlock_init(&lock2, NULL));
668 ASSERT_EQ(0, memcmp(&lock1, &lock2, sizeof(lock1)));
669}
670
Elliott Hughesc3f11402013-10-30 14:40:09 -0700671TEST(pthread, pthread_rwlock_smoke) {
672 pthread_rwlock_t l;
673 ASSERT_EQ(0, pthread_rwlock_init(&l, NULL));
674
Calin Juravle76f352e2014-05-19 13:41:10 +0100675 // Single read lock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700676 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
677 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
678
Calin Juravle76f352e2014-05-19 13:41:10 +0100679 // Multiple read lock
680 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
681 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
682 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
683 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
684
685 // Write lock
Calin Juravle92687e42014-05-22 19:21:22 +0100686 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
687 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100688
689 // Try writer lock
690 ASSERT_EQ(0, pthread_rwlock_trywrlock(&l));
691 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
692 ASSERT_EQ(EBUSY, pthread_rwlock_tryrdlock(&l));
693 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
694
695 // Try reader lock
696 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
697 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
698 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
699 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
700 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
701
702 // Try writer lock after unlock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700703 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
704 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
705
Calin Juravle76f352e2014-05-19 13:41:10 +0100706 // EDEADLK in "read after write"
707 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
708 ASSERT_EQ(EDEADLK, pthread_rwlock_rdlock(&l));
709 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
710
711 // EDEADLK in "write after write"
712 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
713 ASSERT_EQ(EDEADLK, pthread_rwlock_wrlock(&l));
714 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100715
Elliott Hughesc3f11402013-10-30 14:40:09 -0700716 ASSERT_EQ(0, pthread_rwlock_destroy(&l));
717}
718
Yabin Cui08ee8d22015-02-11 17:04:36 -0800719struct RwlockWakeupHelperArg {
720 pthread_rwlock_t lock;
721 enum Progress {
722 LOCK_INITIALIZED,
723 LOCK_WAITING,
724 LOCK_RELEASED,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800725 LOCK_ACCESSED,
726 LOCK_TIMEDOUT,
Yabin Cui08ee8d22015-02-11 17:04:36 -0800727 };
728 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -0700729 std::atomic<pid_t> tid;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800730 std::function<int (pthread_rwlock_t*)> trylock_function;
731 std::function<int (pthread_rwlock_t*)> lock_function;
732 std::function<int (pthread_rwlock_t*, const timespec*)> timed_lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800733};
734
Yabin Cuic9a659c2015-11-05 15:36:08 -0800735static void pthread_rwlock_wakeup_helper(RwlockWakeupHelperArg* arg) {
Yabin Cuif7969852015-04-02 17:47:48 -0700736 arg->tid = gettid();
Yabin Cui08ee8d22015-02-11 17:04:36 -0800737 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
738 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
739
Yabin Cuic9a659c2015-11-05 15:36:08 -0800740 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
741 ASSERT_EQ(0, arg->lock_function(&arg->lock));
Yabin Cui08ee8d22015-02-11 17:04:36 -0800742 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_RELEASED, arg->progress);
743 ASSERT_EQ(0, pthread_rwlock_unlock(&arg->lock));
744
745 arg->progress = RwlockWakeupHelperArg::LOCK_ACCESSED;
746}
747
Yabin Cuic9a659c2015-11-05 15:36:08 -0800748static void test_pthread_rwlock_reader_wakeup_writer(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -0800749 RwlockWakeupHelperArg wakeup_arg;
750 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, NULL));
751 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
752 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -0700753 wakeup_arg.tid = 0;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800754 wakeup_arg.trylock_function = pthread_rwlock_trywrlock;
755 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800756
757 pthread_t thread;
758 ASSERT_EQ(0, pthread_create(&thread, NULL,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800759 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -0700760 WaitUntilThreadSleep(wakeup_arg.tid);
761 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
762
Yabin Cui08ee8d22015-02-11 17:04:36 -0800763 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
764 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
765
766 ASSERT_EQ(0, pthread_join(thread, NULL));
767 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
768 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
769}
770
Yabin Cuic9a659c2015-11-05 15:36:08 -0800771TEST(pthread, pthread_rwlock_reader_wakeup_writer) {
772 test_pthread_rwlock_reader_wakeup_writer(pthread_rwlock_wrlock);
Yabin Cui08ee8d22015-02-11 17:04:36 -0800773}
774
Yabin Cuic9a659c2015-11-05 15:36:08 -0800775TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait) {
776 timespec ts;
777 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
778 ts.tv_sec += 1;
779 test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) {
780 return pthread_rwlock_timedwrlock(lock, &ts);
781 });
782}
783
784static void test_pthread_rwlock_writer_wakeup_reader(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -0800785 RwlockWakeupHelperArg wakeup_arg;
786 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, NULL));
787 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
788 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -0700789 wakeup_arg.tid = 0;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800790 wakeup_arg.trylock_function = pthread_rwlock_tryrdlock;
791 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800792
793 pthread_t thread;
794 ASSERT_EQ(0, pthread_create(&thread, NULL,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800795 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -0700796 WaitUntilThreadSleep(wakeup_arg.tid);
797 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
798
Yabin Cui08ee8d22015-02-11 17:04:36 -0800799 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
800 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
801
802 ASSERT_EQ(0, pthread_join(thread, NULL));
803 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
804 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
805}
806
Yabin Cuic9a659c2015-11-05 15:36:08 -0800807TEST(pthread, pthread_rwlock_writer_wakeup_reader) {
808 test_pthread_rwlock_writer_wakeup_reader(pthread_rwlock_rdlock);
809}
810
811TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait) {
812 timespec ts;
813 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
814 ts.tv_sec += 1;
815 test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) {
816 return pthread_rwlock_timedrdlock(lock, &ts);
817 });
818}
819
820static void pthread_rwlock_wakeup_timeout_helper(RwlockWakeupHelperArg* arg) {
821 arg->tid = gettid();
822 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
823 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
824
825 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
826
827 timespec ts;
828 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
829 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
830 ts.tv_nsec = -1;
831 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
832 ts.tv_nsec = NS_PER_S;
833 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
834 ts.tv_nsec = NS_PER_S - 1;
835 ts.tv_sec = -1;
836 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
837 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
838 ts.tv_sec += 1;
839 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
840 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, arg->progress);
841 arg->progress = RwlockWakeupHelperArg::LOCK_TIMEDOUT;
842}
843
844TEST(pthread, pthread_rwlock_timedrdlock_timeout) {
845 RwlockWakeupHelperArg wakeup_arg;
846 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
847 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
848 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
849 wakeup_arg.tid = 0;
850 wakeup_arg.trylock_function = pthread_rwlock_tryrdlock;
851 wakeup_arg.timed_lock_function = pthread_rwlock_timedrdlock;
852
853 pthread_t thread;
854 ASSERT_EQ(0, pthread_create(&thread, nullptr,
855 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
856 WaitUntilThreadSleep(wakeup_arg.tid);
857 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
858
859 ASSERT_EQ(0, pthread_join(thread, nullptr));
860 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
861 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
862 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
863}
864
865TEST(pthread, pthread_rwlock_timedwrlock_timeout) {
866 RwlockWakeupHelperArg wakeup_arg;
867 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
868 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
869 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
870 wakeup_arg.tid = 0;
871 wakeup_arg.trylock_function = pthread_rwlock_trywrlock;
872 wakeup_arg.timed_lock_function = pthread_rwlock_timedwrlock;
873
874 pthread_t thread;
875 ASSERT_EQ(0, pthread_create(&thread, nullptr,
876 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
877 WaitUntilThreadSleep(wakeup_arg.tid);
878 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
879
880 ASSERT_EQ(0, pthread_join(thread, nullptr));
881 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
882 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
883 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
884}
885
Yabin Cui76615da2015-03-17 14:22:09 -0700886class RwlockKindTestHelper {
887 private:
888 struct ThreadArg {
889 RwlockKindTestHelper* helper;
890 std::atomic<pid_t>& tid;
891
892 ThreadArg(RwlockKindTestHelper* helper, std::atomic<pid_t>& tid)
893 : helper(helper), tid(tid) { }
894 };
895
896 public:
897 pthread_rwlock_t lock;
898
899 public:
900 RwlockKindTestHelper(int kind_type) {
901 InitRwlock(kind_type);
902 }
903
904 ~RwlockKindTestHelper() {
905 DestroyRwlock();
906 }
907
908 void CreateWriterThread(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*)>(WriterThreadFn), arg));
913 }
914
915 void CreateReaderThread(pthread_t& thread, std::atomic<pid_t>& tid) {
916 tid = 0;
917 ThreadArg* arg = new ThreadArg(this, tid);
918 ASSERT_EQ(0, pthread_create(&thread, NULL,
919 reinterpret_cast<void* (*)(void*)>(ReaderThreadFn), arg));
920 }
921
922 private:
923 void InitRwlock(int kind_type) {
924 pthread_rwlockattr_t attr;
925 ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
926 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_type));
927 ASSERT_EQ(0, pthread_rwlock_init(&lock, &attr));
928 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
929 }
930
931 void DestroyRwlock() {
932 ASSERT_EQ(0, pthread_rwlock_destroy(&lock));
933 }
934
935 static void WriterThreadFn(ThreadArg* arg) {
936 arg->tid = gettid();
937
938 RwlockKindTestHelper* helper = arg->helper;
939 ASSERT_EQ(0, pthread_rwlock_wrlock(&helper->lock));
940 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
941 delete arg;
942 }
943
944 static void ReaderThreadFn(ThreadArg* arg) {
945 arg->tid = gettid();
946
947 RwlockKindTestHelper* helper = arg->helper;
948 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper->lock));
949 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
950 delete arg;
951 }
952};
953
954TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_READER_NP) {
955 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_READER_NP);
956 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
957
958 pthread_t writer_thread;
959 std::atomic<pid_t> writer_tid;
960 helper.CreateWriterThread(writer_thread, writer_tid);
961 WaitUntilThreadSleep(writer_tid);
962
963 pthread_t reader_thread;
964 std::atomic<pid_t> reader_tid;
965 helper.CreateReaderThread(reader_thread, reader_tid);
966 ASSERT_EQ(0, pthread_join(reader_thread, NULL));
967
968 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
969 ASSERT_EQ(0, pthread_join(writer_thread, NULL));
970}
971
972TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP) {
973 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
974 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
975
976 pthread_t writer_thread;
977 std::atomic<pid_t> writer_tid;
978 helper.CreateWriterThread(writer_thread, writer_tid);
979 WaitUntilThreadSleep(writer_tid);
980
981 pthread_t reader_thread;
982 std::atomic<pid_t> reader_tid;
983 helper.CreateReaderThread(reader_thread, reader_tid);
984 WaitUntilThreadSleep(reader_tid);
985
986 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
987 ASSERT_EQ(0, pthread_join(writer_thread, NULL));
988 ASSERT_EQ(0, pthread_join(reader_thread, NULL));
989}
990
Elliott Hughes1728b232014-05-14 10:02:03 -0700991static int g_once_fn_call_count = 0;
Elliott Hughesc3f11402013-10-30 14:40:09 -0700992static void OnceFn() {
Elliott Hughes1728b232014-05-14 10:02:03 -0700993 ++g_once_fn_call_count;
Elliott Hughesc3f11402013-10-30 14:40:09 -0700994}
995
996TEST(pthread, pthread_once_smoke) {
997 pthread_once_t once_control = PTHREAD_ONCE_INIT;
998 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
999 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
Elliott Hughes1728b232014-05-14 10:02:03 -07001000 ASSERT_EQ(1, g_once_fn_call_count);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001001}
1002
Elliott Hughes3694ec62014-05-14 11:46:08 -07001003static std::string pthread_once_1934122_result = "";
1004
1005static void Routine2() {
1006 pthread_once_1934122_result += "2";
1007}
1008
1009static void Routine1() {
1010 pthread_once_t once_control_2 = PTHREAD_ONCE_INIT;
1011 pthread_once_1934122_result += "1";
1012 pthread_once(&once_control_2, &Routine2);
1013}
1014
1015TEST(pthread, pthread_once_1934122) {
1016 // Very old versions of Android couldn't call pthread_once from a
1017 // pthread_once init routine. http://b/1934122.
1018 pthread_once_t once_control_1 = PTHREAD_ONCE_INIT;
1019 ASSERT_EQ(0, pthread_once(&once_control_1, &Routine1));
1020 ASSERT_EQ("12", pthread_once_1934122_result);
1021}
1022
Elliott Hughes1728b232014-05-14 10:02:03 -07001023static int g_atfork_prepare_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001024static void AtForkPrepare1() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 1; }
1025static void AtForkPrepare2() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -07001026static int g_atfork_parent_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001027static void AtForkParent1() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 1; }
1028static void AtForkParent2() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -07001029static int g_atfork_child_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001030static void AtForkChild1() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 1; }
1031static void AtForkChild2() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 2; }
Elliott Hughesc3f11402013-10-30 14:40:09 -07001032
Dmitriy Ivanov00e37812014-11-20 16:53:47 -08001033TEST(pthread, pthread_atfork_smoke) {
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001034 ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1));
1035 ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2));
Elliott Hughesc3f11402013-10-30 14:40:09 -07001036
Elliott Hughes33697a02016-01-26 13:04:57 -08001037 pid_t pid = fork();
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001038 ASSERT_NE(-1, pid) << strerror(errno);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001039
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001040 // Child and parent calls are made in the order they were registered.
1041 if (pid == 0) {
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001042 ASSERT_EQ(12, g_atfork_child_calls);
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001043 _exit(0);
1044 }
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001045 ASSERT_EQ(12, g_atfork_parent_calls);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001046
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001047 // Prepare calls are made in the reverse order.
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001048 ASSERT_EQ(21, g_atfork_prepare_calls);
Elliott Hughes33697a02016-01-26 13:04:57 -08001049 AssertChildExited(pid, 0);
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001050}
1051
Elliott Hughesc3f11402013-10-30 14:40:09 -07001052TEST(pthread, pthread_attr_getscope) {
1053 pthread_attr_t attr;
1054 ASSERT_EQ(0, pthread_attr_init(&attr));
1055
1056 int scope;
1057 ASSERT_EQ(0, pthread_attr_getscope(&attr, &scope));
1058 ASSERT_EQ(PTHREAD_SCOPE_SYSTEM, scope);
1059}
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001060
1061TEST(pthread, pthread_condattr_init) {
1062 pthread_condattr_t attr;
1063 pthread_condattr_init(&attr);
1064
1065 clockid_t clock;
1066 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1067 ASSERT_EQ(CLOCK_REALTIME, clock);
1068
1069 int pshared;
1070 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1071 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
1072}
1073
1074TEST(pthread, pthread_condattr_setclock) {
1075 pthread_condattr_t attr;
1076 pthread_condattr_init(&attr);
1077
1078 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_REALTIME));
1079 clockid_t clock;
1080 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1081 ASSERT_EQ(CLOCK_REALTIME, clock);
1082
1083 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1084 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1085 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1086
1087 ASSERT_EQ(EINVAL, pthread_condattr_setclock(&attr, CLOCK_PROCESS_CPUTIME_ID));
1088}
1089
1090TEST(pthread, pthread_cond_broadcast__preserves_condattr_flags) {
Yabin Cui32651b82015-03-13 20:30:00 -07001091#if defined(__BIONIC__)
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001092 pthread_condattr_t attr;
1093 pthread_condattr_init(&attr);
1094
1095 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1096 ASSERT_EQ(0, pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
1097
1098 pthread_cond_t cond_var;
1099 ASSERT_EQ(0, pthread_cond_init(&cond_var, &attr));
1100
1101 ASSERT_EQ(0, pthread_cond_signal(&cond_var));
1102 ASSERT_EQ(0, pthread_cond_broadcast(&cond_var));
1103
Yabin Cui32651b82015-03-13 20:30:00 -07001104 attr = static_cast<pthread_condattr_t>(*reinterpret_cast<uint32_t*>(cond_var.__private));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001105 clockid_t clock;
1106 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1107 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1108 int pshared;
1109 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1110 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
Yabin Cui32651b82015-03-13 20:30:00 -07001111#else // !defined(__BIONIC__)
1112 GTEST_LOG_(INFO) << "This tests a bionic implementation detail.\n";
1113#endif // !defined(__BIONIC__)
1114}
1115
1116class pthread_CondWakeupTest : public ::testing::Test {
1117 protected:
1118 pthread_mutex_t mutex;
1119 pthread_cond_t cond;
1120
1121 enum Progress {
1122 INITIALIZED,
1123 WAITING,
1124 SIGNALED,
1125 FINISHED,
1126 };
1127 std::atomic<Progress> progress;
1128 pthread_t thread;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001129 std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function;
Yabin Cui32651b82015-03-13 20:30:00 -07001130
1131 protected:
Yabin Cuic9a659c2015-11-05 15:36:08 -08001132 void SetUp() override {
1133 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1134 }
1135
1136 void InitCond(clockid_t clock=CLOCK_REALTIME) {
1137 pthread_condattr_t attr;
1138 ASSERT_EQ(0, pthread_condattr_init(&attr));
1139 ASSERT_EQ(0, pthread_condattr_setclock(&attr, clock));
1140 ASSERT_EQ(0, pthread_cond_init(&cond, &attr));
1141 ASSERT_EQ(0, pthread_condattr_destroy(&attr));
1142 }
1143
1144 void StartWaitingThread(std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function) {
Yabin Cui32651b82015-03-13 20:30:00 -07001145 progress = INITIALIZED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001146 this->wait_function = wait_function;
1147 ASSERT_EQ(0, pthread_create(&thread, NULL, reinterpret_cast<void* (*)(void*)>(WaitThreadFn), this));
1148 while (progress != WAITING) {
Yabin Cui32651b82015-03-13 20:30:00 -07001149 usleep(5000);
1150 }
1151 usleep(5000);
1152 }
1153
Yabin Cuic9a659c2015-11-05 15:36:08 -08001154 void TearDown() override {
1155 ASSERT_EQ(0, pthread_join(thread, nullptr));
1156 ASSERT_EQ(FINISHED, progress);
1157 ASSERT_EQ(0, pthread_cond_destroy(&cond));
1158 ASSERT_EQ(0, pthread_mutex_destroy(&mutex));
1159 }
1160
Yabin Cui32651b82015-03-13 20:30:00 -07001161 private:
1162 static void WaitThreadFn(pthread_CondWakeupTest* test) {
1163 ASSERT_EQ(0, pthread_mutex_lock(&test->mutex));
1164 test->progress = WAITING;
1165 while (test->progress == WAITING) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001166 ASSERT_EQ(0, test->wait_function(&test->cond, &test->mutex));
Yabin Cui32651b82015-03-13 20:30:00 -07001167 }
1168 ASSERT_EQ(SIGNALED, test->progress);
1169 test->progress = FINISHED;
1170 ASSERT_EQ(0, pthread_mutex_unlock(&test->mutex));
1171 }
1172};
1173
Yabin Cuic9a659c2015-11-05 15:36:08 -08001174TEST_F(pthread_CondWakeupTest, signal_wait) {
1175 InitCond();
1176 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1177 return pthread_cond_wait(cond, mutex);
1178 });
Yabin Cui32651b82015-03-13 20:30:00 -07001179 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001180 ASSERT_EQ(0, pthread_cond_signal(&cond));
Yabin Cui32651b82015-03-13 20:30:00 -07001181}
1182
Yabin Cuic9a659c2015-11-05 15:36:08 -08001183TEST_F(pthread_CondWakeupTest, broadcast_wait) {
1184 InitCond();
1185 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1186 return pthread_cond_wait(cond, mutex);
1187 });
Yabin Cui32651b82015-03-13 20:30:00 -07001188 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001189 ASSERT_EQ(0, pthread_cond_broadcast(&cond));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001190}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001191
Yabin Cuic9a659c2015-11-05 15:36:08 -08001192TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_REALTIME) {
1193 InitCond(CLOCK_REALTIME);
Elliott Hughes0e714a52014-03-03 16:42:47 -08001194 timespec ts;
1195 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001196 ts.tv_sec += 1;
1197 StartWaitingThread([&](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1198 return pthread_cond_timedwait(cond, mutex, &ts);
1199 });
1200 progress = SIGNALED;
1201 ASSERT_EQ(0, pthread_cond_signal(&cond));
1202}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001203
Yabin Cuic9a659c2015-11-05 15:36:08 -08001204TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC) {
1205 InitCond(CLOCK_MONOTONIC);
1206 timespec ts;
1207 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1208 ts.tv_sec += 1;
1209 StartWaitingThread([&](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1210 return pthread_cond_timedwait(cond, mutex, &ts);
1211 });
1212 progress = SIGNALED;
1213 ASSERT_EQ(0, pthread_cond_signal(&cond));
1214}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001215
Yabin Cuic9a659c2015-11-05 15:36:08 -08001216TEST(pthread, pthread_cond_timedwait_timeout) {
1217 pthread_mutex_t mutex;
1218 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1219 pthread_cond_t cond;
1220 ASSERT_EQ(0, pthread_cond_init(&cond, nullptr));
1221 ASSERT_EQ(0, pthread_mutex_lock(&mutex));
1222 timespec ts;
Elliott Hughes0e714a52014-03-03 16:42:47 -08001223 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001224 ASSERT_EQ(ETIMEDOUT, pthread_cond_timedwait(&cond, &mutex, &ts));
1225 ts.tv_nsec = -1;
1226 ASSERT_EQ(EINVAL, pthread_cond_timedwait(&cond, &mutex, &ts));
1227 ts.tv_nsec = NS_PER_S;
1228 ASSERT_EQ(EINVAL, pthread_cond_timedwait(&cond, &mutex, &ts));
1229 ts.tv_nsec = NS_PER_S - 1;
1230 ts.tv_sec = -1;
1231 ASSERT_EQ(ETIMEDOUT, pthread_cond_timedwait(&cond, &mutex, &ts));
1232 ASSERT_EQ(0, pthread_mutex_unlock(&mutex));
Elliott Hughes0e714a52014-03-03 16:42:47 -08001233}
Elliott Hughes57b7a612014-08-25 17:26:50 -07001234
1235TEST(pthread, pthread_attr_getstack__main_thread) {
1236 // This test is only meaningful for the main thread, so make sure we're running on it!
1237 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1238
1239 // Get the main thread's attributes.
1240 pthread_attr_t attributes;
1241 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1242
1243 // Check that we correctly report that the main thread has no guard page.
1244 size_t guard_size;
1245 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
1246 ASSERT_EQ(0U, guard_size); // The main thread has no guard page.
1247
1248 // Get the stack base and the stack size (both ways).
1249 void* stack_base;
1250 size_t stack_size;
1251 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1252 size_t stack_size2;
1253 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1254
1255 // The two methods of asking for the stack size should agree.
1256 EXPECT_EQ(stack_size, stack_size2);
1257
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001258#if defined(__BIONIC__)
Elliott Hughes57b7a612014-08-25 17:26:50 -07001259 // What does /proc/self/maps' [stack] line say?
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001260 void* maps_stack_hi = NULL;
Elliott Hughes15dfd632015-09-22 16:40:14 -07001261 std::vector<map_record> maps;
1262 ASSERT_TRUE(Maps::parse_maps(&maps));
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07001263 for (const auto& map : maps) {
Elliott Hughes15dfd632015-09-22 16:40:14 -07001264 if (map.pathname == "[stack]") {
1265 maps_stack_hi = reinterpret_cast<void*>(map.addr_end);
Elliott Hughes57b7a612014-08-25 17:26:50 -07001266 break;
1267 }
1268 }
Elliott Hughes57b7a612014-08-25 17:26:50 -07001269
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001270 // The high address of the /proc/self/maps [stack] region should equal stack_base + stack_size.
1271 // Remember that the stack grows down (and is mapped in on demand), so the low address of the
1272 // region isn't very interesting.
1273 EXPECT_EQ(maps_stack_hi, reinterpret_cast<uint8_t*>(stack_base) + stack_size);
1274
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001275 // The stack size should correspond to RLIMIT_STACK.
Elliott Hughes57b7a612014-08-25 17:26:50 -07001276 rlimit rl;
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001277 ASSERT_EQ(0, getrlimit(RLIMIT_STACK, &rl));
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001278 uint64_t original_rlim_cur = rl.rlim_cur;
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001279 if (rl.rlim_cur == RLIM_INFINITY) {
1280 rl.rlim_cur = 8 * 1024 * 1024; // Bionic reports unlimited stacks as 8MiB.
1281 }
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001282 EXPECT_EQ(rl.rlim_cur, stack_size);
1283
Dmitriy Ivanovd9ff7222014-09-08 16:22:22 -07001284 auto guard = make_scope_guard([&rl, original_rlim_cur]() {
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001285 rl.rlim_cur = original_rlim_cur;
1286 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1287 });
1288
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001289 //
1290 // What if RLIMIT_STACK is smaller than the stack's current extent?
1291 //
Elliott Hughes57b7a612014-08-25 17:26:50 -07001292 rl.rlim_cur = rl.rlim_max = 1024; // 1KiB. We know the stack must be at least a page already.
1293 rl.rlim_max = RLIM_INFINITY;
1294 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1295
1296 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1297 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1298 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1299
1300 EXPECT_EQ(stack_size, stack_size2);
1301 ASSERT_EQ(1024U, stack_size);
1302
1303 //
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001304 // What if RLIMIT_STACK isn't a whole number of pages?
Elliott Hughes57b7a612014-08-25 17:26:50 -07001305 //
1306 rl.rlim_cur = rl.rlim_max = 6666; // Not a whole number of pages.
1307 rl.rlim_max = RLIM_INFINITY;
1308 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1309
1310 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1311 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1312 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1313
1314 EXPECT_EQ(stack_size, stack_size2);
1315 ASSERT_EQ(6666U, stack_size);
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001316#endif
Elliott Hughes57b7a612014-08-25 17:26:50 -07001317}
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001318
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001319struct GetStackSignalHandlerArg {
1320 volatile bool done;
1321 void* signal_handler_sp;
1322 void* main_stack_base;
1323 size_t main_stack_size;
1324};
1325
1326static GetStackSignalHandlerArg getstack_signal_handler_arg;
1327
1328static void getstack_signal_handler(int sig) {
1329 ASSERT_EQ(SIGUSR1, sig);
1330 // Use sleep() to make current thread be switched out by the kernel to provoke the error.
1331 sleep(1);
1332 pthread_attr_t attr;
1333 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1334 void* stack_base;
1335 size_t stack_size;
1336 ASSERT_EQ(0, pthread_attr_getstack(&attr, &stack_base, &stack_size));
1337 getstack_signal_handler_arg.signal_handler_sp = &attr;
1338 getstack_signal_handler_arg.main_stack_base = stack_base;
1339 getstack_signal_handler_arg.main_stack_size = stack_size;
1340 getstack_signal_handler_arg.done = true;
1341}
1342
1343// The previous code obtained the main thread's stack by reading the entry in
1344// /proc/self/task/<pid>/maps that was labeled [stack]. Unfortunately, on x86/x86_64, the kernel
1345// relies on sp0 in task state segment(tss) to label the stack map with [stack]. If the kernel
1346// switches a process while the main thread is in an alternate stack, then the kernel will label
1347// the wrong map with [stack]. This test verifies that when the above situation happens, the main
1348// thread's stack is found correctly.
1349TEST(pthread, pthread_attr_getstack_in_signal_handler) {
1350 const size_t sig_stack_size = 16 * 1024;
1351 void* sig_stack = mmap(NULL, sig_stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS,
1352 -1, 0);
1353 ASSERT_NE(MAP_FAILED, sig_stack);
1354 stack_t ss;
1355 ss.ss_sp = sig_stack;
1356 ss.ss_size = sig_stack_size;
1357 ss.ss_flags = 0;
1358 stack_t oss;
1359 ASSERT_EQ(0, sigaltstack(&ss, &oss));
1360
1361 ScopedSignalHandler handler(SIGUSR1, getstack_signal_handler, SA_ONSTACK);
1362 getstack_signal_handler_arg.done = false;
1363 kill(getpid(), SIGUSR1);
1364 ASSERT_EQ(true, getstack_signal_handler_arg.done);
1365
1366 // Verify if the stack used by the signal handler is the alternate stack just registered.
1367 ASSERT_LE(sig_stack, getstack_signal_handler_arg.signal_handler_sp);
1368 ASSERT_GE(reinterpret_cast<char*>(sig_stack) + sig_stack_size,
1369 getstack_signal_handler_arg.signal_handler_sp);
1370
1371 // Verify if the main thread's stack got in the signal handler is correct.
1372 ASSERT_LE(getstack_signal_handler_arg.main_stack_base, &ss);
1373 ASSERT_GE(reinterpret_cast<char*>(getstack_signal_handler_arg.main_stack_base) +
1374 getstack_signal_handler_arg.main_stack_size, reinterpret_cast<void*>(&ss));
1375
1376 ASSERT_EQ(0, sigaltstack(&oss, nullptr));
1377 ASSERT_EQ(0, munmap(sig_stack, sig_stack_size));
1378}
1379
Yabin Cui917d3902015-01-08 12:32:42 -08001380static void pthread_attr_getstack_18908062_helper(void*) {
1381 char local_variable;
1382 pthread_attr_t attributes;
1383 pthread_getattr_np(pthread_self(), &attributes);
1384 void* stack_base;
1385 size_t stack_size;
1386 pthread_attr_getstack(&attributes, &stack_base, &stack_size);
1387
1388 // Test whether &local_variable is in [stack_base, stack_base + stack_size).
1389 ASSERT_LE(reinterpret_cast<char*>(stack_base), &local_variable);
1390 ASSERT_LT(&local_variable, reinterpret_cast<char*>(stack_base) + stack_size);
1391}
1392
1393// Check whether something on stack is in the range of
1394// [stack_base, stack_base + stack_size). see b/18908062.
1395TEST(pthread, pthread_attr_getstack_18908062) {
1396 pthread_t t;
1397 ASSERT_EQ(0, pthread_create(&t, NULL,
1398 reinterpret_cast<void* (*)(void*)>(pthread_attr_getstack_18908062_helper),
1399 NULL));
1400 pthread_join(t, NULL);
1401}
1402
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001403#if defined(__BIONIC__)
Elliott Hughesf2083612015-11-11 13:32:28 -08001404static pthread_mutex_t pthread_gettid_np_mutex = PTHREAD_MUTEX_INITIALIZER;
1405
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001406static void* pthread_gettid_np_helper(void* arg) {
1407 *reinterpret_cast<pid_t*>(arg) = gettid();
Elliott Hughesf2083612015-11-11 13:32:28 -08001408
1409 // Wait for our parent to call pthread_gettid_np on us before exiting.
1410 pthread_mutex_lock(&pthread_gettid_np_mutex);
1411 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001412 return NULL;
1413}
1414#endif
1415
1416TEST(pthread, pthread_gettid_np) {
1417#if defined(__BIONIC__)
1418 ASSERT_EQ(gettid(), pthread_gettid_np(pthread_self()));
1419
Elliott Hughesf2083612015-11-11 13:32:28 -08001420 // Ensure the other thread doesn't exit until after we've called
1421 // pthread_gettid_np on it.
1422 pthread_mutex_lock(&pthread_gettid_np_mutex);
1423
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001424 pid_t t_gettid_result;
1425 pthread_t t;
1426 pthread_create(&t, NULL, pthread_gettid_np_helper, &t_gettid_result);
1427
1428 pid_t t_pthread_gettid_np_result = pthread_gettid_np(t);
1429
Elliott Hughesf2083612015-11-11 13:32:28 -08001430 // Release the other thread and wait for it to exit.
1431 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Elliott Hughes34c987a2014-09-22 16:01:26 -07001432 pthread_join(t, NULL);
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001433
1434 ASSERT_EQ(t_gettid_result, t_pthread_gettid_np_result);
1435#else
1436 GTEST_LOG_(INFO) << "This test does nothing.\n";
1437#endif
1438}
Elliott Hughes34c987a2014-09-22 16:01:26 -07001439
1440static size_t cleanup_counter = 0;
1441
Derek Xue41996952014-09-25 11:05:32 +01001442static void AbortCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001443 abort();
1444}
1445
Derek Xue41996952014-09-25 11:05:32 +01001446static void CountCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001447 ++cleanup_counter;
1448}
1449
Derek Xue41996952014-09-25 11:05:32 +01001450static void PthreadCleanupTester() {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001451 pthread_cleanup_push(CountCleanupRoutine, NULL);
1452 pthread_cleanup_push(CountCleanupRoutine, NULL);
1453 pthread_cleanup_push(AbortCleanupRoutine, NULL);
1454
1455 pthread_cleanup_pop(0); // Pop the abort without executing it.
1456 pthread_cleanup_pop(1); // Pop one count while executing it.
1457 ASSERT_EQ(1U, cleanup_counter);
1458 // Exit while the other count is still on the cleanup stack.
1459 pthread_exit(NULL);
1460
1461 // Calls to pthread_cleanup_pop/pthread_cleanup_push must always be balanced.
1462 pthread_cleanup_pop(0);
1463}
1464
Derek Xue41996952014-09-25 11:05:32 +01001465static void* PthreadCleanupStartRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001466 PthreadCleanupTester();
1467 return NULL;
1468}
1469
1470TEST(pthread, pthread_cleanup_push__pthread_cleanup_pop) {
1471 pthread_t t;
1472 ASSERT_EQ(0, pthread_create(&t, NULL, PthreadCleanupStartRoutine, NULL));
1473 pthread_join(t, NULL);
1474 ASSERT_EQ(2U, cleanup_counter);
1475}
Derek Xue41996952014-09-25 11:05:32 +01001476
1477TEST(pthread, PTHREAD_MUTEX_DEFAULT_is_PTHREAD_MUTEX_NORMAL) {
1478 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_DEFAULT);
1479}
1480
1481TEST(pthread, pthread_mutexattr_gettype) {
1482 pthread_mutexattr_t attr;
1483 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1484
1485 int attr_type;
1486
1487 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL));
1488 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1489 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, attr_type);
1490
1491 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK));
1492 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1493 ASSERT_EQ(PTHREAD_MUTEX_ERRORCHECK, attr_type);
1494
1495 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE));
1496 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1497 ASSERT_EQ(PTHREAD_MUTEX_RECURSIVE, attr_type);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001498
1499 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
1500}
1501
Yabin Cui17393b02015-03-21 15:08:25 -07001502struct PthreadMutex {
1503 pthread_mutex_t lock;
1504
1505 PthreadMutex(int mutex_type) {
1506 init(mutex_type);
1507 }
1508
1509 ~PthreadMutex() {
1510 destroy();
1511 }
1512
1513 private:
1514 void init(int mutex_type) {
1515 pthread_mutexattr_t attr;
1516 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1517 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, mutex_type));
1518 ASSERT_EQ(0, pthread_mutex_init(&lock, &attr));
1519 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
1520 }
1521
1522 void destroy() {
1523 ASSERT_EQ(0, pthread_mutex_destroy(&lock));
1524 }
1525
1526 DISALLOW_COPY_AND_ASSIGN(PthreadMutex);
1527};
Derek Xue41996952014-09-25 11:05:32 +01001528
1529TEST(pthread, pthread_mutex_lock_NORMAL) {
Yabin Cui17393b02015-03-21 15:08:25 -07001530 PthreadMutex m(PTHREAD_MUTEX_NORMAL);
Derek Xue41996952014-09-25 11:05:32 +01001531
Yabin Cui17393b02015-03-21 15:08:25 -07001532 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1533 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08001534 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
1535 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
1536 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01001537}
1538
1539TEST(pthread, pthread_mutex_lock_ERRORCHECK) {
Yabin Cui17393b02015-03-21 15:08:25 -07001540 PthreadMutex m(PTHREAD_MUTEX_ERRORCHECK);
Derek Xue41996952014-09-25 11:05:32 +01001541
Yabin Cui17393b02015-03-21 15:08:25 -07001542 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1543 ASSERT_EQ(EDEADLK, pthread_mutex_lock(&m.lock));
1544 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1545 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
1546 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
1547 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1548 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01001549}
1550
1551TEST(pthread, pthread_mutex_lock_RECURSIVE) {
Yabin Cui17393b02015-03-21 15:08:25 -07001552 PthreadMutex m(PTHREAD_MUTEX_RECURSIVE);
Derek Xue41996952014-09-25 11:05:32 +01001553
Yabin Cui17393b02015-03-21 15:08:25 -07001554 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1555 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1556 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1557 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1558 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08001559 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
1560 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07001561 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1562 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
1563}
1564
1565TEST(pthread, pthread_mutex_init_same_as_static_initializers) {
1566 pthread_mutex_t lock_normal = PTHREAD_MUTEX_INITIALIZER;
1567 PthreadMutex m1(PTHREAD_MUTEX_NORMAL);
1568 ASSERT_EQ(0, memcmp(&lock_normal, &m1.lock, sizeof(pthread_mutex_t)));
1569 pthread_mutex_destroy(&lock_normal);
1570
1571 pthread_mutex_t lock_errorcheck = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
1572 PthreadMutex m2(PTHREAD_MUTEX_ERRORCHECK);
1573 ASSERT_EQ(0, memcmp(&lock_errorcheck, &m2.lock, sizeof(pthread_mutex_t)));
1574 pthread_mutex_destroy(&lock_errorcheck);
1575
1576 pthread_mutex_t lock_recursive = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
1577 PthreadMutex m3(PTHREAD_MUTEX_RECURSIVE);
1578 ASSERT_EQ(0, memcmp(&lock_recursive, &m3.lock, sizeof(pthread_mutex_t)));
1579 ASSERT_EQ(0, pthread_mutex_destroy(&lock_recursive));
Derek Xue41996952014-09-25 11:05:32 +01001580}
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001581class MutexWakeupHelper {
1582 private:
Yabin Cui17393b02015-03-21 15:08:25 -07001583 PthreadMutex m;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001584 enum Progress {
1585 LOCK_INITIALIZED,
1586 LOCK_WAITING,
1587 LOCK_RELEASED,
1588 LOCK_ACCESSED
1589 };
1590 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -07001591 std::atomic<pid_t> tid;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001592
1593 static void thread_fn(MutexWakeupHelper* helper) {
Yabin Cuif7969852015-04-02 17:47:48 -07001594 helper->tid = gettid();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001595 ASSERT_EQ(LOCK_INITIALIZED, helper->progress);
1596 helper->progress = LOCK_WAITING;
1597
Yabin Cui17393b02015-03-21 15:08:25 -07001598 ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001599 ASSERT_EQ(LOCK_RELEASED, helper->progress);
Yabin Cui17393b02015-03-21 15:08:25 -07001600 ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001601
1602 helper->progress = LOCK_ACCESSED;
1603 }
1604
1605 public:
Yabin Cui17393b02015-03-21 15:08:25 -07001606 MutexWakeupHelper(int mutex_type) : m(mutex_type) {
1607 }
1608
1609 void test() {
1610 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001611 progress = LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -07001612 tid = 0;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001613
1614 pthread_t thread;
1615 ASSERT_EQ(0, pthread_create(&thread, NULL,
1616 reinterpret_cast<void* (*)(void*)>(MutexWakeupHelper::thread_fn), this));
1617
Yabin Cuif7969852015-04-02 17:47:48 -07001618 WaitUntilThreadSleep(tid);
1619 ASSERT_EQ(LOCK_WAITING, progress);
1620
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001621 progress = LOCK_RELEASED;
Yabin Cui17393b02015-03-21 15:08:25 -07001622 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001623
1624 ASSERT_EQ(0, pthread_join(thread, NULL));
1625 ASSERT_EQ(LOCK_ACCESSED, progress);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001626 }
1627};
1628
1629TEST(pthread, pthread_mutex_NORMAL_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07001630 MutexWakeupHelper helper(PTHREAD_MUTEX_NORMAL);
1631 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001632}
1633
1634TEST(pthread, pthread_mutex_ERRORCHECK_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07001635 MutexWakeupHelper helper(PTHREAD_MUTEX_ERRORCHECK);
1636 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001637}
1638
1639TEST(pthread, pthread_mutex_RECURSIVE_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07001640 MutexWakeupHelper helper(PTHREAD_MUTEX_RECURSIVE);
1641 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001642}
1643
Yabin Cui140f3672015-02-03 10:32:00 -08001644TEST(pthread, pthread_mutex_owner_tid_limit) {
Yabin Cuie69c2452015-02-13 16:21:25 -08001645#if defined(__BIONIC__) && !defined(__LP64__)
Yabin Cui140f3672015-02-03 10:32:00 -08001646 FILE* fp = fopen("/proc/sys/kernel/pid_max", "r");
1647 ASSERT_TRUE(fp != NULL);
1648 long pid_max;
1649 ASSERT_EQ(1, fscanf(fp, "%ld", &pid_max));
1650 fclose(fp);
Yabin Cuie69c2452015-02-13 16:21:25 -08001651 // Bionic's pthread_mutex implementation on 32-bit devices uses 16 bits to represent owner tid.
Yabin Cui140f3672015-02-03 10:32:00 -08001652 ASSERT_LE(pid_max, 65536);
Yabin Cuie69c2452015-02-13 16:21:25 -08001653#else
1654 GTEST_LOG_(INFO) << "This test does nothing as 32-bit tid is supported by pthread_mutex.\n";
1655#endif
Yabin Cui140f3672015-02-03 10:32:00 -08001656}
Yabin Cuib5845722015-03-16 22:46:42 -07001657
Yabin Cuic9a659c2015-11-05 15:36:08 -08001658TEST(pthread, pthread_mutex_timedlock) {
1659 pthread_mutex_t m;
1660 ASSERT_EQ(0, pthread_mutex_init(&m, nullptr));
1661
1662 // If the mutex is already locked, pthread_mutex_timedlock should time out.
1663 ASSERT_EQ(0, pthread_mutex_lock(&m));
1664
1665 timespec ts;
1666 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1667 ASSERT_EQ(ETIMEDOUT, pthread_mutex_timedlock(&m, &ts));
1668 ts.tv_nsec = -1;
1669 ASSERT_EQ(EINVAL, pthread_mutex_timedlock(&m, &ts));
1670 ts.tv_nsec = NS_PER_S;
1671 ASSERT_EQ(EINVAL, pthread_mutex_timedlock(&m, &ts));
1672 ts.tv_nsec = NS_PER_S - 1;
1673 ts.tv_sec = -1;
1674 ASSERT_EQ(ETIMEDOUT, pthread_mutex_timedlock(&m, &ts));
1675
1676 // If the mutex is unlocked, pthread_mutex_timedlock should succeed.
1677 ASSERT_EQ(0, pthread_mutex_unlock(&m));
1678
1679 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1680 ts.tv_sec += 1;
1681 ASSERT_EQ(0, pthread_mutex_timedlock(&m, &ts));
1682
1683 ASSERT_EQ(0, pthread_mutex_unlock(&m));
1684 ASSERT_EQ(0, pthread_mutex_destroy(&m));
1685}
1686
Yabin Cuib5845722015-03-16 22:46:42 -07001687class StrictAlignmentAllocator {
1688 public:
1689 void* allocate(size_t size, size_t alignment) {
1690 char* p = new char[size + alignment * 2];
1691 allocated_array.push_back(p);
1692 while (!is_strict_aligned(p, alignment)) {
1693 ++p;
1694 }
1695 return p;
1696 }
1697
1698 ~StrictAlignmentAllocator() {
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07001699 for (const auto& p : allocated_array) {
1700 delete[] p;
Yabin Cuib5845722015-03-16 22:46:42 -07001701 }
1702 }
1703
1704 private:
1705 bool is_strict_aligned(char* p, size_t alignment) {
1706 return (reinterpret_cast<uintptr_t>(p) % (alignment * 2)) == alignment;
1707 }
1708
1709 std::vector<char*> allocated_array;
1710};
1711
1712TEST(pthread, pthread_types_allow_four_bytes_alignment) {
1713#if defined(__BIONIC__)
1714 // For binary compatibility with old version, we need to allow 4-byte aligned data for pthread types.
1715 StrictAlignmentAllocator allocator;
1716 pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(
1717 allocator.allocate(sizeof(pthread_mutex_t), 4));
1718 ASSERT_EQ(0, pthread_mutex_init(mutex, NULL));
1719 ASSERT_EQ(0, pthread_mutex_lock(mutex));
1720 ASSERT_EQ(0, pthread_mutex_unlock(mutex));
1721 ASSERT_EQ(0, pthread_mutex_destroy(mutex));
1722
1723 pthread_cond_t* cond = reinterpret_cast<pthread_cond_t*>(
1724 allocator.allocate(sizeof(pthread_cond_t), 4));
1725 ASSERT_EQ(0, pthread_cond_init(cond, NULL));
1726 ASSERT_EQ(0, pthread_cond_signal(cond));
1727 ASSERT_EQ(0, pthread_cond_broadcast(cond));
1728 ASSERT_EQ(0, pthread_cond_destroy(cond));
1729
1730 pthread_rwlock_t* rwlock = reinterpret_cast<pthread_rwlock_t*>(
1731 allocator.allocate(sizeof(pthread_rwlock_t), 4));
1732 ASSERT_EQ(0, pthread_rwlock_init(rwlock, NULL));
1733 ASSERT_EQ(0, pthread_rwlock_rdlock(rwlock));
1734 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
1735 ASSERT_EQ(0, pthread_rwlock_wrlock(rwlock));
1736 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
1737 ASSERT_EQ(0, pthread_rwlock_destroy(rwlock));
1738
1739#else
1740 GTEST_LOG_(INFO) << "This test tests bionic implementation details.";
1741#endif
1742}
Christopher Ferris60907c72015-06-09 18:46:15 -07001743
1744TEST(pthread, pthread_mutex_lock_null_32) {
1745#if defined(__BIONIC__) && !defined(__LP64__)
1746 ASSERT_EQ(EINVAL, pthread_mutex_lock(NULL));
1747#else
1748 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 32 bit devices.";
1749#endif
1750}
1751
1752TEST(pthread, pthread_mutex_unlock_null_32) {
1753#if defined(__BIONIC__) && !defined(__LP64__)
1754 ASSERT_EQ(EINVAL, pthread_mutex_unlock(NULL));
1755#else
1756 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 32 bit devices.";
1757#endif
1758}
1759
1760TEST_F(pthread_DeathTest, pthread_mutex_lock_null_64) {
1761#if defined(__BIONIC__) && defined(__LP64__)
1762 pthread_mutex_t* null_value = nullptr;
1763 ASSERT_EXIT(pthread_mutex_lock(null_value), testing::KilledBySignal(SIGSEGV), "");
1764#else
1765 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 64 bit devices.";
1766#endif
1767}
1768
1769TEST_F(pthread_DeathTest, pthread_mutex_unlock_null_64) {
1770#if defined(__BIONIC__) && defined(__LP64__)
1771 pthread_mutex_t* null_value = nullptr;
1772 ASSERT_EXIT(pthread_mutex_unlock(null_value), testing::KilledBySignal(SIGSEGV), "");
1773#else
1774 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 64 bit devices.";
1775#endif
1776}
Yabin Cui33ac04a2015-09-22 11:16:15 -07001777
1778extern _Unwind_Reason_Code FrameCounter(_Unwind_Context* ctx, void* arg);
1779
1780static volatile bool signal_handler_on_altstack_done;
1781
1782static void SignalHandlerOnAltStack(int signo, siginfo_t*, void*) {
1783 ASSERT_EQ(SIGUSR1, signo);
1784 // Check if we have enough stack space for unwinding.
1785 int count = 0;
1786 _Unwind_Backtrace(FrameCounter, &count);
1787 ASSERT_GT(count, 0);
1788 // Check if we have enough stack space for logging.
1789 std::string s(2048, '*');
1790 GTEST_LOG_(INFO) << s;
1791 signal_handler_on_altstack_done = true;
1792}
1793
1794TEST(pthread, big_enough_signal_stack_for_64bit_arch) {
1795 signal_handler_on_altstack_done = false;
1796 ScopedSignalHandler handler(SIGUSR1, SignalHandlerOnAltStack, SA_SIGINFO | SA_ONSTACK);
1797 kill(getpid(), SIGUSR1);
1798 ASSERT_TRUE(signal_handler_on_altstack_done);
1799}
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001800
1801TEST(pthread, pthread_barrierattr_smoke) {
1802 pthread_barrierattr_t attr;
1803 ASSERT_EQ(0, pthread_barrierattr_init(&attr));
1804 int pshared;
1805 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
1806 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
1807 ASSERT_EQ(0, pthread_barrierattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
1808 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
1809 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
1810 ASSERT_EQ(0, pthread_barrierattr_destroy(&attr));
1811}
1812
1813struct BarrierTestHelperArg {
1814 std::atomic<pid_t> tid;
1815 pthread_barrier_t* barrier;
1816 size_t iteration_count;
1817};
1818
1819static void BarrierTestHelper(BarrierTestHelperArg* arg) {
1820 arg->tid = gettid();
1821 for (size_t i = 0; i < arg->iteration_count; ++i) {
1822 ASSERT_EQ(0, pthread_barrier_wait(arg->barrier));
1823 }
1824}
1825
1826TEST(pthread, pthread_barrier_smoke) {
1827 const size_t BARRIER_ITERATION_COUNT = 10;
1828 const size_t BARRIER_THREAD_COUNT = 10;
1829 pthread_barrier_t barrier;
1830 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, BARRIER_THREAD_COUNT + 1));
1831 std::vector<pthread_t> threads(BARRIER_THREAD_COUNT);
1832 std::vector<BarrierTestHelperArg> args(threads.size());
1833 for (size_t i = 0; i < threads.size(); ++i) {
1834 args[i].tid = 0;
1835 args[i].barrier = &barrier;
1836 args[i].iteration_count = BARRIER_ITERATION_COUNT;
1837 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
1838 reinterpret_cast<void* (*)(void*)>(BarrierTestHelper), &args[i]));
1839 }
1840 for (size_t iteration = 0; iteration < BARRIER_ITERATION_COUNT; ++iteration) {
1841 for (size_t i = 0; i < threads.size(); ++i) {
1842 WaitUntilThreadSleep(args[i].tid);
1843 }
1844 ASSERT_EQ(PTHREAD_BARRIER_SERIAL_THREAD, pthread_barrier_wait(&barrier));
1845 }
1846 for (size_t i = 0; i < threads.size(); ++i) {
1847 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
1848 }
1849 ASSERT_EQ(0, pthread_barrier_destroy(&barrier));
1850}
1851
1852TEST(pthread, pthread_barrier_destroy) {
1853 pthread_barrier_t barrier;
1854 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, 2));
1855 pthread_t thread;
1856 BarrierTestHelperArg arg;
1857 arg.tid = 0;
1858 arg.barrier = &barrier;
1859 arg.iteration_count = 1;
1860 ASSERT_EQ(0, pthread_create(&thread, nullptr,
1861 reinterpret_cast<void* (*)(void*)>(BarrierTestHelper), &arg));
1862 WaitUntilThreadSleep(arg.tid);
1863 ASSERT_EQ(EBUSY, pthread_barrier_destroy(&barrier));
1864 ASSERT_EQ(PTHREAD_BARRIER_SERIAL_THREAD, pthread_barrier_wait(&barrier));
1865 // Verify if the barrier can be destroyed directly after pthread_barrier_wait().
1866 ASSERT_EQ(0, pthread_barrier_destroy(&barrier));
1867 ASSERT_EQ(0, pthread_join(thread, nullptr));
1868#if defined(__BIONIC__)
1869 ASSERT_EQ(EINVAL, pthread_barrier_destroy(&barrier));
1870#endif
1871}
1872
1873struct BarrierOrderingTestHelperArg {
1874 pthread_barrier_t* barrier;
1875 size_t* array;
1876 size_t array_length;
1877 size_t id;
1878};
1879
1880void BarrierOrderingTestHelper(BarrierOrderingTestHelperArg* arg) {
1881 const size_t ITERATION_COUNT = 10000;
1882 for (size_t i = 1; i <= ITERATION_COUNT; ++i) {
1883 arg->array[arg->id] = i;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001884 int result = pthread_barrier_wait(arg->barrier);
1885 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001886 for (size_t j = 0; j < arg->array_length; ++j) {
1887 ASSERT_EQ(i, arg->array[j]);
1888 }
Yabin Cuic9a659c2015-11-05 15:36:08 -08001889 result = pthread_barrier_wait(arg->barrier);
1890 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001891 }
1892}
1893
1894TEST(pthread, pthread_barrier_check_ordering) {
1895 const size_t THREAD_COUNT = 4;
1896 pthread_barrier_t barrier;
1897 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, THREAD_COUNT));
1898 size_t array[THREAD_COUNT];
1899 std::vector<pthread_t> threads(THREAD_COUNT);
1900 std::vector<BarrierOrderingTestHelperArg> args(THREAD_COUNT);
1901 for (size_t i = 0; i < THREAD_COUNT; ++i) {
1902 args[i].barrier = &barrier;
1903 args[i].array = array;
1904 args[i].array_length = THREAD_COUNT;
1905 args[i].id = i;
1906 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
1907 reinterpret_cast<void* (*)(void*)>(BarrierOrderingTestHelper),
1908 &args[i]));
1909 }
1910 for (size_t i = 0; i < THREAD_COUNT; ++i) {
1911 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
1912 }
1913}
Yabin Cuife3a83a2015-11-17 16:03:18 -08001914
1915TEST(pthread, pthread_spinlock_smoke) {
1916 pthread_spinlock_t lock;
1917 ASSERT_EQ(0, pthread_spin_init(&lock, 0));
1918 ASSERT_EQ(0, pthread_spin_trylock(&lock));
1919 ASSERT_EQ(0, pthread_spin_unlock(&lock));
1920 ASSERT_EQ(0, pthread_spin_lock(&lock));
1921 ASSERT_EQ(EBUSY, pthread_spin_trylock(&lock));
1922 ASSERT_EQ(0, pthread_spin_unlock(&lock));
1923 ASSERT_EQ(0, pthread_spin_destroy(&lock));
1924}