blob: 974652ef35d0e011c35c40d0f86252cc99cc7306 [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 Cuif7969852015-04-02 17:47:48 -070033#include <regex>
Yabin Cuib5845722015-03-16 22:46:42 -070034#include <vector>
Yabin Cui08ee8d22015-02-11 17:04:36 -080035
Yabin Cuif7969852015-04-02 17:47:48 -070036#include <base/file.h>
37#include <base/stringprintf.h>
38
Yabin Cuic9a659c2015-11-05 15:36:08 -080039#include "private/bionic_constants.h"
Yabin Cui17393b02015-03-21 15:08:25 -070040#include "private/bionic_macros.h"
41#include "private/ScopeGuard.h"
42#include "BionicDeathTest.h"
43#include "ScopedSignalHandler.h"
44
Elliott Hughes15dfd632015-09-22 16:40:14 -070045#include "utils.h"
46
Yabin Cuif7969852015-04-02 17:47:48 -070047extern "C" pid_t gettid();
48
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070049TEST(pthread, pthread_key_create) {
50 pthread_key_t key;
51 ASSERT_EQ(0, pthread_key_create(&key, NULL));
52 ASSERT_EQ(0, pthread_key_delete(key));
53 // Can't delete a key that's already been deleted.
54 ASSERT_EQ(EINVAL, pthread_key_delete(key));
55}
Elliott Hughes4d014e12012-09-07 16:47:54 -070056
Dan Albertc4bcc752014-09-30 11:48:24 -070057TEST(pthread, pthread_keys_max) {
Yabin Cui6c238f22014-12-11 20:50:41 -080058 // POSIX says PTHREAD_KEYS_MAX should be at least _POSIX_THREAD_KEYS_MAX.
59 ASSERT_GE(PTHREAD_KEYS_MAX, _POSIX_THREAD_KEYS_MAX);
Dan Albertc4bcc752014-09-30 11:48:24 -070060}
Elliott Hughes718a5b52014-01-28 17:02:03 -080061
Yabin Cui6c238f22014-12-11 20:50:41 -080062TEST(pthread, sysconf_SC_THREAD_KEYS_MAX_eq_PTHREAD_KEYS_MAX) {
Dan Albertc4bcc752014-09-30 11:48:24 -070063 int sysconf_max = sysconf(_SC_THREAD_KEYS_MAX);
Yabin Cui6c238f22014-12-11 20:50:41 -080064 ASSERT_EQ(sysconf_max, PTHREAD_KEYS_MAX);
Dan Albertc4bcc752014-09-30 11:48:24 -070065}
66
67TEST(pthread, pthread_key_many_distinct) {
Yabin Cui6c238f22014-12-11 20:50:41 -080068 // As gtest uses pthread keys, we can't allocate exactly PTHREAD_KEYS_MAX
69 // pthread keys, but We should be able to allocate at least this many keys.
70 int nkeys = PTHREAD_KEYS_MAX / 2;
Dan Albertc4bcc752014-09-30 11:48:24 -070071 std::vector<pthread_key_t> keys;
72
73 auto scope_guard = make_scope_guard([&keys]{
Elliott Hughes0b2acdf2015-10-02 18:25:19 -070074 for (const auto& key : keys) {
Dan Albertc4bcc752014-09-30 11:48:24 -070075 EXPECT_EQ(0, pthread_key_delete(key));
76 }
77 });
78
79 for (int i = 0; i < nkeys; ++i) {
80 pthread_key_t key;
Elliott Hughes61706932015-03-31 10:56:58 -070081 // If this fails, it's likely that LIBC_PTHREAD_KEY_RESERVED_COUNT is wrong.
Dan Albertc4bcc752014-09-30 11:48:24 -070082 ASSERT_EQ(0, pthread_key_create(&key, NULL)) << i << " of " << nkeys;
83 keys.push_back(key);
84 ASSERT_EQ(0, pthread_setspecific(key, reinterpret_cast<void*>(i)));
85 }
86
87 for (int i = keys.size() - 1; i >= 0; --i) {
88 ASSERT_EQ(reinterpret_cast<void*>(i), pthread_getspecific(keys.back()));
89 pthread_key_t key = keys.back();
90 keys.pop_back();
91 ASSERT_EQ(0, pthread_key_delete(key));
92 }
93}
94
Yabin Cui6c238f22014-12-11 20:50:41 -080095TEST(pthread, pthread_key_not_exceed_PTHREAD_KEYS_MAX) {
Elliott Hughes44b53ad2013-02-11 20:18:47 +000096 std::vector<pthread_key_t> keys;
Dan Albertc4bcc752014-09-30 11:48:24 -070097 int rv = 0;
Yabin Cui6c238f22014-12-11 20:50:41 -080098
99 // Pthread keys are used by gtest, so PTHREAD_KEYS_MAX should
100 // be more than we are allowed to allocate now.
101 for (int i = 0; i < PTHREAD_KEYS_MAX; i++) {
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000102 pthread_key_t key;
Dan Albertc4bcc752014-09-30 11:48:24 -0700103 rv = pthread_key_create(&key, NULL);
104 if (rv == EAGAIN) {
105 break;
106 }
107 EXPECT_EQ(0, rv);
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000108 keys.push_back(key);
109 }
110
Dan Albertc4bcc752014-09-30 11:48:24 -0700111 // Don't leak keys.
Elliott Hughes0b2acdf2015-10-02 18:25:19 -0700112 for (const auto& key : keys) {
Dan Albertc4bcc752014-09-30 11:48:24 -0700113 EXPECT_EQ(0, pthread_key_delete(key));
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000114 }
Dan Albertc4bcc752014-09-30 11:48:24 -0700115 keys.clear();
116
117 // We should have eventually reached the maximum number of keys and received
118 // EAGAIN.
119 ASSERT_EQ(EAGAIN, rv);
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000120}
121
Elliott Hughesebb770f2014-06-25 13:46:46 -0700122TEST(pthread, pthread_key_delete) {
123 void* expected = reinterpret_cast<void*>(1234);
124 pthread_key_t key;
125 ASSERT_EQ(0, pthread_key_create(&key, NULL));
126 ASSERT_EQ(0, pthread_setspecific(key, expected));
127 ASSERT_EQ(expected, pthread_getspecific(key));
128 ASSERT_EQ(0, pthread_key_delete(key));
129 // After deletion, pthread_getspecific returns NULL.
130 ASSERT_EQ(NULL, pthread_getspecific(key));
131 // And you can't use pthread_setspecific with the deleted key.
132 ASSERT_EQ(EINVAL, pthread_setspecific(key, expected));
133}
134
Elliott Hughes40a52172014-07-30 14:48:10 -0700135TEST(pthread, pthread_key_fork) {
136 void* expected = reinterpret_cast<void*>(1234);
137 pthread_key_t key;
138 ASSERT_EQ(0, pthread_key_create(&key, NULL));
139 ASSERT_EQ(0, pthread_setspecific(key, expected));
140 ASSERT_EQ(expected, pthread_getspecific(key));
141
142 pid_t pid = fork();
143 ASSERT_NE(-1, pid) << strerror(errno);
144
145 if (pid == 0) {
146 // The surviving thread inherits all the forking thread's TLS values...
147 ASSERT_EQ(expected, pthread_getspecific(key));
148 _exit(99);
149 }
150
151 int status;
152 ASSERT_EQ(pid, waitpid(pid, &status, 0));
153 ASSERT_TRUE(WIFEXITED(status));
154 ASSERT_EQ(99, WEXITSTATUS(status));
155
156 ASSERT_EQ(expected, pthread_getspecific(key));
Dan Albert1d53ae22014-09-02 15:24:26 -0700157 ASSERT_EQ(0, pthread_key_delete(key));
Elliott Hughes40a52172014-07-30 14:48:10 -0700158}
159
160static void* DirtyKeyFn(void* key) {
161 return pthread_getspecific(*reinterpret_cast<pthread_key_t*>(key));
162}
163
164TEST(pthread, pthread_key_dirty) {
165 pthread_key_t key;
166 ASSERT_EQ(0, pthread_key_create(&key, NULL));
167
168 size_t stack_size = 128 * 1024;
169 void* stack = mmap(NULL, stack_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
170 ASSERT_NE(MAP_FAILED, stack);
171 memset(stack, 0xff, stack_size);
172
173 pthread_attr_t attr;
174 ASSERT_EQ(0, pthread_attr_init(&attr));
175 ASSERT_EQ(0, pthread_attr_setstack(&attr, stack, stack_size));
176
177 pthread_t t;
178 ASSERT_EQ(0, pthread_create(&t, &attr, DirtyKeyFn, &key));
179
180 void* result;
181 ASSERT_EQ(0, pthread_join(t, &result));
182 ASSERT_EQ(nullptr, result); // Not ~0!
183
184 ASSERT_EQ(0, munmap(stack, stack_size));
Dan Albert1d53ae22014-09-02 15:24:26 -0700185 ASSERT_EQ(0, pthread_key_delete(key));
Elliott Hughes40a52172014-07-30 14:48:10 -0700186}
187
Yabin Cui5ddbb3f2015-03-05 20:35:32 -0800188TEST(pthread, static_pthread_key_used_before_creation) {
189#if defined(__BIONIC__)
190 // See http://b/19625804. The bug is about a static/global pthread key being used before creation.
191 // So here tests if the static/global default value 0 can be detected as invalid key.
192 static pthread_key_t key;
193 ASSERT_EQ(nullptr, pthread_getspecific(key));
194 ASSERT_EQ(EINVAL, pthread_setspecific(key, nullptr));
195 ASSERT_EQ(EINVAL, pthread_key_delete(key));
196#else
197 GTEST_LOG_(INFO) << "This test tests bionic pthread key implementation detail.\n";
198#endif
199}
200
Elliott Hughes4d014e12012-09-07 16:47:54 -0700201static void* IdFn(void* arg) {
202 return arg;
203}
204
Yabin Cui63481602014-12-01 17:41:04 -0800205class SpinFunctionHelper {
206 public:
207 SpinFunctionHelper() {
208 SpinFunctionHelper::spin_flag_ = true;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400209 }
Yabin Cui63481602014-12-01 17:41:04 -0800210 ~SpinFunctionHelper() {
211 UnSpin();
212 }
213 auto GetFunction() -> void* (*)(void*) {
214 return SpinFunctionHelper::SpinFn;
215 }
216
217 void UnSpin() {
218 SpinFunctionHelper::spin_flag_ = false;
219 }
220
221 private:
222 static void* SpinFn(void*) {
223 while (spin_flag_) {}
224 return NULL;
225 }
226 static volatile bool spin_flag_;
227};
228
229// It doesn't matter if spin_flag_ is used in several tests,
230// because it is always set to false after each test. Each thread
231// loops on spin_flag_ can find it becomes false at some time.
232volatile bool SpinFunctionHelper::spin_flag_ = false;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400233
Elliott Hughes4d014e12012-09-07 16:47:54 -0700234static void* JoinFn(void* arg) {
235 return reinterpret_cast<void*>(pthread_join(reinterpret_cast<pthread_t>(arg), NULL));
236}
237
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400238static void AssertDetached(pthread_t t, bool is_detached) {
239 pthread_attr_t attr;
240 ASSERT_EQ(0, pthread_getattr_np(t, &attr));
241 int detach_state;
242 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &detach_state));
243 pthread_attr_destroy(&attr);
244 ASSERT_EQ(is_detached, (detach_state == PTHREAD_CREATE_DETACHED));
245}
246
Elliott Hughes9d23e042013-02-15 19:21:51 -0800247static void MakeDeadThread(pthread_t& t) {
248 ASSERT_EQ(0, pthread_create(&t, NULL, IdFn, NULL));
Elliott Hughes34c987a2014-09-22 16:01:26 -0700249 ASSERT_EQ(0, pthread_join(t, NULL));
Elliott Hughes9d23e042013-02-15 19:21:51 -0800250}
251
Elliott Hughes4d014e12012-09-07 16:47:54 -0700252TEST(pthread, pthread_create) {
253 void* expected_result = reinterpret_cast<void*>(123);
254 // Can we create a thread?
255 pthread_t t;
256 ASSERT_EQ(0, pthread_create(&t, NULL, IdFn, expected_result));
257 // If we join, do we get the expected value back?
258 void* result;
259 ASSERT_EQ(0, pthread_join(t, &result));
260 ASSERT_EQ(expected_result, result);
261}
262
Elliott Hughes3e898472013-02-12 16:40:24 +0000263TEST(pthread, pthread_create_EAGAIN) {
264 pthread_attr_t attributes;
265 ASSERT_EQ(0, pthread_attr_init(&attributes));
266 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, static_cast<size_t>(-1) & ~(getpagesize() - 1)));
267
268 pthread_t t;
269 ASSERT_EQ(EAGAIN, pthread_create(&t, &attributes, IdFn, NULL));
270}
271
Elliott Hughes4d014e12012-09-07 16:47:54 -0700272TEST(pthread, pthread_no_join_after_detach) {
Yabin Cui63481602014-12-01 17:41:04 -0800273 SpinFunctionHelper spinhelper;
274
Elliott Hughes4d014e12012-09-07 16:47:54 -0700275 pthread_t t1;
Yabin Cui63481602014-12-01 17:41:04 -0800276 ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700277
278 // After a pthread_detach...
279 ASSERT_EQ(0, pthread_detach(t1));
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400280 AssertDetached(t1, true);
Elliott Hughes4d014e12012-09-07 16:47:54 -0700281
282 // ...pthread_join should fail.
Elliott Hughes34c987a2014-09-22 16:01:26 -0700283 ASSERT_EQ(EINVAL, pthread_join(t1, NULL));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700284}
285
286TEST(pthread, pthread_no_op_detach_after_join) {
Yabin Cui63481602014-12-01 17:41:04 -0800287 SpinFunctionHelper spinhelper;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400288
Elliott Hughes4d014e12012-09-07 16:47:54 -0700289 pthread_t t1;
Yabin Cui63481602014-12-01 17:41:04 -0800290 ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700291
292 // If thread 2 is already waiting to join thread 1...
293 pthread_t t2;
294 ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1)));
295
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400296 sleep(1); // (Give t2 a chance to call pthread_join.)
Elliott Hughes4d014e12012-09-07 16:47:54 -0700297
Yabin Cuibbb04322015-03-19 15:19:25 -0700298#if defined(__BIONIC__)
299 ASSERT_EQ(EINVAL, pthread_detach(t1));
300#else
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400301 ASSERT_EQ(0, pthread_detach(t1));
Yabin Cuibbb04322015-03-19 15:19:25 -0700302#endif
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400303 AssertDetached(t1, false);
304
Yabin Cui63481602014-12-01 17:41:04 -0800305 spinhelper.UnSpin();
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400306
307 // ...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 -0700308 void* join_result;
309 ASSERT_EQ(0, pthread_join(t2, &join_result));
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700310 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700311}
Elliott Hughes14f19592012-10-29 10:19:44 -0700312
313TEST(pthread, pthread_join_self) {
Elliott Hughes34c987a2014-09-22 16:01:26 -0700314 ASSERT_EQ(EDEADLK, pthread_join(pthread_self(), NULL));
Elliott Hughes14f19592012-10-29 10:19:44 -0700315}
Elliott Hughes4f251be2012-11-01 16:33:29 -0700316
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800317struct TestBug37410 {
318 pthread_t main_thread;
319 pthread_mutex_t mutex;
Elliott Hughes4f251be2012-11-01 16:33:29 -0700320
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800321 static void main() {
322 TestBug37410 data;
323 data.main_thread = pthread_self();
324 ASSERT_EQ(0, pthread_mutex_init(&data.mutex, NULL));
325 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
326
327 pthread_t t;
328 ASSERT_EQ(0, pthread_create(&t, NULL, TestBug37410::thread_fn, reinterpret_cast<void*>(&data)));
329
330 // Wait for the thread to be running...
331 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
332 ASSERT_EQ(0, pthread_mutex_unlock(&data.mutex));
333
334 // ...and exit.
335 pthread_exit(NULL);
336 }
337
338 private:
339 static void* thread_fn(void* arg) {
340 TestBug37410* data = reinterpret_cast<TestBug37410*>(arg);
341
342 // Let the main thread know we're running.
343 pthread_mutex_unlock(&data->mutex);
344
345 // And wait for the main thread to exit.
346 pthread_join(data->main_thread, NULL);
347
348 return NULL;
349 }
350};
Elliott Hughes4f251be2012-11-01 16:33:29 -0700351
Elliott Hughes7fd803c2013-02-14 16:33:52 -0800352// Even though this isn't really a death test, we have to say "DeathTest" here so gtest knows to
353// run this test (which exits normally) in its own process.
Yabin Cui9df70402014-11-05 18:01:01 -0800354
355class pthread_DeathTest : public BionicDeathTest {};
356
357TEST_F(pthread_DeathTest, pthread_bug_37410) {
Elliott Hughes4f251be2012-11-01 16:33:29 -0700358 // http://code.google.com/p/android/issues/detail?id=37410
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800359 ASSERT_EXIT(TestBug37410::main(), ::testing::ExitedWithCode(0), "");
Elliott Hughes4f251be2012-11-01 16:33:29 -0700360}
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800361
362static void* SignalHandlerFn(void* arg) {
363 sigset_t wait_set;
364 sigfillset(&wait_set);
365 return reinterpret_cast<void*>(sigwait(&wait_set, reinterpret_cast<int*>(arg)));
366}
367
368TEST(pthread, pthread_sigmask) {
Elliott Hughes19e62322013-10-15 11:23:57 -0700369 // Check that SIGUSR1 isn't blocked.
370 sigset_t original_set;
371 sigemptyset(&original_set);
372 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, NULL, &original_set));
373 ASSERT_FALSE(sigismember(&original_set, SIGUSR1));
374
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800375 // Block SIGUSR1.
376 sigset_t set;
377 sigemptyset(&set);
378 sigaddset(&set, SIGUSR1);
379 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, &set, NULL));
380
Elliott Hughes19e62322013-10-15 11:23:57 -0700381 // Check that SIGUSR1 is blocked.
382 sigset_t final_set;
383 sigemptyset(&final_set);
384 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, NULL, &final_set));
385 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
386 // ...and that sigprocmask agrees with pthread_sigmask.
387 sigemptyset(&final_set);
388 ASSERT_EQ(0, sigprocmask(SIG_BLOCK, NULL, &final_set));
389 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
390
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800391 // Spawn a thread that calls sigwait and tells us what it received.
392 pthread_t signal_thread;
393 int received_signal = -1;
394 ASSERT_EQ(0, pthread_create(&signal_thread, NULL, SignalHandlerFn, &received_signal));
395
396 // Send that thread SIGUSR1.
397 pthread_kill(signal_thread, SIGUSR1);
398
399 // See what it got.
400 void* join_result;
401 ASSERT_EQ(0, pthread_join(signal_thread, &join_result));
402 ASSERT_EQ(SIGUSR1, received_signal);
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700403 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
Elliott Hughes19e62322013-10-15 11:23:57 -0700404
405 // Restore the original signal mask.
406 ASSERT_EQ(0, pthread_sigmask(SIG_SETMASK, &original_set, NULL));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800407}
Elliott Hughes5e3fc432013-02-11 16:36:48 -0800408
Elliott Hughes3e898472013-02-12 16:40:24 +0000409TEST(pthread, pthread_setname_np__too_long) {
Elliott Hughesd1aea302015-04-25 10:05:24 -0700410 // The limit is 15 characters --- the kernel's buffer is 16, but includes a NUL.
411 ASSERT_EQ(0, pthread_setname_np(pthread_self(), "123456789012345"));
412 ASSERT_EQ(ERANGE, pthread_setname_np(pthread_self(), "1234567890123456"));
Elliott Hughes3e898472013-02-12 16:40:24 +0000413}
414
415TEST(pthread, pthread_setname_np__self) {
416 ASSERT_EQ(0, pthread_setname_np(pthread_self(), "short 1"));
417}
418
419TEST(pthread, pthread_setname_np__other) {
Yabin Cui63481602014-12-01 17:41:04 -0800420 SpinFunctionHelper spinhelper;
421
Elliott Hughesed29e852014-10-27 12:01:51 -0700422 pthread_t t1;
Yabin Cui63481602014-12-01 17:41:04 -0800423 ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL));
Elliott Hughesed29e852014-10-27 12:01:51 -0700424 ASSERT_EQ(0, pthread_setname_np(t1, "short 2"));
Elliott Hughes3e898472013-02-12 16:40:24 +0000425}
426
Yabin Cui220b99b2015-03-26 18:13:07 +0000427TEST(pthread, pthread_setname_np__no_such_thread) {
Elliott Hughes9d23e042013-02-15 19:21:51 -0800428 pthread_t dead_thread;
429 MakeDeadThread(dead_thread);
Elliott Hughes3e898472013-02-12 16:40:24 +0000430
431 // Call pthread_setname_np after thread has already exited.
Elliott Hughes68d98d82014-11-12 21:03:26 -0800432 ASSERT_EQ(ENOENT, pthread_setname_np(dead_thread, "short 3"));
Elliott Hughes3e898472013-02-12 16:40:24 +0000433}
Elliott Hughes9d23e042013-02-15 19:21:51 -0800434
435TEST(pthread, pthread_kill__0) {
436 // Signal 0 just tests that the thread exists, so it's safe to call on ourselves.
437 ASSERT_EQ(0, pthread_kill(pthread_self(), 0));
438}
439
440TEST(pthread, pthread_kill__invalid_signal) {
441 ASSERT_EQ(EINVAL, pthread_kill(pthread_self(), -1));
442}
443
Elliott Hughesfae89fc2013-02-21 11:22:23 -0800444static void pthread_kill__in_signal_handler_helper(int signal_number) {
445 static int count = 0;
446 ASSERT_EQ(SIGALRM, signal_number);
447 if (++count == 1) {
448 // Can we call pthread_kill from a signal handler?
449 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
450 }
451}
452
453TEST(pthread, pthread_kill__in_signal_handler) {
Elliott Hughes4b558f52014-03-04 15:58:02 -0800454 ScopedSignalHandler ssh(SIGALRM, pthread_kill__in_signal_handler_helper);
Elliott Hughesfae89fc2013-02-21 11:22:23 -0800455 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
456}
457
Yabin Cui220b99b2015-03-26 18:13:07 +0000458TEST(pthread, pthread_detach__no_such_thread) {
Elliott Hughes9d23e042013-02-15 19:21:51 -0800459 pthread_t dead_thread;
460 MakeDeadThread(dead_thread);
461
462 ASSERT_EQ(ESRCH, pthread_detach(dead_thread));
463}
464
Jeff Hao9b06cc32013-08-15 14:51:16 -0700465TEST(pthread, pthread_getcpuclockid__clock_gettime) {
Yabin Cui63481602014-12-01 17:41:04 -0800466 SpinFunctionHelper spinhelper;
467
Jeff Hao9b06cc32013-08-15 14:51:16 -0700468 pthread_t t;
Yabin Cui63481602014-12-01 17:41:04 -0800469 ASSERT_EQ(0, pthread_create(&t, NULL, spinhelper.GetFunction(), NULL));
Jeff Hao9b06cc32013-08-15 14:51:16 -0700470
471 clockid_t c;
472 ASSERT_EQ(0, pthread_getcpuclockid(t, &c));
473 timespec ts;
474 ASSERT_EQ(0, clock_gettime(c, &ts));
475}
476
Yabin Cui220b99b2015-03-26 18:13:07 +0000477TEST(pthread, pthread_getcpuclockid__no_such_thread) {
Elliott Hughes9d23e042013-02-15 19:21:51 -0800478 pthread_t dead_thread;
479 MakeDeadThread(dead_thread);
480
481 clockid_t c;
482 ASSERT_EQ(ESRCH, pthread_getcpuclockid(dead_thread, &c));
483}
484
Yabin Cui220b99b2015-03-26 18:13:07 +0000485TEST(pthread, pthread_getschedparam__no_such_thread) {
Elliott Hughes9d23e042013-02-15 19:21:51 -0800486 pthread_t dead_thread;
487 MakeDeadThread(dead_thread);
488
489 int policy;
490 sched_param param;
491 ASSERT_EQ(ESRCH, pthread_getschedparam(dead_thread, &policy, &param));
492}
493
Yabin Cui220b99b2015-03-26 18:13:07 +0000494TEST(pthread, pthread_setschedparam__no_such_thread) {
Elliott Hughes9d23e042013-02-15 19:21:51 -0800495 pthread_t dead_thread;
496 MakeDeadThread(dead_thread);
497
498 int policy = 0;
499 sched_param param;
500 ASSERT_EQ(ESRCH, pthread_setschedparam(dead_thread, policy, &param));
501}
502
Yabin Cui220b99b2015-03-26 18:13:07 +0000503TEST(pthread, pthread_join__no_such_thread) {
Elliott Hughes9d23e042013-02-15 19:21:51 -0800504 pthread_t dead_thread;
505 MakeDeadThread(dead_thread);
506
Elliott Hughes34c987a2014-09-22 16:01:26 -0700507 ASSERT_EQ(ESRCH, pthread_join(dead_thread, NULL));
Elliott Hughes9d23e042013-02-15 19:21:51 -0800508}
509
Yabin Cui220b99b2015-03-26 18:13:07 +0000510TEST(pthread, pthread_kill__no_such_thread) {
Elliott Hughes9d23e042013-02-15 19:21:51 -0800511 pthread_t dead_thread;
512 MakeDeadThread(dead_thread);
513
514 ASSERT_EQ(ESRCH, pthread_kill(dead_thread, 0));
515}
msg5550f020d12013-06-06 14:59:28 -0400516
517TEST(pthread, pthread_join__multijoin) {
Yabin Cui63481602014-12-01 17:41:04 -0800518 SpinFunctionHelper spinhelper;
msg5550f020d12013-06-06 14:59:28 -0400519
520 pthread_t t1;
Yabin Cui63481602014-12-01 17:41:04 -0800521 ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL));
msg5550f020d12013-06-06 14:59:28 -0400522
523 pthread_t t2;
524 ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1)));
525
526 sleep(1); // (Give t2 a chance to call pthread_join.)
527
528 // Multiple joins to the same thread should fail.
529 ASSERT_EQ(EINVAL, pthread_join(t1, NULL));
530
Yabin Cui63481602014-12-01 17:41:04 -0800531 spinhelper.UnSpin();
msg5550f020d12013-06-06 14:59:28 -0400532
533 // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes).
534 void* join_result;
535 ASSERT_EQ(0, pthread_join(t2, &join_result));
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700536 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
msg5550f020d12013-06-06 14:59:28 -0400537}
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700538
Elliott Hughes70b24b12013-11-15 11:51:07 -0800539TEST(pthread, pthread_join__race) {
540 // http://b/11693195 --- pthread_join could return before the thread had actually exited.
541 // If the joiner unmapped the thread's stack, that could lead to SIGSEGV in the thread.
542 for (size_t i = 0; i < 1024; ++i) {
543 size_t stack_size = 64*1024;
544 void* stack = mmap(NULL, stack_size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
545
546 pthread_attr_t a;
547 pthread_attr_init(&a);
548 pthread_attr_setstack(&a, stack, stack_size);
549
550 pthread_t t;
551 ASSERT_EQ(0, pthread_create(&t, &a, IdFn, NULL));
552 ASSERT_EQ(0, pthread_join(t, NULL));
553 ASSERT_EQ(0, munmap(stack, stack_size));
554 }
555}
556
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700557static void* GetActualGuardSizeFn(void* arg) {
558 pthread_attr_t attributes;
559 pthread_getattr_np(pthread_self(), &attributes);
560 pthread_attr_getguardsize(&attributes, reinterpret_cast<size_t*>(arg));
561 return NULL;
562}
563
564static size_t GetActualGuardSize(const pthread_attr_t& attributes) {
565 size_t result;
566 pthread_t t;
567 pthread_create(&t, &attributes, GetActualGuardSizeFn, &result);
Elliott Hughes34c987a2014-09-22 16:01:26 -0700568 pthread_join(t, NULL);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700569 return result;
570}
571
572static void* GetActualStackSizeFn(void* arg) {
573 pthread_attr_t attributes;
574 pthread_getattr_np(pthread_self(), &attributes);
575 pthread_attr_getstacksize(&attributes, reinterpret_cast<size_t*>(arg));
576 return NULL;
577}
578
579static size_t GetActualStackSize(const pthread_attr_t& attributes) {
580 size_t result;
581 pthread_t t;
582 pthread_create(&t, &attributes, GetActualStackSizeFn, &result);
Elliott Hughes34c987a2014-09-22 16:01:26 -0700583 pthread_join(t, NULL);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700584 return result;
585}
586
587TEST(pthread, pthread_attr_setguardsize) {
588 pthread_attr_t attributes;
589 ASSERT_EQ(0, pthread_attr_init(&attributes));
590
591 // Get the default guard size.
592 size_t default_guard_size;
593 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &default_guard_size));
594
595 // No such thing as too small: will be rounded up to one page by pthread_create.
596 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 128));
597 size_t guard_size;
598 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
599 ASSERT_EQ(128U, guard_size);
600 ASSERT_EQ(4096U, GetActualGuardSize(attributes));
601
602 // Large enough and a multiple of the page size.
603 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024));
604 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
605 ASSERT_EQ(32*1024U, guard_size);
606
607 // Large enough but not a multiple of the page size; will be rounded up by pthread_create.
608 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024 + 1));
609 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
610 ASSERT_EQ(32*1024U + 1, guard_size);
611}
612
613TEST(pthread, pthread_attr_setstacksize) {
614 pthread_attr_t attributes;
615 ASSERT_EQ(0, pthread_attr_init(&attributes));
616
617 // Get the default stack size.
618 size_t default_stack_size;
619 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &default_stack_size));
620
621 // Too small.
622 ASSERT_EQ(EINVAL, pthread_attr_setstacksize(&attributes, 128));
623 size_t stack_size;
624 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
625 ASSERT_EQ(default_stack_size, stack_size);
626 ASSERT_GE(GetActualStackSize(attributes), default_stack_size);
627
Yabin Cui917d3902015-01-08 12:32:42 -0800628 // Large enough and a multiple of the page size; may be rounded up by pthread_create.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700629 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024));
630 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
631 ASSERT_EQ(32*1024U, stack_size);
Yabin Cui917d3902015-01-08 12:32:42 -0800632 ASSERT_GE(GetActualStackSize(attributes), 32*1024U);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700633
Yabin Cui917d3902015-01-08 12:32:42 -0800634 // Large enough but not aligned; will be rounded up by pthread_create.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700635 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024 + 1));
636 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
637 ASSERT_EQ(32*1024U + 1, stack_size);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800638#if defined(__BIONIC__)
Yabin Cui917d3902015-01-08 12:32:42 -0800639 ASSERT_GT(GetActualStackSize(attributes), 32*1024U + 1);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800640#else // __BIONIC__
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700641 // glibc rounds down, in violation of POSIX. They document this in their BUGS section.
642 ASSERT_EQ(GetActualStackSize(attributes), 32*1024U);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800643#endif // __BIONIC__
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700644}
Elliott Hughesc3f11402013-10-30 14:40:09 -0700645
Yabin Cui76615da2015-03-17 14:22:09 -0700646TEST(pthread, pthread_rwlockattr_smoke) {
647 pthread_rwlockattr_t attr;
648 ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
649
650 int pshared_value_array[] = {PTHREAD_PROCESS_PRIVATE, PTHREAD_PROCESS_SHARED};
651 for (size_t i = 0; i < sizeof(pshared_value_array) / sizeof(pshared_value_array[0]); ++i) {
652 ASSERT_EQ(0, pthread_rwlockattr_setpshared(&attr, pshared_value_array[i]));
653 int pshared;
654 ASSERT_EQ(0, pthread_rwlockattr_getpshared(&attr, &pshared));
655 ASSERT_EQ(pshared_value_array[i], pshared);
656 }
657
658 int kind_array[] = {PTHREAD_RWLOCK_PREFER_READER_NP,
659 PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP};
660 for (size_t i = 0; i < sizeof(kind_array) / sizeof(kind_array[0]); ++i) {
661 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_array[i]));
662 int kind;
663 ASSERT_EQ(0, pthread_rwlockattr_getkind_np(&attr, &kind));
664 ASSERT_EQ(kind_array[i], kind);
665 }
666
667 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
668}
669
670TEST(pthread, pthread_rwlock_init_same_as_PTHREAD_RWLOCK_INITIALIZER) {
671 pthread_rwlock_t lock1 = PTHREAD_RWLOCK_INITIALIZER;
672 pthread_rwlock_t lock2;
673 ASSERT_EQ(0, pthread_rwlock_init(&lock2, NULL));
674 ASSERT_EQ(0, memcmp(&lock1, &lock2, sizeof(lock1)));
675}
676
Elliott Hughesc3f11402013-10-30 14:40:09 -0700677TEST(pthread, pthread_rwlock_smoke) {
678 pthread_rwlock_t l;
679 ASSERT_EQ(0, pthread_rwlock_init(&l, NULL));
680
Calin Juravle76f352e2014-05-19 13:41:10 +0100681 // Single read lock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700682 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
683 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
684
Calin Juravle76f352e2014-05-19 13:41:10 +0100685 // Multiple read lock
686 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
687 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
688 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
689 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
690
691 // Write lock
Calin Juravle92687e42014-05-22 19:21:22 +0100692 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
693 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100694
695 // Try writer lock
696 ASSERT_EQ(0, pthread_rwlock_trywrlock(&l));
697 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
698 ASSERT_EQ(EBUSY, pthread_rwlock_tryrdlock(&l));
699 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
700
701 // Try reader lock
702 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
703 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
704 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
705 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
706 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
707
708 // Try writer lock after unlock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700709 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
710 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
711
Calin Juravle76f352e2014-05-19 13:41:10 +0100712 // EDEADLK in "read after write"
713 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
714 ASSERT_EQ(EDEADLK, pthread_rwlock_rdlock(&l));
715 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
716
717 // EDEADLK in "write after write"
718 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
719 ASSERT_EQ(EDEADLK, pthread_rwlock_wrlock(&l));
720 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100721
Elliott Hughesc3f11402013-10-30 14:40:09 -0700722 ASSERT_EQ(0, pthread_rwlock_destroy(&l));
723}
724
Yabin Cuie7c2fff2015-11-05 22:06:09 -0800725static void WaitUntilThreadSleep(std::atomic<pid_t>& tid) {
726 while (tid == 0) {
Yabin Cuif7969852015-04-02 17:47:48 -0700727 usleep(1000);
728 }
Yabin Cuie7c2fff2015-11-05 22:06:09 -0800729 std::string filename = android::base::StringPrintf("/proc/%d/stat", tid.load());
Yabin Cuif7969852015-04-02 17:47:48 -0700730 std::regex regex {R"(\s+S\s+)"};
731
732 while (true) {
733 std::string content;
734 ASSERT_TRUE(android::base::ReadFileToString(filename, &content));
735 if (std::regex_search(content, regex)) {
736 break;
737 }
738 usleep(1000);
739 }
740}
741
Yabin Cui08ee8d22015-02-11 17:04:36 -0800742struct RwlockWakeupHelperArg {
743 pthread_rwlock_t lock;
744 enum Progress {
745 LOCK_INITIALIZED,
746 LOCK_WAITING,
747 LOCK_RELEASED,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800748 LOCK_ACCESSED,
749 LOCK_TIMEDOUT,
Yabin Cui08ee8d22015-02-11 17:04:36 -0800750 };
751 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -0700752 std::atomic<pid_t> tid;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800753 std::function<int (pthread_rwlock_t*)> trylock_function;
754 std::function<int (pthread_rwlock_t*)> lock_function;
755 std::function<int (pthread_rwlock_t*, const timespec*)> timed_lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800756};
757
Yabin Cuic9a659c2015-11-05 15:36:08 -0800758static void pthread_rwlock_wakeup_helper(RwlockWakeupHelperArg* arg) {
Yabin Cuif7969852015-04-02 17:47:48 -0700759 arg->tid = gettid();
Yabin Cui08ee8d22015-02-11 17:04:36 -0800760 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
761 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
762
Yabin Cuic9a659c2015-11-05 15:36:08 -0800763 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
764 ASSERT_EQ(0, arg->lock_function(&arg->lock));
Yabin Cui08ee8d22015-02-11 17:04:36 -0800765 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_RELEASED, arg->progress);
766 ASSERT_EQ(0, pthread_rwlock_unlock(&arg->lock));
767
768 arg->progress = RwlockWakeupHelperArg::LOCK_ACCESSED;
769}
770
Yabin Cuic9a659c2015-11-05 15:36:08 -0800771static void test_pthread_rwlock_reader_wakeup_writer(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -0800772 RwlockWakeupHelperArg wakeup_arg;
773 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, NULL));
774 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
775 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -0700776 wakeup_arg.tid = 0;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800777 wakeup_arg.trylock_function = pthread_rwlock_trywrlock;
778 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800779
780 pthread_t thread;
781 ASSERT_EQ(0, pthread_create(&thread, NULL,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800782 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -0700783 WaitUntilThreadSleep(wakeup_arg.tid);
784 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
785
Yabin Cui08ee8d22015-02-11 17:04:36 -0800786 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
787 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
788
789 ASSERT_EQ(0, pthread_join(thread, NULL));
790 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
791 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
792}
793
Yabin Cuic9a659c2015-11-05 15:36:08 -0800794TEST(pthread, pthread_rwlock_reader_wakeup_writer) {
795 test_pthread_rwlock_reader_wakeup_writer(pthread_rwlock_wrlock);
Yabin Cui08ee8d22015-02-11 17:04:36 -0800796}
797
Yabin Cuic9a659c2015-11-05 15:36:08 -0800798TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait) {
799 timespec ts;
800 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
801 ts.tv_sec += 1;
802 test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) {
803 return pthread_rwlock_timedwrlock(lock, &ts);
804 });
805}
806
807static void test_pthread_rwlock_writer_wakeup_reader(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -0800808 RwlockWakeupHelperArg wakeup_arg;
809 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, NULL));
810 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
811 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -0700812 wakeup_arg.tid = 0;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800813 wakeup_arg.trylock_function = pthread_rwlock_tryrdlock;
814 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800815
816 pthread_t thread;
817 ASSERT_EQ(0, pthread_create(&thread, NULL,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800818 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -0700819 WaitUntilThreadSleep(wakeup_arg.tid);
820 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
821
Yabin Cui08ee8d22015-02-11 17:04:36 -0800822 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
823 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
824
825 ASSERT_EQ(0, pthread_join(thread, NULL));
826 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
827 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
828}
829
Yabin Cuic9a659c2015-11-05 15:36:08 -0800830TEST(pthread, pthread_rwlock_writer_wakeup_reader) {
831 test_pthread_rwlock_writer_wakeup_reader(pthread_rwlock_rdlock);
832}
833
834TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait) {
835 timespec ts;
836 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
837 ts.tv_sec += 1;
838 test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) {
839 return pthread_rwlock_timedrdlock(lock, &ts);
840 });
841}
842
843static void pthread_rwlock_wakeup_timeout_helper(RwlockWakeupHelperArg* arg) {
844 arg->tid = gettid();
845 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
846 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
847
848 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
849
850 timespec ts;
851 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
852 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
853 ts.tv_nsec = -1;
854 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
855 ts.tv_nsec = NS_PER_S;
856 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
857 ts.tv_nsec = NS_PER_S - 1;
858 ts.tv_sec = -1;
859 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
860 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
861 ts.tv_sec += 1;
862 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
863 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, arg->progress);
864 arg->progress = RwlockWakeupHelperArg::LOCK_TIMEDOUT;
865}
866
867TEST(pthread, pthread_rwlock_timedrdlock_timeout) {
868 RwlockWakeupHelperArg wakeup_arg;
869 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
870 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
871 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
872 wakeup_arg.tid = 0;
873 wakeup_arg.trylock_function = pthread_rwlock_tryrdlock;
874 wakeup_arg.timed_lock_function = pthread_rwlock_timedrdlock;
875
876 pthread_t thread;
877 ASSERT_EQ(0, pthread_create(&thread, nullptr,
878 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
879 WaitUntilThreadSleep(wakeup_arg.tid);
880 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
881
882 ASSERT_EQ(0, pthread_join(thread, nullptr));
883 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
884 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
885 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
886}
887
888TEST(pthread, pthread_rwlock_timedwrlock_timeout) {
889 RwlockWakeupHelperArg wakeup_arg;
890 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
891 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
892 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
893 wakeup_arg.tid = 0;
894 wakeup_arg.trylock_function = pthread_rwlock_trywrlock;
895 wakeup_arg.timed_lock_function = pthread_rwlock_timedwrlock;
896
897 pthread_t thread;
898 ASSERT_EQ(0, pthread_create(&thread, nullptr,
899 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
900 WaitUntilThreadSleep(wakeup_arg.tid);
901 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
902
903 ASSERT_EQ(0, pthread_join(thread, nullptr));
904 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
905 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
906 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
907}
908
Yabin Cui76615da2015-03-17 14:22:09 -0700909class RwlockKindTestHelper {
910 private:
911 struct ThreadArg {
912 RwlockKindTestHelper* helper;
913 std::atomic<pid_t>& tid;
914
915 ThreadArg(RwlockKindTestHelper* helper, std::atomic<pid_t>& tid)
916 : helper(helper), tid(tid) { }
917 };
918
919 public:
920 pthread_rwlock_t lock;
921
922 public:
923 RwlockKindTestHelper(int kind_type) {
924 InitRwlock(kind_type);
925 }
926
927 ~RwlockKindTestHelper() {
928 DestroyRwlock();
929 }
930
931 void CreateWriterThread(pthread_t& thread, std::atomic<pid_t>& tid) {
932 tid = 0;
933 ThreadArg* arg = new ThreadArg(this, tid);
934 ASSERT_EQ(0, pthread_create(&thread, NULL,
935 reinterpret_cast<void* (*)(void*)>(WriterThreadFn), arg));
936 }
937
938 void CreateReaderThread(pthread_t& thread, std::atomic<pid_t>& tid) {
939 tid = 0;
940 ThreadArg* arg = new ThreadArg(this, tid);
941 ASSERT_EQ(0, pthread_create(&thread, NULL,
942 reinterpret_cast<void* (*)(void*)>(ReaderThreadFn), arg));
943 }
944
945 private:
946 void InitRwlock(int kind_type) {
947 pthread_rwlockattr_t attr;
948 ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
949 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_type));
950 ASSERT_EQ(0, pthread_rwlock_init(&lock, &attr));
951 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
952 }
953
954 void DestroyRwlock() {
955 ASSERT_EQ(0, pthread_rwlock_destroy(&lock));
956 }
957
958 static void WriterThreadFn(ThreadArg* arg) {
959 arg->tid = gettid();
960
961 RwlockKindTestHelper* helper = arg->helper;
962 ASSERT_EQ(0, pthread_rwlock_wrlock(&helper->lock));
963 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
964 delete arg;
965 }
966
967 static void ReaderThreadFn(ThreadArg* arg) {
968 arg->tid = gettid();
969
970 RwlockKindTestHelper* helper = arg->helper;
971 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper->lock));
972 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
973 delete arg;
974 }
975};
976
977TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_READER_NP) {
978 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_READER_NP);
979 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
980
981 pthread_t writer_thread;
982 std::atomic<pid_t> writer_tid;
983 helper.CreateWriterThread(writer_thread, writer_tid);
984 WaitUntilThreadSleep(writer_tid);
985
986 pthread_t reader_thread;
987 std::atomic<pid_t> reader_tid;
988 helper.CreateReaderThread(reader_thread, reader_tid);
989 ASSERT_EQ(0, pthread_join(reader_thread, NULL));
990
991 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
992 ASSERT_EQ(0, pthread_join(writer_thread, NULL));
993}
994
995TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP) {
996 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
997 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
998
999 pthread_t writer_thread;
1000 std::atomic<pid_t> writer_tid;
1001 helper.CreateWriterThread(writer_thread, writer_tid);
1002 WaitUntilThreadSleep(writer_tid);
1003
1004 pthread_t reader_thread;
1005 std::atomic<pid_t> reader_tid;
1006 helper.CreateReaderThread(reader_thread, reader_tid);
1007 WaitUntilThreadSleep(reader_tid);
1008
1009 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
1010 ASSERT_EQ(0, pthread_join(writer_thread, NULL));
1011 ASSERT_EQ(0, pthread_join(reader_thread, NULL));
1012}
1013
Elliott Hughes1728b232014-05-14 10:02:03 -07001014static int g_once_fn_call_count = 0;
Elliott Hughesc3f11402013-10-30 14:40:09 -07001015static void OnceFn() {
Elliott Hughes1728b232014-05-14 10:02:03 -07001016 ++g_once_fn_call_count;
Elliott Hughesc3f11402013-10-30 14:40:09 -07001017}
1018
1019TEST(pthread, pthread_once_smoke) {
1020 pthread_once_t once_control = PTHREAD_ONCE_INIT;
1021 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
1022 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
Elliott Hughes1728b232014-05-14 10:02:03 -07001023 ASSERT_EQ(1, g_once_fn_call_count);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001024}
1025
Elliott Hughes3694ec62014-05-14 11:46:08 -07001026static std::string pthread_once_1934122_result = "";
1027
1028static void Routine2() {
1029 pthread_once_1934122_result += "2";
1030}
1031
1032static void Routine1() {
1033 pthread_once_t once_control_2 = PTHREAD_ONCE_INIT;
1034 pthread_once_1934122_result += "1";
1035 pthread_once(&once_control_2, &Routine2);
1036}
1037
1038TEST(pthread, pthread_once_1934122) {
1039 // Very old versions of Android couldn't call pthread_once from a
1040 // pthread_once init routine. http://b/1934122.
1041 pthread_once_t once_control_1 = PTHREAD_ONCE_INIT;
1042 ASSERT_EQ(0, pthread_once(&once_control_1, &Routine1));
1043 ASSERT_EQ("12", pthread_once_1934122_result);
1044}
1045
Elliott Hughes1728b232014-05-14 10:02:03 -07001046static int g_atfork_prepare_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001047static void AtForkPrepare1() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 1; }
1048static void AtForkPrepare2() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -07001049static int g_atfork_parent_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001050static void AtForkParent1() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 1; }
1051static void AtForkParent2() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -07001052static int g_atfork_child_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001053static void AtForkChild1() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 1; }
1054static void AtForkChild2() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 2; }
Elliott Hughesc3f11402013-10-30 14:40:09 -07001055
Dmitriy Ivanov00e37812014-11-20 16:53:47 -08001056TEST(pthread, pthread_atfork_smoke) {
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001057 ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1));
1058 ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2));
Elliott Hughesc3f11402013-10-30 14:40:09 -07001059
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001060 int pid = fork();
1061 ASSERT_NE(-1, pid) << strerror(errno);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001062
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001063 // Child and parent calls are made in the order they were registered.
1064 if (pid == 0) {
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001065 ASSERT_EQ(12, g_atfork_child_calls);
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001066 _exit(0);
1067 }
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001068 ASSERT_EQ(12, g_atfork_parent_calls);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001069
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001070 // Prepare calls are made in the reverse order.
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001071 ASSERT_EQ(21, g_atfork_prepare_calls);
1072 int status;
1073 ASSERT_EQ(pid, waitpid(pid, &status, 0));
1074}
1075
Elliott Hughesc3f11402013-10-30 14:40:09 -07001076TEST(pthread, pthread_attr_getscope) {
1077 pthread_attr_t attr;
1078 ASSERT_EQ(0, pthread_attr_init(&attr));
1079
1080 int scope;
1081 ASSERT_EQ(0, pthread_attr_getscope(&attr, &scope));
1082 ASSERT_EQ(PTHREAD_SCOPE_SYSTEM, scope);
1083}
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001084
1085TEST(pthread, pthread_condattr_init) {
1086 pthread_condattr_t attr;
1087 pthread_condattr_init(&attr);
1088
1089 clockid_t clock;
1090 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1091 ASSERT_EQ(CLOCK_REALTIME, clock);
1092
1093 int pshared;
1094 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1095 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
1096}
1097
1098TEST(pthread, pthread_condattr_setclock) {
1099 pthread_condattr_t attr;
1100 pthread_condattr_init(&attr);
1101
1102 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_REALTIME));
1103 clockid_t clock;
1104 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1105 ASSERT_EQ(CLOCK_REALTIME, clock);
1106
1107 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1108 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1109 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1110
1111 ASSERT_EQ(EINVAL, pthread_condattr_setclock(&attr, CLOCK_PROCESS_CPUTIME_ID));
1112}
1113
1114TEST(pthread, pthread_cond_broadcast__preserves_condattr_flags) {
Yabin Cui32651b82015-03-13 20:30:00 -07001115#if defined(__BIONIC__)
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001116 pthread_condattr_t attr;
1117 pthread_condattr_init(&attr);
1118
1119 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1120 ASSERT_EQ(0, pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
1121
1122 pthread_cond_t cond_var;
1123 ASSERT_EQ(0, pthread_cond_init(&cond_var, &attr));
1124
1125 ASSERT_EQ(0, pthread_cond_signal(&cond_var));
1126 ASSERT_EQ(0, pthread_cond_broadcast(&cond_var));
1127
Yabin Cui32651b82015-03-13 20:30:00 -07001128 attr = static_cast<pthread_condattr_t>(*reinterpret_cast<uint32_t*>(cond_var.__private));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001129 clockid_t clock;
1130 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1131 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1132 int pshared;
1133 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1134 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
Yabin Cui32651b82015-03-13 20:30:00 -07001135#else // !defined(__BIONIC__)
1136 GTEST_LOG_(INFO) << "This tests a bionic implementation detail.\n";
1137#endif // !defined(__BIONIC__)
1138}
1139
1140class pthread_CondWakeupTest : public ::testing::Test {
1141 protected:
1142 pthread_mutex_t mutex;
1143 pthread_cond_t cond;
1144
1145 enum Progress {
1146 INITIALIZED,
1147 WAITING,
1148 SIGNALED,
1149 FINISHED,
1150 };
1151 std::atomic<Progress> progress;
1152 pthread_t thread;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001153 std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function;
Yabin Cui32651b82015-03-13 20:30:00 -07001154
1155 protected:
Yabin Cuic9a659c2015-11-05 15:36:08 -08001156 void SetUp() override {
1157 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1158 }
1159
1160 void InitCond(clockid_t clock=CLOCK_REALTIME) {
1161 pthread_condattr_t attr;
1162 ASSERT_EQ(0, pthread_condattr_init(&attr));
1163 ASSERT_EQ(0, pthread_condattr_setclock(&attr, clock));
1164 ASSERT_EQ(0, pthread_cond_init(&cond, &attr));
1165 ASSERT_EQ(0, pthread_condattr_destroy(&attr));
1166 }
1167
1168 void StartWaitingThread(std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function) {
Yabin Cui32651b82015-03-13 20:30:00 -07001169 progress = INITIALIZED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001170 this->wait_function = wait_function;
1171 ASSERT_EQ(0, pthread_create(&thread, NULL, reinterpret_cast<void* (*)(void*)>(WaitThreadFn), this));
1172 while (progress != WAITING) {
Yabin Cui32651b82015-03-13 20:30:00 -07001173 usleep(5000);
1174 }
1175 usleep(5000);
1176 }
1177
Yabin Cuic9a659c2015-11-05 15:36:08 -08001178 void TearDown() override {
1179 ASSERT_EQ(0, pthread_join(thread, nullptr));
1180 ASSERT_EQ(FINISHED, progress);
1181 ASSERT_EQ(0, pthread_cond_destroy(&cond));
1182 ASSERT_EQ(0, pthread_mutex_destroy(&mutex));
1183 }
1184
Yabin Cui32651b82015-03-13 20:30:00 -07001185 private:
1186 static void WaitThreadFn(pthread_CondWakeupTest* test) {
1187 ASSERT_EQ(0, pthread_mutex_lock(&test->mutex));
1188 test->progress = WAITING;
1189 while (test->progress == WAITING) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001190 ASSERT_EQ(0, test->wait_function(&test->cond, &test->mutex));
Yabin Cui32651b82015-03-13 20:30:00 -07001191 }
1192 ASSERT_EQ(SIGNALED, test->progress);
1193 test->progress = FINISHED;
1194 ASSERT_EQ(0, pthread_mutex_unlock(&test->mutex));
1195 }
1196};
1197
Yabin Cuic9a659c2015-11-05 15:36:08 -08001198TEST_F(pthread_CondWakeupTest, signal_wait) {
1199 InitCond();
1200 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1201 return pthread_cond_wait(cond, mutex);
1202 });
Yabin Cui32651b82015-03-13 20:30:00 -07001203 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001204 ASSERT_EQ(0, pthread_cond_signal(&cond));
Yabin Cui32651b82015-03-13 20:30:00 -07001205}
1206
Yabin Cuic9a659c2015-11-05 15:36:08 -08001207TEST_F(pthread_CondWakeupTest, broadcast_wait) {
1208 InitCond();
1209 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1210 return pthread_cond_wait(cond, mutex);
1211 });
Yabin Cui32651b82015-03-13 20:30:00 -07001212 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001213 ASSERT_EQ(0, pthread_cond_broadcast(&cond));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001214}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001215
Yabin Cuic9a659c2015-11-05 15:36:08 -08001216TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_REALTIME) {
1217 InitCond(CLOCK_REALTIME);
Elliott Hughes0e714a52014-03-03 16:42:47 -08001218 timespec ts;
1219 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001220 ts.tv_sec += 1;
1221 StartWaitingThread([&](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1222 return pthread_cond_timedwait(cond, mutex, &ts);
1223 });
1224 progress = SIGNALED;
1225 ASSERT_EQ(0, pthread_cond_signal(&cond));
1226}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001227
Yabin Cuic9a659c2015-11-05 15:36:08 -08001228TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC) {
1229 InitCond(CLOCK_MONOTONIC);
1230 timespec ts;
1231 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1232 ts.tv_sec += 1;
1233 StartWaitingThread([&](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1234 return pthread_cond_timedwait(cond, mutex, &ts);
1235 });
1236 progress = SIGNALED;
1237 ASSERT_EQ(0, pthread_cond_signal(&cond));
1238}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001239
Yabin Cuic9a659c2015-11-05 15:36:08 -08001240TEST(pthread, pthread_cond_timedwait_timeout) {
1241 pthread_mutex_t mutex;
1242 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1243 pthread_cond_t cond;
1244 ASSERT_EQ(0, pthread_cond_init(&cond, nullptr));
1245 ASSERT_EQ(0, pthread_mutex_lock(&mutex));
1246 timespec ts;
Elliott Hughes0e714a52014-03-03 16:42:47 -08001247 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001248 ASSERT_EQ(ETIMEDOUT, pthread_cond_timedwait(&cond, &mutex, &ts));
1249 ts.tv_nsec = -1;
1250 ASSERT_EQ(EINVAL, pthread_cond_timedwait(&cond, &mutex, &ts));
1251 ts.tv_nsec = NS_PER_S;
1252 ASSERT_EQ(EINVAL, pthread_cond_timedwait(&cond, &mutex, &ts));
1253 ts.tv_nsec = NS_PER_S - 1;
1254 ts.tv_sec = -1;
1255 ASSERT_EQ(ETIMEDOUT, pthread_cond_timedwait(&cond, &mutex, &ts));
1256 ASSERT_EQ(0, pthread_mutex_unlock(&mutex));
Elliott Hughes0e714a52014-03-03 16:42:47 -08001257}
Elliott Hughes57b7a612014-08-25 17:26:50 -07001258
1259TEST(pthread, pthread_attr_getstack__main_thread) {
1260 // This test is only meaningful for the main thread, so make sure we're running on it!
1261 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1262
1263 // Get the main thread's attributes.
1264 pthread_attr_t attributes;
1265 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1266
1267 // Check that we correctly report that the main thread has no guard page.
1268 size_t guard_size;
1269 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
1270 ASSERT_EQ(0U, guard_size); // The main thread has no guard page.
1271
1272 // Get the stack base and the stack size (both ways).
1273 void* stack_base;
1274 size_t stack_size;
1275 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1276 size_t stack_size2;
1277 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1278
1279 // The two methods of asking for the stack size should agree.
1280 EXPECT_EQ(stack_size, stack_size2);
1281
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001282#if defined(__BIONIC__)
Elliott Hughes57b7a612014-08-25 17:26:50 -07001283 // What does /proc/self/maps' [stack] line say?
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001284 void* maps_stack_hi = NULL;
Elliott Hughes15dfd632015-09-22 16:40:14 -07001285 std::vector<map_record> maps;
1286 ASSERT_TRUE(Maps::parse_maps(&maps));
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07001287 for (const auto& map : maps) {
Elliott Hughes15dfd632015-09-22 16:40:14 -07001288 if (map.pathname == "[stack]") {
1289 maps_stack_hi = reinterpret_cast<void*>(map.addr_end);
Elliott Hughes57b7a612014-08-25 17:26:50 -07001290 break;
1291 }
1292 }
Elliott Hughes57b7a612014-08-25 17:26:50 -07001293
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001294 // The high address of the /proc/self/maps [stack] region should equal stack_base + stack_size.
1295 // Remember that the stack grows down (and is mapped in on demand), so the low address of the
1296 // region isn't very interesting.
1297 EXPECT_EQ(maps_stack_hi, reinterpret_cast<uint8_t*>(stack_base) + stack_size);
1298
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001299 // The stack size should correspond to RLIMIT_STACK.
Elliott Hughes57b7a612014-08-25 17:26:50 -07001300 rlimit rl;
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001301 ASSERT_EQ(0, getrlimit(RLIMIT_STACK, &rl));
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001302 uint64_t original_rlim_cur = rl.rlim_cur;
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001303 if (rl.rlim_cur == RLIM_INFINITY) {
1304 rl.rlim_cur = 8 * 1024 * 1024; // Bionic reports unlimited stacks as 8MiB.
1305 }
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001306 EXPECT_EQ(rl.rlim_cur, stack_size);
1307
Dmitriy Ivanovd9ff7222014-09-08 16:22:22 -07001308 auto guard = make_scope_guard([&rl, original_rlim_cur]() {
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001309 rl.rlim_cur = original_rlim_cur;
1310 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1311 });
1312
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001313 //
1314 // What if RLIMIT_STACK is smaller than the stack's current extent?
1315 //
Elliott Hughes57b7a612014-08-25 17:26:50 -07001316 rl.rlim_cur = rl.rlim_max = 1024; // 1KiB. We know the stack must be at least a page already.
1317 rl.rlim_max = RLIM_INFINITY;
1318 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1319
1320 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1321 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1322 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1323
1324 EXPECT_EQ(stack_size, stack_size2);
1325 ASSERT_EQ(1024U, stack_size);
1326
1327 //
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001328 // What if RLIMIT_STACK isn't a whole number of pages?
Elliott Hughes57b7a612014-08-25 17:26:50 -07001329 //
1330 rl.rlim_cur = rl.rlim_max = 6666; // Not a whole number of pages.
1331 rl.rlim_max = RLIM_INFINITY;
1332 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1333
1334 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1335 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1336 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1337
1338 EXPECT_EQ(stack_size, stack_size2);
1339 ASSERT_EQ(6666U, stack_size);
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001340#endif
Elliott Hughes57b7a612014-08-25 17:26:50 -07001341}
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001342
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001343struct GetStackSignalHandlerArg {
1344 volatile bool done;
1345 void* signal_handler_sp;
1346 void* main_stack_base;
1347 size_t main_stack_size;
1348};
1349
1350static GetStackSignalHandlerArg getstack_signal_handler_arg;
1351
1352static void getstack_signal_handler(int sig) {
1353 ASSERT_EQ(SIGUSR1, sig);
1354 // Use sleep() to make current thread be switched out by the kernel to provoke the error.
1355 sleep(1);
1356 pthread_attr_t attr;
1357 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1358 void* stack_base;
1359 size_t stack_size;
1360 ASSERT_EQ(0, pthread_attr_getstack(&attr, &stack_base, &stack_size));
1361 getstack_signal_handler_arg.signal_handler_sp = &attr;
1362 getstack_signal_handler_arg.main_stack_base = stack_base;
1363 getstack_signal_handler_arg.main_stack_size = stack_size;
1364 getstack_signal_handler_arg.done = true;
1365}
1366
1367// The previous code obtained the main thread's stack by reading the entry in
1368// /proc/self/task/<pid>/maps that was labeled [stack]. Unfortunately, on x86/x86_64, the kernel
1369// relies on sp0 in task state segment(tss) to label the stack map with [stack]. If the kernel
1370// switches a process while the main thread is in an alternate stack, then the kernel will label
1371// the wrong map with [stack]. This test verifies that when the above situation happens, the main
1372// thread's stack is found correctly.
1373TEST(pthread, pthread_attr_getstack_in_signal_handler) {
1374 const size_t sig_stack_size = 16 * 1024;
1375 void* sig_stack = mmap(NULL, sig_stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS,
1376 -1, 0);
1377 ASSERT_NE(MAP_FAILED, sig_stack);
1378 stack_t ss;
1379 ss.ss_sp = sig_stack;
1380 ss.ss_size = sig_stack_size;
1381 ss.ss_flags = 0;
1382 stack_t oss;
1383 ASSERT_EQ(0, sigaltstack(&ss, &oss));
1384
1385 ScopedSignalHandler handler(SIGUSR1, getstack_signal_handler, SA_ONSTACK);
1386 getstack_signal_handler_arg.done = false;
1387 kill(getpid(), SIGUSR1);
1388 ASSERT_EQ(true, getstack_signal_handler_arg.done);
1389
1390 // Verify if the stack used by the signal handler is the alternate stack just registered.
1391 ASSERT_LE(sig_stack, getstack_signal_handler_arg.signal_handler_sp);
1392 ASSERT_GE(reinterpret_cast<char*>(sig_stack) + sig_stack_size,
1393 getstack_signal_handler_arg.signal_handler_sp);
1394
1395 // Verify if the main thread's stack got in the signal handler is correct.
1396 ASSERT_LE(getstack_signal_handler_arg.main_stack_base, &ss);
1397 ASSERT_GE(reinterpret_cast<char*>(getstack_signal_handler_arg.main_stack_base) +
1398 getstack_signal_handler_arg.main_stack_size, reinterpret_cast<void*>(&ss));
1399
1400 ASSERT_EQ(0, sigaltstack(&oss, nullptr));
1401 ASSERT_EQ(0, munmap(sig_stack, sig_stack_size));
1402}
1403
Yabin Cui917d3902015-01-08 12:32:42 -08001404static void pthread_attr_getstack_18908062_helper(void*) {
1405 char local_variable;
1406 pthread_attr_t attributes;
1407 pthread_getattr_np(pthread_self(), &attributes);
1408 void* stack_base;
1409 size_t stack_size;
1410 pthread_attr_getstack(&attributes, &stack_base, &stack_size);
1411
1412 // Test whether &local_variable is in [stack_base, stack_base + stack_size).
1413 ASSERT_LE(reinterpret_cast<char*>(stack_base), &local_variable);
1414 ASSERT_LT(&local_variable, reinterpret_cast<char*>(stack_base) + stack_size);
1415}
1416
1417// Check whether something on stack is in the range of
1418// [stack_base, stack_base + stack_size). see b/18908062.
1419TEST(pthread, pthread_attr_getstack_18908062) {
1420 pthread_t t;
1421 ASSERT_EQ(0, pthread_create(&t, NULL,
1422 reinterpret_cast<void* (*)(void*)>(pthread_attr_getstack_18908062_helper),
1423 NULL));
1424 pthread_join(t, NULL);
1425}
1426
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001427#if defined(__BIONIC__)
Elliott Hughesf2083612015-11-11 13:32:28 -08001428static pthread_mutex_t pthread_gettid_np_mutex = PTHREAD_MUTEX_INITIALIZER;
1429
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001430static void* pthread_gettid_np_helper(void* arg) {
1431 *reinterpret_cast<pid_t*>(arg) = gettid();
Elliott Hughesf2083612015-11-11 13:32:28 -08001432
1433 // Wait for our parent to call pthread_gettid_np on us before exiting.
1434 pthread_mutex_lock(&pthread_gettid_np_mutex);
1435 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001436 return NULL;
1437}
1438#endif
1439
1440TEST(pthread, pthread_gettid_np) {
1441#if defined(__BIONIC__)
1442 ASSERT_EQ(gettid(), pthread_gettid_np(pthread_self()));
1443
Elliott Hughesf2083612015-11-11 13:32:28 -08001444 // Ensure the other thread doesn't exit until after we've called
1445 // pthread_gettid_np on it.
1446 pthread_mutex_lock(&pthread_gettid_np_mutex);
1447
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001448 pid_t t_gettid_result;
1449 pthread_t t;
1450 pthread_create(&t, NULL, pthread_gettid_np_helper, &t_gettid_result);
1451
1452 pid_t t_pthread_gettid_np_result = pthread_gettid_np(t);
1453
Elliott Hughesf2083612015-11-11 13:32:28 -08001454 // Release the other thread and wait for it to exit.
1455 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Elliott Hughes34c987a2014-09-22 16:01:26 -07001456 pthread_join(t, NULL);
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001457
1458 ASSERT_EQ(t_gettid_result, t_pthread_gettid_np_result);
1459#else
1460 GTEST_LOG_(INFO) << "This test does nothing.\n";
1461#endif
1462}
Elliott Hughes34c987a2014-09-22 16:01:26 -07001463
1464static size_t cleanup_counter = 0;
1465
Derek Xue41996952014-09-25 11:05:32 +01001466static void AbortCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001467 abort();
1468}
1469
Derek Xue41996952014-09-25 11:05:32 +01001470static void CountCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001471 ++cleanup_counter;
1472}
1473
Derek Xue41996952014-09-25 11:05:32 +01001474static void PthreadCleanupTester() {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001475 pthread_cleanup_push(CountCleanupRoutine, NULL);
1476 pthread_cleanup_push(CountCleanupRoutine, NULL);
1477 pthread_cleanup_push(AbortCleanupRoutine, NULL);
1478
1479 pthread_cleanup_pop(0); // Pop the abort without executing it.
1480 pthread_cleanup_pop(1); // Pop one count while executing it.
1481 ASSERT_EQ(1U, cleanup_counter);
1482 // Exit while the other count is still on the cleanup stack.
1483 pthread_exit(NULL);
1484
1485 // Calls to pthread_cleanup_pop/pthread_cleanup_push must always be balanced.
1486 pthread_cleanup_pop(0);
1487}
1488
Derek Xue41996952014-09-25 11:05:32 +01001489static void* PthreadCleanupStartRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001490 PthreadCleanupTester();
1491 return NULL;
1492}
1493
1494TEST(pthread, pthread_cleanup_push__pthread_cleanup_pop) {
1495 pthread_t t;
1496 ASSERT_EQ(0, pthread_create(&t, NULL, PthreadCleanupStartRoutine, NULL));
1497 pthread_join(t, NULL);
1498 ASSERT_EQ(2U, cleanup_counter);
1499}
Derek Xue41996952014-09-25 11:05:32 +01001500
1501TEST(pthread, PTHREAD_MUTEX_DEFAULT_is_PTHREAD_MUTEX_NORMAL) {
1502 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_DEFAULT);
1503}
1504
1505TEST(pthread, pthread_mutexattr_gettype) {
1506 pthread_mutexattr_t attr;
1507 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1508
1509 int attr_type;
1510
1511 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL));
1512 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1513 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, attr_type);
1514
1515 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK));
1516 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1517 ASSERT_EQ(PTHREAD_MUTEX_ERRORCHECK, attr_type);
1518
1519 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE));
1520 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1521 ASSERT_EQ(PTHREAD_MUTEX_RECURSIVE, attr_type);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001522
1523 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
1524}
1525
Yabin Cui17393b02015-03-21 15:08:25 -07001526struct PthreadMutex {
1527 pthread_mutex_t lock;
1528
1529 PthreadMutex(int mutex_type) {
1530 init(mutex_type);
1531 }
1532
1533 ~PthreadMutex() {
1534 destroy();
1535 }
1536
1537 private:
1538 void init(int mutex_type) {
1539 pthread_mutexattr_t attr;
1540 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1541 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, mutex_type));
1542 ASSERT_EQ(0, pthread_mutex_init(&lock, &attr));
1543 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
1544 }
1545
1546 void destroy() {
1547 ASSERT_EQ(0, pthread_mutex_destroy(&lock));
1548 }
1549
1550 DISALLOW_COPY_AND_ASSIGN(PthreadMutex);
1551};
Derek Xue41996952014-09-25 11:05:32 +01001552
1553TEST(pthread, pthread_mutex_lock_NORMAL) {
Yabin Cui17393b02015-03-21 15:08:25 -07001554 PthreadMutex m(PTHREAD_MUTEX_NORMAL);
Derek Xue41996952014-09-25 11:05:32 +01001555
Yabin Cui17393b02015-03-21 15:08:25 -07001556 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1557 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01001558}
1559
1560TEST(pthread, pthread_mutex_lock_ERRORCHECK) {
Yabin Cui17393b02015-03-21 15:08:25 -07001561 PthreadMutex m(PTHREAD_MUTEX_ERRORCHECK);
Derek Xue41996952014-09-25 11:05:32 +01001562
Yabin Cui17393b02015-03-21 15:08:25 -07001563 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1564 ASSERT_EQ(EDEADLK, pthread_mutex_lock(&m.lock));
1565 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1566 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
1567 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
1568 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1569 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01001570}
1571
1572TEST(pthread, pthread_mutex_lock_RECURSIVE) {
Yabin Cui17393b02015-03-21 15:08:25 -07001573 PthreadMutex m(PTHREAD_MUTEX_RECURSIVE);
Derek Xue41996952014-09-25 11:05:32 +01001574
Yabin Cui17393b02015-03-21 15:08:25 -07001575 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1576 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1577 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1578 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1579 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
1580 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1581 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
1582}
1583
1584TEST(pthread, pthread_mutex_init_same_as_static_initializers) {
1585 pthread_mutex_t lock_normal = PTHREAD_MUTEX_INITIALIZER;
1586 PthreadMutex m1(PTHREAD_MUTEX_NORMAL);
1587 ASSERT_EQ(0, memcmp(&lock_normal, &m1.lock, sizeof(pthread_mutex_t)));
1588 pthread_mutex_destroy(&lock_normal);
1589
1590 pthread_mutex_t lock_errorcheck = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
1591 PthreadMutex m2(PTHREAD_MUTEX_ERRORCHECK);
1592 ASSERT_EQ(0, memcmp(&lock_errorcheck, &m2.lock, sizeof(pthread_mutex_t)));
1593 pthread_mutex_destroy(&lock_errorcheck);
1594
1595 pthread_mutex_t lock_recursive = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
1596 PthreadMutex m3(PTHREAD_MUTEX_RECURSIVE);
1597 ASSERT_EQ(0, memcmp(&lock_recursive, &m3.lock, sizeof(pthread_mutex_t)));
1598 ASSERT_EQ(0, pthread_mutex_destroy(&lock_recursive));
Derek Xue41996952014-09-25 11:05:32 +01001599}
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001600class MutexWakeupHelper {
1601 private:
Yabin Cui17393b02015-03-21 15:08:25 -07001602 PthreadMutex m;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001603 enum Progress {
1604 LOCK_INITIALIZED,
1605 LOCK_WAITING,
1606 LOCK_RELEASED,
1607 LOCK_ACCESSED
1608 };
1609 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -07001610 std::atomic<pid_t> tid;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001611
1612 static void thread_fn(MutexWakeupHelper* helper) {
Yabin Cuif7969852015-04-02 17:47:48 -07001613 helper->tid = gettid();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001614 ASSERT_EQ(LOCK_INITIALIZED, helper->progress);
1615 helper->progress = LOCK_WAITING;
1616
Yabin Cui17393b02015-03-21 15:08:25 -07001617 ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001618 ASSERT_EQ(LOCK_RELEASED, helper->progress);
Yabin Cui17393b02015-03-21 15:08:25 -07001619 ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001620
1621 helper->progress = LOCK_ACCESSED;
1622 }
1623
1624 public:
Yabin Cui17393b02015-03-21 15:08:25 -07001625 MutexWakeupHelper(int mutex_type) : m(mutex_type) {
1626 }
1627
1628 void test() {
1629 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001630 progress = LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -07001631 tid = 0;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001632
1633 pthread_t thread;
1634 ASSERT_EQ(0, pthread_create(&thread, NULL,
1635 reinterpret_cast<void* (*)(void*)>(MutexWakeupHelper::thread_fn), this));
1636
Yabin Cuif7969852015-04-02 17:47:48 -07001637 WaitUntilThreadSleep(tid);
1638 ASSERT_EQ(LOCK_WAITING, progress);
1639
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001640 progress = LOCK_RELEASED;
Yabin Cui17393b02015-03-21 15:08:25 -07001641 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001642
1643 ASSERT_EQ(0, pthread_join(thread, NULL));
1644 ASSERT_EQ(LOCK_ACCESSED, progress);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001645 }
1646};
1647
1648TEST(pthread, pthread_mutex_NORMAL_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07001649 MutexWakeupHelper helper(PTHREAD_MUTEX_NORMAL);
1650 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001651}
1652
1653TEST(pthread, pthread_mutex_ERRORCHECK_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07001654 MutexWakeupHelper helper(PTHREAD_MUTEX_ERRORCHECK);
1655 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001656}
1657
1658TEST(pthread, pthread_mutex_RECURSIVE_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07001659 MutexWakeupHelper helper(PTHREAD_MUTEX_RECURSIVE);
1660 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001661}
1662
Yabin Cui140f3672015-02-03 10:32:00 -08001663TEST(pthread, pthread_mutex_owner_tid_limit) {
Yabin Cuie69c2452015-02-13 16:21:25 -08001664#if defined(__BIONIC__) && !defined(__LP64__)
Yabin Cui140f3672015-02-03 10:32:00 -08001665 FILE* fp = fopen("/proc/sys/kernel/pid_max", "r");
1666 ASSERT_TRUE(fp != NULL);
1667 long pid_max;
1668 ASSERT_EQ(1, fscanf(fp, "%ld", &pid_max));
1669 fclose(fp);
Yabin Cuie69c2452015-02-13 16:21:25 -08001670 // Bionic's pthread_mutex implementation on 32-bit devices uses 16 bits to represent owner tid.
Yabin Cui140f3672015-02-03 10:32:00 -08001671 ASSERT_LE(pid_max, 65536);
Yabin Cuie69c2452015-02-13 16:21:25 -08001672#else
1673 GTEST_LOG_(INFO) << "This test does nothing as 32-bit tid is supported by pthread_mutex.\n";
1674#endif
Yabin Cui140f3672015-02-03 10:32:00 -08001675}
Yabin Cuib5845722015-03-16 22:46:42 -07001676
Yabin Cuic9a659c2015-11-05 15:36:08 -08001677TEST(pthread, pthread_mutex_timedlock) {
1678 pthread_mutex_t m;
1679 ASSERT_EQ(0, pthread_mutex_init(&m, nullptr));
1680
1681 // If the mutex is already locked, pthread_mutex_timedlock should time out.
1682 ASSERT_EQ(0, pthread_mutex_lock(&m));
1683
1684 timespec ts;
1685 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1686 ASSERT_EQ(ETIMEDOUT, pthread_mutex_timedlock(&m, &ts));
1687 ts.tv_nsec = -1;
1688 ASSERT_EQ(EINVAL, pthread_mutex_timedlock(&m, &ts));
1689 ts.tv_nsec = NS_PER_S;
1690 ASSERT_EQ(EINVAL, pthread_mutex_timedlock(&m, &ts));
1691 ts.tv_nsec = NS_PER_S - 1;
1692 ts.tv_sec = -1;
1693 ASSERT_EQ(ETIMEDOUT, pthread_mutex_timedlock(&m, &ts));
1694
1695 // If the mutex is unlocked, pthread_mutex_timedlock should succeed.
1696 ASSERT_EQ(0, pthread_mutex_unlock(&m));
1697
1698 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1699 ts.tv_sec += 1;
1700 ASSERT_EQ(0, pthread_mutex_timedlock(&m, &ts));
1701
1702 ASSERT_EQ(0, pthread_mutex_unlock(&m));
1703 ASSERT_EQ(0, pthread_mutex_destroy(&m));
1704}
1705
Yabin Cuib5845722015-03-16 22:46:42 -07001706class StrictAlignmentAllocator {
1707 public:
1708 void* allocate(size_t size, size_t alignment) {
1709 char* p = new char[size + alignment * 2];
1710 allocated_array.push_back(p);
1711 while (!is_strict_aligned(p, alignment)) {
1712 ++p;
1713 }
1714 return p;
1715 }
1716
1717 ~StrictAlignmentAllocator() {
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07001718 for (const auto& p : allocated_array) {
1719 delete[] p;
Yabin Cuib5845722015-03-16 22:46:42 -07001720 }
1721 }
1722
1723 private:
1724 bool is_strict_aligned(char* p, size_t alignment) {
1725 return (reinterpret_cast<uintptr_t>(p) % (alignment * 2)) == alignment;
1726 }
1727
1728 std::vector<char*> allocated_array;
1729};
1730
1731TEST(pthread, pthread_types_allow_four_bytes_alignment) {
1732#if defined(__BIONIC__)
1733 // For binary compatibility with old version, we need to allow 4-byte aligned data for pthread types.
1734 StrictAlignmentAllocator allocator;
1735 pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(
1736 allocator.allocate(sizeof(pthread_mutex_t), 4));
1737 ASSERT_EQ(0, pthread_mutex_init(mutex, NULL));
1738 ASSERT_EQ(0, pthread_mutex_lock(mutex));
1739 ASSERT_EQ(0, pthread_mutex_unlock(mutex));
1740 ASSERT_EQ(0, pthread_mutex_destroy(mutex));
1741
1742 pthread_cond_t* cond = reinterpret_cast<pthread_cond_t*>(
1743 allocator.allocate(sizeof(pthread_cond_t), 4));
1744 ASSERT_EQ(0, pthread_cond_init(cond, NULL));
1745 ASSERT_EQ(0, pthread_cond_signal(cond));
1746 ASSERT_EQ(0, pthread_cond_broadcast(cond));
1747 ASSERT_EQ(0, pthread_cond_destroy(cond));
1748
1749 pthread_rwlock_t* rwlock = reinterpret_cast<pthread_rwlock_t*>(
1750 allocator.allocate(sizeof(pthread_rwlock_t), 4));
1751 ASSERT_EQ(0, pthread_rwlock_init(rwlock, NULL));
1752 ASSERT_EQ(0, pthread_rwlock_rdlock(rwlock));
1753 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
1754 ASSERT_EQ(0, pthread_rwlock_wrlock(rwlock));
1755 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
1756 ASSERT_EQ(0, pthread_rwlock_destroy(rwlock));
1757
1758#else
1759 GTEST_LOG_(INFO) << "This test tests bionic implementation details.";
1760#endif
1761}
Christopher Ferris60907c72015-06-09 18:46:15 -07001762
1763TEST(pthread, pthread_mutex_lock_null_32) {
1764#if defined(__BIONIC__) && !defined(__LP64__)
1765 ASSERT_EQ(EINVAL, pthread_mutex_lock(NULL));
1766#else
1767 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 32 bit devices.";
1768#endif
1769}
1770
1771TEST(pthread, pthread_mutex_unlock_null_32) {
1772#if defined(__BIONIC__) && !defined(__LP64__)
1773 ASSERT_EQ(EINVAL, pthread_mutex_unlock(NULL));
1774#else
1775 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 32 bit devices.";
1776#endif
1777}
1778
1779TEST_F(pthread_DeathTest, pthread_mutex_lock_null_64) {
1780#if defined(__BIONIC__) && defined(__LP64__)
1781 pthread_mutex_t* null_value = nullptr;
1782 ASSERT_EXIT(pthread_mutex_lock(null_value), testing::KilledBySignal(SIGSEGV), "");
1783#else
1784 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 64 bit devices.";
1785#endif
1786}
1787
1788TEST_F(pthread_DeathTest, pthread_mutex_unlock_null_64) {
1789#if defined(__BIONIC__) && defined(__LP64__)
1790 pthread_mutex_t* null_value = nullptr;
1791 ASSERT_EXIT(pthread_mutex_unlock(null_value), testing::KilledBySignal(SIGSEGV), "");
1792#else
1793 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 64 bit devices.";
1794#endif
1795}
Yabin Cui33ac04a2015-09-22 11:16:15 -07001796
1797extern _Unwind_Reason_Code FrameCounter(_Unwind_Context* ctx, void* arg);
1798
1799static volatile bool signal_handler_on_altstack_done;
1800
1801static void SignalHandlerOnAltStack(int signo, siginfo_t*, void*) {
1802 ASSERT_EQ(SIGUSR1, signo);
1803 // Check if we have enough stack space for unwinding.
1804 int count = 0;
1805 _Unwind_Backtrace(FrameCounter, &count);
1806 ASSERT_GT(count, 0);
1807 // Check if we have enough stack space for logging.
1808 std::string s(2048, '*');
1809 GTEST_LOG_(INFO) << s;
1810 signal_handler_on_altstack_done = true;
1811}
1812
1813TEST(pthread, big_enough_signal_stack_for_64bit_arch) {
1814 signal_handler_on_altstack_done = false;
1815 ScopedSignalHandler handler(SIGUSR1, SignalHandlerOnAltStack, SA_SIGINFO | SA_ONSTACK);
1816 kill(getpid(), SIGUSR1);
1817 ASSERT_TRUE(signal_handler_on_altstack_done);
1818}
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001819
1820TEST(pthread, pthread_barrierattr_smoke) {
1821 pthread_barrierattr_t attr;
1822 ASSERT_EQ(0, pthread_barrierattr_init(&attr));
1823 int pshared;
1824 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
1825 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
1826 ASSERT_EQ(0, pthread_barrierattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
1827 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
1828 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
1829 ASSERT_EQ(0, pthread_barrierattr_destroy(&attr));
1830}
1831
1832struct BarrierTestHelperArg {
1833 std::atomic<pid_t> tid;
1834 pthread_barrier_t* barrier;
1835 size_t iteration_count;
1836};
1837
1838static void BarrierTestHelper(BarrierTestHelperArg* arg) {
1839 arg->tid = gettid();
1840 for (size_t i = 0; i < arg->iteration_count; ++i) {
1841 ASSERT_EQ(0, pthread_barrier_wait(arg->barrier));
1842 }
1843}
1844
1845TEST(pthread, pthread_barrier_smoke) {
1846 const size_t BARRIER_ITERATION_COUNT = 10;
1847 const size_t BARRIER_THREAD_COUNT = 10;
1848 pthread_barrier_t barrier;
1849 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, BARRIER_THREAD_COUNT + 1));
1850 std::vector<pthread_t> threads(BARRIER_THREAD_COUNT);
1851 std::vector<BarrierTestHelperArg> args(threads.size());
1852 for (size_t i = 0; i < threads.size(); ++i) {
1853 args[i].tid = 0;
1854 args[i].barrier = &barrier;
1855 args[i].iteration_count = BARRIER_ITERATION_COUNT;
1856 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
1857 reinterpret_cast<void* (*)(void*)>(BarrierTestHelper), &args[i]));
1858 }
1859 for (size_t iteration = 0; iteration < BARRIER_ITERATION_COUNT; ++iteration) {
1860 for (size_t i = 0; i < threads.size(); ++i) {
1861 WaitUntilThreadSleep(args[i].tid);
1862 }
1863 ASSERT_EQ(PTHREAD_BARRIER_SERIAL_THREAD, pthread_barrier_wait(&barrier));
1864 }
1865 for (size_t i = 0; i < threads.size(); ++i) {
1866 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
1867 }
1868 ASSERT_EQ(0, pthread_barrier_destroy(&barrier));
1869}
1870
1871TEST(pthread, pthread_barrier_destroy) {
1872 pthread_barrier_t barrier;
1873 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, 2));
1874 pthread_t thread;
1875 BarrierTestHelperArg arg;
1876 arg.tid = 0;
1877 arg.barrier = &barrier;
1878 arg.iteration_count = 1;
1879 ASSERT_EQ(0, pthread_create(&thread, nullptr,
1880 reinterpret_cast<void* (*)(void*)>(BarrierTestHelper), &arg));
1881 WaitUntilThreadSleep(arg.tid);
1882 ASSERT_EQ(EBUSY, pthread_barrier_destroy(&barrier));
1883 ASSERT_EQ(PTHREAD_BARRIER_SERIAL_THREAD, pthread_barrier_wait(&barrier));
1884 // Verify if the barrier can be destroyed directly after pthread_barrier_wait().
1885 ASSERT_EQ(0, pthread_barrier_destroy(&barrier));
1886 ASSERT_EQ(0, pthread_join(thread, nullptr));
1887#if defined(__BIONIC__)
1888 ASSERT_EQ(EINVAL, pthread_barrier_destroy(&barrier));
1889#endif
1890}
1891
1892struct BarrierOrderingTestHelperArg {
1893 pthread_barrier_t* barrier;
1894 size_t* array;
1895 size_t array_length;
1896 size_t id;
1897};
1898
1899void BarrierOrderingTestHelper(BarrierOrderingTestHelperArg* arg) {
1900 const size_t ITERATION_COUNT = 10000;
1901 for (size_t i = 1; i <= ITERATION_COUNT; ++i) {
1902 arg->array[arg->id] = i;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001903 int result = pthread_barrier_wait(arg->barrier);
1904 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001905 for (size_t j = 0; j < arg->array_length; ++j) {
1906 ASSERT_EQ(i, arg->array[j]);
1907 }
Yabin Cuic9a659c2015-11-05 15:36:08 -08001908 result = pthread_barrier_wait(arg->barrier);
1909 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001910 }
1911}
1912
1913TEST(pthread, pthread_barrier_check_ordering) {
1914 const size_t THREAD_COUNT = 4;
1915 pthread_barrier_t barrier;
1916 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, THREAD_COUNT));
1917 size_t array[THREAD_COUNT];
1918 std::vector<pthread_t> threads(THREAD_COUNT);
1919 std::vector<BarrierOrderingTestHelperArg> args(THREAD_COUNT);
1920 for (size_t i = 0; i < THREAD_COUNT; ++i) {
1921 args[i].barrier = &barrier;
1922 args[i].array = array;
1923 args[i].array_length = THREAD_COUNT;
1924 args[i].id = i;
1925 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
1926 reinterpret_cast<void* (*)(void*)>(BarrierOrderingTestHelper),
1927 &args[i]));
1928 }
1929 for (size_t i = 0; i < THREAD_COUNT; ++i) {
1930 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
1931 }
1932}