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