blob: 183312d98e33258c1820fc0c060e7afdcec2fe9c [file] [log] [blame]
Elliott Hughesbfeab1b2012-09-05 17:47:37 -07001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <gtest/gtest.h>
18
19#include <errno.h>
Elliott Hughes5b9310e2013-10-02 16:59:05 -070020#include <inttypes.h>
Elliott Hughesb95cf0d2013-07-15 14:51:07 -070021#include <limits.h>
Elliott Hughes04620a32014-03-07 17:59:05 -080022#include <malloc.h>
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070023#include <pthread.h>
Christopher Ferrisf04935c2013-12-20 18:43:21 -080024#include <signal.h>
Yabin Cui140f3672015-02-03 10:32:00 -080025#include <stdio.h>
Elliott Hughes70b24b12013-11-15 11:51:07 -080026#include <sys/mman.h>
Elliott Hughes4d098ca2016-04-11 12:43:05 -070027#include <sys/prctl.h>
Elliott Hughes57b7a612014-08-25 17:26:50 -070028#include <sys/syscall.h>
Narayan Kamath51e6cb32014-03-03 15:38:51 +000029#include <time.h>
Elliott Hughes4d014e12012-09-07 16:47:54 -070030#include <unistd.h>
Yabin Cui33ac04a2015-09-22 11:16:15 -070031#include <unwind.h>
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070032
Yabin Cui08ee8d22015-02-11 17:04:36 -080033#include <atomic>
Yabin Cuib5845722015-03-16 22:46:42 -070034#include <vector>
Yabin Cui08ee8d22015-02-11 17:04:36 -080035
Tom Cherryb8ab6182017-04-05 16:20:29 -070036#include <android-base/scopeguard.h>
37
Yabin Cuic9a659c2015-11-05 15:36:08 -080038#include "private/bionic_constants.h"
Yabin Cui17393b02015-03-21 15:08:25 -070039#include "private/bionic_macros.h"
Yabin Cui17393b02015-03-21 15:08:25 -070040#include "BionicDeathTest.h"
41#include "ScopedSignalHandler.h"
Elliott Hughes15dfd632015-09-22 16:40:14 -070042#include "utils.h"
43
Elliott Hughesbfeab1b2012-09-05 17:47:37 -070044TEST(pthread, pthread_key_create) {
45 pthread_key_t key;
46 ASSERT_EQ(0, pthread_key_create(&key, NULL));
47 ASSERT_EQ(0, pthread_key_delete(key));
48 // Can't delete a key that's already been deleted.
49 ASSERT_EQ(EINVAL, pthread_key_delete(key));
50}
Elliott Hughes4d014e12012-09-07 16:47:54 -070051
Dan Albertc4bcc752014-09-30 11:48:24 -070052TEST(pthread, pthread_keys_max) {
Yabin Cui6c238f22014-12-11 20:50:41 -080053 // POSIX says PTHREAD_KEYS_MAX should be at least _POSIX_THREAD_KEYS_MAX.
54 ASSERT_GE(PTHREAD_KEYS_MAX, _POSIX_THREAD_KEYS_MAX);
Dan Albertc4bcc752014-09-30 11:48:24 -070055}
Elliott Hughes718a5b52014-01-28 17:02:03 -080056
Yabin Cui6c238f22014-12-11 20:50:41 -080057TEST(pthread, sysconf_SC_THREAD_KEYS_MAX_eq_PTHREAD_KEYS_MAX) {
Dan Albertc4bcc752014-09-30 11:48:24 -070058 int sysconf_max = sysconf(_SC_THREAD_KEYS_MAX);
Yabin Cui6c238f22014-12-11 20:50:41 -080059 ASSERT_EQ(sysconf_max, PTHREAD_KEYS_MAX);
Dan Albertc4bcc752014-09-30 11:48:24 -070060}
61
62TEST(pthread, pthread_key_many_distinct) {
Yabin Cui6c238f22014-12-11 20:50:41 -080063 // As gtest uses pthread keys, we can't allocate exactly PTHREAD_KEYS_MAX
64 // pthread keys, but We should be able to allocate at least this many keys.
65 int nkeys = PTHREAD_KEYS_MAX / 2;
Dan Albertc4bcc752014-09-30 11:48:24 -070066 std::vector<pthread_key_t> keys;
67
Tom Cherryb8ab6182017-04-05 16:20:29 -070068 auto scope_guard = android::base::make_scope_guard([&keys] {
Elliott Hughes0b2acdf2015-10-02 18:25:19 -070069 for (const auto& key : keys) {
Dan Albertc4bcc752014-09-30 11:48:24 -070070 EXPECT_EQ(0, pthread_key_delete(key));
71 }
72 });
73
74 for (int i = 0; i < nkeys; ++i) {
75 pthread_key_t key;
Elliott Hughes61706932015-03-31 10:56:58 -070076 // If this fails, it's likely that LIBC_PTHREAD_KEY_RESERVED_COUNT is wrong.
Dan Albertc4bcc752014-09-30 11:48:24 -070077 ASSERT_EQ(0, pthread_key_create(&key, NULL)) << i << " of " << nkeys;
78 keys.push_back(key);
79 ASSERT_EQ(0, pthread_setspecific(key, reinterpret_cast<void*>(i)));
80 }
81
82 for (int i = keys.size() - 1; i >= 0; --i) {
83 ASSERT_EQ(reinterpret_cast<void*>(i), pthread_getspecific(keys.back()));
84 pthread_key_t key = keys.back();
85 keys.pop_back();
86 ASSERT_EQ(0, pthread_key_delete(key));
87 }
88}
89
Yabin Cui6c238f22014-12-11 20:50:41 -080090TEST(pthread, pthread_key_not_exceed_PTHREAD_KEYS_MAX) {
Elliott Hughes44b53ad2013-02-11 20:18:47 +000091 std::vector<pthread_key_t> keys;
Dan Albertc4bcc752014-09-30 11:48:24 -070092 int rv = 0;
Yabin Cui6c238f22014-12-11 20:50:41 -080093
94 // Pthread keys are used by gtest, so PTHREAD_KEYS_MAX should
95 // be more than we are allowed to allocate now.
96 for (int i = 0; i < PTHREAD_KEYS_MAX; i++) {
Elliott Hughes44b53ad2013-02-11 20:18:47 +000097 pthread_key_t key;
Dan Albertc4bcc752014-09-30 11:48:24 -070098 rv = pthread_key_create(&key, NULL);
99 if (rv == EAGAIN) {
100 break;
101 }
102 EXPECT_EQ(0, rv);
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000103 keys.push_back(key);
104 }
105
Dan Albertc4bcc752014-09-30 11:48:24 -0700106 // Don't leak keys.
Elliott Hughes0b2acdf2015-10-02 18:25:19 -0700107 for (const auto& key : keys) {
Dan Albertc4bcc752014-09-30 11:48:24 -0700108 EXPECT_EQ(0, pthread_key_delete(key));
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000109 }
Dan Albertc4bcc752014-09-30 11:48:24 -0700110 keys.clear();
111
112 // We should have eventually reached the maximum number of keys and received
113 // EAGAIN.
114 ASSERT_EQ(EAGAIN, rv);
Elliott Hughes44b53ad2013-02-11 20:18:47 +0000115}
116
Elliott Hughesebb770f2014-06-25 13:46:46 -0700117TEST(pthread, pthread_key_delete) {
118 void* expected = reinterpret_cast<void*>(1234);
119 pthread_key_t key;
120 ASSERT_EQ(0, pthread_key_create(&key, NULL));
121 ASSERT_EQ(0, pthread_setspecific(key, expected));
122 ASSERT_EQ(expected, pthread_getspecific(key));
123 ASSERT_EQ(0, pthread_key_delete(key));
124 // After deletion, pthread_getspecific returns NULL.
125 ASSERT_EQ(NULL, pthread_getspecific(key));
126 // And you can't use pthread_setspecific with the deleted key.
127 ASSERT_EQ(EINVAL, pthread_setspecific(key, expected));
128}
129
Elliott Hughes40a52172014-07-30 14:48:10 -0700130TEST(pthread, pthread_key_fork) {
131 void* expected = reinterpret_cast<void*>(1234);
132 pthread_key_t key;
133 ASSERT_EQ(0, pthread_key_create(&key, NULL));
134 ASSERT_EQ(0, pthread_setspecific(key, expected));
135 ASSERT_EQ(expected, pthread_getspecific(key));
136
137 pid_t pid = fork();
138 ASSERT_NE(-1, pid) << strerror(errno);
139
140 if (pid == 0) {
141 // The surviving thread inherits all the forking thread's TLS values...
142 ASSERT_EQ(expected, pthread_getspecific(key));
143 _exit(99);
144 }
145
Elliott Hughes33697a02016-01-26 13:04:57 -0800146 AssertChildExited(pid, 99);
Elliott Hughes40a52172014-07-30 14:48:10 -0700147
148 ASSERT_EQ(expected, pthread_getspecific(key));
Dan Albert1d53ae22014-09-02 15:24:26 -0700149 ASSERT_EQ(0, pthread_key_delete(key));
Elliott Hughes40a52172014-07-30 14:48:10 -0700150}
151
152static void* DirtyKeyFn(void* key) {
153 return pthread_getspecific(*reinterpret_cast<pthread_key_t*>(key));
154}
155
156TEST(pthread, pthread_key_dirty) {
157 pthread_key_t key;
158 ASSERT_EQ(0, pthread_key_create(&key, NULL));
159
Yabin Cuia36158a2015-11-16 21:06:16 -0800160 size_t stack_size = 640 * 1024;
Elliott Hughes40a52172014-07-30 14:48:10 -0700161 void* stack = mmap(NULL, stack_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
162 ASSERT_NE(MAP_FAILED, stack);
163 memset(stack, 0xff, stack_size);
164
165 pthread_attr_t attr;
166 ASSERT_EQ(0, pthread_attr_init(&attr));
167 ASSERT_EQ(0, pthread_attr_setstack(&attr, stack, stack_size));
168
169 pthread_t t;
170 ASSERT_EQ(0, pthread_create(&t, &attr, DirtyKeyFn, &key));
171
172 void* result;
173 ASSERT_EQ(0, pthread_join(t, &result));
174 ASSERT_EQ(nullptr, result); // Not ~0!
175
176 ASSERT_EQ(0, munmap(stack, stack_size));
Dan Albert1d53ae22014-09-02 15:24:26 -0700177 ASSERT_EQ(0, pthread_key_delete(key));
Elliott Hughes40a52172014-07-30 14:48:10 -0700178}
179
Yabin Cui5ddbb3f2015-03-05 20:35:32 -0800180TEST(pthread, static_pthread_key_used_before_creation) {
181#if defined(__BIONIC__)
182 // See http://b/19625804. The bug is about a static/global pthread key being used before creation.
183 // So here tests if the static/global default value 0 can be detected as invalid key.
184 static pthread_key_t key;
185 ASSERT_EQ(nullptr, pthread_getspecific(key));
186 ASSERT_EQ(EINVAL, pthread_setspecific(key, nullptr));
187 ASSERT_EQ(EINVAL, pthread_key_delete(key));
188#else
189 GTEST_LOG_(INFO) << "This test tests bionic pthread key implementation detail.\n";
190#endif
191}
192
Elliott Hughes4d014e12012-09-07 16:47:54 -0700193static void* IdFn(void* arg) {
194 return arg;
195}
196
Yabin Cui63481602014-12-01 17:41:04 -0800197class SpinFunctionHelper {
198 public:
199 SpinFunctionHelper() {
200 SpinFunctionHelper::spin_flag_ = true;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400201 }
Elliott Hughes0bd9d132017-11-02 13:11:13 -0700202
Yabin Cui63481602014-12-01 17:41:04 -0800203 ~SpinFunctionHelper() {
204 UnSpin();
205 }
Elliott Hughes0bd9d132017-11-02 13:11:13 -0700206
Yabin Cui63481602014-12-01 17:41:04 -0800207 auto GetFunction() -> void* (*)(void*) {
208 return SpinFunctionHelper::SpinFn;
209 }
210
211 void UnSpin() {
212 SpinFunctionHelper::spin_flag_ = false;
213 }
214
215 private:
216 static void* SpinFn(void*) {
217 while (spin_flag_) {}
218 return NULL;
219 }
Yabin Cuia36158a2015-11-16 21:06:16 -0800220 static std::atomic<bool> spin_flag_;
Yabin Cui63481602014-12-01 17:41:04 -0800221};
222
223// It doesn't matter if spin_flag_ is used in several tests,
224// because it is always set to false after each test. Each thread
225// loops on spin_flag_ can find it becomes false at some time.
Yabin Cuia36158a2015-11-16 21:06:16 -0800226std::atomic<bool> SpinFunctionHelper::spin_flag_;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400227
Elliott Hughes4d014e12012-09-07 16:47:54 -0700228static void* JoinFn(void* arg) {
229 return reinterpret_cast<void*>(pthread_join(reinterpret_cast<pthread_t>(arg), NULL));
230}
231
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400232static void AssertDetached(pthread_t t, bool is_detached) {
233 pthread_attr_t attr;
234 ASSERT_EQ(0, pthread_getattr_np(t, &attr));
235 int detach_state;
236 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &detach_state));
237 pthread_attr_destroy(&attr);
238 ASSERT_EQ(is_detached, (detach_state == PTHREAD_CREATE_DETACHED));
239}
240
Elliott Hughes7484c212017-02-02 02:41:38 +0000241static void MakeDeadThread(pthread_t& t) {
242 ASSERT_EQ(0, pthread_create(&t, NULL, IdFn, NULL));
243 ASSERT_EQ(0, pthread_join(t, NULL));
244}
245
Elliott Hughes4d014e12012-09-07 16:47:54 -0700246TEST(pthread, pthread_create) {
247 void* expected_result = reinterpret_cast<void*>(123);
248 // Can we create a thread?
249 pthread_t t;
250 ASSERT_EQ(0, pthread_create(&t, NULL, IdFn, expected_result));
251 // If we join, do we get the expected value back?
252 void* result;
253 ASSERT_EQ(0, pthread_join(t, &result));
254 ASSERT_EQ(expected_result, result);
255}
256
Elliott Hughes3e898472013-02-12 16:40:24 +0000257TEST(pthread, pthread_create_EAGAIN) {
258 pthread_attr_t attributes;
259 ASSERT_EQ(0, pthread_attr_init(&attributes));
260 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, static_cast<size_t>(-1) & ~(getpagesize() - 1)));
261
262 pthread_t t;
263 ASSERT_EQ(EAGAIN, pthread_create(&t, &attributes, IdFn, NULL));
264}
265
Elliott Hughes4d014e12012-09-07 16:47:54 -0700266TEST(pthread, pthread_no_join_after_detach) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700267 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800268
Elliott Hughes4d014e12012-09-07 16:47:54 -0700269 pthread_t t1;
Elliott Hughes725b2a92016-03-23 11:20:47 -0700270 ASSERT_EQ(0, pthread_create(&t1, NULL, spin_helper.GetFunction(), NULL));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700271
272 // After a pthread_detach...
273 ASSERT_EQ(0, pthread_detach(t1));
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400274 AssertDetached(t1, true);
Elliott Hughes4d014e12012-09-07 16:47:54 -0700275
276 // ...pthread_join should fail.
Elliott Hughes34c987a2014-09-22 16:01:26 -0700277 ASSERT_EQ(EINVAL, pthread_join(t1, NULL));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700278}
279
280TEST(pthread, pthread_no_op_detach_after_join) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700281 SpinFunctionHelper spin_helper;
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400282
Elliott Hughes4d014e12012-09-07 16:47:54 -0700283 pthread_t t1;
Elliott Hughes725b2a92016-03-23 11:20:47 -0700284 ASSERT_EQ(0, pthread_create(&t1, NULL, spin_helper.GetFunction(), NULL));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700285
286 // If thread 2 is already waiting to join thread 1...
287 pthread_t t2;
288 ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1)));
289
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400290 sleep(1); // (Give t2 a chance to call pthread_join.)
Elliott Hughes4d014e12012-09-07 16:47:54 -0700291
Yabin Cuibbb04322015-03-19 15:19:25 -0700292#if defined(__BIONIC__)
293 ASSERT_EQ(EINVAL, pthread_detach(t1));
294#else
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400295 ASSERT_EQ(0, pthread_detach(t1));
Yabin Cuibbb04322015-03-19 15:19:25 -0700296#endif
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400297 AssertDetached(t1, false);
298
Elliott Hughes725b2a92016-03-23 11:20:47 -0700299 spin_helper.UnSpin();
Sergey Melnikov10ce9692012-10-26 14:06:43 +0400300
301 // ...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 -0700302 void* join_result;
303 ASSERT_EQ(0, pthread_join(t2, &join_result));
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700304 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
Elliott Hughes4d014e12012-09-07 16:47:54 -0700305}
Elliott Hughes14f19592012-10-29 10:19:44 -0700306
307TEST(pthread, pthread_join_self) {
Elliott Hughes34c987a2014-09-22 16:01:26 -0700308 ASSERT_EQ(EDEADLK, pthread_join(pthread_self(), NULL));
Elliott Hughes14f19592012-10-29 10:19:44 -0700309}
Elliott Hughes4f251be2012-11-01 16:33:29 -0700310
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800311struct TestBug37410 {
312 pthread_t main_thread;
313 pthread_mutex_t mutex;
Elliott Hughes4f251be2012-11-01 16:33:29 -0700314
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800315 static void main() {
316 TestBug37410 data;
317 data.main_thread = pthread_self();
318 ASSERT_EQ(0, pthread_mutex_init(&data.mutex, NULL));
319 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
320
321 pthread_t t;
322 ASSERT_EQ(0, pthread_create(&t, NULL, TestBug37410::thread_fn, reinterpret_cast<void*>(&data)));
323
324 // Wait for the thread to be running...
325 ASSERT_EQ(0, pthread_mutex_lock(&data.mutex));
326 ASSERT_EQ(0, pthread_mutex_unlock(&data.mutex));
327
328 // ...and exit.
329 pthread_exit(NULL);
330 }
331
332 private:
333 static void* thread_fn(void* arg) {
334 TestBug37410* data = reinterpret_cast<TestBug37410*>(arg);
335
336 // Let the main thread know we're running.
337 pthread_mutex_unlock(&data->mutex);
338
339 // And wait for the main thread to exit.
340 pthread_join(data->main_thread, NULL);
341
342 return NULL;
343 }
344};
Elliott Hughes4f251be2012-11-01 16:33:29 -0700345
Elliott Hughes7fd803c2013-02-14 16:33:52 -0800346// Even though this isn't really a death test, we have to say "DeathTest" here so gtest knows to
347// run this test (which exits normally) in its own process.
Yabin Cui9df70402014-11-05 18:01:01 -0800348
349class pthread_DeathTest : public BionicDeathTest {};
350
351TEST_F(pthread_DeathTest, pthread_bug_37410) {
Elliott Hughes4f251be2012-11-01 16:33:29 -0700352 // http://code.google.com/p/android/issues/detail?id=37410
Elliott Hughes877ec6d2013-11-15 17:40:18 -0800353 ASSERT_EXIT(TestBug37410::main(), ::testing::ExitedWithCode(0), "");
Elliott Hughes4f251be2012-11-01 16:33:29 -0700354}
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800355
356static void* SignalHandlerFn(void* arg) {
357 sigset_t wait_set;
358 sigfillset(&wait_set);
359 return reinterpret_cast<void*>(sigwait(&wait_set, reinterpret_cast<int*>(arg)));
360}
361
362TEST(pthread, pthread_sigmask) {
Elliott Hughes19e62322013-10-15 11:23:57 -0700363 // Check that SIGUSR1 isn't blocked.
364 sigset_t original_set;
365 sigemptyset(&original_set);
366 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, NULL, &original_set));
367 ASSERT_FALSE(sigismember(&original_set, SIGUSR1));
368
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800369 // Block SIGUSR1.
370 sigset_t set;
371 sigemptyset(&set);
372 sigaddset(&set, SIGUSR1);
373 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, &set, NULL));
374
Elliott Hughes19e62322013-10-15 11:23:57 -0700375 // Check that SIGUSR1 is blocked.
376 sigset_t final_set;
377 sigemptyset(&final_set);
378 ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, NULL, &final_set));
379 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
380 // ...and that sigprocmask agrees with pthread_sigmask.
381 sigemptyset(&final_set);
382 ASSERT_EQ(0, sigprocmask(SIG_BLOCK, NULL, &final_set));
383 ASSERT_TRUE(sigismember(&final_set, SIGUSR1));
384
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800385 // Spawn a thread that calls sigwait and tells us what it received.
386 pthread_t signal_thread;
387 int received_signal = -1;
388 ASSERT_EQ(0, pthread_create(&signal_thread, NULL, SignalHandlerFn, &received_signal));
389
390 // Send that thread SIGUSR1.
391 pthread_kill(signal_thread, SIGUSR1);
392
393 // See what it got.
394 void* join_result;
395 ASSERT_EQ(0, pthread_join(signal_thread, &join_result));
396 ASSERT_EQ(SIGUSR1, received_signal);
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700397 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
Elliott Hughes19e62322013-10-15 11:23:57 -0700398
399 // Restore the original signal mask.
400 ASSERT_EQ(0, pthread_sigmask(SIG_SETMASK, &original_set, NULL));
Elliott Hughesc5d028f2013-01-10 14:42:14 -0800401}
Elliott Hughes5e3fc432013-02-11 16:36:48 -0800402
Elliott Hughes725b2a92016-03-23 11:20:47 -0700403static void test_pthread_setname_np__pthread_getname_np(pthread_t t) {
404 ASSERT_EQ(0, pthread_setname_np(t, "short"));
405 char name[32];
406 ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name)));
407 ASSERT_STREQ("short", name);
408
Elliott Hughesd1aea302015-04-25 10:05:24 -0700409 // The limit is 15 characters --- the kernel's buffer is 16, but includes a NUL.
Elliott Hughes725b2a92016-03-23 11:20:47 -0700410 ASSERT_EQ(0, pthread_setname_np(t, "123456789012345"));
411 ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name)));
412 ASSERT_STREQ("123456789012345", name);
413
414 ASSERT_EQ(ERANGE, pthread_setname_np(t, "1234567890123456"));
415
416 // The passed-in buffer should be at least 16 bytes.
417 ASSERT_EQ(0, pthread_getname_np(t, name, 16));
418 ASSERT_EQ(ERANGE, pthread_getname_np(t, name, 15));
Elliott Hughes3e898472013-02-12 16:40:24 +0000419}
420
Elliott Hughes725b2a92016-03-23 11:20:47 -0700421TEST(pthread, pthread_setname_np__pthread_getname_np__self) {
422 test_pthread_setname_np__pthread_getname_np(pthread_self());
Elliott Hughes3e898472013-02-12 16:40:24 +0000423}
424
Elliott Hughes725b2a92016-03-23 11:20:47 -0700425TEST(pthread, pthread_setname_np__pthread_getname_np__other) {
426 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800427
Elliott Hughes725b2a92016-03-23 11:20:47 -0700428 pthread_t t;
Elliott Hughes4d098ca2016-04-11 12:43:05 -0700429 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
430 test_pthread_setname_np__pthread_getname_np(t);
431 spin_helper.UnSpin();
432 ASSERT_EQ(0, pthread_join(t, nullptr));
433}
434
435// http://b/28051133: a kernel misfeature means that you can't change the
436// name of another thread if you've set PR_SET_DUMPABLE to 0.
437TEST(pthread, pthread_setname_np__pthread_getname_np__other_PR_SET_DUMPABLE) {
438 ASSERT_EQ(0, prctl(PR_SET_DUMPABLE, 0)) << strerror(errno);
439
440 SpinFunctionHelper spin_helper;
441
442 pthread_t t;
443 ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr));
Elliott Hughes725b2a92016-03-23 11:20:47 -0700444 test_pthread_setname_np__pthread_getname_np(t);
445 spin_helper.UnSpin();
446 ASSERT_EQ(0, pthread_join(t, nullptr));
Elliott Hughes3e898472013-02-12 16:40:24 +0000447}
448
Elliott Hughes11859d42017-02-13 17:59:29 -0800449TEST_F(pthread_DeathTest, pthread_setname_np__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000450 pthread_t dead_thread;
451 MakeDeadThread(dead_thread);
452
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800453 EXPECT_DEATH(pthread_setname_np(dead_thread, "short 3"), "invalid pthread_t");
454}
455
456TEST_F(pthread_DeathTest, pthread_setname_np__null_thread) {
457 pthread_t null_thread = 0;
458 EXPECT_EQ(ENOENT, pthread_setname_np(null_thread, "short 3"));
Elliott Hughes11859d42017-02-13 17:59:29 -0800459}
460
461TEST_F(pthread_DeathTest, pthread_getname_np__no_such_thread) {
462 pthread_t dead_thread;
463 MakeDeadThread(dead_thread);
464
Elliott Hughesbcb15292017-02-07 21:05:30 +0000465 char name[64];
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800466 EXPECT_DEATH(pthread_getname_np(dead_thread, name, sizeof(name)), "invalid pthread_t");
467}
468
469TEST_F(pthread_DeathTest, pthread_getname_np__null_thread) {
470 pthread_t null_thread = 0;
471
472 char name[64];
473 EXPECT_EQ(ENOENT, pthread_getname_np(null_thread, name, sizeof(name)));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000474}
475
Elliott Hughes9d23e042013-02-15 19:21:51 -0800476TEST(pthread, pthread_kill__0) {
477 // Signal 0 just tests that the thread exists, so it's safe to call on ourselves.
478 ASSERT_EQ(0, pthread_kill(pthread_self(), 0));
479}
480
481TEST(pthread, pthread_kill__invalid_signal) {
482 ASSERT_EQ(EINVAL, pthread_kill(pthread_self(), -1));
483}
484
Elliott Hughesfae89fc2013-02-21 11:22:23 -0800485static void pthread_kill__in_signal_handler_helper(int signal_number) {
486 static int count = 0;
487 ASSERT_EQ(SIGALRM, signal_number);
488 if (++count == 1) {
489 // Can we call pthread_kill from a signal handler?
490 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
491 }
492}
493
494TEST(pthread, pthread_kill__in_signal_handler) {
Elliott Hughes4b558f52014-03-04 15:58:02 -0800495 ScopedSignalHandler ssh(SIGALRM, pthread_kill__in_signal_handler_helper);
Elliott Hughesfae89fc2013-02-21 11:22:23 -0800496 ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM));
497}
498
Elliott Hughes11859d42017-02-13 17:59:29 -0800499TEST_F(pthread_DeathTest, pthread_detach__no_such_thread) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000500 pthread_t dead_thread;
501 MakeDeadThread(dead_thread);
502
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800503 EXPECT_DEATH(pthread_detach(dead_thread), "invalid pthread_t");
504}
505
506TEST_F(pthread_DeathTest, pthread_detach__null_thread) {
507 pthread_t null_thread = 0;
508 EXPECT_EQ(ESRCH, pthread_detach(null_thread));
Elliott Hughes7484c212017-02-02 02:41:38 +0000509}
510
Jeff Hao9b06cc32013-08-15 14:51:16 -0700511TEST(pthread, pthread_getcpuclockid__clock_gettime) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700512 SpinFunctionHelper spin_helper;
Yabin Cui63481602014-12-01 17:41:04 -0800513
Jeff Hao9b06cc32013-08-15 14:51:16 -0700514 pthread_t t;
Elliott Hughes725b2a92016-03-23 11:20:47 -0700515 ASSERT_EQ(0, pthread_create(&t, NULL, spin_helper.GetFunction(), NULL));
Jeff Hao9b06cc32013-08-15 14:51:16 -0700516
517 clockid_t c;
518 ASSERT_EQ(0, pthread_getcpuclockid(t, &c));
519 timespec ts;
520 ASSERT_EQ(0, clock_gettime(c, &ts));
Elliott Hughes725b2a92016-03-23 11:20:47 -0700521 spin_helper.UnSpin();
Yabin Cuia36158a2015-11-16 21:06:16 -0800522 ASSERT_EQ(0, pthread_join(t, nullptr));
Jeff Hao9b06cc32013-08-15 14:51:16 -0700523}
524
Elliott Hughes11859d42017-02-13 17:59:29 -0800525TEST_F(pthread_DeathTest, pthread_getcpuclockid__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000526 pthread_t dead_thread;
527 MakeDeadThread(dead_thread);
528
529 clockid_t c;
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800530 EXPECT_DEATH(pthread_getcpuclockid(dead_thread, &c), "invalid pthread_t");
531}
532
533TEST_F(pthread_DeathTest, pthread_getcpuclockid__null_thread) {
534 pthread_t null_thread = 0;
535 clockid_t c;
536 EXPECT_EQ(ESRCH, pthread_getcpuclockid(null_thread, &c));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000537}
538
Elliott Hughes11859d42017-02-13 17:59:29 -0800539TEST_F(pthread_DeathTest, pthread_getschedparam__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000540 pthread_t dead_thread;
541 MakeDeadThread(dead_thread);
542
543 int policy;
544 sched_param param;
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800545 EXPECT_DEATH(pthread_getschedparam(dead_thread, &policy, &param), "invalid pthread_t");
546}
547
548TEST_F(pthread_DeathTest, pthread_getschedparam__null_thread) {
549 pthread_t null_thread = 0;
550 int policy;
551 sched_param param;
552 EXPECT_EQ(ESRCH, pthread_getschedparam(null_thread, &policy, &param));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000553}
554
Elliott Hughes11859d42017-02-13 17:59:29 -0800555TEST_F(pthread_DeathTest, pthread_setschedparam__no_such_thread) {
Elliott Hughesbcb15292017-02-07 21:05:30 +0000556 pthread_t dead_thread;
557 MakeDeadThread(dead_thread);
558
559 int policy = 0;
560 sched_param param;
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800561 EXPECT_DEATH(pthread_setschedparam(dead_thread, policy, &param), "invalid pthread_t");
562}
563
564TEST_F(pthread_DeathTest, pthread_setschedparam__null_thread) {
565 pthread_t null_thread = 0;
566 int policy = 0;
567 sched_param param;
568 EXPECT_EQ(ESRCH, pthread_setschedparam(null_thread, policy, &param));
Elliott Hughesbcb15292017-02-07 21:05:30 +0000569}
570
Elliott Hughesdff08ce2017-10-16 09:58:45 -0700571TEST_F(pthread_DeathTest, pthread_setschedprio__no_such_thread) {
572 pthread_t dead_thread;
573 MakeDeadThread(dead_thread);
574
575 EXPECT_DEATH(pthread_setschedprio(dead_thread, 123), "invalid pthread_t");
576}
577
578TEST_F(pthread_DeathTest, pthread_setschedprio__null_thread) {
579 pthread_t null_thread = 0;
580 EXPECT_EQ(ESRCH, pthread_setschedprio(null_thread, 123));
581}
582
Elliott Hughes11859d42017-02-13 17:59:29 -0800583TEST_F(pthread_DeathTest, pthread_join__no_such_thread) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000584 pthread_t dead_thread;
585 MakeDeadThread(dead_thread);
586
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800587 EXPECT_DEATH(pthread_join(dead_thread, NULL), "invalid pthread_t");
588}
589
590TEST_F(pthread_DeathTest, pthread_join__null_thread) {
591 pthread_t null_thread = 0;
592 EXPECT_EQ(ESRCH, pthread_join(null_thread, NULL));
Elliott Hughes7484c212017-02-02 02:41:38 +0000593}
594
Elliott Hughes11859d42017-02-13 17:59:29 -0800595TEST_F(pthread_DeathTest, pthread_kill__no_such_thread) {
Elliott Hughes7484c212017-02-02 02:41:38 +0000596 pthread_t dead_thread;
597 MakeDeadThread(dead_thread);
598
Elliott Hughes6ce686c2017-02-21 13:15:20 -0800599 EXPECT_DEATH(pthread_kill(dead_thread, 0), "invalid pthread_t");
600}
601
602TEST_F(pthread_DeathTest, pthread_kill__null_thread) {
603 pthread_t null_thread = 0;
604 EXPECT_EQ(ESRCH, pthread_kill(null_thread, 0));
Elliott Hughes7484c212017-02-02 02:41:38 +0000605}
606
msg5550f020d12013-06-06 14:59:28 -0400607TEST(pthread, pthread_join__multijoin) {
Elliott Hughes725b2a92016-03-23 11:20:47 -0700608 SpinFunctionHelper spin_helper;
msg5550f020d12013-06-06 14:59:28 -0400609
610 pthread_t t1;
Elliott Hughes725b2a92016-03-23 11:20:47 -0700611 ASSERT_EQ(0, pthread_create(&t1, NULL, spin_helper.GetFunction(), NULL));
msg5550f020d12013-06-06 14:59:28 -0400612
613 pthread_t t2;
614 ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1)));
615
616 sleep(1); // (Give t2 a chance to call pthread_join.)
617
618 // Multiple joins to the same thread should fail.
619 ASSERT_EQ(EINVAL, pthread_join(t1, NULL));
620
Elliott Hughes725b2a92016-03-23 11:20:47 -0700621 spin_helper.UnSpin();
msg5550f020d12013-06-06 14:59:28 -0400622
623 // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes).
624 void* join_result;
625 ASSERT_EQ(0, pthread_join(t2, &join_result));
Elliott Hughes5b9310e2013-10-02 16:59:05 -0700626 ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result));
msg5550f020d12013-06-06 14:59:28 -0400627}
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700628
Elliott Hughes70b24b12013-11-15 11:51:07 -0800629TEST(pthread, pthread_join__race) {
630 // http://b/11693195 --- pthread_join could return before the thread had actually exited.
631 // If the joiner unmapped the thread's stack, that could lead to SIGSEGV in the thread.
632 for (size_t i = 0; i < 1024; ++i) {
Yabin Cuia36158a2015-11-16 21:06:16 -0800633 size_t stack_size = 640*1024;
Elliott Hughes70b24b12013-11-15 11:51:07 -0800634 void* stack = mmap(NULL, stack_size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
635
636 pthread_attr_t a;
637 pthread_attr_init(&a);
638 pthread_attr_setstack(&a, stack, stack_size);
639
640 pthread_t t;
641 ASSERT_EQ(0, pthread_create(&t, &a, IdFn, NULL));
642 ASSERT_EQ(0, pthread_join(t, NULL));
643 ASSERT_EQ(0, munmap(stack, stack_size));
644 }
645}
646
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700647static void* GetActualGuardSizeFn(void* arg) {
648 pthread_attr_t attributes;
649 pthread_getattr_np(pthread_self(), &attributes);
650 pthread_attr_getguardsize(&attributes, reinterpret_cast<size_t*>(arg));
651 return NULL;
652}
653
654static size_t GetActualGuardSize(const pthread_attr_t& attributes) {
655 size_t result;
656 pthread_t t;
657 pthread_create(&t, &attributes, GetActualGuardSizeFn, &result);
Elliott Hughes34c987a2014-09-22 16:01:26 -0700658 pthread_join(t, NULL);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700659 return result;
660}
661
662static void* GetActualStackSizeFn(void* arg) {
663 pthread_attr_t attributes;
664 pthread_getattr_np(pthread_self(), &attributes);
665 pthread_attr_getstacksize(&attributes, reinterpret_cast<size_t*>(arg));
666 return NULL;
667}
668
669static size_t GetActualStackSize(const pthread_attr_t& attributes) {
670 size_t result;
671 pthread_t t;
672 pthread_create(&t, &attributes, GetActualStackSizeFn, &result);
Elliott Hughes34c987a2014-09-22 16:01:26 -0700673 pthread_join(t, NULL);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700674 return result;
675}
676
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700677TEST(pthread, pthread_attr_setguardsize_tiny) {
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700678 pthread_attr_t attributes;
679 ASSERT_EQ(0, pthread_attr_init(&attributes));
680
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700681 // No such thing as too small: will be rounded up to one page by pthread_create.
682 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 128));
683 size_t guard_size;
684 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
685 ASSERT_EQ(128U, guard_size);
686 ASSERT_EQ(4096U, GetActualGuardSize(attributes));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700687}
688
689TEST(pthread, pthread_attr_setguardsize_reasonable) {
690 pthread_attr_t attributes;
691 ASSERT_EQ(0, pthread_attr_init(&attributes));
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700692
693 // Large enough and a multiple of the page size.
694 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700695 size_t guard_size;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700696 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
697 ASSERT_EQ(32*1024U, guard_size);
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700698 ASSERT_EQ(32*1024U, GetActualGuardSize(attributes));
699}
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700700
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700701TEST(pthread, pthread_attr_setguardsize_needs_rounding) {
702 pthread_attr_t attributes;
703 ASSERT_EQ(0, pthread_attr_init(&attributes));
704
705 // Large enough but not a multiple of the page size.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700706 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024 + 1));
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700707 size_t guard_size;
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700708 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
709 ASSERT_EQ(32*1024U + 1, guard_size);
Elliott Hughesd6c678c2017-06-27 17:01:57 -0700710 ASSERT_EQ(36*1024U, GetActualGuardSize(attributes));
711}
712
713TEST(pthread, pthread_attr_setguardsize_enormous) {
714 pthread_attr_t attributes;
715 ASSERT_EQ(0, pthread_attr_init(&attributes));
716
717 // Larger than the stack itself. (Historically we mistakenly carved
718 // the guard out of the stack itself, rather than adding it after the
719 // end.)
720 ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024*1024));
721 size_t guard_size;
722 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
723 ASSERT_EQ(32*1024*1024U, guard_size);
724 ASSERT_EQ(32*1024*1024U, GetActualGuardSize(attributes));
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700725}
726
727TEST(pthread, pthread_attr_setstacksize) {
728 pthread_attr_t attributes;
729 ASSERT_EQ(0, pthread_attr_init(&attributes));
730
731 // Get the default stack size.
732 size_t default_stack_size;
733 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &default_stack_size));
734
735 // Too small.
736 ASSERT_EQ(EINVAL, pthread_attr_setstacksize(&attributes, 128));
737 size_t stack_size;
738 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
739 ASSERT_EQ(default_stack_size, stack_size);
740 ASSERT_GE(GetActualStackSize(attributes), default_stack_size);
741
Yabin Cui917d3902015-01-08 12:32:42 -0800742 // Large enough and a multiple of the page size; may be rounded up by pthread_create.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700743 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024));
744 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
745 ASSERT_EQ(32*1024U, stack_size);
Yabin Cui917d3902015-01-08 12:32:42 -0800746 ASSERT_GE(GetActualStackSize(attributes), 32*1024U);
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700747
Yabin Cui917d3902015-01-08 12:32:42 -0800748 // Large enough but not aligned; will be rounded up by pthread_create.
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700749 ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024 + 1));
750 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size));
751 ASSERT_EQ(32*1024U + 1, stack_size);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800752#if defined(__BIONIC__)
Yabin Cui917d3902015-01-08 12:32:42 -0800753 ASSERT_GT(GetActualStackSize(attributes), 32*1024U + 1);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800754#else // __BIONIC__
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700755 // glibc rounds down, in violation of POSIX. They document this in their BUGS section.
756 ASSERT_EQ(GetActualStackSize(attributes), 32*1024U);
Christopher Ferrisf04935c2013-12-20 18:43:21 -0800757#endif // __BIONIC__
Elliott Hughesb95cf0d2013-07-15 14:51:07 -0700758}
Elliott Hughesc3f11402013-10-30 14:40:09 -0700759
Yabin Cui76615da2015-03-17 14:22:09 -0700760TEST(pthread, pthread_rwlockattr_smoke) {
761 pthread_rwlockattr_t attr;
762 ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
763
764 int pshared_value_array[] = {PTHREAD_PROCESS_PRIVATE, PTHREAD_PROCESS_SHARED};
765 for (size_t i = 0; i < sizeof(pshared_value_array) / sizeof(pshared_value_array[0]); ++i) {
766 ASSERT_EQ(0, pthread_rwlockattr_setpshared(&attr, pshared_value_array[i]));
767 int pshared;
768 ASSERT_EQ(0, pthread_rwlockattr_getpshared(&attr, &pshared));
769 ASSERT_EQ(pshared_value_array[i], pshared);
770 }
771
772 int kind_array[] = {PTHREAD_RWLOCK_PREFER_READER_NP,
773 PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP};
774 for (size_t i = 0; i < sizeof(kind_array) / sizeof(kind_array[0]); ++i) {
775 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_array[i]));
776 int kind;
777 ASSERT_EQ(0, pthread_rwlockattr_getkind_np(&attr, &kind));
778 ASSERT_EQ(kind_array[i], kind);
779 }
780
781 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
782}
783
784TEST(pthread, pthread_rwlock_init_same_as_PTHREAD_RWLOCK_INITIALIZER) {
785 pthread_rwlock_t lock1 = PTHREAD_RWLOCK_INITIALIZER;
786 pthread_rwlock_t lock2;
787 ASSERT_EQ(0, pthread_rwlock_init(&lock2, NULL));
788 ASSERT_EQ(0, memcmp(&lock1, &lock2, sizeof(lock1)));
789}
790
Elliott Hughesc3f11402013-10-30 14:40:09 -0700791TEST(pthread, pthread_rwlock_smoke) {
792 pthread_rwlock_t l;
793 ASSERT_EQ(0, pthread_rwlock_init(&l, NULL));
794
Calin Juravle76f352e2014-05-19 13:41:10 +0100795 // Single read lock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700796 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
797 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
798
Calin Juravle76f352e2014-05-19 13:41:10 +0100799 // Multiple read lock
800 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
801 ASSERT_EQ(0, pthread_rwlock_rdlock(&l));
802 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
803 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
804
805 // Write lock
Calin Juravle92687e42014-05-22 19:21:22 +0100806 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
807 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100808
809 // Try writer lock
810 ASSERT_EQ(0, pthread_rwlock_trywrlock(&l));
811 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
812 ASSERT_EQ(EBUSY, pthread_rwlock_tryrdlock(&l));
813 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
814
815 // Try reader lock
816 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
817 ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l));
818 ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l));
819 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
820 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
821
822 // Try writer lock after unlock
Elliott Hughesc3f11402013-10-30 14:40:09 -0700823 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
824 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
825
Calin Juravle76f352e2014-05-19 13:41:10 +0100826 // EDEADLK in "read after write"
827 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
828 ASSERT_EQ(EDEADLK, pthread_rwlock_rdlock(&l));
829 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
830
831 // EDEADLK in "write after write"
832 ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
833 ASSERT_EQ(EDEADLK, pthread_rwlock_wrlock(&l));
834 ASSERT_EQ(0, pthread_rwlock_unlock(&l));
Calin Juravle76f352e2014-05-19 13:41:10 +0100835
Elliott Hughesc3f11402013-10-30 14:40:09 -0700836 ASSERT_EQ(0, pthread_rwlock_destroy(&l));
837}
838
Yabin Cui08ee8d22015-02-11 17:04:36 -0800839struct RwlockWakeupHelperArg {
840 pthread_rwlock_t lock;
841 enum Progress {
842 LOCK_INITIALIZED,
843 LOCK_WAITING,
844 LOCK_RELEASED,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800845 LOCK_ACCESSED,
846 LOCK_TIMEDOUT,
Yabin Cui08ee8d22015-02-11 17:04:36 -0800847 };
848 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -0700849 std::atomic<pid_t> tid;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800850 std::function<int (pthread_rwlock_t*)> trylock_function;
851 std::function<int (pthread_rwlock_t*)> lock_function;
852 std::function<int (pthread_rwlock_t*, const timespec*)> timed_lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800853};
854
Yabin Cuic9a659c2015-11-05 15:36:08 -0800855static void pthread_rwlock_wakeup_helper(RwlockWakeupHelperArg* arg) {
Yabin Cuif7969852015-04-02 17:47:48 -0700856 arg->tid = gettid();
Yabin Cui08ee8d22015-02-11 17:04:36 -0800857 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
858 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
859
Yabin Cuic9a659c2015-11-05 15:36:08 -0800860 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
861 ASSERT_EQ(0, arg->lock_function(&arg->lock));
Yabin Cui08ee8d22015-02-11 17:04:36 -0800862 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_RELEASED, arg->progress);
863 ASSERT_EQ(0, pthread_rwlock_unlock(&arg->lock));
864
865 arg->progress = RwlockWakeupHelperArg::LOCK_ACCESSED;
866}
867
Yabin Cuic9a659c2015-11-05 15:36:08 -0800868static void test_pthread_rwlock_reader_wakeup_writer(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -0800869 RwlockWakeupHelperArg wakeup_arg;
870 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, NULL));
871 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
872 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -0700873 wakeup_arg.tid = 0;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800874 wakeup_arg.trylock_function = pthread_rwlock_trywrlock;
875 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800876
877 pthread_t thread;
878 ASSERT_EQ(0, pthread_create(&thread, NULL,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800879 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -0700880 WaitUntilThreadSleep(wakeup_arg.tid);
881 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
882
Yabin Cui08ee8d22015-02-11 17:04:36 -0800883 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
884 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
885
886 ASSERT_EQ(0, pthread_join(thread, NULL));
887 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
888 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
889}
890
Yabin Cuic9a659c2015-11-05 15:36:08 -0800891TEST(pthread, pthread_rwlock_reader_wakeup_writer) {
892 test_pthread_rwlock_reader_wakeup_writer(pthread_rwlock_wrlock);
Yabin Cui08ee8d22015-02-11 17:04:36 -0800893}
894
Yabin Cuic9a659c2015-11-05 15:36:08 -0800895TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait) {
896 timespec ts;
897 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
898 ts.tv_sec += 1;
899 test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) {
900 return pthread_rwlock_timedwrlock(lock, &ts);
901 });
902}
903
904static void test_pthread_rwlock_writer_wakeup_reader(std::function<int (pthread_rwlock_t*)> lock_function) {
Yabin Cui08ee8d22015-02-11 17:04:36 -0800905 RwlockWakeupHelperArg wakeup_arg;
906 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, NULL));
907 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
908 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -0700909 wakeup_arg.tid = 0;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800910 wakeup_arg.trylock_function = pthread_rwlock_tryrdlock;
911 wakeup_arg.lock_function = lock_function;
Yabin Cui08ee8d22015-02-11 17:04:36 -0800912
913 pthread_t thread;
914 ASSERT_EQ(0, pthread_create(&thread, NULL,
Yabin Cuic9a659c2015-11-05 15:36:08 -0800915 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg));
Yabin Cuif7969852015-04-02 17:47:48 -0700916 WaitUntilThreadSleep(wakeup_arg.tid);
917 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
918
Yabin Cui08ee8d22015-02-11 17:04:36 -0800919 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED;
920 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
921
922 ASSERT_EQ(0, pthread_join(thread, NULL));
923 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress);
924 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
925}
926
Yabin Cuic9a659c2015-11-05 15:36:08 -0800927TEST(pthread, pthread_rwlock_writer_wakeup_reader) {
928 test_pthread_rwlock_writer_wakeup_reader(pthread_rwlock_rdlock);
929}
930
931TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait) {
932 timespec ts;
933 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
934 ts.tv_sec += 1;
935 test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) {
936 return pthread_rwlock_timedrdlock(lock, &ts);
937 });
938}
939
940static void pthread_rwlock_wakeup_timeout_helper(RwlockWakeupHelperArg* arg) {
941 arg->tid = gettid();
942 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress);
943 arg->progress = RwlockWakeupHelperArg::LOCK_WAITING;
944
945 ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock));
946
947 timespec ts;
948 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
949 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
950 ts.tv_nsec = -1;
951 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
952 ts.tv_nsec = NS_PER_S;
953 ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts));
954 ts.tv_nsec = NS_PER_S - 1;
955 ts.tv_sec = -1;
956 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
957 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
958 ts.tv_sec += 1;
959 ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts));
960 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, arg->progress);
961 arg->progress = RwlockWakeupHelperArg::LOCK_TIMEDOUT;
962}
963
964TEST(pthread, pthread_rwlock_timedrdlock_timeout) {
965 RwlockWakeupHelperArg wakeup_arg;
966 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
967 ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock));
968 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
969 wakeup_arg.tid = 0;
970 wakeup_arg.trylock_function = pthread_rwlock_tryrdlock;
971 wakeup_arg.timed_lock_function = pthread_rwlock_timedrdlock;
972
973 pthread_t thread;
974 ASSERT_EQ(0, pthread_create(&thread, nullptr,
975 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
976 WaitUntilThreadSleep(wakeup_arg.tid);
977 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
978
979 ASSERT_EQ(0, pthread_join(thread, nullptr));
980 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
981 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
982 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
983}
984
985TEST(pthread, pthread_rwlock_timedwrlock_timeout) {
986 RwlockWakeupHelperArg wakeup_arg;
987 ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr));
988 ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock));
989 wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED;
990 wakeup_arg.tid = 0;
991 wakeup_arg.trylock_function = pthread_rwlock_trywrlock;
992 wakeup_arg.timed_lock_function = pthread_rwlock_timedwrlock;
993
994 pthread_t thread;
995 ASSERT_EQ(0, pthread_create(&thread, nullptr,
996 reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg));
997 WaitUntilThreadSleep(wakeup_arg.tid);
998 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress);
999
1000 ASSERT_EQ(0, pthread_join(thread, nullptr));
1001 ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress);
1002 ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock));
1003 ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
1004}
1005
Yabin Cui76615da2015-03-17 14:22:09 -07001006class RwlockKindTestHelper {
1007 private:
1008 struct ThreadArg {
1009 RwlockKindTestHelper* helper;
1010 std::atomic<pid_t>& tid;
1011
1012 ThreadArg(RwlockKindTestHelper* helper, std::atomic<pid_t>& tid)
1013 : helper(helper), tid(tid) { }
1014 };
1015
1016 public:
1017 pthread_rwlock_t lock;
1018
1019 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -07001020 explicit RwlockKindTestHelper(int kind_type) {
Yabin Cui76615da2015-03-17 14:22:09 -07001021 InitRwlock(kind_type);
1022 }
1023
1024 ~RwlockKindTestHelper() {
1025 DestroyRwlock();
1026 }
1027
1028 void CreateWriterThread(pthread_t& thread, std::atomic<pid_t>& tid) {
1029 tid = 0;
1030 ThreadArg* arg = new ThreadArg(this, tid);
1031 ASSERT_EQ(0, pthread_create(&thread, NULL,
1032 reinterpret_cast<void* (*)(void*)>(WriterThreadFn), arg));
1033 }
1034
1035 void CreateReaderThread(pthread_t& thread, std::atomic<pid_t>& tid) {
1036 tid = 0;
1037 ThreadArg* arg = new ThreadArg(this, tid);
1038 ASSERT_EQ(0, pthread_create(&thread, NULL,
1039 reinterpret_cast<void* (*)(void*)>(ReaderThreadFn), arg));
1040 }
1041
1042 private:
1043 void InitRwlock(int kind_type) {
1044 pthread_rwlockattr_t attr;
1045 ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
1046 ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_type));
1047 ASSERT_EQ(0, pthread_rwlock_init(&lock, &attr));
1048 ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
1049 }
1050
1051 void DestroyRwlock() {
1052 ASSERT_EQ(0, pthread_rwlock_destroy(&lock));
1053 }
1054
1055 static void WriterThreadFn(ThreadArg* arg) {
1056 arg->tid = gettid();
1057
1058 RwlockKindTestHelper* helper = arg->helper;
1059 ASSERT_EQ(0, pthread_rwlock_wrlock(&helper->lock));
1060 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
1061 delete arg;
1062 }
1063
1064 static void ReaderThreadFn(ThreadArg* arg) {
1065 arg->tid = gettid();
1066
1067 RwlockKindTestHelper* helper = arg->helper;
1068 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper->lock));
1069 ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
1070 delete arg;
1071 }
1072};
1073
1074TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_READER_NP) {
1075 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_READER_NP);
1076 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
1077
1078 pthread_t writer_thread;
1079 std::atomic<pid_t> writer_tid;
1080 helper.CreateWriterThread(writer_thread, writer_tid);
1081 WaitUntilThreadSleep(writer_tid);
1082
1083 pthread_t reader_thread;
1084 std::atomic<pid_t> reader_tid;
1085 helper.CreateReaderThread(reader_thread, reader_tid);
1086 ASSERT_EQ(0, pthread_join(reader_thread, NULL));
1087
1088 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
1089 ASSERT_EQ(0, pthread_join(writer_thread, NULL));
1090}
1091
1092TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP) {
1093 RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
1094 ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
1095
1096 pthread_t writer_thread;
1097 std::atomic<pid_t> writer_tid;
1098 helper.CreateWriterThread(writer_thread, writer_tid);
1099 WaitUntilThreadSleep(writer_tid);
1100
1101 pthread_t reader_thread;
1102 std::atomic<pid_t> reader_tid;
1103 helper.CreateReaderThread(reader_thread, reader_tid);
1104 WaitUntilThreadSleep(reader_tid);
1105
1106 ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
1107 ASSERT_EQ(0, pthread_join(writer_thread, NULL));
1108 ASSERT_EQ(0, pthread_join(reader_thread, NULL));
1109}
1110
Elliott Hughes1728b232014-05-14 10:02:03 -07001111static int g_once_fn_call_count = 0;
Elliott Hughesc3f11402013-10-30 14:40:09 -07001112static void OnceFn() {
Elliott Hughes1728b232014-05-14 10:02:03 -07001113 ++g_once_fn_call_count;
Elliott Hughesc3f11402013-10-30 14:40:09 -07001114}
1115
1116TEST(pthread, pthread_once_smoke) {
1117 pthread_once_t once_control = PTHREAD_ONCE_INIT;
1118 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
1119 ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
Elliott Hughes1728b232014-05-14 10:02:03 -07001120 ASSERT_EQ(1, g_once_fn_call_count);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001121}
1122
Elliott Hughes3694ec62014-05-14 11:46:08 -07001123static std::string pthread_once_1934122_result = "";
1124
1125static void Routine2() {
1126 pthread_once_1934122_result += "2";
1127}
1128
1129static void Routine1() {
1130 pthread_once_t once_control_2 = PTHREAD_ONCE_INIT;
1131 pthread_once_1934122_result += "1";
1132 pthread_once(&once_control_2, &Routine2);
1133}
1134
1135TEST(pthread, pthread_once_1934122) {
1136 // Very old versions of Android couldn't call pthread_once from a
1137 // pthread_once init routine. http://b/1934122.
1138 pthread_once_t once_control_1 = PTHREAD_ONCE_INIT;
1139 ASSERT_EQ(0, pthread_once(&once_control_1, &Routine1));
1140 ASSERT_EQ("12", pthread_once_1934122_result);
1141}
1142
Elliott Hughes1728b232014-05-14 10:02:03 -07001143static int g_atfork_prepare_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001144static void AtForkPrepare1() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 1; }
1145static void AtForkPrepare2() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -07001146static int g_atfork_parent_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001147static void AtForkParent1() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 1; }
1148static void AtForkParent2() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 2; }
Elliott Hughes1728b232014-05-14 10:02:03 -07001149static int g_atfork_child_calls = 0;
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001150static void AtForkChild1() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 1; }
1151static void AtForkChild2() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 2; }
Elliott Hughesc3f11402013-10-30 14:40:09 -07001152
Dmitriy Ivanov00e37812014-11-20 16:53:47 -08001153TEST(pthread, pthread_atfork_smoke) {
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001154 ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1));
1155 ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2));
Elliott Hughesc3f11402013-10-30 14:40:09 -07001156
Elliott Hughes33697a02016-01-26 13:04:57 -08001157 pid_t pid = fork();
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001158 ASSERT_NE(-1, pid) << strerror(errno);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001159
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001160 // Child and parent calls are made in the order they were registered.
1161 if (pid == 0) {
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001162 ASSERT_EQ(12, g_atfork_child_calls);
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001163 _exit(0);
1164 }
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001165 ASSERT_EQ(12, g_atfork_parent_calls);
Elliott Hughesc3f11402013-10-30 14:40:09 -07001166
Dmitriy Ivanovcb0443c2015-03-16 14:15:46 -07001167 // Prepare calls are made in the reverse order.
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001168 ASSERT_EQ(21, g_atfork_prepare_calls);
Elliott Hughes33697a02016-01-26 13:04:57 -08001169 AssertChildExited(pid, 0);
Dmitriy Ivanovea295f62014-11-20 20:47:02 -08001170}
1171
Elliott Hughesc3f11402013-10-30 14:40:09 -07001172TEST(pthread, pthread_attr_getscope) {
1173 pthread_attr_t attr;
1174 ASSERT_EQ(0, pthread_attr_init(&attr));
1175
1176 int scope;
1177 ASSERT_EQ(0, pthread_attr_getscope(&attr, &scope));
1178 ASSERT_EQ(PTHREAD_SCOPE_SYSTEM, scope);
1179}
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001180
1181TEST(pthread, pthread_condattr_init) {
1182 pthread_condattr_t attr;
1183 pthread_condattr_init(&attr);
1184
1185 clockid_t clock;
1186 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1187 ASSERT_EQ(CLOCK_REALTIME, clock);
1188
1189 int pshared;
1190 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1191 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
1192}
1193
1194TEST(pthread, pthread_condattr_setclock) {
1195 pthread_condattr_t attr;
1196 pthread_condattr_init(&attr);
1197
1198 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_REALTIME));
1199 clockid_t clock;
1200 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1201 ASSERT_EQ(CLOCK_REALTIME, clock);
1202
1203 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1204 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1205 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1206
1207 ASSERT_EQ(EINVAL, pthread_condattr_setclock(&attr, CLOCK_PROCESS_CPUTIME_ID));
1208}
1209
1210TEST(pthread, pthread_cond_broadcast__preserves_condattr_flags) {
Yabin Cui32651b82015-03-13 20:30:00 -07001211#if defined(__BIONIC__)
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001212 pthread_condattr_t attr;
1213 pthread_condattr_init(&attr);
1214
1215 ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC));
1216 ASSERT_EQ(0, pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
1217
1218 pthread_cond_t cond_var;
1219 ASSERT_EQ(0, pthread_cond_init(&cond_var, &attr));
1220
1221 ASSERT_EQ(0, pthread_cond_signal(&cond_var));
1222 ASSERT_EQ(0, pthread_cond_broadcast(&cond_var));
1223
Yabin Cui32651b82015-03-13 20:30:00 -07001224 attr = static_cast<pthread_condattr_t>(*reinterpret_cast<uint32_t*>(cond_var.__private));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001225 clockid_t clock;
1226 ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock));
1227 ASSERT_EQ(CLOCK_MONOTONIC, clock);
1228 int pshared;
1229 ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared));
1230 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
Yabin Cui32651b82015-03-13 20:30:00 -07001231#else // !defined(__BIONIC__)
1232 GTEST_LOG_(INFO) << "This tests a bionic implementation detail.\n";
1233#endif // !defined(__BIONIC__)
1234}
1235
1236class pthread_CondWakeupTest : public ::testing::Test {
1237 protected:
1238 pthread_mutex_t mutex;
1239 pthread_cond_t cond;
1240
1241 enum Progress {
1242 INITIALIZED,
1243 WAITING,
1244 SIGNALED,
1245 FINISHED,
1246 };
1247 std::atomic<Progress> progress;
1248 pthread_t thread;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001249 std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function;
Yabin Cui32651b82015-03-13 20:30:00 -07001250
1251 protected:
Yabin Cuic9a659c2015-11-05 15:36:08 -08001252 void SetUp() override {
1253 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1254 }
1255
1256 void InitCond(clockid_t clock=CLOCK_REALTIME) {
1257 pthread_condattr_t attr;
1258 ASSERT_EQ(0, pthread_condattr_init(&attr));
1259 ASSERT_EQ(0, pthread_condattr_setclock(&attr, clock));
1260 ASSERT_EQ(0, pthread_cond_init(&cond, &attr));
1261 ASSERT_EQ(0, pthread_condattr_destroy(&attr));
1262 }
1263
1264 void StartWaitingThread(std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function) {
Yabin Cui32651b82015-03-13 20:30:00 -07001265 progress = INITIALIZED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001266 this->wait_function = wait_function;
1267 ASSERT_EQ(0, pthread_create(&thread, NULL, reinterpret_cast<void* (*)(void*)>(WaitThreadFn), this));
1268 while (progress != WAITING) {
Yabin Cui32651b82015-03-13 20:30:00 -07001269 usleep(5000);
1270 }
1271 usleep(5000);
1272 }
1273
Yabin Cuic9a659c2015-11-05 15:36:08 -08001274 void TearDown() override {
1275 ASSERT_EQ(0, pthread_join(thread, nullptr));
1276 ASSERT_EQ(FINISHED, progress);
1277 ASSERT_EQ(0, pthread_cond_destroy(&cond));
1278 ASSERT_EQ(0, pthread_mutex_destroy(&mutex));
1279 }
1280
Yabin Cui32651b82015-03-13 20:30:00 -07001281 private:
1282 static void WaitThreadFn(pthread_CondWakeupTest* test) {
1283 ASSERT_EQ(0, pthread_mutex_lock(&test->mutex));
1284 test->progress = WAITING;
1285 while (test->progress == WAITING) {
Yabin Cuic9a659c2015-11-05 15:36:08 -08001286 ASSERT_EQ(0, test->wait_function(&test->cond, &test->mutex));
Yabin Cui32651b82015-03-13 20:30:00 -07001287 }
1288 ASSERT_EQ(SIGNALED, test->progress);
1289 test->progress = FINISHED;
1290 ASSERT_EQ(0, pthread_mutex_unlock(&test->mutex));
1291 }
1292};
1293
Yabin Cuic9a659c2015-11-05 15:36:08 -08001294TEST_F(pthread_CondWakeupTest, signal_wait) {
1295 InitCond();
1296 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1297 return pthread_cond_wait(cond, mutex);
1298 });
Yabin Cui32651b82015-03-13 20:30:00 -07001299 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001300 ASSERT_EQ(0, pthread_cond_signal(&cond));
Yabin Cui32651b82015-03-13 20:30:00 -07001301}
1302
Yabin Cuic9a659c2015-11-05 15:36:08 -08001303TEST_F(pthread_CondWakeupTest, broadcast_wait) {
1304 InitCond();
1305 StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1306 return pthread_cond_wait(cond, mutex);
1307 });
Yabin Cui32651b82015-03-13 20:30:00 -07001308 progress = SIGNALED;
Yabin Cuic9a659c2015-11-05 15:36:08 -08001309 ASSERT_EQ(0, pthread_cond_broadcast(&cond));
Narayan Kamath51e6cb32014-03-03 15:38:51 +00001310}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001311
Yabin Cuic9a659c2015-11-05 15:36:08 -08001312TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_REALTIME) {
1313 InitCond(CLOCK_REALTIME);
Elliott Hughes0e714a52014-03-03 16:42:47 -08001314 timespec ts;
1315 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001316 ts.tv_sec += 1;
1317 StartWaitingThread([&](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1318 return pthread_cond_timedwait(cond, mutex, &ts);
1319 });
1320 progress = SIGNALED;
1321 ASSERT_EQ(0, pthread_cond_signal(&cond));
1322}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001323
Yabin Cuic9a659c2015-11-05 15:36:08 -08001324TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC) {
1325 InitCond(CLOCK_MONOTONIC);
1326 timespec ts;
1327 ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts));
1328 ts.tv_sec += 1;
1329 StartWaitingThread([&](pthread_cond_t* cond, pthread_mutex_t* mutex) {
1330 return pthread_cond_timedwait(cond, mutex, &ts);
1331 });
1332 progress = SIGNALED;
1333 ASSERT_EQ(0, pthread_cond_signal(&cond));
1334}
Elliott Hughes0e714a52014-03-03 16:42:47 -08001335
Yabin Cuic9a659c2015-11-05 15:36:08 -08001336TEST(pthread, pthread_cond_timedwait_timeout) {
1337 pthread_mutex_t mutex;
1338 ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr));
1339 pthread_cond_t cond;
1340 ASSERT_EQ(0, pthread_cond_init(&cond, nullptr));
1341 ASSERT_EQ(0, pthread_mutex_lock(&mutex));
1342 timespec ts;
Elliott Hughes0e714a52014-03-03 16:42:47 -08001343 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
Yabin Cuic9a659c2015-11-05 15:36:08 -08001344 ASSERT_EQ(ETIMEDOUT, pthread_cond_timedwait(&cond, &mutex, &ts));
1345 ts.tv_nsec = -1;
1346 ASSERT_EQ(EINVAL, pthread_cond_timedwait(&cond, &mutex, &ts));
1347 ts.tv_nsec = NS_PER_S;
1348 ASSERT_EQ(EINVAL, pthread_cond_timedwait(&cond, &mutex, &ts));
1349 ts.tv_nsec = NS_PER_S - 1;
1350 ts.tv_sec = -1;
1351 ASSERT_EQ(ETIMEDOUT, pthread_cond_timedwait(&cond, &mutex, &ts));
1352 ASSERT_EQ(0, pthread_mutex_unlock(&mutex));
Elliott Hughes0e714a52014-03-03 16:42:47 -08001353}
Elliott Hughes57b7a612014-08-25 17:26:50 -07001354
1355TEST(pthread, pthread_attr_getstack__main_thread) {
1356 // This test is only meaningful for the main thread, so make sure we're running on it!
1357 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1358
1359 // Get the main thread's attributes.
1360 pthread_attr_t attributes;
1361 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1362
1363 // Check that we correctly report that the main thread has no guard page.
1364 size_t guard_size;
1365 ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size));
1366 ASSERT_EQ(0U, guard_size); // The main thread has no guard page.
1367
1368 // Get the stack base and the stack size (both ways).
1369 void* stack_base;
1370 size_t stack_size;
1371 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1372 size_t stack_size2;
1373 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1374
1375 // The two methods of asking for the stack size should agree.
1376 EXPECT_EQ(stack_size, stack_size2);
1377
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001378#if defined(__BIONIC__)
Elliott Hughes57b7a612014-08-25 17:26:50 -07001379 // What does /proc/self/maps' [stack] line say?
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001380 void* maps_stack_hi = NULL;
Elliott Hughes15dfd632015-09-22 16:40:14 -07001381 std::vector<map_record> maps;
1382 ASSERT_TRUE(Maps::parse_maps(&maps));
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07001383 for (const auto& map : maps) {
Elliott Hughes15dfd632015-09-22 16:40:14 -07001384 if (map.pathname == "[stack]") {
1385 maps_stack_hi = reinterpret_cast<void*>(map.addr_end);
Elliott Hughes57b7a612014-08-25 17:26:50 -07001386 break;
1387 }
1388 }
Elliott Hughes57b7a612014-08-25 17:26:50 -07001389
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001390 // The high address of the /proc/self/maps [stack] region should equal stack_base + stack_size.
1391 // Remember that the stack grows down (and is mapped in on demand), so the low address of the
1392 // region isn't very interesting.
1393 EXPECT_EQ(maps_stack_hi, reinterpret_cast<uint8_t*>(stack_base) + stack_size);
1394
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001395 // The stack size should correspond to RLIMIT_STACK.
Elliott Hughes57b7a612014-08-25 17:26:50 -07001396 rlimit rl;
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001397 ASSERT_EQ(0, getrlimit(RLIMIT_STACK, &rl));
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001398 uint64_t original_rlim_cur = rl.rlim_cur;
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001399 if (rl.rlim_cur == RLIM_INFINITY) {
1400 rl.rlim_cur = 8 * 1024 * 1024; // Bionic reports unlimited stacks as 8MiB.
1401 }
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001402 EXPECT_EQ(rl.rlim_cur, stack_size);
1403
Tom Cherryb8ab6182017-04-05 16:20:29 -07001404 auto guard = android::base::make_scope_guard([&rl, original_rlim_cur]() {
Elliott Hughes27a9aed2014-09-04 16:09:25 -07001405 rl.rlim_cur = original_rlim_cur;
1406 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1407 });
1408
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001409 //
1410 // What if RLIMIT_STACK is smaller than the stack's current extent?
1411 //
Elliott Hughes57b7a612014-08-25 17:26:50 -07001412 rl.rlim_cur = rl.rlim_max = 1024; // 1KiB. We know the stack must be at least a page already.
1413 rl.rlim_max = RLIM_INFINITY;
1414 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1415
1416 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1417 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1418 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1419
1420 EXPECT_EQ(stack_size, stack_size2);
1421 ASSERT_EQ(1024U, stack_size);
1422
1423 //
Elliott Hughes9e4ffa72014-08-27 15:32:01 -07001424 // What if RLIMIT_STACK isn't a whole number of pages?
Elliott Hughes57b7a612014-08-25 17:26:50 -07001425 //
1426 rl.rlim_cur = rl.rlim_max = 6666; // Not a whole number of pages.
1427 rl.rlim_max = RLIM_INFINITY;
1428 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1429
1430 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes));
1431 ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size));
1432 ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2));
1433
1434 EXPECT_EQ(stack_size, stack_size2);
1435 ASSERT_EQ(6666U, stack_size);
Yabin Cuib0c6f2db2015-05-19 15:09:23 -07001436#endif
Elliott Hughes57b7a612014-08-25 17:26:50 -07001437}
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001438
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001439struct GetStackSignalHandlerArg {
1440 volatile bool done;
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001441 void* signal_stack_base;
1442 size_t signal_stack_size;
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001443 void* main_stack_base;
1444 size_t main_stack_size;
1445};
1446
1447static GetStackSignalHandlerArg getstack_signal_handler_arg;
1448
1449static void getstack_signal_handler(int sig) {
1450 ASSERT_EQ(SIGUSR1, sig);
1451 // Use sleep() to make current thread be switched out by the kernel to provoke the error.
1452 sleep(1);
1453 pthread_attr_t attr;
1454 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1455 void* stack_base;
1456 size_t stack_size;
1457 ASSERT_EQ(0, pthread_attr_getstack(&attr, &stack_base, &stack_size));
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001458
1459 // Verify if the stack used by the signal handler is the alternate stack just registered.
1460 ASSERT_LE(getstack_signal_handler_arg.signal_stack_base, &attr);
1461 ASSERT_LT(static_cast<void*>(&attr),
1462 static_cast<char*>(getstack_signal_handler_arg.signal_stack_base) +
1463 getstack_signal_handler_arg.signal_stack_size);
1464
1465 // Verify if the main thread's stack got in the signal handler is correct.
1466 ASSERT_EQ(getstack_signal_handler_arg.main_stack_base, stack_base);
1467 ASSERT_LE(getstack_signal_handler_arg.main_stack_size, stack_size);
1468
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001469 getstack_signal_handler_arg.done = true;
1470}
1471
1472// The previous code obtained the main thread's stack by reading the entry in
1473// /proc/self/task/<pid>/maps that was labeled [stack]. Unfortunately, on x86/x86_64, the kernel
1474// relies on sp0 in task state segment(tss) to label the stack map with [stack]. If the kernel
1475// switches a process while the main thread is in an alternate stack, then the kernel will label
1476// the wrong map with [stack]. This test verifies that when the above situation happens, the main
1477// thread's stack is found correctly.
1478TEST(pthread, pthread_attr_getstack_in_signal_handler) {
Yabin Cui61e4d462016-03-07 17:44:58 -08001479 // This test is only meaningful for the main thread, so make sure we're running on it!
1480 ASSERT_EQ(getpid(), syscall(__NR_gettid));
1481
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001482 const size_t sig_stack_size = 16 * 1024;
1483 void* sig_stack = mmap(NULL, sig_stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS,
1484 -1, 0);
1485 ASSERT_NE(MAP_FAILED, sig_stack);
1486 stack_t ss;
1487 ss.ss_sp = sig_stack;
1488 ss.ss_size = sig_stack_size;
1489 ss.ss_flags = 0;
1490 stack_t oss;
1491 ASSERT_EQ(0, sigaltstack(&ss, &oss));
1492
Yabin Cui61e4d462016-03-07 17:44:58 -08001493 pthread_attr_t attr;
1494 ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr));
1495 void* main_stack_base;
1496 size_t main_stack_size;
1497 ASSERT_EQ(0, pthread_attr_getstack(&attr, &main_stack_base, &main_stack_size));
1498
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001499 ScopedSignalHandler handler(SIGUSR1, getstack_signal_handler, SA_ONSTACK);
1500 getstack_signal_handler_arg.done = false;
Chih-Hung Hsieh9af13d22016-06-02 14:40:09 -07001501 getstack_signal_handler_arg.signal_stack_base = sig_stack;
1502 getstack_signal_handler_arg.signal_stack_size = sig_stack_size;
1503 getstack_signal_handler_arg.main_stack_base = main_stack_base;
1504 getstack_signal_handler_arg.main_stack_size = main_stack_size;
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001505 kill(getpid(), SIGUSR1);
1506 ASSERT_EQ(true, getstack_signal_handler_arg.done);
1507
Mor-sarid, Nitzan56933322015-09-11 05:31:36 +00001508 ASSERT_EQ(0, sigaltstack(&oss, nullptr));
1509 ASSERT_EQ(0, munmap(sig_stack, sig_stack_size));
1510}
1511
Yabin Cui917d3902015-01-08 12:32:42 -08001512static void pthread_attr_getstack_18908062_helper(void*) {
1513 char local_variable;
1514 pthread_attr_t attributes;
1515 pthread_getattr_np(pthread_self(), &attributes);
1516 void* stack_base;
1517 size_t stack_size;
1518 pthread_attr_getstack(&attributes, &stack_base, &stack_size);
1519
1520 // Test whether &local_variable is in [stack_base, stack_base + stack_size).
1521 ASSERT_LE(reinterpret_cast<char*>(stack_base), &local_variable);
1522 ASSERT_LT(&local_variable, reinterpret_cast<char*>(stack_base) + stack_size);
1523}
1524
1525// Check whether something on stack is in the range of
1526// [stack_base, stack_base + stack_size). see b/18908062.
1527TEST(pthread, pthread_attr_getstack_18908062) {
1528 pthread_t t;
1529 ASSERT_EQ(0, pthread_create(&t, NULL,
1530 reinterpret_cast<void* (*)(void*)>(pthread_attr_getstack_18908062_helper),
1531 NULL));
Elliott Hughes8aecba72017-10-17 15:34:41 -07001532 ASSERT_EQ(0, pthread_join(t, NULL));
Yabin Cui917d3902015-01-08 12:32:42 -08001533}
1534
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001535#if defined(__BIONIC__)
Elliott Hughesf2083612015-11-11 13:32:28 -08001536static pthread_mutex_t pthread_gettid_np_mutex = PTHREAD_MUTEX_INITIALIZER;
1537
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001538static void* pthread_gettid_np_helper(void* arg) {
1539 *reinterpret_cast<pid_t*>(arg) = gettid();
Elliott Hughesf2083612015-11-11 13:32:28 -08001540
1541 // Wait for our parent to call pthread_gettid_np on us before exiting.
1542 pthread_mutex_lock(&pthread_gettid_np_mutex);
1543 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001544 return NULL;
1545}
1546#endif
1547
1548TEST(pthread, pthread_gettid_np) {
1549#if defined(__BIONIC__)
1550 ASSERT_EQ(gettid(), pthread_gettid_np(pthread_self()));
1551
Elliott Hughesf2083612015-11-11 13:32:28 -08001552 // Ensure the other thread doesn't exit until after we've called
1553 // pthread_gettid_np on it.
1554 pthread_mutex_lock(&pthread_gettid_np_mutex);
1555
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001556 pid_t t_gettid_result;
1557 pthread_t t;
1558 pthread_create(&t, NULL, pthread_gettid_np_helper, &t_gettid_result);
1559
1560 pid_t t_pthread_gettid_np_result = pthread_gettid_np(t);
1561
Elliott Hughesf2083612015-11-11 13:32:28 -08001562 // Release the other thread and wait for it to exit.
1563 pthread_mutex_unlock(&pthread_gettid_np_mutex);
Elliott Hughes8aecba72017-10-17 15:34:41 -07001564 ASSERT_EQ(0, pthread_join(t, NULL));
Elliott Hughes8fb639c2014-09-12 14:43:07 -07001565
1566 ASSERT_EQ(t_gettid_result, t_pthread_gettid_np_result);
1567#else
1568 GTEST_LOG_(INFO) << "This test does nothing.\n";
1569#endif
1570}
Elliott Hughes34c987a2014-09-22 16:01:26 -07001571
1572static size_t cleanup_counter = 0;
1573
Derek Xue41996952014-09-25 11:05:32 +01001574static void AbortCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001575 abort();
1576}
1577
Derek Xue41996952014-09-25 11:05:32 +01001578static void CountCleanupRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001579 ++cleanup_counter;
1580}
1581
Derek Xue41996952014-09-25 11:05:32 +01001582static void PthreadCleanupTester() {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001583 pthread_cleanup_push(CountCleanupRoutine, NULL);
1584 pthread_cleanup_push(CountCleanupRoutine, NULL);
1585 pthread_cleanup_push(AbortCleanupRoutine, NULL);
1586
1587 pthread_cleanup_pop(0); // Pop the abort without executing it.
1588 pthread_cleanup_pop(1); // Pop one count while executing it.
1589 ASSERT_EQ(1U, cleanup_counter);
1590 // Exit while the other count is still on the cleanup stack.
1591 pthread_exit(NULL);
1592
1593 // Calls to pthread_cleanup_pop/pthread_cleanup_push must always be balanced.
1594 pthread_cleanup_pop(0);
1595}
1596
Derek Xue41996952014-09-25 11:05:32 +01001597static void* PthreadCleanupStartRoutine(void*) {
Elliott Hughes34c987a2014-09-22 16:01:26 -07001598 PthreadCleanupTester();
1599 return NULL;
1600}
1601
1602TEST(pthread, pthread_cleanup_push__pthread_cleanup_pop) {
1603 pthread_t t;
1604 ASSERT_EQ(0, pthread_create(&t, NULL, PthreadCleanupStartRoutine, NULL));
Elliott Hughes8aecba72017-10-17 15:34:41 -07001605 ASSERT_EQ(0, pthread_join(t, NULL));
Elliott Hughes34c987a2014-09-22 16:01:26 -07001606 ASSERT_EQ(2U, cleanup_counter);
1607}
Derek Xue41996952014-09-25 11:05:32 +01001608
1609TEST(pthread, PTHREAD_MUTEX_DEFAULT_is_PTHREAD_MUTEX_NORMAL) {
1610 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_DEFAULT);
1611}
1612
1613TEST(pthread, pthread_mutexattr_gettype) {
1614 pthread_mutexattr_t attr;
1615 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1616
1617 int attr_type;
1618
1619 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL));
1620 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1621 ASSERT_EQ(PTHREAD_MUTEX_NORMAL, attr_type);
1622
1623 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK));
1624 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1625 ASSERT_EQ(PTHREAD_MUTEX_ERRORCHECK, attr_type);
1626
1627 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE));
1628 ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type));
1629 ASSERT_EQ(PTHREAD_MUTEX_RECURSIVE, attr_type);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001630
1631 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
1632}
1633
Yabin Cui17393b02015-03-21 15:08:25 -07001634struct PthreadMutex {
1635 pthread_mutex_t lock;
1636
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -07001637 explicit PthreadMutex(int mutex_type) {
Yabin Cui17393b02015-03-21 15:08:25 -07001638 init(mutex_type);
1639 }
1640
1641 ~PthreadMutex() {
1642 destroy();
1643 }
1644
1645 private:
1646 void init(int mutex_type) {
1647 pthread_mutexattr_t attr;
1648 ASSERT_EQ(0, pthread_mutexattr_init(&attr));
1649 ASSERT_EQ(0, pthread_mutexattr_settype(&attr, mutex_type));
1650 ASSERT_EQ(0, pthread_mutex_init(&lock, &attr));
1651 ASSERT_EQ(0, pthread_mutexattr_destroy(&attr));
1652 }
1653
1654 void destroy() {
1655 ASSERT_EQ(0, pthread_mutex_destroy(&lock));
1656 }
1657
1658 DISALLOW_COPY_AND_ASSIGN(PthreadMutex);
1659};
Derek Xue41996952014-09-25 11:05:32 +01001660
1661TEST(pthread, pthread_mutex_lock_NORMAL) {
Yabin Cui17393b02015-03-21 15:08:25 -07001662 PthreadMutex m(PTHREAD_MUTEX_NORMAL);
Derek Xue41996952014-09-25 11:05:32 +01001663
Yabin Cui17393b02015-03-21 15:08:25 -07001664 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1665 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08001666 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
1667 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
1668 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01001669}
1670
1671TEST(pthread, pthread_mutex_lock_ERRORCHECK) {
Yabin Cui17393b02015-03-21 15:08:25 -07001672 PthreadMutex m(PTHREAD_MUTEX_ERRORCHECK);
Derek Xue41996952014-09-25 11:05:32 +01001673
Yabin Cui17393b02015-03-21 15:08:25 -07001674 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1675 ASSERT_EQ(EDEADLK, pthread_mutex_lock(&m.lock));
1676 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1677 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
1678 ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock));
1679 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1680 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
Derek Xue41996952014-09-25 11:05:32 +01001681}
1682
1683TEST(pthread, pthread_mutex_lock_RECURSIVE) {
Yabin Cui17393b02015-03-21 15:08:25 -07001684 PthreadMutex m(PTHREAD_MUTEX_RECURSIVE);
Derek Xue41996952014-09-25 11:05:32 +01001685
Yabin Cui17393b02015-03-21 15:08:25 -07001686 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1687 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
1688 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1689 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1690 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
Elliott Hughesd31d4c12015-12-14 17:35:10 -08001691 ASSERT_EQ(0, pthread_mutex_trylock(&m.lock));
1692 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui17393b02015-03-21 15:08:25 -07001693 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
1694 ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock));
1695}
1696
1697TEST(pthread, pthread_mutex_init_same_as_static_initializers) {
1698 pthread_mutex_t lock_normal = PTHREAD_MUTEX_INITIALIZER;
1699 PthreadMutex m1(PTHREAD_MUTEX_NORMAL);
1700 ASSERT_EQ(0, memcmp(&lock_normal, &m1.lock, sizeof(pthread_mutex_t)));
1701 pthread_mutex_destroy(&lock_normal);
1702
1703 pthread_mutex_t lock_errorcheck = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
1704 PthreadMutex m2(PTHREAD_MUTEX_ERRORCHECK);
1705 ASSERT_EQ(0, memcmp(&lock_errorcheck, &m2.lock, sizeof(pthread_mutex_t)));
1706 pthread_mutex_destroy(&lock_errorcheck);
1707
1708 pthread_mutex_t lock_recursive = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
1709 PthreadMutex m3(PTHREAD_MUTEX_RECURSIVE);
1710 ASSERT_EQ(0, memcmp(&lock_recursive, &m3.lock, sizeof(pthread_mutex_t)));
1711 ASSERT_EQ(0, pthread_mutex_destroy(&lock_recursive));
Derek Xue41996952014-09-25 11:05:32 +01001712}
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001713class MutexWakeupHelper {
1714 private:
Yabin Cui17393b02015-03-21 15:08:25 -07001715 PthreadMutex m;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001716 enum Progress {
1717 LOCK_INITIALIZED,
1718 LOCK_WAITING,
1719 LOCK_RELEASED,
1720 LOCK_ACCESSED
1721 };
1722 std::atomic<Progress> progress;
Yabin Cuif7969852015-04-02 17:47:48 -07001723 std::atomic<pid_t> tid;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001724
1725 static void thread_fn(MutexWakeupHelper* helper) {
Yabin Cuif7969852015-04-02 17:47:48 -07001726 helper->tid = gettid();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001727 ASSERT_EQ(LOCK_INITIALIZED, helper->progress);
1728 helper->progress = LOCK_WAITING;
1729
Yabin Cui17393b02015-03-21 15:08:25 -07001730 ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001731 ASSERT_EQ(LOCK_RELEASED, helper->progress);
Yabin Cui17393b02015-03-21 15:08:25 -07001732 ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001733
1734 helper->progress = LOCK_ACCESSED;
1735 }
1736
1737 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -07001738 explicit MutexWakeupHelper(int mutex_type) : m(mutex_type) {
Yabin Cui17393b02015-03-21 15:08:25 -07001739 }
1740
1741 void test() {
1742 ASSERT_EQ(0, pthread_mutex_lock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001743 progress = LOCK_INITIALIZED;
Yabin Cuif7969852015-04-02 17:47:48 -07001744 tid = 0;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001745
1746 pthread_t thread;
1747 ASSERT_EQ(0, pthread_create(&thread, NULL,
1748 reinterpret_cast<void* (*)(void*)>(MutexWakeupHelper::thread_fn), this));
1749
Yabin Cuif7969852015-04-02 17:47:48 -07001750 WaitUntilThreadSleep(tid);
1751 ASSERT_EQ(LOCK_WAITING, progress);
1752
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001753 progress = LOCK_RELEASED;
Yabin Cui17393b02015-03-21 15:08:25 -07001754 ASSERT_EQ(0, pthread_mutex_unlock(&m.lock));
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001755
1756 ASSERT_EQ(0, pthread_join(thread, NULL));
1757 ASSERT_EQ(LOCK_ACCESSED, progress);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001758 }
1759};
1760
1761TEST(pthread, pthread_mutex_NORMAL_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07001762 MutexWakeupHelper helper(PTHREAD_MUTEX_NORMAL);
1763 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001764}
1765
1766TEST(pthread, pthread_mutex_ERRORCHECK_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07001767 MutexWakeupHelper helper(PTHREAD_MUTEX_ERRORCHECK);
1768 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001769}
1770
1771TEST(pthread, pthread_mutex_RECURSIVE_wakeup) {
Yabin Cui17393b02015-03-21 15:08:25 -07001772 MutexWakeupHelper helper(PTHREAD_MUTEX_RECURSIVE);
1773 helper.test();
Yabin Cui5b8e7cd2015-03-04 17:36:59 -08001774}
1775
Yabin Cui140f3672015-02-03 10:32:00 -08001776TEST(pthread, pthread_mutex_owner_tid_limit) {
Yabin Cuie69c2452015-02-13 16:21:25 -08001777#if defined(__BIONIC__) && !defined(__LP64__)
Yabin Cui140f3672015-02-03 10:32:00 -08001778 FILE* fp = fopen("/proc/sys/kernel/pid_max", "r");
1779 ASSERT_TRUE(fp != NULL);
1780 long pid_max;
1781 ASSERT_EQ(1, fscanf(fp, "%ld", &pid_max));
1782 fclose(fp);
Yabin Cuie69c2452015-02-13 16:21:25 -08001783 // Bionic's pthread_mutex implementation on 32-bit devices uses 16 bits to represent owner tid.
Yabin Cui140f3672015-02-03 10:32:00 -08001784 ASSERT_LE(pid_max, 65536);
Yabin Cuie69c2452015-02-13 16:21:25 -08001785#else
1786 GTEST_LOG_(INFO) << "This test does nothing as 32-bit tid is supported by pthread_mutex.\n";
1787#endif
Yabin Cui140f3672015-02-03 10:32:00 -08001788}
Yabin Cuib5845722015-03-16 22:46:42 -07001789
Yabin Cuic9a659c2015-11-05 15:36:08 -08001790TEST(pthread, pthread_mutex_timedlock) {
1791 pthread_mutex_t m;
1792 ASSERT_EQ(0, pthread_mutex_init(&m, nullptr));
1793
1794 // If the mutex is already locked, pthread_mutex_timedlock should time out.
1795 ASSERT_EQ(0, pthread_mutex_lock(&m));
1796
1797 timespec ts;
1798 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1799 ASSERT_EQ(ETIMEDOUT, pthread_mutex_timedlock(&m, &ts));
1800 ts.tv_nsec = -1;
1801 ASSERT_EQ(EINVAL, pthread_mutex_timedlock(&m, &ts));
1802 ts.tv_nsec = NS_PER_S;
1803 ASSERT_EQ(EINVAL, pthread_mutex_timedlock(&m, &ts));
1804 ts.tv_nsec = NS_PER_S - 1;
1805 ts.tv_sec = -1;
1806 ASSERT_EQ(ETIMEDOUT, pthread_mutex_timedlock(&m, &ts));
1807
1808 // If the mutex is unlocked, pthread_mutex_timedlock should succeed.
1809 ASSERT_EQ(0, pthread_mutex_unlock(&m));
1810
1811 ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts));
1812 ts.tv_sec += 1;
1813 ASSERT_EQ(0, pthread_mutex_timedlock(&m, &ts));
1814
1815 ASSERT_EQ(0, pthread_mutex_unlock(&m));
1816 ASSERT_EQ(0, pthread_mutex_destroy(&m));
1817}
1818
Yabin Cuib5845722015-03-16 22:46:42 -07001819class StrictAlignmentAllocator {
1820 public:
1821 void* allocate(size_t size, size_t alignment) {
1822 char* p = new char[size + alignment * 2];
1823 allocated_array.push_back(p);
1824 while (!is_strict_aligned(p, alignment)) {
1825 ++p;
1826 }
1827 return p;
1828 }
1829
1830 ~StrictAlignmentAllocator() {
Elliott Hughes0b2acdf2015-10-02 18:25:19 -07001831 for (const auto& p : allocated_array) {
1832 delete[] p;
Yabin Cuib5845722015-03-16 22:46:42 -07001833 }
1834 }
1835
1836 private:
1837 bool is_strict_aligned(char* p, size_t alignment) {
1838 return (reinterpret_cast<uintptr_t>(p) % (alignment * 2)) == alignment;
1839 }
1840
1841 std::vector<char*> allocated_array;
1842};
1843
1844TEST(pthread, pthread_types_allow_four_bytes_alignment) {
1845#if defined(__BIONIC__)
1846 // For binary compatibility with old version, we need to allow 4-byte aligned data for pthread types.
1847 StrictAlignmentAllocator allocator;
1848 pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(
1849 allocator.allocate(sizeof(pthread_mutex_t), 4));
1850 ASSERT_EQ(0, pthread_mutex_init(mutex, NULL));
1851 ASSERT_EQ(0, pthread_mutex_lock(mutex));
1852 ASSERT_EQ(0, pthread_mutex_unlock(mutex));
1853 ASSERT_EQ(0, pthread_mutex_destroy(mutex));
1854
1855 pthread_cond_t* cond = reinterpret_cast<pthread_cond_t*>(
1856 allocator.allocate(sizeof(pthread_cond_t), 4));
1857 ASSERT_EQ(0, pthread_cond_init(cond, NULL));
1858 ASSERT_EQ(0, pthread_cond_signal(cond));
1859 ASSERT_EQ(0, pthread_cond_broadcast(cond));
1860 ASSERT_EQ(0, pthread_cond_destroy(cond));
1861
1862 pthread_rwlock_t* rwlock = reinterpret_cast<pthread_rwlock_t*>(
1863 allocator.allocate(sizeof(pthread_rwlock_t), 4));
1864 ASSERT_EQ(0, pthread_rwlock_init(rwlock, NULL));
1865 ASSERT_EQ(0, pthread_rwlock_rdlock(rwlock));
1866 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
1867 ASSERT_EQ(0, pthread_rwlock_wrlock(rwlock));
1868 ASSERT_EQ(0, pthread_rwlock_unlock(rwlock));
1869 ASSERT_EQ(0, pthread_rwlock_destroy(rwlock));
1870
1871#else
1872 GTEST_LOG_(INFO) << "This test tests bionic implementation details.";
1873#endif
1874}
Christopher Ferris60907c72015-06-09 18:46:15 -07001875
1876TEST(pthread, pthread_mutex_lock_null_32) {
1877#if defined(__BIONIC__) && !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -07001878 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return
1879 // EINVAL in that case: http://b/19995172.
1880 //
1881 // We decorate the public defintion with _Nonnull so that people recompiling
1882 // their code with get a warning and might fix their bug, but need to pass
1883 // NULL here to test that we remain compatible.
1884 pthread_mutex_t* null_value = nullptr;
1885 ASSERT_EQ(EINVAL, pthread_mutex_lock(null_value));
Christopher Ferris60907c72015-06-09 18:46:15 -07001886#else
1887 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 32 bit devices.";
1888#endif
1889}
1890
1891TEST(pthread, pthread_mutex_unlock_null_32) {
1892#if defined(__BIONIC__) && !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -07001893 // For LP32, the pthread lock/unlock functions allow a NULL mutex and return
1894 // EINVAL in that case: http://b/19995172.
1895 //
1896 // We decorate the public defintion with _Nonnull so that people recompiling
1897 // their code with get a warning and might fix their bug, but need to pass
1898 // NULL here to test that we remain compatible.
1899 pthread_mutex_t* null_value = nullptr;
1900 ASSERT_EQ(EINVAL, pthread_mutex_unlock(null_value));
Christopher Ferris60907c72015-06-09 18:46:15 -07001901#else
1902 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 32 bit devices.";
1903#endif
1904}
1905
1906TEST_F(pthread_DeathTest, pthread_mutex_lock_null_64) {
1907#if defined(__BIONIC__) && defined(__LP64__)
1908 pthread_mutex_t* null_value = nullptr;
1909 ASSERT_EXIT(pthread_mutex_lock(null_value), testing::KilledBySignal(SIGSEGV), "");
1910#else
1911 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 64 bit devices.";
1912#endif
1913}
1914
1915TEST_F(pthread_DeathTest, pthread_mutex_unlock_null_64) {
1916#if defined(__BIONIC__) && defined(__LP64__)
1917 pthread_mutex_t* null_value = nullptr;
1918 ASSERT_EXIT(pthread_mutex_unlock(null_value), testing::KilledBySignal(SIGSEGV), "");
1919#else
1920 GTEST_LOG_(INFO) << "This test tests bionic implementation details on 64 bit devices.";
1921#endif
1922}
Yabin Cui33ac04a2015-09-22 11:16:15 -07001923
1924extern _Unwind_Reason_Code FrameCounter(_Unwind_Context* ctx, void* arg);
1925
1926static volatile bool signal_handler_on_altstack_done;
1927
Josh Gao61db9ac2017-03-15 19:42:05 -07001928__attribute__((__noinline__))
1929static void signal_handler_backtrace() {
1930 // Check if we have enough stack space for unwinding.
1931 int count = 0;
1932 _Unwind_Backtrace(FrameCounter, &count);
1933 ASSERT_GT(count, 0);
1934}
1935
1936__attribute__((__noinline__))
1937static void signal_handler_logging() {
1938 // Check if we have enough stack space for logging.
1939 std::string s(2048, '*');
1940 GTEST_LOG_(INFO) << s;
1941 signal_handler_on_altstack_done = true;
1942}
1943
1944__attribute__((__noinline__))
1945static void signal_handler_snprintf() {
1946 // Check if we have enough stack space for snprintf to a PATH_MAX buffer, plus some extra.
1947 char buf[PATH_MAX + 2048];
1948 ASSERT_GT(snprintf(buf, sizeof(buf), "/proc/%d/status", getpid()), 0);
1949}
1950
Yabin Cui33ac04a2015-09-22 11:16:15 -07001951static void SignalHandlerOnAltStack(int signo, siginfo_t*, void*) {
1952 ASSERT_EQ(SIGUSR1, signo);
Josh Gao61db9ac2017-03-15 19:42:05 -07001953 signal_handler_backtrace();
1954 signal_handler_logging();
1955 signal_handler_snprintf();
Yabin Cui33ac04a2015-09-22 11:16:15 -07001956}
1957
Josh Gao415daa82017-03-06 17:45:33 -08001958TEST(pthread, big_enough_signal_stack) {
Yabin Cui33ac04a2015-09-22 11:16:15 -07001959 signal_handler_on_altstack_done = false;
1960 ScopedSignalHandler handler(SIGUSR1, SignalHandlerOnAltStack, SA_SIGINFO | SA_ONSTACK);
1961 kill(getpid(), SIGUSR1);
1962 ASSERT_TRUE(signal_handler_on_altstack_done);
1963}
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001964
1965TEST(pthread, pthread_barrierattr_smoke) {
1966 pthread_barrierattr_t attr;
1967 ASSERT_EQ(0, pthread_barrierattr_init(&attr));
1968 int pshared;
1969 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
1970 ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared);
1971 ASSERT_EQ(0, pthread_barrierattr_setpshared(&attr, PTHREAD_PROCESS_SHARED));
1972 ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared));
1973 ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared);
1974 ASSERT_EQ(0, pthread_barrierattr_destroy(&attr));
1975}
1976
Yabin Cui81d27972016-03-22 13:45:55 -07001977struct BarrierTestHelperData {
1978 size_t thread_count;
1979 pthread_barrier_t barrier;
1980 std::atomic<int> finished_mask;
1981 std::atomic<int> serial_thread_count;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001982 size_t iteration_count;
Yabin Cui81d27972016-03-22 13:45:55 -07001983 std::atomic<size_t> finished_iteration_count;
1984
1985 BarrierTestHelperData(size_t thread_count, size_t iteration_count)
1986 : thread_count(thread_count), finished_mask(0), serial_thread_count(0),
1987 iteration_count(iteration_count), finished_iteration_count(0) {
1988 }
1989};
1990
1991struct BarrierTestHelperArg {
1992 int id;
1993 BarrierTestHelperData* data;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08001994};
1995
1996static void BarrierTestHelper(BarrierTestHelperArg* arg) {
Yabin Cui81d27972016-03-22 13:45:55 -07001997 for (size_t i = 0; i < arg->data->iteration_count; ++i) {
1998 int result = pthread_barrier_wait(&arg->data->barrier);
1999 if (result == PTHREAD_BARRIER_SERIAL_THREAD) {
2000 arg->data->serial_thread_count++;
2001 } else {
2002 ASSERT_EQ(0, result);
2003 }
Yabin Cuid5c04c52017-05-02 12:57:39 -07002004 int mask = arg->data->finished_mask.fetch_or(1 << arg->id);
Yabin Cuiab4cddc2017-05-02 16:18:13 -07002005 mask |= 1 << arg->id;
Yabin Cuid5c04c52017-05-02 12:57:39 -07002006 if (mask == ((1 << arg->data->thread_count) - 1)) {
Yabin Cui81d27972016-03-22 13:45:55 -07002007 ASSERT_EQ(1, arg->data->serial_thread_count);
2008 arg->data->finished_iteration_count++;
2009 arg->data->finished_mask = 0;
2010 arg->data->serial_thread_count = 0;
2011 }
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002012 }
2013}
2014
2015TEST(pthread, pthread_barrier_smoke) {
2016 const size_t BARRIER_ITERATION_COUNT = 10;
2017 const size_t BARRIER_THREAD_COUNT = 10;
Yabin Cui81d27972016-03-22 13:45:55 -07002018 BarrierTestHelperData data(BARRIER_THREAD_COUNT, BARRIER_ITERATION_COUNT);
2019 ASSERT_EQ(0, pthread_barrier_init(&data.barrier, nullptr, data.thread_count));
2020 std::vector<pthread_t> threads(data.thread_count);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002021 std::vector<BarrierTestHelperArg> args(threads.size());
2022 for (size_t i = 0; i < threads.size(); ++i) {
Yabin Cui81d27972016-03-22 13:45:55 -07002023 args[i].id = i;
2024 args[i].data = &data;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002025 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
2026 reinterpret_cast<void* (*)(void*)>(BarrierTestHelper), &args[i]));
2027 }
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002028 for (size_t i = 0; i < threads.size(); ++i) {
2029 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
2030 }
Yabin Cui81d27972016-03-22 13:45:55 -07002031 ASSERT_EQ(data.iteration_count, data.finished_iteration_count);
2032 ASSERT_EQ(0, pthread_barrier_destroy(&data.barrier));
2033}
2034
2035struct BarrierDestroyTestArg {
2036 std::atomic<int> tid;
2037 pthread_barrier_t* barrier;
2038};
2039
2040static void BarrierDestroyTestHelper(BarrierDestroyTestArg* arg) {
2041 arg->tid = gettid();
2042 ASSERT_EQ(0, pthread_barrier_wait(arg->barrier));
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002043}
2044
2045TEST(pthread, pthread_barrier_destroy) {
2046 pthread_barrier_t barrier;
2047 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, 2));
2048 pthread_t thread;
Yabin Cui81d27972016-03-22 13:45:55 -07002049 BarrierDestroyTestArg arg;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002050 arg.tid = 0;
2051 arg.barrier = &barrier;
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002052 ASSERT_EQ(0, pthread_create(&thread, nullptr,
Yabin Cui81d27972016-03-22 13:45:55 -07002053 reinterpret_cast<void* (*)(void*)>(BarrierDestroyTestHelper), &arg));
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002054 WaitUntilThreadSleep(arg.tid);
2055 ASSERT_EQ(EBUSY, pthread_barrier_destroy(&barrier));
2056 ASSERT_EQ(PTHREAD_BARRIER_SERIAL_THREAD, pthread_barrier_wait(&barrier));
2057 // Verify if the barrier can be destroyed directly after pthread_barrier_wait().
2058 ASSERT_EQ(0, pthread_barrier_destroy(&barrier));
2059 ASSERT_EQ(0, pthread_join(thread, nullptr));
2060#if defined(__BIONIC__)
2061 ASSERT_EQ(EINVAL, pthread_barrier_destroy(&barrier));
2062#endif
2063}
2064
2065struct BarrierOrderingTestHelperArg {
2066 pthread_barrier_t* barrier;
2067 size_t* array;
2068 size_t array_length;
2069 size_t id;
2070};
2071
2072void BarrierOrderingTestHelper(BarrierOrderingTestHelperArg* arg) {
2073 const size_t ITERATION_COUNT = 10000;
2074 for (size_t i = 1; i <= ITERATION_COUNT; ++i) {
2075 arg->array[arg->id] = i;
Yabin Cuic9a659c2015-11-05 15:36:08 -08002076 int result = pthread_barrier_wait(arg->barrier);
2077 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002078 for (size_t j = 0; j < arg->array_length; ++j) {
2079 ASSERT_EQ(i, arg->array[j]);
2080 }
Yabin Cuic9a659c2015-11-05 15:36:08 -08002081 result = pthread_barrier_wait(arg->barrier);
2082 ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD);
Yabin Cuie7c2fff2015-11-05 22:06:09 -08002083 }
2084}
2085
2086TEST(pthread, pthread_barrier_check_ordering) {
2087 const size_t THREAD_COUNT = 4;
2088 pthread_barrier_t barrier;
2089 ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, THREAD_COUNT));
2090 size_t array[THREAD_COUNT];
2091 std::vector<pthread_t> threads(THREAD_COUNT);
2092 std::vector<BarrierOrderingTestHelperArg> args(THREAD_COUNT);
2093 for (size_t i = 0; i < THREAD_COUNT; ++i) {
2094 args[i].barrier = &barrier;
2095 args[i].array = array;
2096 args[i].array_length = THREAD_COUNT;
2097 args[i].id = i;
2098 ASSERT_EQ(0, pthread_create(&threads[i], nullptr,
2099 reinterpret_cast<void* (*)(void*)>(BarrierOrderingTestHelper),
2100 &args[i]));
2101 }
2102 for (size_t i = 0; i < THREAD_COUNT; ++i) {
2103 ASSERT_EQ(0, pthread_join(threads[i], nullptr));
2104 }
2105}
Yabin Cuife3a83a2015-11-17 16:03:18 -08002106
2107TEST(pthread, pthread_spinlock_smoke) {
2108 pthread_spinlock_t lock;
2109 ASSERT_EQ(0, pthread_spin_init(&lock, 0));
2110 ASSERT_EQ(0, pthread_spin_trylock(&lock));
2111 ASSERT_EQ(0, pthread_spin_unlock(&lock));
2112 ASSERT_EQ(0, pthread_spin_lock(&lock));
2113 ASSERT_EQ(EBUSY, pthread_spin_trylock(&lock));
2114 ASSERT_EQ(0, pthread_spin_unlock(&lock));
2115 ASSERT_EQ(0, pthread_spin_destroy(&lock));
2116}
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002117
Elliott Hughes8aecba72017-10-17 15:34:41 -07002118TEST(pthread, pthread_attr_getdetachstate__pthread_attr_setdetachstate) {
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002119 pthread_attr_t attr;
2120 ASSERT_EQ(0, pthread_attr_init(&attr));
2121
Elliott Hughes8aecba72017-10-17 15:34:41 -07002122 int state;
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002123 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002124 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2125 ASSERT_EQ(PTHREAD_CREATE_DETACHED, state);
2126
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002127 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002128 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2129 ASSERT_EQ(PTHREAD_CREATE_JOINABLE, state);
2130
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002131 ASSERT_EQ(EINVAL, pthread_attr_setdetachstate(&attr, 123));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002132 ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state));
2133 ASSERT_EQ(PTHREAD_CREATE_JOINABLE, state);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002134}
2135
2136TEST(pthread, pthread_create__mmap_failures) {
2137 pthread_attr_t attr;
2138 ASSERT_EQ(0, pthread_attr_init(&attr));
2139 ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
2140
2141 const auto kPageSize = sysconf(_SC_PAGE_SIZE);
2142
Elliott Hughes57512982017-10-02 22:49:18 -07002143 // Use up all the VMAs. By default this is 64Ki (though some will already be in use).
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002144 std::vector<void*> pages;
Elliott Hughes57512982017-10-02 22:49:18 -07002145 pages.reserve(64 * 1024);
Elliott Hughes53dc9dd2017-09-19 14:02:50 -07002146 int prot = PROT_NONE;
2147 while (true) {
2148 void* page = mmap(nullptr, kPageSize, prot, MAP_ANON|MAP_PRIVATE, -1, 0);
2149 if (page == MAP_FAILED) break;
2150 pages.push_back(page);
2151 prot = (prot == PROT_NONE) ? PROT_READ : PROT_NONE;
2152 }
2153
2154 // Try creating threads, freeing up a page each time we fail.
2155 size_t EAGAIN_count = 0;
2156 size_t i = 0;
2157 for (; i < pages.size(); ++i) {
2158 pthread_t t;
2159 int status = pthread_create(&t, &attr, IdFn, nullptr);
2160 if (status != EAGAIN) break;
2161 ++EAGAIN_count;
2162 ASSERT_EQ(0, munmap(pages[i], kPageSize));
2163 }
2164
2165 // Creating a thread uses at least six VMAs: the stack, the TLS, and a guard each side of both.
2166 // So we should have seen at least six failures.
2167 ASSERT_GE(EAGAIN_count, 6U);
2168
2169 for (; i < pages.size(); ++i) {
2170 ASSERT_EQ(0, munmap(pages[i], kPageSize));
2171 }
2172}
Elliott Hughesdff08ce2017-10-16 09:58:45 -07002173
2174TEST(pthread, pthread_setschedparam) {
2175 sched_param p = { .sched_priority = INT_MIN };
2176 ASSERT_EQ(EINVAL, pthread_setschedparam(pthread_self(), INT_MIN, &p));
2177}
2178
2179TEST(pthread, pthread_setschedprio) {
2180 ASSERT_EQ(EINVAL, pthread_setschedprio(pthread_self(), INT_MIN));
2181}
Elliott Hughes8aecba72017-10-17 15:34:41 -07002182
2183TEST(pthread, pthread_attr_getinheritsched__pthread_attr_setinheritsched) {
2184 pthread_attr_t attr;
2185 ASSERT_EQ(0, pthread_attr_init(&attr));
2186
2187 int state;
2188 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2189 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
2190 ASSERT_EQ(PTHREAD_INHERIT_SCHED, state);
2191
2192 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
2193 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
2194 ASSERT_EQ(PTHREAD_EXPLICIT_SCHED, state);
2195
2196 ASSERT_EQ(EINVAL, pthread_attr_setinheritsched(&attr, 123));
2197 ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state));
2198 ASSERT_EQ(PTHREAD_EXPLICIT_SCHED, state);
2199}
2200
2201TEST(pthread, pthread_attr_setinheritsched__PTHREAD_INHERIT_SCHED__PTHREAD_EXPLICIT_SCHED) {
2202 pthread_attr_t attr;
2203 ASSERT_EQ(0, pthread_attr_init(&attr));
2204
2205 // If we set invalid scheduling attributes but choose to inherit, everything's fine...
2206 sched_param param = { .sched_priority = sched_get_priority_max(SCHED_FIFO) + 1 };
2207 ASSERT_EQ(0, pthread_attr_setschedparam(&attr, &param));
2208 ASSERT_EQ(0, pthread_attr_setschedpolicy(&attr, SCHED_FIFO));
2209 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2210
2211 pthread_t t;
2212 ASSERT_EQ(0, pthread_create(&t, &attr, IdFn, nullptr));
2213 ASSERT_EQ(0, pthread_join(t, nullptr));
2214
Elliott Hughes7a660662017-10-30 09:26:06 -07002215#if defined(__LP64__)
2216 // If we ask to use them, though, we'll see a failure...
Elliott Hughes8aecba72017-10-17 15:34:41 -07002217 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
2218 ASSERT_EQ(EINVAL, pthread_create(&t, &attr, IdFn, nullptr));
Elliott Hughes7a660662017-10-30 09:26:06 -07002219#else
2220 // For backwards compatibility with broken apps, we just ignore failures
2221 // to set scheduler attributes on LP32.
2222#endif
Elliott Hughes8aecba72017-10-17 15:34:41 -07002223}
2224
2225TEST(pthread, pthread_attr_setinheritsched_PTHREAD_INHERIT_SCHED_takes_effect) {
2226 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
2227 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO, &param);
2228 if (rc == EPERM) {
2229 GTEST_LOG_(INFO) << "pthread_setschedparam failed with EPERM, skipping test\n";
2230 return;
2231 }
2232 ASSERT_EQ(0, rc);
2233
2234 pthread_attr_t attr;
2235 ASSERT_EQ(0, pthread_attr_init(&attr));
2236 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2237
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002238 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07002239 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002240 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002241 int actual_policy;
2242 sched_param actual_param;
2243 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
2244 ASSERT_EQ(SCHED_FIFO, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002245 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07002246 ASSERT_EQ(0, pthread_join(t, nullptr));
2247}
2248
2249TEST(pthread, pthread_attr_setinheritsched_PTHREAD_EXPLICIT_SCHED_takes_effect) {
2250 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
2251 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO, &param);
2252 if (rc == EPERM) {
2253 GTEST_LOG_(INFO) << "pthread_setschedparam failed with EPERM, skipping test\n";
2254 return;
2255 }
2256 ASSERT_EQ(0, rc);
2257
2258 pthread_attr_t attr;
2259 ASSERT_EQ(0, pthread_attr_init(&attr));
2260 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED));
2261 ASSERT_EQ(0, pthread_attr_setschedpolicy(&attr, SCHED_OTHER));
2262
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002263 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07002264 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002265 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002266 int actual_policy;
2267 sched_param actual_param;
2268 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
2269 ASSERT_EQ(SCHED_OTHER, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002270 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07002271 ASSERT_EQ(0, pthread_join(t, nullptr));
2272}
2273
2274TEST(pthread, pthread_attr_setinheritsched__takes_effect_despite_SCHED_RESET_ON_FORK) {
2275 sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) };
2276 int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param);
2277 if (rc == EPERM) {
2278 GTEST_LOG_(INFO) << "pthread_setschedparam failed with EPERM, skipping test\n";
2279 return;
2280 }
2281 ASSERT_EQ(0, rc);
2282
2283 pthread_attr_t attr;
2284 ASSERT_EQ(0, pthread_attr_init(&attr));
2285 ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
2286
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002287 SpinFunctionHelper spin_helper;
Elliott Hughes8aecba72017-10-17 15:34:41 -07002288 pthread_t t;
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002289 ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr));
Elliott Hughes8aecba72017-10-17 15:34:41 -07002290 int actual_policy;
2291 sched_param actual_param;
2292 ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param));
2293 ASSERT_EQ(SCHED_FIFO | SCHED_RESET_ON_FORK, actual_policy);
Elliott Hughes0bd9d132017-11-02 13:11:13 -07002294 spin_helper.UnSpin();
Elliott Hughes8aecba72017-10-17 15:34:41 -07002295 ASSERT_EQ(0, pthread_join(t, nullptr));
2296}