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