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