1 /*
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 "SignalUtils.h"
20 #include "utils.h"
21
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <libgen.h>
25 #include <limits.h>
26 #include <stdint.h>
27 #include <sys/capability.h>
28 #include <sys/param.h>
29 #include <sys/resource.h>
30 #include <sys/syscall.h>
31 #include <sys/types.h>
32 #include <sys/utsname.h>
33 #include <sys/wait.h>
34 #include <unistd.h>
35
36 #include <chrono>
37
38 #include <android-base/file.h>
39 #include <android-base/silent_death_test.h>
40 #include <android-base/strings.h>
41
42 #include "private/get_cpu_count_from_string.h"
43
44 #if defined(__BIONIC__)
45 #include "bionic/pthread_internal.h"
46 #endif
47
48 #if defined(NOFORTIFY)
49 #define UNISTD_TEST unistd_nofortify
50 #define UNISTD_DEATHTEST unistd_nofortify_DeathTest
51 #else
52 #define UNISTD_TEST unistd
53 #define UNISTD_DEATHTEST unistd_DeathTest
54 #endif
55
56 using UNISTD_DEATHTEST = SilentDeathTest;
57
58 using namespace std::chrono_literals;
59
get_brk()60 static void* get_brk() {
61 return sbrk(0);
62 }
63
page_align(uintptr_t addr)64 static void* page_align(uintptr_t addr) {
65 uintptr_t mask = sysconf(_SC_PAGE_SIZE) - 1;
66 return reinterpret_cast<void*>((addr + mask) & ~mask);
67 }
68
TEST(UNISTD_TEST,brk)69 TEST(UNISTD_TEST, brk) {
70 void* initial_break = get_brk();
71
72 void* new_break = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(initial_break) + 1);
73 int ret = brk(new_break);
74 if (ret == -1) {
75 ASSERT_EQ(errno, ENOMEM);
76 } else {
77 ASSERT_EQ(0, ret);
78 ASSERT_GE(get_brk(), new_break);
79 }
80
81 // Expand by a full page to force the mapping to expand
82 new_break = page_align(reinterpret_cast<uintptr_t>(initial_break) + sysconf(_SC_PAGE_SIZE));
83 ret = brk(new_break);
84 if (ret == -1) {
85 ASSERT_EQ(errno, ENOMEM);
86 } else {
87 ASSERT_EQ(0, ret);
88 ASSERT_EQ(get_brk(), new_break);
89 }
90 }
91
TEST(UNISTD_TEST,brk_ENOMEM)92 TEST(UNISTD_TEST, brk_ENOMEM) {
93 ASSERT_EQ(-1, brk(reinterpret_cast<void*>(-1)));
94 ASSERT_EQ(ENOMEM, errno);
95 }
96
97 #if defined(__GLIBC__)
98 #define SBRK_MIN INTPTR_MIN
99 #define SBRK_MAX INTPTR_MAX
100 #else
101 #define SBRK_MIN PTRDIFF_MIN
102 #define SBRK_MAX PTRDIFF_MAX
103 #endif
104
TEST(UNISTD_TEST,sbrk_ENOMEM)105 TEST(UNISTD_TEST, sbrk_ENOMEM) {
106 #if defined(__BIONIC__) && !defined(__LP64__)
107 // There is no way to guarantee that all overflow conditions can be tested
108 // without manipulating the underlying values of the current break.
109 extern void* __bionic_brk;
110
111 class ScopedBrk {
112 public:
113 ScopedBrk() : saved_brk_(__bionic_brk) {}
114 virtual ~ScopedBrk() { __bionic_brk = saved_brk_; }
115
116 private:
117 void* saved_brk_;
118 };
119
120 ScopedBrk scope_brk;
121
122 // Set the current break to a point that will cause an overflow.
123 __bionic_brk = reinterpret_cast<void*>(static_cast<uintptr_t>(PTRDIFF_MAX) + 2);
124
125 // Can't increase by so much that we'd overflow.
126 ASSERT_EQ(reinterpret_cast<void*>(-1), sbrk(PTRDIFF_MAX));
127 ASSERT_EQ(ENOMEM, errno);
128
129 // Set the current break to a point that will cause an overflow.
130 __bionic_brk = reinterpret_cast<void*>(static_cast<uintptr_t>(PTRDIFF_MAX));
131
132 ASSERT_EQ(reinterpret_cast<void*>(-1), sbrk(PTRDIFF_MIN));
133 ASSERT_EQ(ENOMEM, errno);
134
135 __bionic_brk = reinterpret_cast<void*>(static_cast<uintptr_t>(PTRDIFF_MAX) - 1);
136
137 ASSERT_EQ(reinterpret_cast<void*>(-1), sbrk(PTRDIFF_MIN + 1));
138 ASSERT_EQ(ENOMEM, errno);
139 #else
140 class ScopedBrk {
141 public:
142 ScopedBrk() : saved_brk_(get_brk()) {}
143 virtual ~ScopedBrk() { brk(saved_brk_); }
144
145 private:
146 void* saved_brk_;
147 };
148
149 ScopedBrk scope_brk;
150
151 uintptr_t cur_brk = reinterpret_cast<uintptr_t>(get_brk());
152 if (cur_brk < static_cast<uintptr_t>(-(SBRK_MIN+1))) {
153 // Do the overflow test for a max negative increment.
154 ASSERT_EQ(reinterpret_cast<void*>(-1), sbrk(SBRK_MIN));
155 #if defined(__BIONIC__)
156 // GLIBC does not set errno in overflow case.
157 ASSERT_EQ(ENOMEM, errno);
158 #endif
159 }
160
161 uintptr_t overflow_brk = static_cast<uintptr_t>(SBRK_MAX) + 2;
162 if (cur_brk < overflow_brk) {
163 // Try and move the value to PTRDIFF_MAX + 2.
164 cur_brk = reinterpret_cast<uintptr_t>(sbrk(overflow_brk));
165 }
166 if (cur_brk >= overflow_brk) {
167 ASSERT_EQ(reinterpret_cast<void*>(-1), sbrk(SBRK_MAX));
168 #if defined(__BIONIC__)
169 // GLIBC does not set errno in overflow case.
170 ASSERT_EQ(ENOMEM, errno);
171 #endif
172 }
173 #endif
174 }
175
TEST(UNISTD_TEST,truncate)176 TEST(UNISTD_TEST, truncate) {
177 TemporaryFile tf;
178 ASSERT_EQ(0, close(tf.fd));
179 ASSERT_EQ(0, truncate(tf.path, 123));
180
181 struct stat sb;
182 ASSERT_EQ(0, stat(tf.path, &sb));
183 ASSERT_EQ(123, sb.st_size);
184 }
185
TEST(UNISTD_TEST,truncate64_smoke)186 TEST(UNISTD_TEST, truncate64_smoke) {
187 TemporaryFile tf;
188 ASSERT_EQ(0, close(tf.fd));
189 ASSERT_EQ(0, truncate64(tf.path, 123));
190
191 struct stat sb;
192 ASSERT_EQ(0, stat(tf.path, &sb));
193 ASSERT_EQ(123, sb.st_size);
194 }
195
TEST(UNISTD_TEST,ftruncate)196 TEST(UNISTD_TEST, ftruncate) {
197 TemporaryFile tf;
198 ASSERT_EQ(0, ftruncate(tf.fd, 123));
199 ASSERT_EQ(0, close(tf.fd));
200
201 struct stat sb;
202 ASSERT_EQ(0, stat(tf.path, &sb));
203 ASSERT_EQ(123, sb.st_size);
204 }
205
TEST(UNISTD_TEST,ftruncate64_smoke)206 TEST(UNISTD_TEST, ftruncate64_smoke) {
207 TemporaryFile tf;
208 ASSERT_EQ(0, ftruncate64(tf.fd, 123));
209 ASSERT_EQ(0, close(tf.fd));
210
211 struct stat sb;
212 ASSERT_EQ(0, stat(tf.path, &sb));
213 ASSERT_EQ(123, sb.st_size);
214 }
215
TEST(UNISTD_TEST,ftruncate_negative)216 TEST(UNISTD_TEST, ftruncate_negative) {
217 TemporaryFile tf;
218 errno = 0;
219 ASSERT_EQ(-1, ftruncate(tf.fd, -123));
220 ASSERT_EQ(EINVAL, errno);
221 }
222
223 static bool g_pause_test_flag = false;
PauseTestSignalHandler(int)224 static void PauseTestSignalHandler(int) {
225 g_pause_test_flag = true;
226 }
227
TEST(UNISTD_TEST,pause)228 TEST(UNISTD_TEST, pause) {
229 ScopedSignalHandler handler(SIGALRM, PauseTestSignalHandler);
230
231 alarm(1);
232 ASSERT_FALSE(g_pause_test_flag);
233 ASSERT_EQ(-1, pause());
234 ASSERT_TRUE(g_pause_test_flag);
235 }
236
TEST(UNISTD_TEST,read)237 TEST(UNISTD_TEST, read) {
238 int fd = open("/proc/version", O_RDONLY);
239 ASSERT_TRUE(fd != -1);
240
241 char buf[5];
242 ASSERT_EQ(5, read(fd, buf, 5));
243 ASSERT_EQ(buf[0], 'L');
244 ASSERT_EQ(buf[1], 'i');
245 ASSERT_EQ(buf[2], 'n');
246 ASSERT_EQ(buf[3], 'u');
247 ASSERT_EQ(buf[4], 'x');
248 close(fd);
249 }
250
TEST(UNISTD_TEST,read_EBADF)251 TEST(UNISTD_TEST, read_EBADF) {
252 // read returns ssize_t which is 64-bits on LP64, so it's worth explicitly checking that
253 // our syscall stubs correctly return a 64-bit -1.
254 char buf[1];
255 ASSERT_EQ(-1, read(-1, buf, sizeof(buf)));
256 ASSERT_EQ(EBADF, errno);
257 }
258
TEST(UNISTD_TEST,syscall_long)259 TEST(UNISTD_TEST, syscall_long) {
260 // Check that syscall(3) correctly returns long results.
261 // https://code.google.com/p/android/issues/detail?id=73952
262 // We assume that the break is > 4GiB, but this is potentially flaky.
263 uintptr_t p = reinterpret_cast<uintptr_t>(sbrk(0));
264 ASSERT_EQ(p, static_cast<uintptr_t>(syscall(__NR_brk, 0)));
265 }
266
TEST(UNISTD_TEST,alarm)267 TEST(UNISTD_TEST, alarm) {
268 ASSERT_EQ(0U, alarm(0));
269 }
270
TEST(UNISTD_TEST,_exit)271 TEST(UNISTD_TEST, _exit) {
272 pid_t pid = fork();
273 ASSERT_NE(-1, pid) << strerror(errno);
274
275 if (pid == 0) {
276 _exit(99);
277 }
278
279 AssertChildExited(pid, 99);
280 }
281
TEST(UNISTD_TEST,getenv_unsetenv)282 TEST(UNISTD_TEST, getenv_unsetenv) {
283 ASSERT_EQ(0, setenv("test-variable", "hello", 1));
284 ASSERT_STREQ("hello", getenv("test-variable"));
285 ASSERT_EQ(0, unsetenv("test-variable"));
286 ASSERT_TRUE(getenv("test-variable") == nullptr);
287 }
288
TEST(UNISTD_TEST,unsetenv_EINVAL)289 TEST(UNISTD_TEST, unsetenv_EINVAL) {
290 EXPECT_EQ(-1, unsetenv(""));
291 EXPECT_EQ(EINVAL, errno);
292 EXPECT_EQ(-1, unsetenv("a=b"));
293 EXPECT_EQ(EINVAL, errno);
294 }
295
TEST(UNISTD_TEST,setenv_EINVAL)296 TEST(UNISTD_TEST, setenv_EINVAL) {
297 #pragma clang diagnostic push
298 #pragma clang diagnostic ignored "-Wnonnull"
299 EXPECT_EQ(-1, setenv(nullptr, "value", 0));
300 EXPECT_EQ(EINVAL, errno);
301 EXPECT_EQ(-1, setenv(nullptr, "value", 1));
302 EXPECT_EQ(EINVAL, errno);
303 #pragma clang diagnostic pop
304 EXPECT_EQ(-1, setenv("", "value", 0));
305 EXPECT_EQ(EINVAL, errno);
306 EXPECT_EQ(-1, setenv("", "value", 1));
307 EXPECT_EQ(EINVAL, errno);
308 EXPECT_EQ(-1, setenv("a=b", "value", 0));
309 EXPECT_EQ(EINVAL, errno);
310 EXPECT_EQ(-1, setenv("a=b", "value", 1));
311 EXPECT_EQ(EINVAL, errno);
312 }
313
TEST(UNISTD_TEST,setenv)314 TEST(UNISTD_TEST, setenv) {
315 ASSERT_EQ(0, unsetenv("test-variable"));
316
317 char a[] = "a";
318 char b[] = "b";
319 char c[] = "c";
320
321 // New value.
322 EXPECT_EQ(0, setenv("test-variable", a, 0));
323 EXPECT_STREQ(a, getenv("test-variable"));
324
325 // Existing value, no overwrite.
326 EXPECT_EQ(0, setenv("test-variable", b, 0));
327 EXPECT_STREQ(a, getenv("test-variable"));
328
329 // Existing value, overwrite.
330 EXPECT_EQ(0, setenv("test-variable", c, 1));
331 EXPECT_STREQ(c, getenv("test-variable"));
332 // But the arrays backing the values are unchanged.
333 EXPECT_EQ('a', a[0]);
334 EXPECT_EQ('b', b[0]);
335 EXPECT_EQ('c', c[0]);
336
337 ASSERT_EQ(0, unsetenv("test-variable"));
338 }
339
TEST(UNISTD_TEST,putenv)340 TEST(UNISTD_TEST, putenv) {
341 ASSERT_EQ(0, unsetenv("a"));
342
343 char* s1 = strdup("a=b");
344 ASSERT_EQ(0, putenv(s1));
345
346 ASSERT_STREQ("b", getenv("a"));
347 s1[2] = 'c';
348 ASSERT_STREQ("c", getenv("a"));
349
350 char* s2 = strdup("a=b");
351 ASSERT_EQ(0, putenv(s2));
352
353 ASSERT_STREQ("b", getenv("a"));
354 ASSERT_EQ('c', s1[2]);
355
356 ASSERT_EQ(0, unsetenv("a"));
357 free(s1);
358 free(s2);
359 }
360
TEST(UNISTD_TEST,clearenv)361 TEST(UNISTD_TEST, clearenv) {
362 extern char** environ;
363
364 // Guarantee that environ is not initially empty...
365 ASSERT_EQ(0, setenv("test-variable", "a", 1));
366
367 // Stash a copy.
368 std::vector<char*> old_environ;
369 for (size_t i = 0; environ[i] != nullptr; ++i) {
370 old_environ.push_back(strdup(environ[i]));
371 }
372
373 ASSERT_EQ(0, clearenv());
374
375 EXPECT_TRUE(environ == nullptr || environ[0] == nullptr);
376 EXPECT_EQ(nullptr, getenv("test-variable"));
377 EXPECT_EQ(0, setenv("test-variable", "post-clear", 1));
378 EXPECT_STREQ("post-clear", getenv("test-variable"));
379
380 // Put the old environment back.
381 for (size_t i = 0; i < old_environ.size(); ++i) {
382 EXPECT_EQ(0, putenv(old_environ[i]));
383 }
384
385 // Check it wasn't overwritten.
386 EXPECT_STREQ("a", getenv("test-variable"));
387
388 EXPECT_EQ(0, unsetenv("test-variable"));
389 }
390
TestSyncFunction(int (* fn)(int))391 static void TestSyncFunction(int (*fn)(int)) {
392 int fd;
393
394 // Can't sync an invalid fd.
395 errno = 0;
396 EXPECT_EQ(-1, fn(-1));
397 EXPECT_EQ(EBADF, errno);
398
399 // It doesn't matter whether you've opened a file for write or not.
400 TemporaryFile tf;
401 ASSERT_NE(-1, tf.fd);
402
403 EXPECT_EQ(0, fn(tf.fd));
404
405 ASSERT_NE(-1, fd = open(tf.path, O_RDONLY));
406 EXPECT_EQ(0, fn(fd));
407 close(fd);
408
409 ASSERT_NE(-1, fd = open(tf.path, O_RDWR));
410 EXPECT_EQ(0, fn(fd));
411 close(fd);
412
413 // The fd can even be a directory.
414 ASSERT_NE(-1, fd = open("/data/local/tmp", O_RDONLY));
415 EXPECT_EQ(0, fn(fd));
416 close(fd);
417 }
418
TestFsyncFunction(int (* fn)(int))419 static void TestFsyncFunction(int (*fn)(int)) {
420 TestSyncFunction(fn);
421
422 // But some file systems are fussy about fsync/fdatasync...
423 errno = 0;
424 int fd = open("/proc/version", O_RDONLY);
425 ASSERT_NE(-1, fd);
426 EXPECT_EQ(-1, fn(fd));
427 EXPECT_EQ(EINVAL, errno);
428 close(fd);
429 }
430
TEST(UNISTD_TEST,fdatasync)431 TEST(UNISTD_TEST, fdatasync) {
432 TestFsyncFunction(fdatasync);
433 }
434
TEST(UNISTD_TEST,fsync)435 TEST(UNISTD_TEST, fsync) {
436 TestFsyncFunction(fsync);
437 }
438
TEST(UNISTD_TEST,syncfs)439 TEST(UNISTD_TEST, syncfs) {
440 TestSyncFunction(syncfs);
441 }
442
TEST(UNISTD_TEST,vfork)443 TEST(UNISTD_TEST, vfork) {
444 #if defined(__BIONIC__)
445 pthread_internal_t* self = __get_thread();
446
447 pid_t cached_pid;
448 ASSERT_TRUE(self->get_cached_pid(&cached_pid));
449 ASSERT_EQ(syscall(__NR_getpid), cached_pid);
450 ASSERT_FALSE(self->is_vforked());
451
452 pid_t rc = vfork();
453 ASSERT_NE(-1, rc);
454 if (rc == 0) {
455 if (self->get_cached_pid(&cached_pid)) {
456 const char* error = "__get_thread()->cached_pid_ set after vfork\n";
457 write(STDERR_FILENO, error, strlen(error));
458 _exit(1);
459 }
460
461 if (!self->is_vforked()) {
462 const char* error = "__get_thread()->vforked_ not set after vfork\n";
463 write(STDERR_FILENO, error, strlen(error));
464 _exit(1);
465 }
466
467 _exit(0);
468 } else {
469 ASSERT_TRUE(self->get_cached_pid(&cached_pid));
470 ASSERT_EQ(syscall(__NR_getpid), cached_pid);
471 ASSERT_FALSE(self->is_vforked());
472
473 int status;
474 pid_t wait_result = waitpid(rc, &status, 0);
475 ASSERT_EQ(wait_result, rc);
476 ASSERT_TRUE(WIFEXITED(status));
477 ASSERT_EQ(0, WEXITSTATUS(status));
478 }
479 #endif
480 }
481
AssertGetPidCorrect()482 static void AssertGetPidCorrect() {
483 // The loop is just to make manual testing/debugging with strace easier.
484 pid_t getpid_syscall_result = syscall(__NR_getpid);
485 for (size_t i = 0; i < 128; ++i) {
486 ASSERT_EQ(getpid_syscall_result, getpid());
487 }
488 }
489
TestGetPidCachingWithFork(int (* fork_fn)(),void (* exit_fn)(int))490 static void TestGetPidCachingWithFork(int (*fork_fn)(), void (*exit_fn)(int)) {
491 pid_t parent_pid = getpid();
492 ASSERT_EQ(syscall(__NR_getpid), parent_pid);
493
494 pid_t fork_result = fork_fn();
495 ASSERT_NE(fork_result, -1);
496 if (fork_result == 0) {
497 // We're the child.
498 ASSERT_NO_FATAL_FAILURE(AssertGetPidCorrect());
499 ASSERT_EQ(parent_pid, getppid());
500 exit_fn(123);
501 } else {
502 // We're the parent.
503 ASSERT_EQ(parent_pid, getpid());
504 AssertChildExited(fork_result, 123);
505 }
506 }
507
508 // gettid() is marked as __attribute_const__, which will have the compiler
509 // optimize out multiple calls to gettid in the same function. This wrapper
510 // defeats that optimization.
GetTidForTest()511 static __attribute__((__noinline__)) pid_t GetTidForTest() {
512 __asm__("");
513 return gettid();
514 }
515
AssertGetTidCorrect()516 static void AssertGetTidCorrect() {
517 // The loop is just to make manual testing/debugging with strace easier.
518 pid_t gettid_syscall_result = syscall(__NR_gettid);
519 for (size_t i = 0; i < 128; ++i) {
520 ASSERT_EQ(gettid_syscall_result, GetTidForTest());
521 }
522 }
523
TestGetTidCachingWithFork(int (* fork_fn)(),void (* exit_fn)(int))524 static void TestGetTidCachingWithFork(int (*fork_fn)(), void (*exit_fn)(int)) {
525 pid_t parent_tid = GetTidForTest();
526 ASSERT_EQ(syscall(__NR_gettid), parent_tid);
527
528 pid_t fork_result = fork_fn();
529 ASSERT_NE(fork_result, -1);
530 if (fork_result == 0) {
531 // We're the child.
532 EXPECT_EQ(syscall(__NR_getpid), syscall(__NR_gettid));
533 EXPECT_EQ(getpid(), GetTidForTest()) << "real tid is " << syscall(__NR_gettid)
534 << ", pid is " << syscall(__NR_getpid);
535 ASSERT_NO_FATAL_FAILURE(AssertGetTidCorrect());
536 exit_fn(123);
537 } else {
538 // We're the parent.
539 ASSERT_EQ(parent_tid, GetTidForTest());
540 AssertChildExited(fork_result, 123);
541 }
542 }
543
TEST(UNISTD_TEST,getpid_caching_and_fork)544 TEST(UNISTD_TEST, getpid_caching_and_fork) {
545 TestGetPidCachingWithFork(fork, exit);
546 }
547
TEST(UNISTD_TEST,gettid_caching_and_fork)548 TEST(UNISTD_TEST, gettid_caching_and_fork) {
549 TestGetTidCachingWithFork(fork, exit);
550 }
551
TEST(UNISTD_TEST,getpid_caching_and_vfork)552 TEST(UNISTD_TEST, getpid_caching_and_vfork) {
553 TestGetPidCachingWithFork(vfork, _exit);
554 }
555
CloneLikeFork()556 static int CloneLikeFork() {
557 return clone(nullptr, nullptr, SIGCHLD, nullptr);
558 }
559
TEST(UNISTD_TEST,getpid_caching_and_clone_process)560 TEST(UNISTD_TEST, getpid_caching_and_clone_process) {
561 TestGetPidCachingWithFork(CloneLikeFork, exit);
562 }
563
TEST(UNISTD_TEST,gettid_caching_and_clone_process)564 TEST(UNISTD_TEST, gettid_caching_and_clone_process) {
565 TestGetTidCachingWithFork(CloneLikeFork, exit);
566 }
567
CloneAndSetTid()568 static int CloneAndSetTid() {
569 pid_t child_tid = 0;
570 pid_t parent_tid = GetTidForTest();
571
572 int rv = clone(nullptr, nullptr, CLONE_CHILD_SETTID | SIGCHLD, nullptr, nullptr, nullptr, &child_tid);
573 EXPECT_NE(-1, rv);
574
575 if (rv == 0) {
576 // Child.
577 EXPECT_EQ(child_tid, GetTidForTest());
578 EXPECT_NE(child_tid, parent_tid);
579 } else {
580 EXPECT_NE(child_tid, GetTidForTest());
581 EXPECT_NE(child_tid, parent_tid);
582 EXPECT_EQ(GetTidForTest(), parent_tid);
583 }
584
585 return rv;
586 }
587
TEST(UNISTD_TEST,gettid_caching_and_clone_process_settid)588 TEST(UNISTD_TEST, gettid_caching_and_clone_process_settid) {
589 TestGetTidCachingWithFork(CloneAndSetTid, exit);
590 }
591
592 __attribute__((no_sanitize("hwaddress", "memtag")))
CloneStartRoutine(int (* start_routine)(void *))593 static int CloneStartRoutine(int (*start_routine)(void*)) {
594 void* child_stack[1024];
595 return clone(start_routine, &child_stack[1024], SIGCHLD, nullptr);
596 }
597
GetPidCachingCloneStartRoutine(void *)598 static int GetPidCachingCloneStartRoutine(void*) {
599 AssertGetPidCorrect();
600 return 123;
601 }
602
TEST(UNISTD_TEST,getpid_caching_and_clone)603 TEST(UNISTD_TEST, getpid_caching_and_clone) {
604 pid_t parent_pid = getpid();
605 ASSERT_EQ(syscall(__NR_getpid), parent_pid);
606
607 int clone_result = CloneStartRoutine(GetPidCachingCloneStartRoutine);
608 ASSERT_NE(clone_result, -1);
609
610 ASSERT_EQ(parent_pid, getpid());
611
612 AssertChildExited(clone_result, 123);
613 }
614
GetTidCachingCloneStartRoutine(void *)615 static int GetTidCachingCloneStartRoutine(void*) {
616 AssertGetTidCorrect();
617 return 123;
618 }
619
TEST(UNISTD_TEST,gettid_caching_and_clone)620 TEST(UNISTD_TEST, gettid_caching_and_clone) {
621 pid_t parent_tid = GetTidForTest();
622 ASSERT_EQ(syscall(__NR_gettid), parent_tid);
623
624 int clone_result = CloneStartRoutine(GetTidCachingCloneStartRoutine);
625 ASSERT_NE(clone_result, -1);
626
627 ASSERT_EQ(parent_tid, GetTidForTest());
628
629 AssertChildExited(clone_result, 123);
630 }
631
CloneChildExit(void *)632 static int CloneChildExit(void*) {
633 AssertGetPidCorrect();
634 AssertGetTidCorrect();
635 exit(33);
636 }
637
TEST(UNISTD_TEST,clone_fn_and_exit)638 TEST(UNISTD_TEST, clone_fn_and_exit) {
639 int clone_result = CloneStartRoutine(CloneChildExit);
640 ASSERT_NE(-1, clone_result);
641
642 AssertGetPidCorrect();
643 AssertGetTidCorrect();
644
645 AssertChildExited(clone_result, 33);
646 }
647
GetPidCachingPthreadStartRoutine(void *)648 static void* GetPidCachingPthreadStartRoutine(void*) {
649 AssertGetPidCorrect();
650 return nullptr;
651 }
652
TEST(UNISTD_TEST,getpid_caching_and_pthread_create)653 TEST(UNISTD_TEST, getpid_caching_and_pthread_create) {
654 pid_t parent_pid = getpid();
655
656 pthread_t t;
657 ASSERT_EQ(0, pthread_create(&t, nullptr, GetPidCachingPthreadStartRoutine, nullptr));
658
659 ASSERT_EQ(parent_pid, getpid());
660
661 void* result;
662 ASSERT_EQ(0, pthread_join(t, &result));
663 ASSERT_EQ(nullptr, result);
664 }
665
GetTidCachingPthreadStartRoutine(void *)666 static void* GetTidCachingPthreadStartRoutine(void*) {
667 AssertGetTidCorrect();
668 uint64_t tid = GetTidForTest();
669 return reinterpret_cast<void*>(tid);
670 }
671
TEST(UNISTD_TEST,gettid_caching_and_pthread_create)672 TEST(UNISTD_TEST, gettid_caching_and_pthread_create) {
673 pid_t parent_tid = GetTidForTest();
674
675 pthread_t t;
676 ASSERT_EQ(0, pthread_create(&t, nullptr, GetTidCachingPthreadStartRoutine, &parent_tid));
677
678 ASSERT_EQ(parent_tid, GetTidForTest());
679
680 void* result;
681 ASSERT_EQ(0, pthread_join(t, &result));
682 ASSERT_NE(static_cast<uint64_t>(parent_tid), reinterpret_cast<uint64_t>(result));
683 }
684
HwasanVforkTestChild()685 __attribute__((noinline)) static void HwasanVforkTestChild() {
686 // Allocate a tagged region on stack and leave it there.
687 char x[10000];
688 DoNotOptimize(x);
689 _exit(0);
690 }
691
HwasanReadMemory(const char * p,size_t size)692 __attribute__((noinline)) static void HwasanReadMemory(const char* p, size_t size) {
693 // Read memory byte-by-byte. This will blow up if the pointer tag in p does not match any memory
694 // tag in [p, p+size).
695 char z;
696 for (size_t i = 0; i < size; ++i) {
697 DoNotOptimize(z = p[i]);
698 }
699 }
700
HwasanVforkTestParent()701 __attribute__((noinline, no_sanitize("hwaddress"))) static void HwasanVforkTestParent() {
702 // Allocate a region on stack, but don't tag it (see the function attribute).
703 // This depends on unallocated stack space at current function entry being untagged.
704 char x[10000];
705 DoNotOptimize(x);
706 // Verify that contents of x[] are untagged.
707 HwasanReadMemory(x, sizeof(x));
708 }
709
TEST(UNISTD_TEST,hwasan_vfork)710 TEST(UNISTD_TEST, hwasan_vfork) {
711 // Test hwasan annotation in vfork. This test is only interesting when built with hwasan, but it
712 // is supposed to work correctly either way.
713 if (vfork()) {
714 HwasanVforkTestParent();
715 } else {
716 HwasanVforkTestChild();
717 }
718 }
719
TEST_F(UNISTD_DEATHTEST,abort)720 TEST_F(UNISTD_DEATHTEST, abort) {
721 ASSERT_EXIT(abort(), testing::KilledBySignal(SIGABRT), "");
722 }
723
TEST(UNISTD_TEST,sethostname)724 TEST(UNISTD_TEST, sethostname) {
725 // The permissions check happens before the argument check, so this will
726 // fail for a different reason if you're running as root than if you're
727 // not, but it'll fail either way. Checking that we have the symbol is about
728 // all we can do for sethostname(2).
729 ASSERT_EQ(-1, sethostname("", -1));
730 }
731
TEST(UNISTD_TEST,gethostname)732 TEST(UNISTD_TEST, gethostname) {
733 char hostname[HOST_NAME_MAX + 1];
734 memset(hostname, 0, sizeof(hostname));
735
736 // Can we get the hostname with a big buffer?
737 ASSERT_EQ(0, gethostname(hostname, HOST_NAME_MAX));
738
739 // Can we get the hostname with a right-sized buffer?
740 errno = 0;
741 ASSERT_EQ(0, gethostname(hostname, strlen(hostname) + 1));
742
743 // Does uname(2) agree?
744 utsname buf;
745 ASSERT_EQ(0, uname(&buf));
746 ASSERT_EQ(0, strncmp(hostname, buf.nodename, sizeof(buf.nodename)));
747 ASSERT_GT(strlen(hostname), 0U);
748
749 // Do we correctly detect truncation?
750 errno = 0;
751 ASSERT_EQ(-1, gethostname(hostname, strlen(hostname)));
752 ASSERT_EQ(ENAMETOOLONG, errno);
753 }
754
TEST(UNISTD_TEST,pathconf_fpathconf)755 TEST(UNISTD_TEST, pathconf_fpathconf) {
756 TemporaryFile tf;
757 long rc = 0L;
758 // As a file system's block size is always power of 2, the configure values
759 // for ALLOC and XFER should be power of 2 as well.
760 rc = pathconf(tf.path, _PC_ALLOC_SIZE_MIN);
761 ASSERT_TRUE(rc > 0 && powerof2(rc));
762 rc = pathconf(tf.path, _PC_REC_MIN_XFER_SIZE);
763 ASSERT_TRUE(rc > 0 && powerof2(rc));
764 rc = pathconf(tf.path, _PC_REC_XFER_ALIGN);
765 ASSERT_TRUE(rc > 0 && powerof2(rc));
766
767 rc = fpathconf(tf.fd, _PC_ALLOC_SIZE_MIN);
768 ASSERT_TRUE(rc > 0 && powerof2(rc));
769 rc = fpathconf(tf.fd, _PC_REC_MIN_XFER_SIZE);
770 ASSERT_TRUE(rc > 0 && powerof2(rc));
771 rc = fpathconf(tf.fd, _PC_REC_XFER_ALIGN);
772 ASSERT_TRUE(rc > 0 && powerof2(rc));
773 }
774
TEST(UNISTD_TEST,_POSIX_constants)775 TEST(UNISTD_TEST, _POSIX_constants) {
776 // Make a tight verification of _POSIX_* / _POSIX2_* / _XOPEN_* macros, to prevent change by mistake.
777 // Verify according to POSIX.1-2008.
778 EXPECT_EQ(200809L, _POSIX_VERSION);
779
780 EXPECT_EQ(2, _POSIX_AIO_LISTIO_MAX);
781 EXPECT_EQ(1, _POSIX_AIO_MAX);
782 EXPECT_EQ(4096, _POSIX_ARG_MAX);
783 EXPECT_EQ(25, _POSIX_CHILD_MAX);
784 EXPECT_EQ(20000000, _POSIX_CLOCKRES_MIN);
785 EXPECT_EQ(32, _POSIX_DELAYTIMER_MAX);
786 EXPECT_EQ(255, _POSIX_HOST_NAME_MAX);
787 EXPECT_EQ(8, _POSIX_LINK_MAX);
788 EXPECT_EQ(9, _POSIX_LOGIN_NAME_MAX);
789 EXPECT_EQ(255, _POSIX_MAX_CANON);
790 EXPECT_EQ(255, _POSIX_MAX_INPUT);
791 EXPECT_EQ(8, _POSIX_MQ_OPEN_MAX);
792 EXPECT_EQ(32, _POSIX_MQ_PRIO_MAX);
793 EXPECT_EQ(14, _POSIX_NAME_MAX);
794 EXPECT_EQ(8, _POSIX_NGROUPS_MAX);
795 EXPECT_EQ(20, _POSIX_OPEN_MAX);
796 EXPECT_EQ(256, _POSIX_PATH_MAX);
797 EXPECT_EQ(512, _POSIX_PIPE_BUF);
798 EXPECT_EQ(255, _POSIX_RE_DUP_MAX);
799 EXPECT_EQ(8, _POSIX_RTSIG_MAX);
800 EXPECT_EQ(256, _POSIX_SEM_NSEMS_MAX);
801 EXPECT_EQ(32767, _POSIX_SEM_VALUE_MAX);
802 EXPECT_EQ(32, _POSIX_SIGQUEUE_MAX);
803 EXPECT_EQ(32767, _POSIX_SSIZE_MAX);
804 EXPECT_EQ(8, _POSIX_STREAM_MAX);
805 #if !defined(__GLIBC__)
806 EXPECT_EQ(4, _POSIX_SS_REPL_MAX);
807 #endif
808 EXPECT_EQ(255, _POSIX_SYMLINK_MAX);
809 EXPECT_EQ(8, _POSIX_SYMLOOP_MAX);
810 EXPECT_EQ(4, _POSIX_THREAD_DESTRUCTOR_ITERATIONS);
811 EXPECT_EQ(128, _POSIX_THREAD_KEYS_MAX);
812 EXPECT_EQ(64, _POSIX_THREAD_THREADS_MAX);
813 EXPECT_EQ(32, _POSIX_TIMER_MAX);
814 #if !defined(__GLIBC__)
815 EXPECT_EQ(30, _POSIX_TRACE_EVENT_NAME_MAX);
816 EXPECT_EQ(8, _POSIX_TRACE_NAME_MAX);
817 EXPECT_EQ(8, _POSIX_TRACE_SYS_MAX);
818 EXPECT_EQ(32, _POSIX_TRACE_USER_EVENT_MAX);
819 #endif
820 EXPECT_EQ(9, _POSIX_TTY_NAME_MAX);
821 EXPECT_EQ(6, _POSIX_TZNAME_MAX);
822 EXPECT_EQ(99, _POSIX2_BC_BASE_MAX);
823 EXPECT_EQ(2048, _POSIX2_BC_DIM_MAX);
824 EXPECT_EQ(99, _POSIX2_BC_SCALE_MAX);
825 EXPECT_EQ(1000, _POSIX2_BC_STRING_MAX);
826 EXPECT_EQ(14, _POSIX2_CHARCLASS_NAME_MAX);
827 EXPECT_EQ(2, _POSIX2_COLL_WEIGHTS_MAX);
828 EXPECT_EQ(32, _POSIX2_EXPR_NEST_MAX);
829 EXPECT_EQ(2048, _POSIX2_LINE_MAX);
830 EXPECT_EQ(255, _POSIX2_RE_DUP_MAX);
831
832 EXPECT_EQ(16, _XOPEN_IOV_MAX);
833 #if !defined(__GLIBC__)
834 EXPECT_EQ(255, _XOPEN_NAME_MAX);
835 EXPECT_EQ(1024, _XOPEN_PATH_MAX);
836 #endif
837 }
838
TEST(UNISTD_TEST,_POSIX_options)839 TEST(UNISTD_TEST, _POSIX_options) {
840 EXPECT_EQ(_POSIX_VERSION, _POSIX_ADVISORY_INFO);
841 EXPECT_GT(_POSIX_BARRIERS, 0);
842 EXPECT_GT(_POSIX_SPIN_LOCKS, 0);
843 EXPECT_NE(_POSIX_CHOWN_RESTRICTED, -1);
844 EXPECT_EQ(_POSIX_VERSION, _POSIX_CLOCK_SELECTION);
845 #if !defined(__GLIBC__) // glibc supports ancient kernels.
846 EXPECT_EQ(_POSIX_VERSION, _POSIX_CPUTIME);
847 #endif
848 EXPECT_EQ(_POSIX_VERSION, _POSIX_FSYNC);
849 EXPECT_EQ(_POSIX_VERSION, _POSIX_IPV6);
850 EXPECT_GT(_POSIX_JOB_CONTROL, 0);
851 EXPECT_EQ(_POSIX_VERSION, _POSIX_MAPPED_FILES);
852 EXPECT_EQ(_POSIX_VERSION, _POSIX_MEMLOCK);
853 EXPECT_EQ(_POSIX_VERSION, _POSIX_MEMLOCK_RANGE);
854 EXPECT_EQ(_POSIX_VERSION, _POSIX_MEMORY_PROTECTION);
855 #if !defined(__GLIBC__) // glibc supports ancient kernels.
856 EXPECT_EQ(_POSIX_VERSION, _POSIX_MONOTONIC_CLOCK);
857 #endif
858 EXPECT_GT(_POSIX_NO_TRUNC, 0);
859 #if !defined(ANDROID_HOST_MUSL)
860 EXPECT_EQ(_POSIX_VERSION, _POSIX_PRIORITY_SCHEDULING);
861 #endif
862 EXPECT_EQ(_POSIX_VERSION, _POSIX_RAW_SOCKETS);
863 EXPECT_EQ(_POSIX_VERSION, _POSIX_READER_WRITER_LOCKS);
864 EXPECT_EQ(_POSIX_VERSION, _POSIX_REALTIME_SIGNALS);
865 EXPECT_GT(_POSIX_REGEXP, 0);
866 EXPECT_GT(_POSIX_SAVED_IDS, 0);
867 EXPECT_EQ(_POSIX_VERSION, _POSIX_SEMAPHORES);
868 EXPECT_GT(_POSIX_SHELL, 0);
869 EXPECT_EQ(_POSIX_VERSION, _POSIX_SPAWN);
870 #if !defined(ANDROID_HOST_MUSL)
871 EXPECT_EQ(-1, _POSIX_SPORADIC_SERVER);
872 EXPECT_EQ(_POSIX_VERSION, _POSIX_SYNCHRONIZED_IO);
873 #endif
874 EXPECT_EQ(_POSIX_VERSION, _POSIX_THREADS);
875 EXPECT_EQ(_POSIX_VERSION, _POSIX_THREAD_ATTR_STACKADDR);
876 EXPECT_EQ(_POSIX_VERSION, _POSIX_THREAD_ATTR_STACKSIZE);
877 #if !defined(__GLIBC__) // glibc supports ancient kernels.
878 EXPECT_EQ(_POSIX_VERSION, _POSIX_THREAD_CPUTIME);
879 #endif
880 EXPECT_EQ(_POSIX_VERSION, _POSIX_THREAD_PRIORITY_SCHEDULING);
881 EXPECT_EQ(_POSIX_VERSION, _POSIX_THREAD_PROCESS_SHARED);
882 #if !defined(ANDROID_HOST_MUSL)
883 EXPECT_EQ(-1, _POSIX_THREAD_ROBUST_PRIO_PROTECT);
884 #endif
885 EXPECT_EQ(_POSIX_VERSION, _POSIX_THREAD_SAFE_FUNCTIONS);
886 #if !defined(ANDROID_HOST_MUSL)
887 EXPECT_EQ(-1, _POSIX_THREAD_SPORADIC_SERVER);
888 #endif
889 EXPECT_EQ(_POSIX_VERSION, _POSIX_TIMEOUTS);
890 EXPECT_EQ(_POSIX_VERSION, _POSIX_TIMERS);
891 #if !defined(ANDROID_HOST_MUSL)
892 EXPECT_EQ(-1, _POSIX_TRACE);
893 EXPECT_EQ(-1, _POSIX_TRACE_EVENT_FILTER);
894 EXPECT_EQ(-1, _POSIX_TRACE_INHERIT);
895 EXPECT_EQ(-1, _POSIX_TRACE_LOG);
896 EXPECT_EQ(-1, _POSIX_TYPED_MEMORY_OBJECTS);
897 #endif
898 EXPECT_NE(-1, _POSIX_VDISABLE);
899
900 EXPECT_EQ(_POSIX_VERSION, _POSIX2_VERSION);
901 EXPECT_EQ(_POSIX_VERSION, _POSIX2_C_BIND);
902 #if !defined(ANDROID_HOST_MUSL)
903 EXPECT_EQ(_POSIX_VERSION, _POSIX2_CHAR_TERM);
904 #endif
905
906 EXPECT_EQ(700, _XOPEN_VERSION);
907 EXPECT_EQ(1, _XOPEN_ENH_I18N);
908 #if !defined(ANDROID_HOST_MUSL)
909 EXPECT_EQ(1, _XOPEN_REALTIME);
910 EXPECT_EQ(1, _XOPEN_REALTIME_THREADS);
911 EXPECT_EQ(1, _XOPEN_SHM);
912 #endif
913 EXPECT_EQ(1, _XOPEN_UNIX);
914
915 #if defined(__BIONIC__)
916 // These tests only pass on bionic, as bionic and glibc has different support on these macros.
917 // Macros like _POSIX_ASYNCHRONOUS_IO are not supported on bionic yet.
918 EXPECT_EQ(-1, _POSIX_ASYNCHRONOUS_IO);
919 EXPECT_EQ(-1, _POSIX_MESSAGE_PASSING);
920 EXPECT_EQ(-1, _POSIX_PRIORITIZED_IO);
921 EXPECT_EQ(-1, _POSIX_SHARED_MEMORY_OBJECTS);
922 EXPECT_EQ(-1, _POSIX_THREAD_PRIO_INHERIT);
923 EXPECT_EQ(-1, _POSIX_THREAD_PRIO_PROTECT);
924 EXPECT_EQ(-1, _POSIX_THREAD_ROBUST_PRIO_INHERIT);
925
926 EXPECT_EQ(-1, _POSIX2_C_DEV);
927 EXPECT_EQ(-1, _POSIX2_FORT_DEV);
928 EXPECT_EQ(-1, _POSIX2_FORT_RUN);
929 EXPECT_EQ(-1, _POSIX2_LOCALEDEF);
930 EXPECT_EQ(-1, _POSIX2_SW_DEV);
931 EXPECT_EQ(-1, _POSIX2_UPE);
932
933 EXPECT_EQ(-1, _XOPEN_CRYPT);
934 EXPECT_EQ(-1, _XOPEN_LEGACY);
935 EXPECT_EQ(-1, _XOPEN_STREAMS);
936 #endif // defined(__BIONIC__)
937 }
938
939 #define VERIFY_SYSCONF_UNKNOWN(name) \
940 VerifySysconf(name, #name, [](long v){return v == -1 && errno == EINVAL;})
941
942 #define VERIFY_SYSCONF_UNSUPPORTED(name) \
943 VerifySysconf(name, #name, [](long v){return v == -1 && errno == 0;})
944
945 // sysconf() means unlimited when it returns -1 with errno unchanged.
946 #define VERIFY_SYSCONF_POSITIVE(name) \
947 VerifySysconf(name, #name, [](long v){return (v > 0 || v == -1) && errno == 0;})
948
949 #define VERIFY_SYSCONF_POSIX_VERSION(name) \
950 VerifySysconf(name, #name, [](long v){return v == _POSIX_VERSION && errno == 0;})
951
VerifySysconf(int option,const char * option_name,bool (* verify)(long))952 static void VerifySysconf(int option, const char *option_name, bool (*verify)(long)) {
953 errno = 0;
954 long ret = sysconf(option);
955 EXPECT_TRUE(verify(ret)) << "name = " << option_name << ", ret = "
956 << ret <<", Error Message: " << strerror(errno);
957 }
958
TEST(UNISTD_TEST,sysconf)959 TEST(UNISTD_TEST, sysconf) {
960 VERIFY_SYSCONF_POSIX_VERSION(_SC_ADVISORY_INFO);
961 VERIFY_SYSCONF_POSITIVE(_SC_ARG_MAX);
962 VERIFY_SYSCONF_POSIX_VERSION(_SC_BARRIERS);
963 VERIFY_SYSCONF_POSITIVE(_SC_BC_BASE_MAX);
964 VERIFY_SYSCONF_POSITIVE(_SC_BC_DIM_MAX);
965 VERIFY_SYSCONF_POSITIVE(_SC_BC_SCALE_MAX);
966 VERIFY_SYSCONF_POSITIVE(_SC_CHILD_MAX);
967 VERIFY_SYSCONF_POSITIVE(_SC_CLK_TCK);
968 VERIFY_SYSCONF_POSITIVE(_SC_COLL_WEIGHTS_MAX);
969 VERIFY_SYSCONF_POSIX_VERSION(_SC_CPUTIME);
970 VERIFY_SYSCONF_POSITIVE(_SC_EXPR_NEST_MAX);
971 VERIFY_SYSCONF_POSITIVE(_SC_LINE_MAX);
972 VERIFY_SYSCONF_POSITIVE(_SC_NGROUPS_MAX);
973 VERIFY_SYSCONF_POSITIVE(_SC_OPEN_MAX);
974 VERIFY_SYSCONF_POSITIVE(_SC_PASS_MAX);
975 VERIFY_SYSCONF_POSIX_VERSION(_SC_2_C_BIND);
976 VERIFY_SYSCONF_UNSUPPORTED(_SC_2_FORT_DEV);
977 VERIFY_SYSCONF_UNSUPPORTED(_SC_2_FORT_RUN);
978 VERIFY_SYSCONF_UNSUPPORTED(_SC_2_UPE);
979 VERIFY_SYSCONF_POSIX_VERSION(_SC_2_VERSION);
980 VERIFY_SYSCONF_POSITIVE(_SC_JOB_CONTROL);
981 VERIFY_SYSCONF_POSITIVE(_SC_SAVED_IDS);
982 VERIFY_SYSCONF_POSIX_VERSION(_SC_VERSION);
983 VERIFY_SYSCONF_POSITIVE(_SC_RE_DUP_MAX);
984 VERIFY_SYSCONF_POSITIVE(_SC_STREAM_MAX);
985 VERIFY_SYSCONF_POSITIVE(_SC_TZNAME_MAX);
986 VerifySysconf(_SC_XOPEN_VERSION, "_SC_XOPEN_VERSION", [](long v){return v == _XOPEN_VERSION && errno == 0;});
987 VERIFY_SYSCONF_POSITIVE(_SC_ATEXIT_MAX);
988 VERIFY_SYSCONF_POSITIVE(_SC_IOV_MAX);
989 VERIFY_SYSCONF_POSITIVE(_SC_UIO_MAXIOV);
990 EXPECT_EQ(sysconf(_SC_IOV_MAX), sysconf(_SC_UIO_MAXIOV));
991 VERIFY_SYSCONF_POSITIVE(_SC_PAGESIZE);
992 VERIFY_SYSCONF_POSITIVE(_SC_PAGE_SIZE);
993 VerifySysconf(_SC_PAGE_SIZE, "_SC_PAGE_SIZE",
994 [](long v){return v == sysconf(_SC_PAGESIZE) && errno == 0 && v == getpagesize();});
995 VERIFY_SYSCONF_POSITIVE(_SC_XOPEN_UNIX);
996 VERIFY_SYSCONF_POSITIVE(_SC_AIO_LISTIO_MAX);
997 VERIFY_SYSCONF_POSITIVE(_SC_AIO_MAX);
998 VerifySysconf(_SC_AIO_PRIO_DELTA_MAX, "_SC_AIO_PRIO_DELTA_MAX", [](long v){return v >= 0 && errno == 0;});
999 VERIFY_SYSCONF_POSITIVE(_SC_DELAYTIMER_MAX);
1000 VERIFY_SYSCONF_POSITIVE(_SC_MQ_OPEN_MAX);
1001 VERIFY_SYSCONF_POSITIVE(_SC_MQ_PRIO_MAX);
1002 VERIFY_SYSCONF_POSITIVE(_SC_RTSIG_MAX);
1003 VERIFY_SYSCONF_POSITIVE(_SC_SEM_NSEMS_MAX);
1004 VERIFY_SYSCONF_POSITIVE(_SC_SEM_VALUE_MAX);
1005 VERIFY_SYSCONF_POSIX_VERSION(_SC_SPIN_LOCKS);
1006 VERIFY_SYSCONF_POSITIVE(_SC_TIMER_MAX);
1007 VERIFY_SYSCONF_POSIX_VERSION(_SC_FSYNC);
1008 VERIFY_SYSCONF_POSIX_VERSION(_SC_MAPPED_FILES);
1009 VERIFY_SYSCONF_POSIX_VERSION(_SC_MEMLOCK);
1010 VERIFY_SYSCONF_POSIX_VERSION(_SC_MEMLOCK_RANGE);
1011 VERIFY_SYSCONF_POSIX_VERSION(_SC_MEMORY_PROTECTION);
1012 VERIFY_SYSCONF_POSIX_VERSION(_SC_PRIORITY_SCHEDULING);
1013 VERIFY_SYSCONF_POSIX_VERSION(_SC_REALTIME_SIGNALS);
1014 VERIFY_SYSCONF_POSIX_VERSION(_SC_SEMAPHORES);
1015 VERIFY_SYSCONF_POSIX_VERSION(_SC_SYNCHRONIZED_IO);
1016 VERIFY_SYSCONF_POSIX_VERSION(_SC_TIMERS);
1017 VERIFY_SYSCONF_POSITIVE(_SC_GETGR_R_SIZE_MAX);
1018 VERIFY_SYSCONF_POSITIVE(_SC_GETPW_R_SIZE_MAX);
1019 VERIFY_SYSCONF_POSITIVE(_SC_LOGIN_NAME_MAX);
1020 VERIFY_SYSCONF_POSITIVE(_SC_THREAD_DESTRUCTOR_ITERATIONS);
1021 VERIFY_SYSCONF_POSITIVE(_SC_THREAD_KEYS_MAX);
1022 VERIFY_SYSCONF_POSITIVE(_SC_THREAD_STACK_MIN);
1023 VERIFY_SYSCONF_POSITIVE(_SC_THREAD_THREADS_MAX);
1024 VERIFY_SYSCONF_POSITIVE(_SC_TTY_NAME_MAX);
1025 VERIFY_SYSCONF_POSIX_VERSION(_SC_THREADS);
1026 VERIFY_SYSCONF_POSIX_VERSION(_SC_THREAD_ATTR_STACKADDR);
1027 VERIFY_SYSCONF_POSIX_VERSION(_SC_THREAD_ATTR_STACKSIZE);
1028 VERIFY_SYSCONF_POSIX_VERSION(_SC_THREAD_PRIORITY_SCHEDULING);
1029 VERIFY_SYSCONF_UNSUPPORTED(_SC_THREAD_PRIO_INHERIT);
1030 VERIFY_SYSCONF_UNSUPPORTED(_SC_THREAD_PRIO_PROTECT);
1031 VERIFY_SYSCONF_POSIX_VERSION(_SC_THREAD_SAFE_FUNCTIONS);
1032 VERIFY_SYSCONF_POSITIVE(_SC_NPROCESSORS_CONF);
1033 VERIFY_SYSCONF_POSITIVE(_SC_NPROCESSORS_ONLN);
1034 VERIFY_SYSCONF_POSITIVE(_SC_PHYS_PAGES);
1035 VERIFY_SYSCONF_POSITIVE(_SC_AVPHYS_PAGES);
1036 VERIFY_SYSCONF_POSIX_VERSION(_SC_MONOTONIC_CLOCK);
1037 VERIFY_SYSCONF_UNSUPPORTED(_SC_2_PBS);
1038 VERIFY_SYSCONF_UNSUPPORTED(_SC_2_PBS_ACCOUNTING);
1039 VERIFY_SYSCONF_UNSUPPORTED(_SC_2_PBS_CHECKPOINT);
1040 VERIFY_SYSCONF_UNSUPPORTED(_SC_2_PBS_LOCATE);
1041 VERIFY_SYSCONF_UNSUPPORTED(_SC_2_PBS_MESSAGE);
1042 VERIFY_SYSCONF_UNSUPPORTED(_SC_2_PBS_TRACK);
1043 VERIFY_SYSCONF_POSIX_VERSION(_SC_CLOCK_SELECTION);
1044 VERIFY_SYSCONF_POSITIVE(_SC_HOST_NAME_MAX);
1045 VERIFY_SYSCONF_POSIX_VERSION(_SC_IPV6);
1046 VERIFY_SYSCONF_POSIX_VERSION(_SC_RAW_SOCKETS);
1047 VERIFY_SYSCONF_POSIX_VERSION(_SC_READER_WRITER_LOCKS);
1048 VERIFY_SYSCONF_POSITIVE(_SC_REGEXP);
1049 VERIFY_SYSCONF_POSITIVE(_SC_SHELL);
1050 VERIFY_SYSCONF_POSIX_VERSION(_SC_SPAWN);
1051 VERIFY_SYSCONF_UNSUPPORTED(_SC_SPORADIC_SERVER);
1052 VERIFY_SYSCONF_POSITIVE(_SC_SYMLOOP_MAX);
1053 VERIFY_SYSCONF_POSIX_VERSION(_SC_THREAD_CPUTIME);
1054 VERIFY_SYSCONF_POSIX_VERSION(_SC_THREAD_PROCESS_SHARED);
1055 VERIFY_SYSCONF_UNSUPPORTED(_SC_THREAD_SPORADIC_SERVER);
1056 VERIFY_SYSCONF_POSIX_VERSION(_SC_TIMEOUTS);
1057 VERIFY_SYSCONF_UNSUPPORTED(_SC_TRACE);
1058 VERIFY_SYSCONF_UNSUPPORTED(_SC_TRACE_EVENT_FILTER);
1059 VERIFY_SYSCONF_UNSUPPORTED(_SC_TRACE_EVENT_NAME_MAX);
1060 VERIFY_SYSCONF_UNSUPPORTED(_SC_TRACE_INHERIT);
1061 VERIFY_SYSCONF_UNSUPPORTED(_SC_TRACE_LOG);
1062 VERIFY_SYSCONF_UNSUPPORTED(_SC_TRACE_NAME_MAX);
1063 VERIFY_SYSCONF_UNSUPPORTED(_SC_TRACE_SYS_MAX);
1064 VERIFY_SYSCONF_UNSUPPORTED(_SC_TRACE_USER_EVENT_MAX);
1065 VERIFY_SYSCONF_UNSUPPORTED(_SC_TYPED_MEMORY_OBJECTS);
1066 VERIFY_SYSCONF_UNSUPPORTED(_SC_XOPEN_STREAMS);
1067
1068 #if defined(__LP64__)
1069 VERIFY_SYSCONF_UNSUPPORTED(_SC_V7_ILP32_OFF32);
1070 VERIFY_SYSCONF_UNSUPPORTED(_SC_V7_ILP32_OFFBIG);
1071 VERIFY_SYSCONF_POSITIVE(_SC_V7_LP64_OFF64);
1072 VERIFY_SYSCONF_POSITIVE(_SC_V7_LPBIG_OFFBIG);
1073 #else
1074 VERIFY_SYSCONF_POSITIVE(_SC_V7_ILP32_OFF32);
1075 #if defined(__BIONIC__)
1076 // bionic does not support 64 bits off_t type on 32bit machine.
1077 VERIFY_SYSCONF_UNSUPPORTED(_SC_V7_ILP32_OFFBIG);
1078 #endif
1079 VERIFY_SYSCONF_UNSUPPORTED(_SC_V7_LP64_OFF64);
1080 VERIFY_SYSCONF_UNSUPPORTED(_SC_V7_LPBIG_OFFBIG);
1081 #endif
1082
1083 #if defined(__BIONIC__)
1084 // Tests can only run on bionic, as bionic and glibc have different support for these options.
1085 // Below options are not supported on bionic yet.
1086 VERIFY_SYSCONF_UNSUPPORTED(_SC_ASYNCHRONOUS_IO);
1087 VERIFY_SYSCONF_UNSUPPORTED(_SC_MESSAGE_PASSING);
1088 VERIFY_SYSCONF_UNSUPPORTED(_SC_PRIORITIZED_IO);
1089 VERIFY_SYSCONF_UNSUPPORTED(_SC_SHARED_MEMORY_OBJECTS);
1090 VERIFY_SYSCONF_UNSUPPORTED(_SC_THREAD_ROBUST_PRIO_INHERIT);
1091 VERIFY_SYSCONF_UNSUPPORTED(_SC_THREAD_ROBUST_PRIO_PROTECT);
1092
1093 VERIFY_SYSCONF_UNSUPPORTED(_SC_2_C_DEV);
1094 VERIFY_SYSCONF_UNSUPPORTED(_SC_2_LOCALEDEF);
1095 VERIFY_SYSCONF_UNSUPPORTED(_SC_2_SW_DEV);
1096
1097 VERIFY_SYSCONF_UNSUPPORTED(_SC_XOPEN_CRYPT);
1098 VERIFY_SYSCONF_UNSUPPORTED(_SC_XOPEN_LEGACY);
1099 VERIFY_SYSCONF_UNSUPPORTED(_SC_XOPEN_UUCP);
1100 #endif // defined(__BIONIC__)
1101 }
1102
TEST(UNISTD_TEST,get_cpu_count_from_string)1103 TEST(UNISTD_TEST, get_cpu_count_from_string) {
1104 ASSERT_EQ(0, GetCpuCountFromString(" "));
1105 ASSERT_EQ(1, GetCpuCountFromString("0"));
1106 ASSERT_EQ(40, GetCpuCountFromString("0-39"));
1107 ASSERT_EQ(4, GetCpuCountFromString("0, 1-2, 4\n"));
1108 }
1109
TEST(UNISTD_TEST,sysconf_SC_NPROCESSORS_make_sense)1110 TEST(UNISTD_TEST, sysconf_SC_NPROCESSORS_make_sense) {
1111 ASSERT_LE(sysconf(_SC_NPROCESSORS_ONLN), sysconf(_SC_NPROCESSORS_CONF));
1112 }
1113
TEST(UNISTD_TEST,sysconf_SC_NPROCESSORS_ONLN)1114 TEST(UNISTD_TEST, sysconf_SC_NPROCESSORS_ONLN) {
1115 std::string line;
1116 ASSERT_TRUE(android::base::ReadFileToString("/sys/devices/system/cpu/online", &line));
1117 long online_cpus = 0;
1118 for (const std::string& s : android::base::Split(line, ",")) {
1119 std::vector<std::string> numbers = android::base::Split(s, "-");
1120 if (numbers.size() == 1u) {
1121 online_cpus++;
1122 } else {
1123 online_cpus += atoi(numbers[1].c_str()) - atoi(numbers[0].c_str()) + 1;
1124 }
1125 }
1126 ASSERT_EQ(online_cpus, sysconf(_SC_NPROCESSORS_ONLN));
1127 }
1128
TEST(UNISTD_TEST,sysconf_SC_ARG_MAX)1129 TEST(UNISTD_TEST, sysconf_SC_ARG_MAX) {
1130 // Since Linux 2.6.23, ARG_MAX isn't a constant and depends on RLIMIT_STACK.
1131 // See prepare_arg_pages() in the kernel for the gory details:
1132 // https://elixir.bootlin.com/linux/v5.3.11/source/fs/exec.c#L451
1133
1134 // Get our current limit, and set things up so we restore the limit.
1135 rlimit rl;
1136 ASSERT_EQ(0, getrlimit(RLIMIT_STACK, &rl));
1137 uint64_t original_rlim_cur = rl.rlim_cur;
1138 if (rl.rlim_cur == RLIM_INFINITY) {
1139 rl.rlim_cur = 8 * 1024 * 1024; // Bionic reports unlimited stacks as 8MiB.
1140 }
1141 auto guard = android::base::make_scope_guard([&rl, original_rlim_cur]() {
1142 rl.rlim_cur = original_rlim_cur;
1143 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1144 });
1145
1146 // _SC_ARG_MAX should be 1/4 the stack size.
1147 EXPECT_EQ(static_cast<long>(rl.rlim_cur / 4), sysconf(_SC_ARG_MAX));
1148
1149 // If you have a really small stack, the kernel still guarantees "32 pages" (see fs/exec.c).
1150 rl.rlim_cur = 1024;
1151 rl.rlim_max = RLIM_INFINITY;
1152 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1153
1154 EXPECT_EQ(static_cast<long>(32 * sysconf(_SC_PAGE_SIZE)), sysconf(_SC_ARG_MAX));
1155
1156 // With a 128-page stack limit, we know exactly what _SC_ARG_MAX should be...
1157 rl.rlim_cur = 128 * sysconf(_SC_PAGE_SIZE);
1158 rl.rlim_max = RLIM_INFINITY;
1159 ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1160
1161 EXPECT_EQ(static_cast<long>((128 * sysconf(_SC_PAGE_SIZE)) / 4), sysconf(_SC_ARG_MAX));
1162 }
1163
TEST(UNISTD_TEST,sysconf_unknown)1164 TEST(UNISTD_TEST, sysconf_unknown) {
1165 VERIFY_SYSCONF_UNKNOWN(-1);
1166 VERIFY_SYSCONF_UNKNOWN(666);
1167 }
1168
TEST(UNISTD_TEST,dup2_same)1169 TEST(UNISTD_TEST, dup2_same) {
1170 // POSIX says of dup2:
1171 // If fildes2 is already a valid open file descriptor ...
1172 // [and] fildes is equal to fildes2 ... dup2() shall return
1173 // fildes2 without closing it.
1174 // This isn't true of dup3(2), so we need to manually implement that.
1175
1176 // Equal and valid.
1177 int fd = open("/proc/version", O_RDONLY);
1178 ASSERT_TRUE(fd != -1);
1179 ASSERT_EQ(fd, dup2(fd, fd));
1180 ASSERT_EQ(0, close(fd)); // Check that dup2 didn't close fd.
1181
1182 // Equal, but invalid.
1183 errno = 0;
1184 ASSERT_EQ(-1, dup2(fd, fd));
1185 ASSERT_EQ(EBADF, errno);
1186 }
1187
TEST(UNISTD_TEST,dup3)1188 TEST(UNISTD_TEST, dup3) {
1189 int fd = open("/proc/version", O_RDONLY);
1190 ASSERT_EQ(666, dup3(fd, 666, 0));
1191 ASSERT_FALSE(CloseOnExec(666));
1192 close(666);
1193 ASSERT_EQ(667, dup3(fd, 667, O_CLOEXEC));
1194 ASSERT_TRUE(CloseOnExec(667));
1195 close(667);
1196 close(fd);
1197 }
1198
TEST(UNISTD_TEST,lockf_smoke)1199 TEST(UNISTD_TEST, lockf_smoke) {
1200 constexpr off64_t file_size = 32*1024LL;
1201
1202 TemporaryFile tf;
1203 ASSERT_EQ(0, ftruncate(tf.fd, file_size));
1204
1205 // Lock everything.
1206 ASSERT_EQ(0, lseek64(tf.fd, 0, SEEK_SET));
1207 ASSERT_EQ(0, lockf64(tf.fd, F_LOCK, file_size));
1208
1209 // Try-lock everything, this should succeed too.
1210 ASSERT_EQ(0, lseek64(tf.fd, 0, SEEK_SET));
1211 ASSERT_EQ(0, lockf64(tf.fd, F_TLOCK, file_size));
1212
1213 // Check status.
1214 ASSERT_EQ(0, lseek64(tf.fd, 0, SEEK_SET));
1215 ASSERT_EQ(0, lockf64(tf.fd, F_TEST, file_size));
1216
1217 // Unlock file.
1218 ASSERT_EQ(0, lseek64(tf.fd, 0, SEEK_SET));
1219 ASSERT_EQ(0, lockf64(tf.fd, F_ULOCK, file_size));
1220 }
1221
TEST(UNISTD_TEST,lockf_zero)1222 TEST(UNISTD_TEST, lockf_zero) {
1223 constexpr off64_t file_size = 32*1024LL;
1224
1225 TemporaryFile tf;
1226 ASSERT_EQ(0, ftruncate(tf.fd, file_size));
1227
1228 // Lock everything by specifying a size of 0 (meaning "to the end, even if it changes").
1229 ASSERT_EQ(0, lseek64(tf.fd, 0, SEEK_SET));
1230 ASSERT_EQ(0, lockf64(tf.fd, F_LOCK, 0));
1231
1232 // Check that it's locked.
1233 ASSERT_EQ(0, lseek64(tf.fd, 0, SEEK_SET));
1234 ASSERT_EQ(0, lockf64(tf.fd, F_TEST, file_size));
1235
1236 // Move the end.
1237 ASSERT_EQ(0, ftruncate(tf.fd, 2*file_size));
1238
1239 // Check that the new section is locked too.
1240 ASSERT_EQ(file_size, lseek64(tf.fd, file_size, SEEK_SET));
1241 ASSERT_EQ(0, lockf64(tf.fd, F_TEST, 2*file_size));
1242 }
1243
TEST(UNISTD_TEST,lockf_negative)1244 TEST(UNISTD_TEST, lockf_negative) {
1245 constexpr off64_t file_size = 32*1024LL;
1246
1247 TemporaryFile tf;
1248 ASSERT_EQ(0, ftruncate(tf.fd, file_size));
1249
1250 // Lock everything, but specifying the range in reverse.
1251 ASSERT_EQ(file_size, lseek64(tf.fd, file_size, SEEK_SET));
1252 ASSERT_EQ(0, lockf64(tf.fd, F_LOCK, -file_size));
1253
1254 // Check that it's locked.
1255 ASSERT_EQ(0, lseek64(tf.fd, 0, SEEK_SET));
1256 ASSERT_EQ(0, lockf64(tf.fd, F_TEST, file_size));
1257 }
1258
TEST(UNISTD_TEST,lockf_with_child)1259 TEST(UNISTD_TEST, lockf_with_child) {
1260 constexpr off64_t file_size = 32*1024LL;
1261
1262 TemporaryFile tf;
1263 ASSERT_EQ(0, ftruncate(tf.fd, file_size));
1264
1265 // Lock everything.
1266 ASSERT_EQ(0, lseek64(tf.fd, 0, SEEK_SET));
1267 ASSERT_EQ(0, lockf64(tf.fd, F_LOCK, file_size));
1268
1269 // Fork a child process
1270 pid_t pid = fork();
1271 ASSERT_NE(-1, pid);
1272 if (pid == 0) {
1273 // Check that the child cannot lock the file.
1274 ASSERT_EQ(0, lseek64(tf.fd, 0, SEEK_SET));
1275 ASSERT_EQ(-1, lockf64(tf.fd, F_TLOCK, file_size));
1276 ASSERT_EQ(EAGAIN, errno);
1277 // Check also that it reports itself as locked.
1278 ASSERT_EQ(0, lseek64(tf.fd, 0, SEEK_SET));
1279 ASSERT_EQ(-1, lockf64(tf.fd, F_TEST, file_size));
1280 ASSERT_EQ(EACCES, errno);
1281 _exit(0);
1282 }
1283 AssertChildExited(pid, 0);
1284 }
1285
TEST(UNISTD_TEST,lockf_partial_with_child)1286 TEST(UNISTD_TEST, lockf_partial_with_child) {
1287 constexpr off64_t file_size = 32*1024LL;
1288
1289 TemporaryFile tf;
1290 ASSERT_EQ(0, ftruncate(tf.fd, file_size));
1291
1292 // Lock the first half of the file.
1293 ASSERT_EQ(0, lseek64(tf.fd, 0, SEEK_SET));
1294 ASSERT_EQ(0, lockf64(tf.fd, F_LOCK, file_size/2));
1295
1296 // Fork a child process.
1297 pid_t pid = fork();
1298 ASSERT_NE(-1, pid);
1299 if (pid == 0) {
1300 // Check that the child can lock the other half.
1301 ASSERT_EQ(file_size/2, lseek64(tf.fd, file_size/2, SEEK_SET));
1302 ASSERT_EQ(0, lockf64(tf.fd, F_TLOCK, file_size/2));
1303 // Check that the child cannot lock the first half.
1304 ASSERT_EQ(0, lseek64(tf.fd, 0, SEEK_SET));
1305 ASSERT_EQ(-1, lockf64(tf.fd, F_TEST, file_size/2));
1306 ASSERT_EQ(EACCES, errno);
1307 // Check also that it reports itself as locked.
1308 ASSERT_EQ(0, lseek64(tf.fd, 0, SEEK_SET));
1309 ASSERT_EQ(-1, lockf64(tf.fd, F_TEST, file_size/2));
1310 ASSERT_EQ(EACCES, errno);
1311 _exit(0);
1312 }
1313 AssertChildExited(pid, 0);
1314
1315 // The second half was locked by the child, but the lock disappeared
1316 // when the process exited, so check it can be locked now.
1317 ASSERT_EQ(file_size/2, lseek64(tf.fd, file_size/2, SEEK_SET));
1318 ASSERT_EQ(0, lockf64(tf.fd, F_TLOCK, file_size/2));
1319 }
1320
TEST(UNISTD_TEST,getdomainname)1321 TEST(UNISTD_TEST, getdomainname) {
1322 struct utsname u;
1323 ASSERT_EQ(0, uname(&u));
1324
1325 char buf[sizeof(u.domainname)];
1326 ASSERT_EQ(0, getdomainname(buf, sizeof(buf)));
1327 EXPECT_STREQ(u.domainname, buf);
1328
1329 #if defined(__BIONIC__)
1330 // bionic and glibc have different behaviors when len is too small
1331 ASSERT_EQ(-1, getdomainname(buf, strlen(u.domainname)));
1332 EXPECT_EQ(EINVAL, errno);
1333 #endif
1334 }
1335
TEST(UNISTD_TEST,setdomainname)1336 TEST(UNISTD_TEST, setdomainname) {
1337 __user_cap_header_struct header;
1338 memset(&header, 0, sizeof(header));
1339 header.version = _LINUX_CAPABILITY_VERSION_3;
1340
1341 __user_cap_data_struct old_caps[_LINUX_CAPABILITY_U32S_3];
1342 ASSERT_EQ(0, capget(&header, &old_caps[0]));
1343
1344 auto admin_idx = CAP_TO_INDEX(CAP_SYS_ADMIN);
1345 auto admin_mask = CAP_TO_MASK(CAP_SYS_ADMIN);
1346 bool has_admin = old_caps[admin_idx].effective & admin_mask;
1347 if (has_admin) {
1348 __user_cap_data_struct new_caps[_LINUX_CAPABILITY_U32S_3];
1349 memcpy(new_caps, old_caps, sizeof(new_caps));
1350 new_caps[admin_idx].effective &= ~admin_mask;
1351
1352 ASSERT_EQ(0, capset(&header, &new_caps[0])) << "failed to drop admin privileges";
1353 }
1354
1355 const char* name = "newdomainname";
1356 ASSERT_EQ(-1, setdomainname(name, strlen(name)));
1357 ASSERT_EQ(EPERM, errno);
1358
1359 if (has_admin) {
1360 ASSERT_EQ(0, capset(&header, &old_caps[0])) << "failed to restore admin privileges";
1361 }
1362 }
1363
TEST(UNISTD_TEST,execve_failure)1364 TEST(UNISTD_TEST, execve_failure) {
1365 ExecTestHelper eth;
1366 errno = 0;
1367 ASSERT_EQ(-1, execve("/", eth.GetArgs(), eth.GetEnv()));
1368 ASSERT_EQ(EACCES, errno);
1369 }
1370
append_llvm_cov_env_var(std::string & env_str)1371 static void append_llvm_cov_env_var(std::string& env_str) {
1372 if (getenv("LLVM_PROFILE_FILE") != nullptr)
1373 env_str.append("__LLVM_PROFILE_RT_INIT_ONCE=__LLVM_PROFILE_RT_INIT_ONCE\n");
1374 }
1375
TEST(UNISTD_TEST,execve_args)1376 TEST(UNISTD_TEST, execve_args) {
1377 // int execve(const char* path, char* argv[], char* envp[]);
1378
1379 // Test basic argument passing.
1380 ExecTestHelper eth;
1381 eth.SetArgs({"echo", "hello", "world", nullptr});
1382 eth.Run([&]() { execve(BIN_DIR "echo", eth.GetArgs(), eth.GetEnv()); }, 0, "hello world\n");
1383
1384 // Test environment variable setting too.
1385 eth.SetArgs({"printenv", nullptr});
1386 eth.SetEnv({"A=B", nullptr});
1387
1388 std::string expected_output("A=B\n");
1389 append_llvm_cov_env_var(expected_output);
1390
1391 eth.Run([&]() { execve(BIN_DIR "printenv", eth.GetArgs(), eth.GetEnv()); }, 0,
1392 expected_output.c_str());
1393 }
1394
TEST(UNISTD_TEST,execl_failure)1395 TEST(UNISTD_TEST, execl_failure) {
1396 errno = 0;
1397 ASSERT_EQ(-1, execl("/", "/", nullptr));
1398 ASSERT_EQ(EACCES, errno);
1399 }
1400
TEST(UNISTD_TEST,execl)1401 TEST(UNISTD_TEST, execl) {
1402 ExecTestHelper eth;
1403 // int execl(const char* path, const char* arg, ...);
1404 eth.Run([&]() { execl(BIN_DIR "echo", "echo", "hello", "world", nullptr); }, 0, "hello world\n");
1405 }
1406
TEST(UNISTD_TEST,execle_failure)1407 TEST(UNISTD_TEST, execle_failure) {
1408 ExecTestHelper eth;
1409 errno = 0;
1410 ASSERT_EQ(-1, execle("/", "/", nullptr, eth.GetEnv()));
1411 ASSERT_EQ(EACCES, errno);
1412 }
1413
TEST(UNISTD_TEST,execle)1414 TEST(UNISTD_TEST, execle) {
1415 ExecTestHelper eth;
1416 eth.SetEnv({"A=B", nullptr});
1417
1418 std::string expected_output("A=B\n");
1419 append_llvm_cov_env_var(expected_output);
1420
1421 // int execle(const char* path, const char* arg, ..., char* envp[]);
1422 eth.Run([&]() { execle(BIN_DIR "printenv", "printenv", nullptr, eth.GetEnv()); }, 0,
1423 expected_output.c_str());
1424 }
1425
TEST(UNISTD_TEST,execv_failure)1426 TEST(UNISTD_TEST, execv_failure) {
1427 ExecTestHelper eth;
1428 errno = 0;
1429 ASSERT_EQ(-1, execv("/", eth.GetArgs()));
1430 ASSERT_EQ(EACCES, errno);
1431 }
1432
TEST(UNISTD_TEST,execv)1433 TEST(UNISTD_TEST, execv) {
1434 ExecTestHelper eth;
1435 eth.SetArgs({"echo", "hello", "world", nullptr});
1436 // int execv(const char* path, char* argv[]);
1437 eth.Run([&]() { execv(BIN_DIR "echo", eth.GetArgs()); }, 0, "hello world\n");
1438 }
1439
TEST(UNISTD_TEST,execlp_failure)1440 TEST(UNISTD_TEST, execlp_failure) {
1441 errno = 0;
1442 ASSERT_EQ(-1, execlp("/", "/", nullptr));
1443 ASSERT_EQ(EACCES, errno);
1444 }
1445
TEST(UNISTD_TEST,execlp)1446 TEST(UNISTD_TEST, execlp) {
1447 ExecTestHelper eth;
1448 // int execlp(const char* file, const char* arg, ...);
1449 eth.Run([&]() { execlp("echo", "echo", "hello", "world", nullptr); }, 0, "hello world\n");
1450 }
1451
TEST(UNISTD_TEST,execvp_failure)1452 TEST(UNISTD_TEST, execvp_failure) {
1453 ExecTestHelper eth;
1454 eth.SetArgs({nullptr});
1455 errno = 0;
1456 ASSERT_EQ(-1, execvp("/", eth.GetArgs()));
1457 ASSERT_EQ(EACCES, errno);
1458 }
1459
TEST(UNISTD_TEST,execvp)1460 TEST(UNISTD_TEST, execvp) {
1461 ExecTestHelper eth;
1462 eth.SetArgs({"echo", "hello", "world", nullptr});
1463 // int execvp(const char* file, char* argv[]);
1464 eth.Run([&]() { execvp("echo", eth.GetArgs()); }, 0, "hello world\n");
1465 }
1466
TEST(UNISTD_TEST,execvpe_failure)1467 TEST(UNISTD_TEST, execvpe_failure) {
1468 ExecTestHelper eth;
1469 errno = 0;
1470 ASSERT_EQ(-1, execvpe("this-does-not-exist", eth.GetArgs(), eth.GetEnv()));
1471 // Running in CTS we might not even be able to search all directories in $PATH.
1472 ASSERT_TRUE(errno == ENOENT || errno == EACCES);
1473 }
1474
TEST(UNISTD_TEST,execvpe)1475 TEST(UNISTD_TEST, execvpe) {
1476 // int execvpe(const char* file, char* argv[], char* envp[]);
1477
1478 // Test basic argument passing.
1479 ExecTestHelper eth;
1480 eth.SetArgs({"echo", "hello", "world", nullptr});
1481 eth.Run([&]() { execvpe("echo", eth.GetArgs(), eth.GetEnv()); }, 0, "hello world\n");
1482
1483 // Test environment variable setting too.
1484 eth.SetArgs({"printenv", nullptr});
1485 eth.SetEnv({"A=B", nullptr});
1486
1487 std::string expected_output("A=B\n");
1488 append_llvm_cov_env_var(expected_output);
1489
1490 eth.Run([&]() { execvpe("printenv", eth.GetArgs(), eth.GetEnv()); }, 0, expected_output.c_str());
1491 }
1492
TEST(UNISTD_TEST,execvpe_ENOEXEC)1493 TEST(UNISTD_TEST, execvpe_ENOEXEC) {
1494 // Create a shell script with #!.
1495 TemporaryFile tf;
1496 ASSERT_TRUE(android::base::WriteStringToFile("#!" BIN_DIR "sh\necho script\n", tf.path));
1497
1498 // Set $PATH so we can find it.
1499 setenv("PATH", dirname(tf.path), 1);
1500
1501 ExecTestHelper eth;
1502 eth.SetArgs({basename(tf.path), nullptr});
1503
1504 // It's not inherently executable.
1505 errno = 0;
1506 ASSERT_EQ(-1, execvpe(basename(tf.path), eth.GetArgs(), eth.GetEnv()));
1507 ASSERT_EQ(EACCES, errno);
1508
1509 // Make it executable (and keep it writable because we're going to rewrite it below).
1510 ASSERT_EQ(0, chmod(tf.path, 0777));
1511
1512 // TemporaryFile will have a writable fd, so we can test ETXTBSY while we're here...
1513 errno = 0;
1514 ASSERT_EQ(-1, execvpe(basename(tf.path), eth.GetArgs(), eth.GetEnv()));
1515 ASSERT_EQ(ETXTBSY, errno);
1516
1517 // 1. The simplest test: the kernel should handle this.
1518 ASSERT_EQ(0, close(tf.fd));
1519 eth.Run([&]() { execvpe(basename(tf.path), eth.GetArgs(), eth.GetEnv()); }, 0, "script\n");
1520
1521 // 2. Try again without a #!. We should have to handle this ourselves.
1522 ASSERT_TRUE(android::base::WriteStringToFile("echo script\n", tf.path));
1523 eth.Run([&]() { execvpe(basename(tf.path), eth.GetArgs(), eth.GetEnv()); }, 0, "script\n");
1524
1525 // 3. Again without a #!, but also with a leading '/', since that's a special case in the
1526 // implementation.
1527 eth.Run([&]() { execvpe(tf.path, eth.GetArgs(), eth.GetEnv()); }, 0, "script\n");
1528 }
1529
TEST(UNISTD_TEST,execvp_libcore_test_55017)1530 TEST(UNISTD_TEST, execvp_libcore_test_55017) {
1531 ExecTestHelper eth;
1532 eth.SetArgs({"/system/bin/does-not-exist", nullptr});
1533
1534 errno = 0;
1535 ASSERT_EQ(-1, execvp("/system/bin/does-not-exist", eth.GetArgs()));
1536 ASSERT_EQ(ENOENT, errno);
1537 }
1538
TEST(UNISTD_TEST,exec_argv0_null)1539 TEST(UNISTD_TEST, exec_argv0_null) {
1540 // http://b/33276926 and http://b/227498625.
1541 //
1542 // With old kernels, bionic will see the null pointer and use "<unknown>" but
1543 // with new (5.18+) kernels, the kernel will already have substituted the
1544 // empty string, so we don't make any assertion here about what (if anything)
1545 // comes before the first ':'.
1546 //
1547 // If this ever causes trouble, we could change bionic to replace _either_ the
1548 // null pointer or the empty string. We could also use the actual name from
1549 // readlink() on /proc/self/exe if we ever had reason to disallow programs
1550 // from trying to hide like this.
1551 char* args[] = {nullptr};
1552 char* envs[] = {nullptr};
1553 ASSERT_EXIT(execve("/system/bin/run-as", args, envs), testing::ExitedWithCode(1),
1554 ": usage: run-as");
1555 }
1556
TEST(UNISTD_TEST,fexecve_failure)1557 TEST(UNISTD_TEST, fexecve_failure) {
1558 ExecTestHelper eth;
1559 errno = 0;
1560 int fd = open("/", O_RDONLY);
1561 ASSERT_NE(-1, fd);
1562 ASSERT_EQ(-1, fexecve(fd, eth.GetArgs(), eth.GetEnv()));
1563 ASSERT_EQ(EACCES, errno);
1564 close(fd);
1565 }
1566
TEST(UNISTD_TEST,fexecve_bad_fd)1567 TEST(UNISTD_TEST, fexecve_bad_fd) {
1568 ExecTestHelper eth;
1569 errno = 0;
1570 ASSERT_EQ(-1, fexecve(-1, eth.GetArgs(), eth.GetEnv()));
1571 ASSERT_EQ(EBADF, errno);
1572 }
1573
TEST(UNISTD_TEST,fexecve_args)1574 TEST(UNISTD_TEST, fexecve_args) {
1575 // Test basic argument passing.
1576 int echo_fd = open(BIN_DIR "echo", O_RDONLY | O_CLOEXEC);
1577 ASSERT_NE(-1, echo_fd);
1578 ExecTestHelper eth;
1579 eth.SetArgs({"echo", "hello", "world", nullptr});
1580 eth.Run([&]() { fexecve(echo_fd, eth.GetArgs(), eth.GetEnv()); }, 0, "hello world\n");
1581 close(echo_fd);
1582
1583 // Test environment variable setting too.
1584 int printenv_fd = open(BIN_DIR "printenv", O_RDONLY | O_CLOEXEC);
1585 ASSERT_NE(-1, printenv_fd);
1586 eth.SetArgs({"printenv", nullptr});
1587 eth.SetEnv({"A=B", nullptr});
1588
1589 std::string expected_output("A=B\n");
1590 append_llvm_cov_env_var(expected_output);
1591
1592 eth.Run([&]() { fexecve(printenv_fd, eth.GetArgs(), eth.GetEnv()); }, 0, expected_output.c_str());
1593 close(printenv_fd);
1594 }
1595
TEST(UNISTD_TEST,getlogin_r)1596 TEST(UNISTD_TEST, getlogin_r) {
1597 char buf[LOGIN_NAME_MAX] = {};
1598 EXPECT_EQ(ERANGE, getlogin_r(buf, 0));
1599 EXPECT_EQ(0, getlogin_r(buf, sizeof(buf)));
1600 EXPECT_STREQ(getlogin(), buf);
1601 }
1602
TEST(UNISTD_TEST,swab)1603 TEST(UNISTD_TEST, swab) {
1604 // POSIX: "The swab() function shall copy nbytes bytes, which are pointed to by src,
1605 // to the object pointed to by dest, exchanging adjacent bytes."
1606 char buf[BUFSIZ];
1607 memset(buf, 'x', sizeof(buf));
1608 swab("ehll oowlr\0d", buf, 12);
1609 ASSERT_STREQ("hello world", buf);
1610 }
1611
TEST(UNISTD_TEST,swab_odd_byte_count)1612 TEST(UNISTD_TEST, swab_odd_byte_count) {
1613 // POSIX: "If nbytes is odd, swab() copies and exchanges nbytes-1 bytes and the disposition
1614 // of the last byte is unspecified."
1615 // ...but it seems unreasonable to not just leave the last byte alone.
1616 char buf[BUFSIZ];
1617 memset(buf, 'x', sizeof(buf));
1618 swab("012345", buf, 3);
1619 ASSERT_EQ('1', buf[0]);
1620 ASSERT_EQ('0', buf[1]);
1621 ASSERT_EQ('x', buf[2]);
1622 }
1623
TEST(UNISTD_TEST,swab_overlap)1624 TEST(UNISTD_TEST, swab_overlap) {
1625 // POSIX: "If copying takes place between objects that overlap, the behavior is undefined."
1626 // ...but it seems unreasonable to not just do the right thing.
1627 char buf[] = "012345";
1628 swab(buf, buf, 4);
1629 ASSERT_EQ('1', buf[0]);
1630 ASSERT_EQ('0', buf[1]);
1631 ASSERT_EQ('3', buf[2]);
1632 ASSERT_EQ('2', buf[3]);
1633 ASSERT_EQ('4', buf[4]);
1634 ASSERT_EQ('5', buf[5]);
1635 ASSERT_EQ(0, buf[6]);
1636 }
1637
TEST(UNISTD_TEST,swab_negative_byte_count)1638 TEST(UNISTD_TEST, swab_negative_byte_count) {
1639 // POSIX: "If nbytes is negative, swab() does nothing."
1640 char buf[BUFSIZ];
1641 memset(buf, 'x', sizeof(buf));
1642 swab("hello", buf, -1);
1643 ASSERT_EQ('x', buf[0]);
1644 }
1645
TEST(UNISTD_TEST,usleep)1646 TEST(UNISTD_TEST, usleep) {
1647 auto t0 = std::chrono::steady_clock::now();
1648 ASSERT_EQ(0, usleep(5000));
1649 auto t1 = std::chrono::steady_clock::now();
1650 ASSERT_GE(t1-t0, 5000us);
1651 }
1652
TEST(UNISTD_TEST,sleep)1653 TEST(UNISTD_TEST, sleep) {
1654 auto t0 = std::chrono::steady_clock::now();
1655 ASSERT_EQ(0U, sleep(1));
1656 auto t1 = std::chrono::steady_clock::now();
1657 ASSERT_GE(t1-t0, 1s);
1658 }
1659
TEST(UNISTD_TEST,close_range)1660 TEST(UNISTD_TEST, close_range) {
1661 #if defined(__GLIBC__)
1662 GTEST_SKIP() << "glibc too old";
1663 #elif defined(ANDROID_HOST_MUSL)
1664 GTEST_SKIP() << "musl does not have close_range";
1665 #else // __GLIBC__
1666 int fd = open("/proc/version", O_RDONLY);
1667 ASSERT_GE(fd, 0);
1668
1669 // Try to close the file descriptor (this requires a 5.9+ kernel)
1670 if (close_range(fd, fd, 0) == 0) {
1671 // we can't close it *again*
1672 ASSERT_EQ(close(fd), -1);
1673 ASSERT_EQ(errno, EBADF);
1674 } else {
1675 ASSERT_EQ(errno, ENOSYS);
1676 // since close_range() failed, we can close it normally
1677 ASSERT_EQ(close(fd), 0);
1678 }
1679 #endif // __GLIBC__
1680 }
1681
TEST(UNISTD_TEST,copy_file_range)1682 TEST(UNISTD_TEST, copy_file_range) {
1683 #if defined(__GLIBC__)
1684 GTEST_SKIP() << "glibc too old";
1685 #else // __GLIBC__
1686 TemporaryFile tf;
1687 ASSERT_TRUE(android::base::WriteStringToFd("hello world", tf.fd));
1688 ASSERT_EQ(0, lseek(tf.fd, SEEK_SET, 0));
1689 TemporaryFile tf2;
1690 ASSERT_EQ(11, copy_file_range(tf.fd, NULL, tf2.fd, NULL, 11, 0));
1691 ASSERT_EQ(0, lseek(tf2.fd, SEEK_SET, 0));
1692 std::string content;
1693 ASSERT_TRUE(android::base::ReadFdToString(tf2.fd, &content));
1694 ASSERT_EQ("hello world", content);
1695 #endif // __GLIBC__
1696 }
1697