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