• 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)186 TEST(UNISTD_TEST, truncate64) {
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)206 TEST(UNISTD_TEST, ftruncate64) {
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   volatile char z;
692   for (size_t i = 0; i < size; ++i) {
693     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, SYS_NMLN));
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   EXPECT_EQ(_POSIX_VERSION, _POSIX_PRIORITY_SCHEDULING);
856   EXPECT_EQ(_POSIX_VERSION, _POSIX_RAW_SOCKETS);
857   EXPECT_EQ(_POSIX_VERSION, _POSIX_READER_WRITER_LOCKS);
858   EXPECT_EQ(_POSIX_VERSION, _POSIX_REALTIME_SIGNALS);
859   EXPECT_GT(_POSIX_REGEXP, 0);
860   EXPECT_GT(_POSIX_SAVED_IDS, 0);
861   EXPECT_EQ(_POSIX_VERSION, _POSIX_SEMAPHORES);
862   EXPECT_GT(_POSIX_SHELL, 0);
863   EXPECT_EQ(_POSIX_VERSION, _POSIX_SPAWN);
864   EXPECT_EQ(-1, _POSIX_SPORADIC_SERVER);
865   EXPECT_EQ(_POSIX_VERSION, _POSIX_SYNCHRONIZED_IO);
866   EXPECT_EQ(_POSIX_VERSION, _POSIX_THREADS);
867   EXPECT_EQ(_POSIX_VERSION, _POSIX_THREAD_ATTR_STACKADDR);
868   EXPECT_EQ(_POSIX_VERSION, _POSIX_THREAD_ATTR_STACKSIZE);
869 #if !defined(__GLIBC__) // glibc supports ancient kernels.
870   EXPECT_EQ(_POSIX_VERSION, _POSIX_THREAD_CPUTIME);
871 #endif
872   EXPECT_EQ(_POSIX_VERSION, _POSIX_THREAD_PRIORITY_SCHEDULING);
873   EXPECT_EQ(_POSIX_VERSION, _POSIX_THREAD_PROCESS_SHARED);
874   EXPECT_EQ(-1, _POSIX_THREAD_ROBUST_PRIO_PROTECT);
875   EXPECT_EQ(_POSIX_VERSION, _POSIX_THREAD_SAFE_FUNCTIONS);
876   EXPECT_EQ(-1, _POSIX_THREAD_SPORADIC_SERVER);
877   EXPECT_EQ(_POSIX_VERSION, _POSIX_TIMEOUTS);
878   EXPECT_EQ(_POSIX_VERSION, _POSIX_TIMERS);
879   EXPECT_EQ(-1, _POSIX_TRACE);
880   EXPECT_EQ(-1, _POSIX_TRACE_EVENT_FILTER);
881   EXPECT_EQ(-1, _POSIX_TRACE_INHERIT);
882   EXPECT_EQ(-1, _POSIX_TRACE_LOG);
883   EXPECT_EQ(-1, _POSIX_TYPED_MEMORY_OBJECTS);
884   EXPECT_NE(-1, _POSIX_VDISABLE);
885 
886   EXPECT_EQ(_POSIX_VERSION, _POSIX2_VERSION);
887   EXPECT_EQ(_POSIX_VERSION, _POSIX2_C_BIND);
888   EXPECT_EQ(_POSIX_VERSION, _POSIX2_CHAR_TERM);
889 
890   EXPECT_EQ(700, _XOPEN_VERSION);
891   EXPECT_EQ(1, _XOPEN_ENH_I18N);
892   EXPECT_EQ(1, _XOPEN_REALTIME);
893   EXPECT_EQ(1, _XOPEN_REALTIME_THREADS);
894   EXPECT_EQ(1, _XOPEN_SHM);
895   EXPECT_EQ(1, _XOPEN_UNIX);
896 
897 #if defined(__BIONIC__)
898   // These tests only pass on bionic, as bionic and glibc has different support on these macros.
899   // Macros like _POSIX_ASYNCHRONOUS_IO are not supported on bionic yet.
900   EXPECT_EQ(-1, _POSIX_ASYNCHRONOUS_IO);
901   EXPECT_EQ(-1, _POSIX_MESSAGE_PASSING);
902   EXPECT_EQ(-1, _POSIX_PRIORITIZED_IO);
903   EXPECT_EQ(-1, _POSIX_SHARED_MEMORY_OBJECTS);
904   EXPECT_EQ(-1, _POSIX_THREAD_PRIO_INHERIT);
905   EXPECT_EQ(-1, _POSIX_THREAD_PRIO_PROTECT);
906   EXPECT_EQ(-1, _POSIX_THREAD_ROBUST_PRIO_INHERIT);
907 
908   EXPECT_EQ(-1, _POSIX2_C_DEV);
909   EXPECT_EQ(-1, _POSIX2_FORT_DEV);
910   EXPECT_EQ(-1, _POSIX2_FORT_RUN);
911   EXPECT_EQ(-1, _POSIX2_LOCALEDEF);
912   EXPECT_EQ(-1, _POSIX2_SW_DEV);
913   EXPECT_EQ(-1, _POSIX2_UPE);
914 
915   EXPECT_EQ(-1, _XOPEN_CRYPT);
916   EXPECT_EQ(-1, _XOPEN_LEGACY);
917   EXPECT_EQ(-1, _XOPEN_STREAMS);
918 #endif // defined(__BIONIC__)
919 }
920 
921 #define VERIFY_SYSCONF_UNKNOWN(name) \
922   VerifySysconf(name, #name, [](long v){return v == -1 && errno == EINVAL;})
923 
924 #define VERIFY_SYSCONF_UNSUPPORTED(name) \
925   VerifySysconf(name, #name, [](long v){return v == -1 && errno == 0;})
926 
927 // sysconf() means unlimited when it returns -1 with errno unchanged.
928 #define VERIFY_SYSCONF_POSITIVE(name) \
929   VerifySysconf(name, #name, [](long v){return (v > 0 || v == -1) && errno == 0;})
930 
931 #define VERIFY_SYSCONF_POSIX_VERSION(name) \
932   VerifySysconf(name, #name, [](long v){return v == _POSIX_VERSION && errno == 0;})
933 
VerifySysconf(int option,const char * option_name,bool (* verify)(long))934 static void VerifySysconf(int option, const char *option_name, bool (*verify)(long)) {
935   errno = 0;
936   long ret = sysconf(option);
937   EXPECT_TRUE(verify(ret)) << "name = " << option_name << ", ret = "
938       << ret <<", Error Message: " << strerror(errno);
939 }
940 
TEST(UNISTD_TEST,sysconf)941 TEST(UNISTD_TEST, sysconf) {
942   VERIFY_SYSCONF_POSIX_VERSION(_SC_ADVISORY_INFO);
943   VERIFY_SYSCONF_POSITIVE(_SC_ARG_MAX);
944   VERIFY_SYSCONF_POSIX_VERSION(_SC_BARRIERS);
945   VERIFY_SYSCONF_POSITIVE(_SC_BC_BASE_MAX);
946   VERIFY_SYSCONF_POSITIVE(_SC_BC_DIM_MAX);
947   VERIFY_SYSCONF_POSITIVE(_SC_BC_SCALE_MAX);
948   VERIFY_SYSCONF_POSITIVE(_SC_CHILD_MAX);
949   VERIFY_SYSCONF_POSITIVE(_SC_CLK_TCK);
950   VERIFY_SYSCONF_POSITIVE(_SC_COLL_WEIGHTS_MAX);
951   VERIFY_SYSCONF_POSIX_VERSION(_SC_CPUTIME);
952   VERIFY_SYSCONF_POSITIVE(_SC_EXPR_NEST_MAX);
953   VERIFY_SYSCONF_POSITIVE(_SC_LINE_MAX);
954   VERIFY_SYSCONF_POSITIVE(_SC_NGROUPS_MAX);
955   VERIFY_SYSCONF_POSITIVE(_SC_OPEN_MAX);
956   VERIFY_SYSCONF_POSITIVE(_SC_PASS_MAX);
957   VERIFY_SYSCONF_POSIX_VERSION(_SC_2_C_BIND);
958   VERIFY_SYSCONF_UNSUPPORTED(_SC_2_FORT_DEV);
959   VERIFY_SYSCONF_UNSUPPORTED(_SC_2_FORT_RUN);
960   VERIFY_SYSCONF_UNSUPPORTED(_SC_2_UPE);
961   VERIFY_SYSCONF_POSIX_VERSION(_SC_2_VERSION);
962   VERIFY_SYSCONF_POSITIVE(_SC_JOB_CONTROL);
963   VERIFY_SYSCONF_POSITIVE(_SC_SAVED_IDS);
964   VERIFY_SYSCONF_POSIX_VERSION(_SC_VERSION);
965   VERIFY_SYSCONF_POSITIVE(_SC_RE_DUP_MAX);
966   VERIFY_SYSCONF_POSITIVE(_SC_STREAM_MAX);
967   VERIFY_SYSCONF_POSITIVE(_SC_TZNAME_MAX);
968   VerifySysconf(_SC_XOPEN_VERSION, "_SC_XOPEN_VERSION", [](long v){return v == _XOPEN_VERSION && errno == 0;});
969   VERIFY_SYSCONF_POSITIVE(_SC_ATEXIT_MAX);
970   VERIFY_SYSCONF_POSITIVE(_SC_IOV_MAX);
971   VERIFY_SYSCONF_POSITIVE(_SC_UIO_MAXIOV);
972   EXPECT_EQ(sysconf(_SC_IOV_MAX), sysconf(_SC_UIO_MAXIOV));
973   VERIFY_SYSCONF_POSITIVE(_SC_PAGESIZE);
974   VERIFY_SYSCONF_POSITIVE(_SC_PAGE_SIZE);
975   VerifySysconf(_SC_PAGE_SIZE, "_SC_PAGE_SIZE",
976                 [](long v){return v == sysconf(_SC_PAGESIZE) && errno == 0 && v == getpagesize();});
977   VERIFY_SYSCONF_POSITIVE(_SC_XOPEN_UNIX);
978   VERIFY_SYSCONF_POSITIVE(_SC_AIO_LISTIO_MAX);
979   VERIFY_SYSCONF_POSITIVE(_SC_AIO_MAX);
980   VerifySysconf(_SC_AIO_PRIO_DELTA_MAX, "_SC_AIO_PRIO_DELTA_MAX", [](long v){return v >= 0 && errno == 0;});
981   VERIFY_SYSCONF_POSITIVE(_SC_DELAYTIMER_MAX);
982   VERIFY_SYSCONF_POSITIVE(_SC_MQ_OPEN_MAX);
983   VERIFY_SYSCONF_POSITIVE(_SC_MQ_PRIO_MAX);
984   VERIFY_SYSCONF_POSITIVE(_SC_RTSIG_MAX);
985   VERIFY_SYSCONF_POSITIVE(_SC_SEM_NSEMS_MAX);
986   VERIFY_SYSCONF_POSITIVE(_SC_SEM_VALUE_MAX);
987   VERIFY_SYSCONF_POSIX_VERSION(_SC_SPIN_LOCKS);
988   VERIFY_SYSCONF_POSITIVE(_SC_TIMER_MAX);
989   VERIFY_SYSCONF_POSIX_VERSION(_SC_FSYNC);
990   VERIFY_SYSCONF_POSIX_VERSION(_SC_MAPPED_FILES);
991   VERIFY_SYSCONF_POSIX_VERSION(_SC_MEMLOCK);
992   VERIFY_SYSCONF_POSIX_VERSION(_SC_MEMLOCK_RANGE);
993   VERIFY_SYSCONF_POSIX_VERSION(_SC_MEMORY_PROTECTION);
994   VERIFY_SYSCONF_POSIX_VERSION(_SC_PRIORITY_SCHEDULING);
995   VERIFY_SYSCONF_POSIX_VERSION(_SC_REALTIME_SIGNALS);
996   VERIFY_SYSCONF_POSIX_VERSION(_SC_SEMAPHORES);
997   VERIFY_SYSCONF_POSIX_VERSION(_SC_SYNCHRONIZED_IO);
998   VERIFY_SYSCONF_POSIX_VERSION(_SC_TIMERS);
999   VERIFY_SYSCONF_POSITIVE(_SC_GETGR_R_SIZE_MAX);
1000   VERIFY_SYSCONF_POSITIVE(_SC_GETPW_R_SIZE_MAX);
1001   VERIFY_SYSCONF_POSITIVE(_SC_LOGIN_NAME_MAX);
1002   VERIFY_SYSCONF_POSITIVE(_SC_THREAD_DESTRUCTOR_ITERATIONS);
1003   VERIFY_SYSCONF_POSITIVE(_SC_THREAD_KEYS_MAX);
1004   VERIFY_SYSCONF_POSITIVE(_SC_THREAD_STACK_MIN);
1005   VERIFY_SYSCONF_POSITIVE(_SC_THREAD_THREADS_MAX);
1006   VERIFY_SYSCONF_POSITIVE(_SC_TTY_NAME_MAX);
1007   VERIFY_SYSCONF_POSIX_VERSION(_SC_THREADS);
1008   VERIFY_SYSCONF_POSIX_VERSION(_SC_THREAD_ATTR_STACKADDR);
1009   VERIFY_SYSCONF_POSIX_VERSION(_SC_THREAD_ATTR_STACKSIZE);
1010   VERIFY_SYSCONF_POSIX_VERSION(_SC_THREAD_PRIORITY_SCHEDULING);
1011   VERIFY_SYSCONF_UNSUPPORTED(_SC_THREAD_PRIO_INHERIT);
1012   VERIFY_SYSCONF_UNSUPPORTED(_SC_THREAD_PRIO_PROTECT);
1013   VERIFY_SYSCONF_POSIX_VERSION(_SC_THREAD_SAFE_FUNCTIONS);
1014   VERIFY_SYSCONF_POSITIVE(_SC_NPROCESSORS_CONF);
1015   VERIFY_SYSCONF_POSITIVE(_SC_NPROCESSORS_ONLN);
1016   VERIFY_SYSCONF_POSITIVE(_SC_PHYS_PAGES);
1017   VERIFY_SYSCONF_POSITIVE(_SC_AVPHYS_PAGES);
1018   VERIFY_SYSCONF_POSIX_VERSION(_SC_MONOTONIC_CLOCK);
1019   VERIFY_SYSCONF_UNSUPPORTED(_SC_2_PBS);
1020   VERIFY_SYSCONF_UNSUPPORTED(_SC_2_PBS_ACCOUNTING);
1021   VERIFY_SYSCONF_UNSUPPORTED(_SC_2_PBS_CHECKPOINT);
1022   VERIFY_SYSCONF_UNSUPPORTED(_SC_2_PBS_LOCATE);
1023   VERIFY_SYSCONF_UNSUPPORTED(_SC_2_PBS_MESSAGE);
1024   VERIFY_SYSCONF_UNSUPPORTED(_SC_2_PBS_TRACK);
1025   VERIFY_SYSCONF_POSIX_VERSION(_SC_CLOCK_SELECTION);
1026   VERIFY_SYSCONF_POSITIVE(_SC_HOST_NAME_MAX);
1027   VERIFY_SYSCONF_POSIX_VERSION(_SC_IPV6);
1028   VERIFY_SYSCONF_POSIX_VERSION(_SC_RAW_SOCKETS);
1029   VERIFY_SYSCONF_POSIX_VERSION(_SC_READER_WRITER_LOCKS);
1030   VERIFY_SYSCONF_POSITIVE(_SC_REGEXP);
1031   VERIFY_SYSCONF_POSITIVE(_SC_SHELL);
1032   VERIFY_SYSCONF_POSIX_VERSION(_SC_SPAWN);
1033   VERIFY_SYSCONF_UNSUPPORTED(_SC_SPORADIC_SERVER);
1034   VERIFY_SYSCONF_POSITIVE(_SC_SYMLOOP_MAX);
1035   VERIFY_SYSCONF_POSIX_VERSION(_SC_THREAD_CPUTIME);
1036   VERIFY_SYSCONF_POSIX_VERSION(_SC_THREAD_PROCESS_SHARED);
1037   VERIFY_SYSCONF_UNSUPPORTED(_SC_THREAD_SPORADIC_SERVER);
1038   VERIFY_SYSCONF_POSIX_VERSION(_SC_TIMEOUTS);
1039   VERIFY_SYSCONF_UNSUPPORTED(_SC_TRACE);
1040   VERIFY_SYSCONF_UNSUPPORTED(_SC_TRACE_EVENT_FILTER);
1041   VERIFY_SYSCONF_UNSUPPORTED(_SC_TRACE_EVENT_NAME_MAX);
1042   VERIFY_SYSCONF_UNSUPPORTED(_SC_TRACE_INHERIT);
1043   VERIFY_SYSCONF_UNSUPPORTED(_SC_TRACE_LOG);
1044   VERIFY_SYSCONF_UNSUPPORTED(_SC_TRACE_NAME_MAX);
1045   VERIFY_SYSCONF_UNSUPPORTED(_SC_TRACE_SYS_MAX);
1046   VERIFY_SYSCONF_UNSUPPORTED(_SC_TRACE_USER_EVENT_MAX);
1047   VERIFY_SYSCONF_UNSUPPORTED(_SC_TYPED_MEMORY_OBJECTS);
1048   VERIFY_SYSCONF_UNSUPPORTED(_SC_XOPEN_STREAMS);
1049 
1050 #if defined(__LP64__)
1051   VERIFY_SYSCONF_UNSUPPORTED(_SC_V7_ILP32_OFF32);
1052   VERIFY_SYSCONF_UNSUPPORTED(_SC_V7_ILP32_OFFBIG);
1053   VERIFY_SYSCONF_POSITIVE(_SC_V7_LP64_OFF64);
1054   VERIFY_SYSCONF_POSITIVE(_SC_V7_LPBIG_OFFBIG);
1055 #else
1056   VERIFY_SYSCONF_POSITIVE(_SC_V7_ILP32_OFF32);
1057 #if defined(__BIONIC__)
1058   // bionic does not support 64 bits off_t type on 32bit machine.
1059   VERIFY_SYSCONF_UNSUPPORTED(_SC_V7_ILP32_OFFBIG);
1060 #endif
1061   VERIFY_SYSCONF_UNSUPPORTED(_SC_V7_LP64_OFF64);
1062   VERIFY_SYSCONF_UNSUPPORTED(_SC_V7_LPBIG_OFFBIG);
1063 #endif
1064 
1065 #if defined(__BIONIC__)
1066   // Tests can only run on bionic, as bionic and glibc have different support for these options.
1067   // Below options are not supported on bionic yet.
1068   VERIFY_SYSCONF_UNSUPPORTED(_SC_ASYNCHRONOUS_IO);
1069   VERIFY_SYSCONF_UNSUPPORTED(_SC_MESSAGE_PASSING);
1070   VERIFY_SYSCONF_UNSUPPORTED(_SC_PRIORITIZED_IO);
1071   VERIFY_SYSCONF_UNSUPPORTED(_SC_SHARED_MEMORY_OBJECTS);
1072   VERIFY_SYSCONF_UNSUPPORTED(_SC_THREAD_ROBUST_PRIO_INHERIT);
1073   VERIFY_SYSCONF_UNSUPPORTED(_SC_THREAD_ROBUST_PRIO_PROTECT);
1074 
1075   VERIFY_SYSCONF_UNSUPPORTED(_SC_2_C_DEV);
1076   VERIFY_SYSCONF_UNSUPPORTED(_SC_2_LOCALEDEF);
1077   VERIFY_SYSCONF_UNSUPPORTED(_SC_2_SW_DEV);
1078 
1079   VERIFY_SYSCONF_UNSUPPORTED(_SC_XOPEN_CRYPT);
1080   VERIFY_SYSCONF_UNSUPPORTED(_SC_XOPEN_LEGACY);
1081   VERIFY_SYSCONF_UNSUPPORTED(_SC_XOPEN_UUCP);
1082 #endif // defined(__BIONIC__)
1083 }
1084 
TEST(UNISTD_TEST,get_cpu_count_from_string)1085 TEST(UNISTD_TEST, get_cpu_count_from_string) {
1086   ASSERT_EQ(0, GetCpuCountFromString(" "));
1087   ASSERT_EQ(1, GetCpuCountFromString("0"));
1088   ASSERT_EQ(40, GetCpuCountFromString("0-39"));
1089   ASSERT_EQ(4, GetCpuCountFromString("0, 1-2, 4\n"));
1090 }
1091 
TEST(UNISTD_TEST,sysconf_SC_NPROCESSORS_ONLN)1092 TEST(UNISTD_TEST, sysconf_SC_NPROCESSORS_ONLN) {
1093   std::string line;
1094   ASSERT_TRUE(android::base::ReadFileToString("/sys/devices/system/cpu/online", &line));
1095   long online_cpus = 0;
1096   for (const std::string& s : android::base::Split(line, ",")) {
1097     std::vector<std::string> numbers = android::base::Split(s, "-");
1098     if (numbers.size() == 1u) {
1099       online_cpus++;
1100     } else {
1101       online_cpus += atoi(numbers[1].c_str()) - atoi(numbers[0].c_str()) + 1;
1102     }
1103   }
1104   ASSERT_EQ(online_cpus, sysconf(_SC_NPROCESSORS_ONLN));
1105 }
1106 
TEST(UNISTD_TEST,sysconf_SC_ARG_MAX)1107 TEST(UNISTD_TEST, sysconf_SC_ARG_MAX) {
1108   // Since Linux 2.6.23, ARG_MAX isn't a constant and depends on RLIMIT_STACK.
1109   // See prepare_arg_pages() in the kernel for the gory details:
1110   // https://elixir.bootlin.com/linux/v5.3.11/source/fs/exec.c#L451
1111 
1112   // Get our current limit, and set things up so we restore the limit.
1113   rlimit rl;
1114   ASSERT_EQ(0, getrlimit(RLIMIT_STACK, &rl));
1115   uint64_t original_rlim_cur = rl.rlim_cur;
1116   if (rl.rlim_cur == RLIM_INFINITY) {
1117     rl.rlim_cur = 8 * 1024 * 1024; // Bionic reports unlimited stacks as 8MiB.
1118   }
1119   auto guard = android::base::make_scope_guard([&rl, original_rlim_cur]() {
1120     rl.rlim_cur = original_rlim_cur;
1121     ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1122   });
1123 
1124   // _SC_ARG_MAX should be 1/4 the stack size.
1125   EXPECT_EQ(static_cast<long>(rl.rlim_cur / 4), sysconf(_SC_ARG_MAX));
1126 
1127   // If you have a really small stack, the kernel still guarantees "32 pages" (see fs/exec.c).
1128   rl.rlim_cur = 1024;
1129   rl.rlim_max = RLIM_INFINITY;
1130   ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1131 
1132   EXPECT_EQ(static_cast<long>(32 * sysconf(_SC_PAGE_SIZE)), sysconf(_SC_ARG_MAX));
1133 
1134   // With a 128-page stack limit, we know exactly what _SC_ARG_MAX should be...
1135   rl.rlim_cur = 128 * sysconf(_SC_PAGE_SIZE);
1136   rl.rlim_max = RLIM_INFINITY;
1137   ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
1138 
1139   EXPECT_EQ(static_cast<long>((128 * sysconf(_SC_PAGE_SIZE)) / 4), sysconf(_SC_ARG_MAX));
1140 }
1141 
TEST(UNISTD_TEST,sysconf_unknown)1142 TEST(UNISTD_TEST, sysconf_unknown) {
1143   VERIFY_SYSCONF_UNKNOWN(-1);
1144   VERIFY_SYSCONF_UNKNOWN(666);
1145 }
1146 
TEST(UNISTD_TEST,dup2_same)1147 TEST(UNISTD_TEST, dup2_same) {
1148   // POSIX says of dup2:
1149   // If fildes2 is already a valid open file descriptor ...
1150   // [and] fildes is equal to fildes2 ... dup2() shall return
1151   // fildes2 without closing it.
1152   // This isn't true of dup3(2), so we need to manually implement that.
1153 
1154   // Equal and valid.
1155   int fd = open("/proc/version", O_RDONLY);
1156   ASSERT_TRUE(fd != -1);
1157   ASSERT_EQ(fd, dup2(fd, fd));
1158   ASSERT_EQ(0, close(fd)); // Check that dup2 didn't close fd.
1159 
1160   // Equal, but invalid.
1161   errno = 0;
1162   ASSERT_EQ(-1, dup2(fd, fd));
1163   ASSERT_EQ(EBADF, errno);
1164 }
1165 
TEST(UNISTD_TEST,dup3)1166 TEST(UNISTD_TEST, dup3) {
1167   int fd = open("/proc/version", O_RDONLY);
1168   ASSERT_EQ(666, dup3(fd, 666, 0));
1169   ASSERT_FALSE(CloseOnExec(666));
1170   close(666);
1171   ASSERT_EQ(667, dup3(fd, 667, O_CLOEXEC));
1172   ASSERT_TRUE(CloseOnExec(667));
1173   close(667);
1174   close(fd);
1175 }
1176 
TEST(UNISTD_TEST,lockf_smoke)1177 TEST(UNISTD_TEST, lockf_smoke) {
1178   constexpr off64_t file_size = 32*1024LL;
1179 
1180   TemporaryFile tf;
1181   ASSERT_EQ(0, ftruncate(tf.fd, file_size));
1182 
1183   // Lock everything.
1184   ASSERT_EQ(0, lseek64(tf.fd, 0, SEEK_SET));
1185   ASSERT_EQ(0, lockf64(tf.fd, F_LOCK, file_size));
1186 
1187   // Try-lock everything, this should succeed too.
1188   ASSERT_EQ(0, lseek64(tf.fd, 0, SEEK_SET));
1189   ASSERT_EQ(0, lockf64(tf.fd, F_TLOCK, file_size));
1190 
1191   // Check status.
1192   ASSERT_EQ(0, lseek64(tf.fd, 0, SEEK_SET));
1193   ASSERT_EQ(0, lockf64(tf.fd, F_TEST, file_size));
1194 
1195   // Unlock file.
1196   ASSERT_EQ(0, lseek64(tf.fd, 0, SEEK_SET));
1197   ASSERT_EQ(0, lockf64(tf.fd, F_ULOCK, file_size));
1198 }
1199 
TEST(UNISTD_TEST,lockf_zero)1200 TEST(UNISTD_TEST, lockf_zero) {
1201   constexpr off64_t file_size = 32*1024LL;
1202 
1203   TemporaryFile tf;
1204   ASSERT_EQ(0, ftruncate(tf.fd, file_size));
1205 
1206   // Lock everything by specifying a size of 0 (meaning "to the end, even if it changes").
1207   ASSERT_EQ(0, lseek64(tf.fd, 0, SEEK_SET));
1208   ASSERT_EQ(0, lockf64(tf.fd, F_LOCK, 0));
1209 
1210   // Check that it's locked.
1211   ASSERT_EQ(0, lseek64(tf.fd, 0, SEEK_SET));
1212   ASSERT_EQ(0, lockf64(tf.fd, F_TEST, file_size));
1213 
1214   // Move the end.
1215   ASSERT_EQ(0, ftruncate(tf.fd, 2*file_size));
1216 
1217   // Check that the new section is locked too.
1218   ASSERT_EQ(file_size, lseek64(tf.fd, file_size, SEEK_SET));
1219   ASSERT_EQ(0, lockf64(tf.fd, F_TEST, 2*file_size));
1220 }
1221 
TEST(UNISTD_TEST,lockf_negative)1222 TEST(UNISTD_TEST, lockf_negative) {
1223   constexpr off64_t file_size = 32*1024LL;
1224 
1225   TemporaryFile tf;
1226   ASSERT_EQ(0, ftruncate(tf.fd, file_size));
1227 
1228   // Lock everything, but specifying the range in reverse.
1229   ASSERT_EQ(file_size, lseek64(tf.fd, file_size, SEEK_SET));
1230   ASSERT_EQ(0, lockf64(tf.fd, F_LOCK, -file_size));
1231 
1232   // Check that it's locked.
1233   ASSERT_EQ(0, lseek64(tf.fd, 0, SEEK_SET));
1234   ASSERT_EQ(0, lockf64(tf.fd, F_TEST, file_size));
1235 }
1236 
TEST(UNISTD_TEST,lockf_with_child)1237 TEST(UNISTD_TEST, lockf_with_child) {
1238   constexpr off64_t file_size = 32*1024LL;
1239 
1240   TemporaryFile tf;
1241   ASSERT_EQ(0, ftruncate(tf.fd, file_size));
1242 
1243   // Lock everything.
1244   ASSERT_EQ(0, lseek64(tf.fd, 0, SEEK_SET));
1245   ASSERT_EQ(0, lockf64(tf.fd, F_LOCK, file_size));
1246 
1247   // Fork a child process
1248   pid_t pid = fork();
1249   ASSERT_NE(-1, pid);
1250   if (pid == 0) {
1251     // Check that the child cannot lock the file.
1252     ASSERT_EQ(0, lseek64(tf.fd, 0, SEEK_SET));
1253     ASSERT_EQ(-1, lockf64(tf.fd, F_TLOCK, file_size));
1254     ASSERT_EQ(EAGAIN, errno);
1255     // Check also that it reports itself as locked.
1256     ASSERT_EQ(0, lseek64(tf.fd, 0, SEEK_SET));
1257     ASSERT_EQ(-1, lockf64(tf.fd, F_TEST, file_size));
1258     ASSERT_EQ(EACCES, errno);
1259     _exit(0);
1260   }
1261   AssertChildExited(pid, 0);
1262 }
1263 
TEST(UNISTD_TEST,lockf_partial_with_child)1264 TEST(UNISTD_TEST, lockf_partial_with_child) {
1265   constexpr off64_t file_size = 32*1024LL;
1266 
1267   TemporaryFile tf;
1268   ASSERT_EQ(0, ftruncate(tf.fd, file_size));
1269 
1270   // Lock the first half of the file.
1271   ASSERT_EQ(0, lseek64(tf.fd, 0, SEEK_SET));
1272   ASSERT_EQ(0, lockf64(tf.fd, F_LOCK, file_size/2));
1273 
1274   // Fork a child process.
1275   pid_t pid = fork();
1276   ASSERT_NE(-1, pid);
1277   if (pid == 0) {
1278     // Check that the child can lock the other half.
1279     ASSERT_EQ(file_size/2, lseek64(tf.fd, file_size/2, SEEK_SET));
1280     ASSERT_EQ(0, lockf64(tf.fd, F_TLOCK, file_size/2));
1281     // Check that the child cannot lock the first half.
1282     ASSERT_EQ(0, lseek64(tf.fd, 0, SEEK_SET));
1283     ASSERT_EQ(-1, lockf64(tf.fd, F_TEST, file_size/2));
1284     ASSERT_EQ(EACCES, errno);
1285     // Check also that it reports itself as locked.
1286     ASSERT_EQ(0, lseek64(tf.fd, 0, SEEK_SET));
1287     ASSERT_EQ(-1, lockf64(tf.fd, F_TEST, file_size/2));
1288     ASSERT_EQ(EACCES, errno);
1289     _exit(0);
1290   }
1291   AssertChildExited(pid, 0);
1292 
1293   // The second half was locked by the child, but the lock disappeared
1294   // when the process exited, so check it can be locked now.
1295   ASSERT_EQ(file_size/2, lseek64(tf.fd, file_size/2, SEEK_SET));
1296   ASSERT_EQ(0, lockf64(tf.fd, F_TLOCK, file_size/2));
1297 }
1298 
TEST(UNISTD_TEST,getdomainname)1299 TEST(UNISTD_TEST, getdomainname) {
1300   struct utsname u;
1301   ASSERT_EQ(0, uname(&u));
1302 
1303   char buf[sizeof(u.domainname)];
1304   ASSERT_EQ(0, getdomainname(buf, sizeof(buf)));
1305   EXPECT_STREQ(u.domainname, buf);
1306 
1307 #if defined(__BIONIC__)
1308   // bionic and glibc have different behaviors when len is too small
1309   ASSERT_EQ(-1, getdomainname(buf, strlen(u.domainname)));
1310   EXPECT_EQ(EINVAL, errno);
1311 #endif
1312 }
1313 
TEST(UNISTD_TEST,setdomainname)1314 TEST(UNISTD_TEST, setdomainname) {
1315   __user_cap_header_struct header;
1316   memset(&header, 0, sizeof(header));
1317   header.version = _LINUX_CAPABILITY_VERSION_3;
1318 
1319   __user_cap_data_struct old_caps[_LINUX_CAPABILITY_U32S_3];
1320   ASSERT_EQ(0, capget(&header, &old_caps[0]));
1321 
1322   auto admin_idx = CAP_TO_INDEX(CAP_SYS_ADMIN);
1323   auto admin_mask = CAP_TO_MASK(CAP_SYS_ADMIN);
1324   bool has_admin = old_caps[admin_idx].effective & admin_mask;
1325   if (has_admin) {
1326     __user_cap_data_struct new_caps[_LINUX_CAPABILITY_U32S_3];
1327     memcpy(new_caps, old_caps, sizeof(new_caps));
1328     new_caps[admin_idx].effective &= ~admin_mask;
1329 
1330     ASSERT_EQ(0, capset(&header, &new_caps[0])) << "failed to drop admin privileges";
1331   }
1332 
1333   const char* name = "newdomainname";
1334   ASSERT_EQ(-1, setdomainname(name, strlen(name)));
1335   ASSERT_EQ(EPERM, errno);
1336 
1337   if (has_admin) {
1338     ASSERT_EQ(0, capset(&header, &old_caps[0])) << "failed to restore admin privileges";
1339   }
1340 }
1341 
TEST(UNISTD_TEST,execve_failure)1342 TEST(UNISTD_TEST, execve_failure) {
1343   ExecTestHelper eth;
1344   errno = 0;
1345   ASSERT_EQ(-1, execve("/", eth.GetArgs(), eth.GetEnv()));
1346   ASSERT_EQ(EACCES, errno);
1347 }
1348 
append_llvm_cov_env_var(std::string & env_str)1349 static void append_llvm_cov_env_var(std::string& env_str) {
1350   if (getenv("LLVM_PROFILE_FILE") != nullptr)
1351     env_str.append("__LLVM_PROFILE_RT_INIT_ONCE=__LLVM_PROFILE_RT_INIT_ONCE\n");
1352 }
1353 
TEST(UNISTD_TEST,execve_args)1354 TEST(UNISTD_TEST, execve_args) {
1355   // int execve(const char* path, char* argv[], char* envp[]);
1356 
1357   // Test basic argument passing.
1358   ExecTestHelper eth;
1359   eth.SetArgs({"echo", "hello", "world", nullptr});
1360   eth.Run([&]() { execve(BIN_DIR "echo", eth.GetArgs(), eth.GetEnv()); }, 0, "hello world\n");
1361 
1362   // Test environment variable setting too.
1363   eth.SetArgs({"printenv", nullptr});
1364   eth.SetEnv({"A=B", nullptr});
1365 
1366   std::string expected_output("A=B\n");
1367   append_llvm_cov_env_var(expected_output);
1368 
1369   eth.Run([&]() { execve(BIN_DIR "printenv", eth.GetArgs(), eth.GetEnv()); }, 0,
1370           expected_output.c_str());
1371 }
1372 
TEST(UNISTD_TEST,execl_failure)1373 TEST(UNISTD_TEST, execl_failure) {
1374   errno = 0;
1375   ASSERT_EQ(-1, execl("/", "/", nullptr));
1376   ASSERT_EQ(EACCES, errno);
1377 }
1378 
TEST(UNISTD_TEST,execl)1379 TEST(UNISTD_TEST, execl) {
1380   ExecTestHelper eth;
1381   // int execl(const char* path, const char* arg, ...);
1382   eth.Run([&]() { execl(BIN_DIR "echo", "echo", "hello", "world", nullptr); }, 0, "hello world\n");
1383 }
1384 
TEST(UNISTD_TEST,execle_failure)1385 TEST(UNISTD_TEST, execle_failure) {
1386   ExecTestHelper eth;
1387   errno = 0;
1388   ASSERT_EQ(-1, execle("/", "/", nullptr, eth.GetEnv()));
1389   ASSERT_EQ(EACCES, errno);
1390 }
1391 
TEST(UNISTD_TEST,execle)1392 TEST(UNISTD_TEST, execle) {
1393   ExecTestHelper eth;
1394   eth.SetEnv({"A=B", nullptr});
1395 
1396   std::string expected_output("A=B\n");
1397   append_llvm_cov_env_var(expected_output);
1398 
1399   // int execle(const char* path, const char* arg, ..., char* envp[]);
1400   eth.Run([&]() { execle(BIN_DIR "printenv", "printenv", nullptr, eth.GetEnv()); }, 0,
1401           expected_output.c_str());
1402 }
1403 
TEST(UNISTD_TEST,execv_failure)1404 TEST(UNISTD_TEST, execv_failure) {
1405   ExecTestHelper eth;
1406   errno = 0;
1407   ASSERT_EQ(-1, execv("/", eth.GetArgs()));
1408   ASSERT_EQ(EACCES, errno);
1409 }
1410 
TEST(UNISTD_TEST,execv)1411 TEST(UNISTD_TEST, execv) {
1412   ExecTestHelper eth;
1413   eth.SetArgs({"echo", "hello", "world", nullptr});
1414   // int execv(const char* path, char* argv[]);
1415   eth.Run([&]() { execv(BIN_DIR "echo", eth.GetArgs()); }, 0, "hello world\n");
1416 }
1417 
TEST(UNISTD_TEST,execlp_failure)1418 TEST(UNISTD_TEST, execlp_failure) {
1419   errno = 0;
1420   ASSERT_EQ(-1, execlp("/", "/", nullptr));
1421   ASSERT_EQ(EACCES, errno);
1422 }
1423 
TEST(UNISTD_TEST,execlp)1424 TEST(UNISTD_TEST, execlp) {
1425   ExecTestHelper eth;
1426   // int execlp(const char* file, const char* arg, ...);
1427   eth.Run([&]() { execlp("echo", "echo", "hello", "world", nullptr); }, 0, "hello world\n");
1428 }
1429 
TEST(UNISTD_TEST,execvp_failure)1430 TEST(UNISTD_TEST, execvp_failure) {
1431   ExecTestHelper eth;
1432   eth.SetArgs({nullptr});
1433   errno = 0;
1434   ASSERT_EQ(-1, execvp("/", eth.GetArgs()));
1435   ASSERT_EQ(EACCES, errno);
1436 }
1437 
TEST(UNISTD_TEST,execvp)1438 TEST(UNISTD_TEST, execvp) {
1439   ExecTestHelper eth;
1440   eth.SetArgs({"echo", "hello", "world", nullptr});
1441   // int execvp(const char* file, char* argv[]);
1442   eth.Run([&]() { execvp("echo", eth.GetArgs()); }, 0, "hello world\n");
1443 }
1444 
TEST(UNISTD_TEST,execvpe_failure)1445 TEST(UNISTD_TEST, execvpe_failure) {
1446   ExecTestHelper eth;
1447   errno = 0;
1448   ASSERT_EQ(-1, execvpe("this-does-not-exist", eth.GetArgs(), eth.GetEnv()));
1449   // Running in CTS we might not even be able to search all directories in $PATH.
1450   ASSERT_TRUE(errno == ENOENT || errno == EACCES);
1451 }
1452 
TEST(UNISTD_TEST,execvpe)1453 TEST(UNISTD_TEST, execvpe) {
1454   // int execvpe(const char* file, char* argv[], char* envp[]);
1455 
1456   // Test basic argument passing.
1457   ExecTestHelper eth;
1458   eth.SetArgs({"echo", "hello", "world", nullptr});
1459   eth.Run([&]() { execvpe("echo", eth.GetArgs(), eth.GetEnv()); }, 0, "hello world\n");
1460 
1461   // Test environment variable setting too.
1462   eth.SetArgs({"printenv", nullptr});
1463   eth.SetEnv({"A=B", nullptr});
1464 
1465   std::string expected_output("A=B\n");
1466   append_llvm_cov_env_var(expected_output);
1467 
1468   eth.Run([&]() { execvpe("printenv", eth.GetArgs(), eth.GetEnv()); }, 0, expected_output.c_str());
1469 }
1470 
TEST(UNISTD_TEST,execvpe_ENOEXEC)1471 TEST(UNISTD_TEST, execvpe_ENOEXEC) {
1472   // Create a shell script with #!.
1473   TemporaryFile tf;
1474   ASSERT_TRUE(android::base::WriteStringToFile("#!" BIN_DIR "sh\necho script\n", tf.path));
1475 
1476   // Set $PATH so we can find it.
1477   setenv("PATH", dirname(tf.path), 1);
1478 
1479   ExecTestHelper eth;
1480   eth.SetArgs({basename(tf.path), nullptr});
1481 
1482   // It's not inherently executable.
1483   errno = 0;
1484   ASSERT_EQ(-1, execvpe(basename(tf.path), eth.GetArgs(), eth.GetEnv()));
1485   ASSERT_EQ(EACCES, errno);
1486 
1487   // Make it executable (and keep it writable because we're going to rewrite it below).
1488   ASSERT_EQ(0, chmod(tf.path, 0777));
1489 
1490   // TemporaryFile will have a writable fd, so we can test ETXTBSY while we're here...
1491   errno = 0;
1492   ASSERT_EQ(-1, execvpe(basename(tf.path), eth.GetArgs(), eth.GetEnv()));
1493   ASSERT_EQ(ETXTBSY, errno);
1494 
1495   // 1. The simplest test: the kernel should handle this.
1496   ASSERT_EQ(0, close(tf.fd));
1497   eth.Run([&]() { execvpe(basename(tf.path), eth.GetArgs(), eth.GetEnv()); }, 0, "script\n");
1498 
1499   // 2. Try again without a #!. We should have to handle this ourselves.
1500   ASSERT_TRUE(android::base::WriteStringToFile("echo script\n", tf.path));
1501   eth.Run([&]() { execvpe(basename(tf.path), eth.GetArgs(), eth.GetEnv()); }, 0, "script\n");
1502 
1503   // 3. Again without a #!, but also with a leading '/', since that's a special case in the
1504   // implementation.
1505   eth.Run([&]() { execvpe(tf.path, eth.GetArgs(), eth.GetEnv()); }, 0, "script\n");
1506 }
1507 
TEST(UNISTD_TEST,execvp_libcore_test_55017)1508 TEST(UNISTD_TEST, execvp_libcore_test_55017) {
1509   ExecTestHelper eth;
1510   eth.SetArgs({"/system/bin/does-not-exist", nullptr});
1511 
1512   errno = 0;
1513   ASSERT_EQ(-1, execvp("/system/bin/does-not-exist", eth.GetArgs()));
1514   ASSERT_EQ(ENOENT, errno);
1515 }
1516 
TEST(UNISTD_TEST,exec_argv0_null)1517 TEST(UNISTD_TEST, exec_argv0_null) {
1518   // http://b/33276926
1519   char* args[] = {nullptr};
1520   char* envs[] = {nullptr};
1521   ASSERT_EXIT(execve("/system/bin/run-as", args, envs), testing::ExitedWithCode(1),
1522               "<unknown>: usage: run-as");
1523 }
1524 
TEST(UNISTD_TEST,fexecve_failure)1525 TEST(UNISTD_TEST, fexecve_failure) {
1526   ExecTestHelper eth;
1527   errno = 0;
1528   int fd = open("/", O_RDONLY);
1529   ASSERT_NE(-1, fd);
1530   ASSERT_EQ(-1, fexecve(fd, eth.GetArgs(), eth.GetEnv()));
1531   ASSERT_EQ(EACCES, errno);
1532   close(fd);
1533 }
1534 
TEST(UNISTD_TEST,fexecve_bad_fd)1535 TEST(UNISTD_TEST, fexecve_bad_fd) {
1536   ExecTestHelper eth;
1537   errno = 0;
1538   ASSERT_EQ(-1, fexecve(-1, eth.GetArgs(), eth.GetEnv()));
1539   ASSERT_EQ(EBADF, errno);
1540 }
1541 
TEST(UNISTD_TEST,fexecve_args)1542 TEST(UNISTD_TEST, fexecve_args) {
1543   // Test basic argument passing.
1544   int echo_fd = open(BIN_DIR "echo", O_RDONLY | O_CLOEXEC);
1545   ASSERT_NE(-1, echo_fd);
1546   ExecTestHelper eth;
1547   eth.SetArgs({"echo", "hello", "world", nullptr});
1548   eth.Run([&]() { fexecve(echo_fd, eth.GetArgs(), eth.GetEnv()); }, 0, "hello world\n");
1549   close(echo_fd);
1550 
1551   // Test environment variable setting too.
1552   int printenv_fd = open(BIN_DIR "printenv", O_RDONLY | O_CLOEXEC);
1553   ASSERT_NE(-1, printenv_fd);
1554   eth.SetArgs({"printenv", nullptr});
1555   eth.SetEnv({"A=B", nullptr});
1556 
1557   std::string expected_output("A=B\n");
1558   append_llvm_cov_env_var(expected_output);
1559 
1560   eth.Run([&]() { fexecve(printenv_fd, eth.GetArgs(), eth.GetEnv()); }, 0, expected_output.c_str());
1561   close(printenv_fd);
1562 }
1563 
TEST(UNISTD_TEST,getlogin_r)1564 TEST(UNISTD_TEST, getlogin_r) {
1565   char buf[LOGIN_NAME_MAX] = {};
1566   EXPECT_EQ(ERANGE, getlogin_r(buf, 0));
1567   EXPECT_EQ(0, getlogin_r(buf, sizeof(buf)));
1568   EXPECT_STREQ(getlogin(), buf);
1569 }
1570 
TEST(UNISTD_TEST,swab)1571 TEST(UNISTD_TEST, swab) {
1572   // POSIX: "The swab() function shall copy nbytes bytes, which are pointed to by src,
1573   // to the object pointed to by dest, exchanging adjacent bytes."
1574   char buf[BUFSIZ];
1575   memset(buf, 'x', sizeof(buf));
1576   swab("ehll oowlr\0d", buf, 12);
1577   ASSERT_STREQ("hello world", buf);
1578 }
1579 
TEST(UNISTD_TEST,swab_odd_byte_count)1580 TEST(UNISTD_TEST, swab_odd_byte_count) {
1581   // POSIX: "If nbytes is odd, swab() copies and exchanges nbytes-1 bytes and the disposition
1582   // of the last byte is unspecified."
1583   // ...but it seems unreasonable to not just leave the last byte alone.
1584   char buf[BUFSIZ];
1585   memset(buf, 'x', sizeof(buf));
1586   swab("012345", buf, 3);
1587   ASSERT_EQ('1', buf[0]);
1588   ASSERT_EQ('0', buf[1]);
1589   ASSERT_EQ('x', buf[2]);
1590 }
1591 
TEST(UNISTD_TEST,swab_overlap)1592 TEST(UNISTD_TEST, swab_overlap) {
1593   // POSIX: "If copying takes place between objects that overlap, the behavior is undefined."
1594   // ...but it seems unreasonable to not just do the right thing.
1595   char buf[] = "012345";
1596   swab(buf, buf, 4);
1597   ASSERT_EQ('1', buf[0]);
1598   ASSERT_EQ('0', buf[1]);
1599   ASSERT_EQ('3', buf[2]);
1600   ASSERT_EQ('2', buf[3]);
1601   ASSERT_EQ('4', buf[4]);
1602   ASSERT_EQ('5', buf[5]);
1603   ASSERT_EQ(0, buf[6]);
1604 }
1605 
TEST(UNISTD_TEST,swab_negative_byte_count)1606 TEST(UNISTD_TEST, swab_negative_byte_count) {
1607   // POSIX: "If nbytes is negative, swab() does nothing."
1608   char buf[BUFSIZ];
1609   memset(buf, 'x', sizeof(buf));
1610   swab("hello", buf, -1);
1611   ASSERT_EQ('x', buf[0]);
1612 }
1613 
TEST(UNISTD_TEST,usleep)1614 TEST(UNISTD_TEST, usleep) {
1615   auto t0 = std::chrono::steady_clock::now();
1616   ASSERT_EQ(0, usleep(5000));
1617   auto t1 = std::chrono::steady_clock::now();
1618   ASSERT_GE(t1-t0, 5000us);
1619 }
1620 
TEST(UNISTD_TEST,sleep)1621 TEST(UNISTD_TEST, sleep) {
1622   auto t0 = std::chrono::steady_clock::now();
1623   ASSERT_EQ(0U, sleep(1));
1624   auto t1 = std::chrono::steady_clock::now();
1625   ASSERT_GE(t1-t0, 1s);
1626 }
1627