Merge "Introduce a new heap tagging level, M_HEAP_TAGGING_LEVEL_SYNC."
diff --git a/libc/Android.bp b/libc/Android.bp
index f73ae4a..0f540c8 100644
--- a/libc/Android.bp
+++ b/libc/Android.bp
@@ -65,7 +65,13 @@
         "bionic/libc/async_safe/include",
     ],
 
-    header_libs: ["gwp_asan_headers"],
+    header_libs: [
+        "libc_headers",
+        "gwp_asan_headers",
+    ],
+    export_header_lib_headers: [
+        "libc_headers",
+    ],
 
     stl: "none",
     system_shared_libs: [],
@@ -88,6 +94,12 @@
         experimental_mte: {
             cflags: ["-DANDROID_EXPERIMENTAL_MTE"],
         },
+        malloc_zero_contents: {
+            cflags: ["-DSCUDO_ZERO_CONTENTS"],
+        },
+        malloc_pattern_fill_contents: {
+            cflags: ["-DSCUDO_PATTERN_FILL_CONTENTS"],
+        },
     },
 }
 
@@ -1022,8 +1034,7 @@
         "bionic/dup.cpp",
         "bionic/environ.cpp",
         "bionic/error.cpp",
-        "bionic/eventfd_read.cpp",
-        "bionic/eventfd_write.cpp",
+        "bionic/eventfd.cpp",
         "bionic/exec.cpp",
         "bionic/faccessat.cpp",
         "bionic/fchmod.cpp",
@@ -1114,6 +1125,7 @@
         "bionic/signal.cpp",
         "bionic/sigprocmask.cpp",
         "bionic/sleep.cpp",
+        "bionic/socketpair.cpp",
         "bionic/spawn.cpp",
         "bionic/stat.cpp",
         "bionic/stdlib_l.cpp",
@@ -1577,7 +1589,6 @@
     ],
     name: "libc",
     static_ndk_lib: true,
-    export_include_dirs: ["include"],
     product_variables: {
         platform_sdk_version: {
             asflags: ["-DPLATFORM_SDK_VERSION=%d"],
@@ -1751,6 +1762,7 @@
 // Headers that only other parts of the platform can include.
 cc_library_headers {
     name: "bionic_libc_platform_headers",
+    defaults: ["linux_bionic_supported"],
     visibility: [
         "//art:__subpackages__",
         "//bionic:__subpackages__",
@@ -1762,7 +1774,6 @@
         "//system/core/libunwindstack:__subpackages__",
         "//system/memory/libmemunreachable:__subpackages__",
     ],
-    host_supported: true,
     vendor_available: true,
     ramdisk_available: true,
     recovery_available: true,
@@ -1775,9 +1786,13 @@
     sdk_version: "current",
 }
 
-// libc_headers for libasync_safe and libpropertyinfoparser
 cc_library_headers {
-    name: "libc_headers",
+    // Internal lib for use in libc_headers. Since we cannot intersect arch{}
+    // and target{} in the same module, this one specifies the arch-dependent
+    // include paths, and then libc_headers filters by target so that the
+    // headers only are included for Bionic targets.
+    name: "libc_headers_arch",
+    visibility: ["//visibility:private"],
 
     host_supported: true,
     vendor_available: true,
@@ -1788,14 +1803,8 @@
         "//apex_available:platform",
         "//apex_available:anyapex",
     ],
-    visibility: [
-        ":__subpackages__", // visible to bionic
-        // ... and only to these places (b/152668052)
-        "//external/gwp_asan",
-        "//external/libunwind_llvm",
-        "//system/core/property_service/libpropertyinfoparser",
-        "//system/extras/toolchain-extras",
-    ],
+    // used by most APEXes indirectly via libunwind_llvm
+    min_sdk_version: "apex_inherit",
 
     no_libcrt: true,
     stl: "none",
@@ -1809,36 +1818,77 @@
     // is correct because the headers can support any sdk_version.
     sdk_version: "1",
 
-    export_include_dirs: [
+    export_system_include_dirs: [
         "include",
         "kernel/uapi",
+        "kernel/android/scsi",
         "kernel/android/uapi",
     ],
 
     arch: {
         arm: {
-            export_include_dirs: [
-                "kernel/uapi/asm-arm",
-            ],
+            export_system_include_dirs: ["kernel/uapi/asm-arm"],
         },
         arm64: {
-            export_include_dirs: [
-                "kernel/uapi/asm-arm64",
-            ],
+            export_system_include_dirs: ["kernel/uapi/asm-arm64"],
         },
         x86: {
-            export_include_dirs: [
-                "kernel/uapi/asm-x86",
-            ],
+            export_system_include_dirs: ["kernel/uapi/asm-x86"],
         },
         x86_64: {
-            export_include_dirs: [
-                "kernel/uapi/asm-x86",
-            ],
+            export_system_include_dirs: ["kernel/uapi/asm-x86"],
         },
     },
 }
 
+cc_library_headers {
+    name: "libc_headers",
+    host_supported: true,
+    native_bridge_supported: true,
+    vendor_available: true,
+    ramdisk_available: true,
+    recovery_available: true,
+    sdk_version: "1",
+
+    apex_available: [
+        "//apex_available:platform",
+        "//apex_available:anyapex",
+    ],
+    // used by most APEXes indirectly via libunwind_llvm
+    min_sdk_version: "apex_inherit",
+    visibility: [
+        "//bionic:__subpackages__", // visible to bionic
+        // ... and only to these places (b/152668052)
+        "//external/arm-optimized-routines",
+        "//external/gwp_asan",
+        "//external/jemalloc_new",
+        "//external/libunwind_llvm",
+        "//external/scudo",
+        "//system/core/property_service/libpropertyinfoparser",
+        "//system/extras/toolchain-extras",
+        // TODO(b/153662223): Clean up these users that needed visibility when
+        // the implicit addition of system Bionic paths was removed.
+        "//art/tools/cpp-define-generator",
+        "//external/boringssl",
+        "//external/minijail",
+    ],
+
+    stl: "none",
+    no_libcrt: true,
+    system_shared_libs: [],
+
+    target: {
+        android: {
+            header_libs: ["libc_headers_arch"],
+            export_header_lib_headers: ["libc_headers_arch"],
+        },
+        linux_bionic: {
+            header_libs: ["libc_headers_arch"],
+            export_header_lib_headers: ["libc_headers_arch"],
+        },
+    }
+}
+
 // ========================================================
 // libstdc++.so and libstdc++.a.
 // ========================================================
@@ -1931,7 +1981,8 @@
         "//apex_available:platform",
         "//apex_available:anyapex",
     ],
-
+    // crt* objects are used by most cc_binary/cc_library in "anyapex"
+    min_sdk_version: "apex_inherit",
     cflags: [
         "-Wno-gcc-compat",
         "-Wall",
@@ -2485,6 +2536,11 @@
     allow_undefined_symbols: true,
     // Like libc, disable native coverage for libc_scudo.
     native_coverage: false,
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.media.swcodec",
+    ],
+    min_sdk_version: "29",
 }
 
 subdirs = [
diff --git a/libc/SYSCALLS.TXT b/libc/SYSCALLS.TXT
index ab309e6..6142baf 100644
--- a/libc/SYSCALLS.TXT
+++ b/libc/SYSCALLS.TXT
@@ -126,7 +126,7 @@
 int         __fcntl:fcntl(int, int, void*)  lp64
 int         flock(int, int)   all
 int         __fchmod:fchmod(int, mode_t)  all
-int         pipe2(int*, int) all
+int         __pipe2:pipe2(int*, int) all
 int         __dup:dup(int)  all
 int         __dup3:dup3(int, int, int)   all
 int         fsync(int)  all
@@ -243,7 +243,7 @@
 
 # sockets
 int           __socket:socket(int, int, int)              arm,lp64
-int           socketpair(int, int, int, int*)    arm,lp64
+int           __socketpair:socketpair(int, int, int, int*)    arm,lp64
 int           bind(int, struct sockaddr*, socklen_t)  arm,lp64
 int           __connect:connect(int, struct sockaddr*, socklen_t)   arm,lp64
 int           listen(int, int)                   arm,lp64
@@ -267,7 +267,7 @@
 int           listen:socketcall:4(int, int)                   x86
 int           getsockname:socketcall:6(int, struct sockaddr*, socklen_t*)  x86
 int           getpeername:socketcall:7(int, struct sockaddr*, socklen_t*)  x86
-int           socketpair:socketcall:8(int, int, int, int*)    x86
+int           __socketpair:socketcall:8(int, int, int, int*)    x86
 ssize_t       __sendto:socketcall:11(int, const void*, size_t, int, const struct sockaddr*, socklen_t)  x86
 ssize_t       recvfrom:socketcall:12(int, void*, size_t, unsigned int, struct sockaddr*, socklen_t*)  x86
 int           shutdown:socketcall:13(int, int)  x86
@@ -308,11 +308,11 @@
 ssize_t splice(int, off64_t*, int, off64_t*, size_t, unsigned int)  all
 ssize_t vmsplice(int, const struct iovec*, size_t, unsigned int)  all
 
-int epoll_create1(int)  all
+int __epoll_create1:epoll_create1(int)  all
 int epoll_ctl(int, int op, int, struct epoll_event*)  all
 int __epoll_pwait:epoll_pwait(int, struct epoll_event*, int, int, const sigset64_t*, size_t)  all
 
-int eventfd:eventfd2(unsigned int, int)  all
+int __eventfd:eventfd2(unsigned int, int)  all
 
 void _exit|_Exit:exit_group(int)  all
 void __exit:exit(int)  all
diff --git a/libc/bionic/eventfd_read.cpp b/libc/bionic/eventfd.cpp
similarity index 82%
rename from libc/bionic/eventfd_read.cpp
rename to libc/bionic/eventfd.cpp
index 50e73fd..f13c6a3 100644
--- a/libc/bionic/eventfd_read.cpp
+++ b/libc/bionic/eventfd.cpp
@@ -29,6 +29,18 @@
 #include <sys/eventfd.h>
 #include <unistd.h>
 
+#include "private/bionic_fdtrack.h"
+
+extern "C" int __eventfd(unsigned int initval, int flags);
+
+int eventfd(unsigned int initval, int flags) {
+  return FDTRACK_CREATE(__eventfd(initval, flags));
+}
+
 int eventfd_read(int fd, eventfd_t* value) {
   return (read(fd, value, sizeof(*value)) == sizeof(*value)) ? 0 : -1;
 }
+
+int eventfd_write(int fd, eventfd_t value) {
+  return (write(fd, &value, sizeof(value)) == sizeof(value)) ? 0 : -1;
+}
diff --git a/libc/bionic/eventfd_write.cpp b/libc/bionic/eventfd_write.cpp
index 3c3d3f1..6d86d8c 100644
--- a/libc/bionic/eventfd_write.cpp
+++ b/libc/bionic/eventfd_write.cpp
@@ -29,6 +29,3 @@
 #include <sys/eventfd.h>
 #include <unistd.h>
 
-int eventfd_write(int fd, eventfd_t value) {
-  return (write(fd, &value, sizeof(value)) == sizeof(value)) ? 0 : -1;
-}
diff --git a/libc/bionic/libc_init_common.cpp b/libc/bionic/libc_init_common.cpp
index 12628f7..a47c2fc 100644
--- a/libc/bionic/libc_init_common.cpp
+++ b/libc/bionic/libc_init_common.cpp
@@ -52,6 +52,8 @@
 #include "pthread_internal.h"
 
 extern "C" int __system_properties_init(void);
+extern "C" void scudo_malloc_set_zero_contents(int);
+extern "C" void scudo_malloc_set_pattern_fill_contents(int);
 
 __LIBC_HIDDEN__ WriteProtected<libc_globals> __libc_globals;
 
@@ -83,6 +85,14 @@
   _thread_arc4_lock();
 }
 
+static void __libc_init_malloc_fill_contents() {
+#if defined(SCUDO_PATTERN_FILL_CONTENTS)
+  scudo_malloc_set_pattern_fill_contents(1);
+#elif defined(SCUDO_ZERO_CONTENTS)
+  scudo_malloc_set_zero_contents(1);
+#endif
+}
+
 __BIONIC_WEAK_FOR_NATIVE_BRIDGE
 void __libc_add_main_thread() {
   // Get the main thread from TLS and add it to the thread list.
@@ -106,6 +116,7 @@
   __libc_init_fdsan(); // Requires system properties (for debug.fdsan).
   __libc_init_fdtrack();
 
+  __libc_init_malloc_fill_contents();
   SetDefaultHeapTaggingLevel();
 }
 
diff --git a/libc/bionic/pipe.cpp b/libc/bionic/pipe.cpp
index a81afe8..f197656 100644
--- a/libc/bionic/pipe.cpp
+++ b/libc/bionic/pipe.cpp
@@ -28,6 +28,24 @@
 
 #include <unistd.h>
 
+#include "private/bionic_fdtrack.h"
+
+extern "C" int __pipe2(int pipefd[2], int flags);
+
 int pipe(int pipefd[2]) {
-  return pipe2(pipefd, 0);
+  int rc = __pipe2(pipefd, 0);
+  if (rc == 0) {
+    FDTRACK_CREATE(pipefd[0]);
+    FDTRACK_CREATE(pipefd[1]);
+  }
+  return rc;
+}
+
+int pipe2(int pipefd[2], int flags) {
+  int rc = __pipe2(pipefd, flags);
+  if (rc == 0) {
+    FDTRACK_CREATE(pipefd[0]);
+    FDTRACK_CREATE(pipefd[1]);
+  }
+  return rc;
 }
diff --git a/libc/bionic/eventfd_read.cpp b/libc/bionic/socketpair.cpp
similarity index 77%
copy from libc/bionic/eventfd_read.cpp
copy to libc/bionic/socketpair.cpp
index 50e73fd..d2b4c19 100644
--- a/libc/bionic/eventfd_read.cpp
+++ b/libc/bionic/socketpair.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010 The Android Open Source Project
+ * Copyright (C) 2020 The Android Open Source Project
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -26,9 +26,18 @@
  * SUCH DAMAGE.
  */
 
-#include <sys/eventfd.h>
+#include <sys/socket.h>
 #include <unistd.h>
 
-int eventfd_read(int fd, eventfd_t* value) {
-  return (read(fd, value, sizeof(*value)) == sizeof(*value)) ? 0 : -1;
+#include "private/bionic_fdtrack.h"
+
+extern "C" int __socketpair(int domain, int type, int protocol, int sv[2]);
+
+int socketpair(int domain, int type, int protocol, int sv[2]) {
+  int rc = __socketpair(domain, type, protocol, sv);
+  if (rc == 0) {
+    FDTRACK_CREATE(sv[0]);
+    FDTRACK_CREATE(sv[1]);
+  }
+  return rc;
 }
diff --git a/libc/bionic/sys_epoll.cpp b/libc/bionic/sys_epoll.cpp
index 9f82912..22d0a98 100644
--- a/libc/bionic/sys_epoll.cpp
+++ b/libc/bionic/sys_epoll.cpp
@@ -30,7 +30,9 @@
 #include <sys/epoll.h>
 
 #include "private/SigSetConverter.h"
+#include "private/bionic_fdtrack.h"
 
+extern "C" int __epoll_create1(int flags);
 extern "C" int __epoll_pwait(int, epoll_event*, int, int, const sigset64_t*, size_t);
 
 int epoll_create(int size) {
@@ -38,7 +40,11 @@
     errno = EINVAL;
     return -1;
   }
-  return epoll_create1(0);
+  return FDTRACK_CREATE(__epoll_create1(0));
+}
+
+int epoll_create1(int flags) {
+  return FDTRACK_CREATE(__epoll_create1(flags));
 }
 
 int epoll_pwait(int fd, epoll_event* events, int max_events, int timeout, const sigset_t* ss) {
diff --git a/libc/include/android/api-level.h b/libc/include/android/api-level.h
index 1b8af78..50cb61a 100644
--- a/libc/include/android/api-level.h
+++ b/libc/include/android/api-level.h
@@ -110,6 +110,9 @@
 /** Names the "R" API level (30), for comparison against `__ANDROID_API__`. */
 #define __ANDROID_API_R__ 30
 
+/** Names the "S" API level (31), for comparison against `__ANDROID_API__`. */
+#define __ANDROID_API_S__ 31
+
 /**
  * Returns the `targetSdkVersion` of the caller, or `__ANDROID_API_FUTURE__`
  * if there is no known target SDK version (for code not running in the
diff --git a/libc/libc.map.txt b/libc/libc.map.txt
index 2284775..10732a1 100644
--- a/libc/libc.map.txt
+++ b/libc/libc.map.txt
@@ -1550,7 +1550,7 @@
     _Unwind_VRS_Set; # apex llndk arm
 } LIBC_Q;
 
-LIBC_S { # introduced=31
+LIBC_S { # introduced=S
   global:
     ffsl;
     ffsll;
diff --git a/libdl/Android.bp b/libdl/Android.bp
index 8e3a3fc..6a3a82e 100644
--- a/libdl/Android.bp
+++ b/libdl/Android.bp
@@ -25,6 +25,8 @@
 
     stl: "none",
     system_shared_libs: [],
+    header_libs: ["libc_headers"],
+    export_header_lib_headers: ["libc_headers"],
 
     sanitize: {
         never: true,
@@ -97,6 +99,7 @@
 
     nocrt: true,
     system_shared_libs: [],
+    header_libs: ["libc_headers"],
 
     // Opt out of native_coverage when opting out of system_shared_libs
     native_coverage: false,
@@ -175,6 +178,7 @@
 
     nocrt: true,
     system_shared_libs: [],
+    header_libs: ["libc_headers"],
 
     // Opt out of native_coverage when opting out of system_shared_libs
     native_coverage: false,
diff --git a/libfdtrack/fdtrack.cpp b/libfdtrack/fdtrack.cpp
index 8d9d61d..d371577 100644
--- a/libfdtrack/fdtrack.cpp
+++ b/libfdtrack/fdtrack.cpp
@@ -60,7 +60,7 @@
 static constexpr size_t kStackDepth = 10;
 
 static bool installed = false;
-static std::array<FdEntry, kFdTableSize> stack_traces;
+static std::array<FdEntry, kFdTableSize> stack_traces [[clang::no_destroy]];
 static unwindstack::LocalUnwinder& Unwinder() {
   static android::base::NoDestructor<unwindstack::LocalUnwinder> unwinder;
   return *unwinder.get();
diff --git a/linker/Android.bp b/linker/Android.bp
index 4be080b..1792c74 100644
--- a/linker/Android.bp
+++ b/linker/Android.bp
@@ -46,6 +46,8 @@
 
     prefix_symbols: "__dlwrap_",
 
+    header_libs: ["libc_headers"],
+
     // We need to access Bionic private headers in the linker.
     include_dirs: ["bionic/libc"],
 }
@@ -404,6 +406,7 @@
 
     nocrt: true,
     system_shared_libs: [],
+    header_libs: ["libc_headers"],
 
     // Opt out of native_coverage when opting out of system_shared_libs
     native_coverage: false,
diff --git a/tests/Android.bp b/tests/Android.bp
index 1f45595..598865b 100644
--- a/tests/Android.bp
+++ b/tests/Android.bp
@@ -22,6 +22,12 @@
         darwin: {
             enabled: false,
         },
+        android: {
+            header_libs: ["bionic_libc_platform_headers"],
+        },
+        linux_bionic: {
+            header_libs: ["bionic_libc_platform_headers"],
+        },
     },
     cflags: [
         "-fstack-protector-all",
@@ -38,7 +44,6 @@
         // For glibc.
         "-D__STDC_LIMIT_MACROS",
     ],
-    header_libs: ["bionic_libc_platform_headers"],
     // Ensure that the tests exercise shadow call stack support and
     // the hint space PAC/BTI instructions.
     arch: {
diff --git a/tests/android_get_device_api_level.cpp b/tests/android_get_device_api_level.cpp
index 0662404..9bd6b3a 100644
--- a/tests/android_get_device_api_level.cpp
+++ b/tests/android_get_device_api_level.cpp
@@ -35,6 +35,6 @@
 TEST(android_get_device_api_level, smoke) {
 #if __BIONIC__
   // This will fail if you run the tests on an old device, but who does that?
-  ASSERT_GE(29, android_get_device_api_level());
+  ASSERT_GE(android_get_device_api_level(), 29);
 #endif
 }
diff --git a/tests/clang_fortify_tests.cpp b/tests/clang_fortify_tests.cpp
index 018880f..715f9c8 100644
--- a/tests/clang_fortify_tests.cpp
+++ b/tests/clang_fortify_tests.cpp
@@ -167,6 +167,8 @@
     EXPECT_FORTIFY_DEATH(memcpy(small_buffer, large_buffer, sizeof(large_buffer)));
     // expected-error@+1{{will always overflow}}
     EXPECT_FORTIFY_DEATH(memmove(small_buffer, large_buffer, sizeof(large_buffer)));
+    // FIXME(gbiv): look into removing mempcpy's diagnose_if bits once the b/149839606 roll sticks.
+    // expected-error@+2{{will always overflow}}
     // expected-error@+1{{size bigger than buffer}}
     EXPECT_FORTIFY_DEATH(mempcpy(small_buffer, large_buffer, sizeof(large_buffer)));
     // expected-error@+1{{will always overflow}}
diff --git a/tests/fdtrack_test.cpp b/tests/fdtrack_test.cpp
index fca92ce..0613f45 100644
--- a/tests/fdtrack_test.cpp
+++ b/tests/fdtrack_test.cpp
@@ -20,19 +20,41 @@
 #include <err.h>
 #include <errno.h>
 #include <fcntl.h>
+#include <netinet/in.h>
 #include <stdlib.h>
+#include <sys/epoll.h>
+#include <sys/eventfd.h>
 #include <sys/types.h>
 #include <unistd.h>
 
 #if defined(__BIONIC__)
 #include "platform/bionic/fdtrack.h"
+#include "platform/bionic/reserved_signals.h"
 #endif
 
 #include <vector>
 
+#include <android-base/cmsg.h>
+#include <android-base/logging.h>
 #include <android-base/unique_fd.h>
 
+using android::base::ReceiveFileDescriptors;
+using android::base::SendFileDescriptors;
+using android::base::unique_fd;
+
 #if defined(__BIONIC__)
+void DumpEvent(std::vector<android_fdtrack_event>* events, size_t index) {
+  auto& event = (*events)[index];
+  if (event.type == ANDROID_FDTRACK_EVENT_TYPE_CREATE) {
+    fprintf(stderr, "  event %zu: fd %d created by %s\n", index, event.fd,
+            event.data.create.function_name);
+  } else if (event.type == ANDROID_FDTRACK_EVENT_TYPE_CLOSE) {
+    fprintf(stderr, "  event %zu: fd %d closed\n", index, event.fd);
+  } else {
+    errx(1, "unexpected fdtrack event type: %d", event.type);
+  }
+}
+
 std::vector<android_fdtrack_event> FdtrackRun(void (*func)()) {
   // Each bionic test is run in separate process, so we can safely use a static here.
   static std::vector<android_fdtrack_event> events;
@@ -40,6 +62,7 @@
 
   android_fdtrack_hook_t previous = nullptr;
   android_fdtrack_hook_t hook = [](android_fdtrack_event* event) {
+    raise(BIONIC_SIGNAL_DEBUGGER);
     events.push_back(*event);
   };
 
@@ -58,21 +81,42 @@
     errx(1, "failed to reset hook");
   }
 
+  // Filter out temporary fds created and closed as a result of the call.
+  // (e.g. accept creating a socket to tell netd about the newly accepted socket)
+  size_t i = 0;
+  while (i + 1 < events.size()) {
+    auto& event = events[i];
+    if (event.type == ANDROID_FDTRACK_EVENT_TYPE_CREATE) {
+      for (size_t j = i + 1; j < events.size(); ++j) {
+        if (event.fd == events[j].fd) {
+          if (events[j].type == ANDROID_FDTRACK_EVENT_TYPE_CREATE) {
+            fprintf(stderr, "error: multiple create events for the same fd:\n");
+            DumpEvent(&events, i);
+            DumpEvent(&events, j);
+            exit(1);
+          }
+
+          events.erase(events.begin() + j);
+          events.erase(events.begin() + i);
+          continue;
+        }
+      }
+    }
+    ++i;
+  }
+
   return std::move(events);
 }
-#endif
 
-TEST(fdtrack, open) {
-#if defined(__BIONIC__)
-  static int fd = -1;
-  auto events = FdtrackRun([]() { fd = open("/dev/null", O_WRONLY | O_CLOEXEC); });
-  ASSERT_NE(-1, fd);
-  ASSERT_EQ(1U, events.size());
-  ASSERT_EQ(fd, events[0].fd);
-  ASSERT_EQ(ANDROID_FDTRACK_EVENT_TYPE_CREATE, events[0].type);
-  ASSERT_STREQ("open", events[0].data.create.function_name);
-#endif
+const char* FdtrackEventTypeToName(android_fdtrack_event_type event_type) {
+  switch (event_type) {
+    case ANDROID_FDTRACK_EVENT_TYPE_CREATE:
+      return "created";
+    case ANDROID_FDTRACK_EVENT_TYPE_CLOSE:
+      return "closed";
+  }
 }
+#endif
 
 TEST(fdtrack, close) {
 #if defined(__BIONIC__)
@@ -118,3 +162,131 @@
   ASSERT_STREQ("open", events[1].data.create.function_name);
 #endif
 }
+
+struct require_semicolon;
+
+#if defined(__BIONIC__)
+void SetFdResult(std::vector<int>* output, int fd) {
+  output->push_back(fd);
+}
+
+void SetFdResult(std::vector<int>* output, std::vector<int> fds) {
+  *output = fds;
+}
+
+#define FDTRACK_TEST_NAME(test_name, fdtrack_name, expression)                                   \
+  TEST(fdtrack, test_name) {                                                                     \
+    static std::vector<int> expected_fds;                                                        \
+    auto events = FdtrackRun([]() { SetFdResult(&expected_fds, expression); });                  \
+    for (auto& fd : expected_fds) {                                                              \
+      ASSERT_NE(-1, fd);                                                                         \
+    }                                                                                            \
+    if (events.size() != expected_fds.size()) {                                                  \
+      fprintf(stderr, "too many events received: expected %zu, got %zu:\n", expected_fds.size(), \
+              events.size());                                                                    \
+      for (size_t i = 0; i < events.size(); ++i) {                                               \
+        DumpEvent(&events, i);                                                                   \
+      }                                                                                          \
+      FAIL();                                                                                    \
+      return;                                                                                    \
+    }                                                                                            \
+    for (auto& event : events) {                                                                 \
+      ASSERT_NE(expected_fds.end(),                                                              \
+                std::find(expected_fds.begin(), expected_fds.end(), events[0].fd));              \
+      ASSERT_EQ(ANDROID_FDTRACK_EVENT_TYPE_CREATE, event.type);                                  \
+      ASSERT_STREQ(fdtrack_name, event.data.create.function_name);                               \
+    }                                                                                            \
+  }                                                                                              \
+  struct require_semicolon
+#else
+#define FDTRACK_TEST_NAME(name, fdtrack_name, expression) \
+  TEST(fdtrack, name) {}                                  \
+  struct require_semicolon
+#endif
+
+#define FDTRACK_TEST(name, expression) FDTRACK_TEST_NAME(name, #name, expression)
+
+// clang-format misformats statement expressions pretty badly here:
+// clang-format off
+FDTRACK_TEST(open, open("/dev/null", O_WRONLY | O_CLOEXEC));
+FDTRACK_TEST(openat, openat(AT_EMPTY_PATH, "/dev/null", O_WRONLY | O_CLOEXEC));
+FDTRACK_TEST(socket, socket(AF_UNIX, SOCK_STREAM, 0));
+
+FDTRACK_TEST(dup, dup(STDOUT_FILENO));
+FDTRACK_TEST(dup2, dup2(STDOUT_FILENO, STDERR_FILENO));
+FDTRACK_TEST(dup3, dup3(STDOUT_FILENO, STDERR_FILENO, 0));
+FDTRACK_TEST_NAME(fcntl_F_DUPFD, "F_DUPFD", fcntl(STDOUT_FILENO, F_DUPFD, 0));
+FDTRACK_TEST_NAME(fcntl_F_DUPFD_CLOEXEC, "F_DUPFD_CLOEXEC", fcntl(STDOUT_FILENO, F_DUPFD_CLOEXEC, 0));
+
+FDTRACK_TEST(pipe, ({
+  std::vector<int> fds = { -1, -1};
+  if (pipe(fds.data()) != 0) {
+    err(1, "pipe failed");
+  }
+  fds;
+}));
+
+FDTRACK_TEST(pipe2, ({
+  std::vector<int> fds = { -1, -1};
+  if (pipe2(fds.data(), O_CLOEXEC) != 0) {
+    err(1, "pipe failed");
+  }
+  fds;
+}));
+
+FDTRACK_TEST(socketpair, ({
+  std::vector<int> fds = { -1, -1};
+  if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, fds.data()) != 0) {
+    err(1, "socketpair failed");
+  }
+  fds;
+}));
+
+FDTRACK_TEST(epoll_create, epoll_create(1));
+FDTRACK_TEST(epoll_create1, epoll_create1(0));
+
+FDTRACK_TEST(eventfd, eventfd(0, 0));
+
+#if defined(__BIONIC__)
+static int CreateListener() {
+  android_fdtrack_set_enabled(false);
+  int listener = socket(AF_INET, SOCK_STREAM, 0);
+  CHECK_NE(-1, listener);
+
+  sockaddr_in addr = {
+      .sin_family = AF_INET,
+      .sin_port = 0,
+      .sin_addr = {htonl(INADDR_LOOPBACK)},
+  };
+  socklen_t addrlen = sizeof(addr);
+
+  CHECK_NE(-1, bind(listener, reinterpret_cast<sockaddr*>(&addr), addrlen)) << strerror(errno);
+  CHECK_NE(-1, getsockname(listener, reinterpret_cast<sockaddr*>(&addr), &addrlen));
+  CHECK_EQ(static_cast<size_t>(addrlen), sizeof(addr));
+  CHECK_NE(-1, listen(listener, 1));
+
+  int connector = socket(AF_INET, SOCK_STREAM, 0);
+  CHECK_NE(-1, connector);
+  CHECK_NE(-1, connect(connector, reinterpret_cast<sockaddr*>(&addr), addrlen));
+  android_fdtrack_set_enabled(true);
+
+  return listener;
+}
+#endif
+
+FDTRACK_TEST_NAME(accept, "accept4", accept(CreateListener(), nullptr, nullptr));
+FDTRACK_TEST(accept4, accept4(CreateListener(), nullptr, nullptr, 0));
+
+FDTRACK_TEST(recvmsg, ({
+  android_fdtrack_set_enabled(false);
+  int sockets[2];
+  ASSERT_NE(-1, socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets));
+  ASSERT_EQ(3, SendFileDescriptors(sockets[0], "foo", 3, STDIN_FILENO));
+  android_fdtrack_set_enabled(true);
+
+  char buf[4];
+  unique_fd received_fd;
+  ASSERT_EQ(3, ReceiveFileDescriptors(sockets[1], buf, sizeof(buf), &received_fd));
+  received_fd.release();
+}));
+// clang-format on
diff --git a/tests/mte_test.cpp b/tests/mte_test.cpp
index 8928805..ff8cde6 100644
--- a/tests/mte_test.cpp
+++ b/tests/mte_test.cpp
@@ -14,6 +14,10 @@
  * limitations under the License.
  */
 
+#include <sys/cdefs.h>
+
+#if defined(__BIONIC__)
+
 #include <gtest/gtest.h>
 
 #include <android-base/macros.h>
@@ -46,3 +50,5 @@
 TEST(mte_test, ScopedDisableMTE) {
   test_tag_mismatch();
 }
+
+#endif  // __BIONIC__
diff --git a/tests/utils.h b/tests/utils.h
index 5085a7a..a9b8513 100644
--- a/tests/utils.h
+++ b/tests/utils.h
@@ -25,7 +25,11 @@
 #include <sys/wait.h>
 #include <unistd.h>
 
+#if defined(__BIONIC__)
 #include <bionic/macros.h>
+#else
+#define untag_address(p) p
+#endif
 
 #include <atomic>
 #include <string>
diff --git a/tools/versioner/src/DeclarationDatabase.cpp b/tools/versioner/src/DeclarationDatabase.cpp
index 3c6f643..b41c865 100644
--- a/tools/versioner/src/DeclarationDatabase.cpp
+++ b/tools/versioner/src/DeclarationDatabase.cpp
@@ -72,7 +72,7 @@
 
     // <math.h> maps fool onto foo on 32-bit, since long double is the same as double.
     if (auto asm_attr = decl->getAttr<AsmLabelAttr>()) {
-      return asm_attr->getLabel();
+      return asm_attr->getLabel().str();
     }
 
     // The decl might not have a name (e.g. bitfields).
@@ -84,7 +84,7 @@
         return mangled;
       }
 
-      return identifier->getName();
+      return identifier->getName().str();
     }
 
     return "<unnamed>";
@@ -173,7 +173,7 @@
               &arch_availability[Arch::x86_64].introduced } },
         };
 
-        if (auto it = prefix_map.find(fragments[0]); it != prefix_map.end()) {
+        if (auto it = prefix_map.find(fragments[0].str()); it != prefix_map.end()) {
           int value;
           if (fragments[1].getAsInteger(10, value)) {
             errx(1, "invalid __ANDROID_AVAILABILITY_DUMP__ annotation: '%s'",
@@ -201,7 +201,7 @@
     }
 
     Location location = {
-      .filename = filename,
+      .filename = filename.str(),
       .start = {
         .line = src_manager.getExpansionLineNumber(expansion_range.getBegin()),
         .column = src_manager.getExpansionColumnNumber(expansion_range.getBegin()),
diff --git a/tools/versioner/src/Preprocessor.cpp b/tools/versioner/src/Preprocessor.cpp
index 4ee3446..7a5b502 100644
--- a/tools/versioner/src/Preprocessor.cpp
+++ b/tools/versioner/src/Preprocessor.cpp
@@ -446,7 +446,7 @@
       continue;
     }
 
-    std::string rel_path = path.substr(src_dir.length() + 1);
+    std::string rel_path = path.substr(src_dir.length() + 1).str();
     std::string dst_path = dst_dir + "/" + rel_path;
     llvm::StringRef parent_path = llvm::sys::path::parent_path(dst_path);
     if (llvm::sys::fs::create_directories(parent_path)) {
@@ -471,13 +471,13 @@
     GuardMap guard_map;
     for (const auto& it : orig_guard_map) {
       Location loc = it.first;
-      loc.end = findNextSemicolon(file_lines[file_path], loc.end);
+      loc.end = findNextSemicolon(file_lines[file_path.str()], loc.end);
       guard_map[loc] = it.second;
     }
 
     // TODO: Make sure that the Locations don't overlap.
     // TODO: Merge adjacent non-identical guards.
-    mergeGuards(file_lines[file_path], guard_map);
+    mergeGuards(file_lines[file_path.str()], guard_map);
 
     if (!file_path.startswith(src_dir)) {
       errx(1, "input file %s is not in %s\n", file_path.str().c_str(), src_dir.c_str());
@@ -487,7 +487,7 @@
     llvm::StringRef rel_path = file_path.substr(src_dir.size(), file_path.size() - src_dir.size());
     std::string output_path = (llvm::Twine(dst_dir) + rel_path).str();
 
-    rewriteFile(output_path, file_lines[file_path], guard_map);
+    rewriteFile(output_path, file_lines[file_path.str()], guard_map);
   }
 
   return true;