Merge "Remove bazel_module.label from bionic genrules"
diff --git a/TEST_MAPPING b/TEST_MAPPING
index 11efdae..da16e65 100644
--- a/TEST_MAPPING
+++ b/TEST_MAPPING
@@ -4,6 +4,12 @@
       "name": "CtsBionicTestCases"
     },
     {
+      "name": "CtsTaggingHostTestCases"
+    },
+    {
+      "name": "debuggerd_test"
+    },
+    {
       "name": "fdtrack_test"
     },
     {
@@ -17,9 +23,6 @@
     },
     {
       "name": "memunreachable_unit_test"
-    },
-    {
-      "name": "CtsTaggingHostTestCases"
     }
   ]
 }
diff --git a/libc/Android.bp b/libc/Android.bp
index dfbb7c1..4084b96 100644
--- a/libc/Android.bp
+++ b/libc/Android.bp
@@ -21,7 +21,6 @@
 }
 
 libc_common_src_files = [
-    "async_safe/async_safe_log.cpp",
     "bionic/ether_aton.c",
     "bionic/ether_ntoa.c",
     "bionic/exit.cpp",
@@ -1113,6 +1112,7 @@
         "bionic/open.cpp",
         "bionic/pathconf.cpp",
         "bionic/pause.cpp",
+        "bionic/pidfd.cpp",
         "bionic/pipe.cpp",
         "bionic/poll.cpp",
         "bionic/posix_fadvise.cpp",
@@ -1415,6 +1415,7 @@
     whole_static_libs: [
         "gwp_asan",
         "libarm-optimized-routines-string",
+        "libasync_safe",
         "libc_bionic_ndk",
         "libc_bootstrap",
         "libc_fortify",
@@ -1446,6 +1447,7 @@
 
     whole_static_libs: [
         "libarm-optimized-routines-string",
+        "libasync_safe",
         "libc_bionic",
         "libc_bionic_ndk",
         "libc_bootstrap",
@@ -2107,23 +2109,12 @@
 }
 
 cc_object {
-    name: "crtbegin_so1",
+    name: "crtbegin_so",
     local_include_dirs: ["include"],
     srcs: ["arch-common/bionic/crtbegin_so.c"],
 
     defaults: ["crt_so_defaults"],
-
-    bazel_module: {
-        bp2build_available: true,
-    },
-}
-
-cc_object {
-    name: "crtbegin_so",
-
-    defaults: ["crt_so_defaults"],
     objs: [
-        "crtbegin_so1",
         "crtbrand",
     ],
 
@@ -2132,7 +2123,10 @@
 
 cc_object {
     name: "crtend_so",
-    local_include_dirs: ["include"],
+    local_include_dirs: [
+        "include",
+        "private",  // crtend_so.S depends on private/bionic_asm_arm64.h
+    ],
     srcs: ["arch-common/bionic/crtend_so.S"],
 
     defaults: ["crt_so_defaults"],
@@ -2141,24 +2135,15 @@
 }
 
 cc_object {
-    name: "crtbegin_static1",
+    name: "crtbegin_static",
+
     local_include_dirs: [
         "include",
         "bionic", // crtbegin.c includes bionic/libc_init_common.h
     ],
+
     srcs: ["arch-common/bionic/crtbegin.c"],
-    defaults: ["crt_defaults"],
-    // When using libc.a, we're using the latest library regardless of target API level.
-    min_sdk_version: "current",
-
-    bazel_module: { bp2build_available: true },
-}
-
-cc_object {
-    name: "crtbegin_static",
-
     objs: [
-        "crtbegin_static1",
         "crtbrand",
     ],
     defaults: ["crt_defaults"],
@@ -2169,22 +2154,14 @@
 }
 
 cc_object {
-    name: "crtbegin_dynamic1",
+    name: "crtbegin_dynamic",
+
     local_include_dirs: [
         "include",
         "bionic", // crtbegin.c includes bionic/libc_init_common.h
     ],
     srcs: ["arch-common/bionic/crtbegin.c"],
-    defaults: ["crt_defaults"],
-
-    bazel_module: { bp2build_available: true },
-}
-
-cc_object {
-    name: "crtbegin_dynamic",
-
     objs: [
-        "crtbegin_dynamic1",
         "crtbrand",
     ],
     target: {
@@ -2204,7 +2181,10 @@
     // We rename crtend.o to crtend_android.o to avoid a
     // name clash between gcc and bionic.
     name: "crtend_android",
-    local_include_dirs: ["include"],
+    local_include_dirs: [
+        "include",
+        "private",  // crtend.S depends on private/bionic_asm_arm64.h
+    ],
     srcs: ["arch-common/bionic/crtend.S"],
 
     defaults: ["crt_defaults"],
@@ -2219,6 +2199,7 @@
         srcs: ["arch-arm64/bionic/note_memtag_heap_async.S"],
       }
     },
+    sdk_version: "minimum",
 
     defaults: ["crt_defaults"],
 }
@@ -2230,6 +2211,7 @@
         srcs: ["arch-arm64/bionic/note_memtag_heap_sync.S"],
       }
     },
+    sdk_version: "minimum",
 
     defaults: ["crt_defaults"],
 }
diff --git a/libc/SECCOMP_ALLOWLIST_COMMON.TXT b/libc/SECCOMP_ALLOWLIST_COMMON.TXT
index 804676e..6650d7e 100644
--- a/libc/SECCOMP_ALLOWLIST_COMMON.TXT
+++ b/libc/SECCOMP_ALLOWLIST_COMMON.TXT
@@ -72,5 +72,5 @@
 int rt_sigtimedwait_time64(const sigset64_t*, siginfo_t*, const timespec64*, size_t) lp32
 int futex_time64(int*, int, int, const timespec64*, int*, int) lp32
 int sched_rr_get_interval_time64(pid_t, timespec64*) lp32
-# Since Linux 5.3, not in glibc.
-int pidfd_open(pid_t pid, unsigned int flags) all
+# Since Linux 5.4, not in glibc. Probed for and conditionally used by ART.
+int userfaultfd(int) all
diff --git a/libc/SYSCALLS.TXT b/libc/SYSCALLS.TXT
index 33a8a61..d263508 100644
--- a/libc/SYSCALLS.TXT
+++ b/libc/SYSCALLS.TXT
@@ -358,3 +358,8 @@
 
 # <sys/random.h>
 ssize_t getrandom(void*, size_t, unsigned) all
+
+# <sys/pidfd.h>
+int __pidfd_open:pidfd_open(pid_t, unsigned int) all
+int __pidfd_getfd:pidfd_getfd(int, int, unsigned int) all
+int pidfd_send_signal(int, int, siginfo_t*, unsigned int) all
diff --git a/libc/async_safe/Android.bp b/libc/async_safe/Android.bp
index aed28d0..2e05d7a 100644
--- a/libc/async_safe/Android.bp
+++ b/libc/async_safe/Android.bp
@@ -37,6 +37,7 @@
         "com.android.media",
         "com.android.media.swcodec",
     ],
+    min_sdk_version: "apex_inherit",
 }
 
 cc_library_headers {
diff --git a/libc/bionic/fgetxattr.cpp b/libc/bionic/fgetxattr.cpp
index c753235..136d41f 100644
--- a/libc/bionic/fgetxattr.cpp
+++ b/libc/bionic/fgetxattr.cpp
@@ -37,7 +37,7 @@
 
 extern "C" ssize_t __fgetxattr(int, const char*, void*, size_t);
 
-ssize_t fgetxattr(int fd, const char *name, void *value, size_t size) {
+ssize_t fgetxattr(int fd, const char* name, void* value, size_t size) {
   int saved_errno = errno;
   ssize_t result = __fgetxattr(fd, name, value, size);
 
diff --git a/libc/bionic/flistxattr.cpp b/libc/bionic/flistxattr.cpp
index 3bad383..e42419f 100644
--- a/libc/bionic/flistxattr.cpp
+++ b/libc/bionic/flistxattr.cpp
@@ -37,7 +37,7 @@
 
 extern "C" ssize_t __flistxattr(int, char*, size_t);
 
-ssize_t flistxattr(int fd, char *list, size_t size) {
+ssize_t flistxattr(int fd, char* list, size_t size) {
   int saved_errno = errno;
   ssize_t result = __flistxattr(fd, list, size);
   if (result != -1 || errno != EBADF) {
@@ -45,7 +45,7 @@
   }
 
   // fd could be an O_PATH file descriptor, and the kernel
-  // may not directly support fgetxattr() on such a file descriptor.
+  // may not directly support flistxattr() on such a file descriptor.
   // Use /proc/self/fd instead to emulate this support.
   int fd_flag = fcntl(fd, F_GETFL);
   if (fd_flag == -1 || (fd_flag & O_PATH) == 0) {
diff --git a/libc/bionic/libc_init_common.cpp b/libc/bionic/libc_init_common.cpp
index a710fa8..dd623a5 100644
--- a/libc/bionic/libc_init_common.cpp
+++ b/libc/bionic/libc_init_common.cpp
@@ -132,6 +132,14 @@
   pthread_atfork(arc4random_fork_handler, _thread_arc4_unlock, _thread_arc4_unlock);
 }
 
+extern "C" void scudo_malloc_set_add_large_allocation_slack(int add_slack);
+
+__BIONIC_WEAK_FOR_NATIVE_BRIDGE void __libc_set_target_sdk_version(int target __unused) {
+#if defined(USE_SCUDO)
+  scudo_malloc_set_add_large_allocation_slack(target < __ANDROID_API_S__);
+#endif
+}
+
 __noreturn static void __early_abort(int line) {
   // We can't write to stdout or stderr because we're aborting before we've checked that
   // it's safe for us to use those file descriptors. We probably can't strace either, so
diff --git a/libc/bionic/libc_init_common.h b/libc/bionic/libc_init_common.h
index a899089..15c747e 100644
--- a/libc/bionic/libc_init_common.h
+++ b/libc/bionic/libc_init_common.h
@@ -66,4 +66,6 @@
 // pthread_atfork may call malloc() during its once-init.
 __LIBC_HIDDEN__ void __libc_init_fork_handler();
 
+__LIBC_HIDDEN__ void __libc_set_target_sdk_version(int target);
+
 #endif
diff --git a/libc/bionic/libc_init_dynamic.cpp b/libc/bionic/libc_init_dynamic.cpp
index 175fa3e..4625fa1 100644
--- a/libc/bionic/libc_init_dynamic.cpp
+++ b/libc/bionic/libc_init_dynamic.cpp
@@ -46,6 +46,7 @@
 #include <elf.h>
 #include "libc_init_common.h"
 
+#include "private/bionic_defs.h"
 #include "private/bionic_elf_tls.h"
 #include "private/bionic_globals.h"
 #include "platform/bionic/macros.h"
@@ -107,6 +108,8 @@
   __libc_shared_globals()->unload_hook = __hwasan_library_unloaded;
 #endif
 
+  __libc_shared_globals()->set_target_sdk_version_hook = __libc_set_target_sdk_version;
+
   netdClientInit();
 }
 
diff --git a/libc/bionic/libc_init_static.cpp b/libc/bionic/libc_init_static.cpp
index 2e4ee11..069ebb0 100644
--- a/libc/bionic/libc_init_static.cpp
+++ b/libc/bionic/libc_init_static.cpp
@@ -400,6 +400,7 @@
 
 extern "C" void android_set_application_target_sdk_version(int target) {
   g_target_sdk_version = target;
+  __libc_set_target_sdk_version(target);
 }
 
 // This function is called in the dynamic linker before ifunc resolvers have run, so this file is
diff --git a/libc/bionic/malloc_common_dynamic.cpp b/libc/bionic/malloc_common_dynamic.cpp
index 3a6958c..31d1e69 100644
--- a/libc/bionic/malloc_common_dynamic.cpp
+++ b/libc/bionic/malloc_common_dynamic.cpp
@@ -370,6 +370,7 @@
 
 extern "C" const char* __scudo_get_stack_depot_addr();
 extern "C" const char* __scudo_get_region_info_addr();
+extern "C" const char* __scudo_get_ring_buffer_addr();
 
 // Initializes memory allocation framework once per process.
 static void MallocInitImpl(libc_globals* globals) {
@@ -381,6 +382,7 @@
 #if defined(USE_SCUDO)
   __libc_shared_globals()->scudo_stack_depot = __scudo_get_stack_depot_addr();
   __libc_shared_globals()->scudo_region_info = __scudo_get_region_info_addr();
+  __libc_shared_globals()->scudo_ring_buffer = __scudo_get_ring_buffer_addr();
 #endif
 
   // Prefer malloc debug since it existed first and is a more complete
diff --git a/libc/bionic/eventfd_write.cpp b/libc/bionic/pidfd.cpp
similarity index 73%
rename from libc/bionic/eventfd_write.cpp
rename to libc/bionic/pidfd.cpp
index 6d86d8c..1dcb1fd 100644
--- a/libc/bionic/eventfd_write.cpp
+++ b/libc/bionic/pidfd.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010 The Android Open Source Project
+ * Copyright (C) 2021 The Android Open Source Project
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -26,6 +26,17 @@
  * SUCH DAMAGE.
  */
 
-#include <sys/eventfd.h>
-#include <unistd.h>
+#include <sys/pidfd.h>
 
+#include "private/bionic_fdtrack.h"
+
+extern "C" int __pidfd_open(pid_t pid, unsigned int flags);
+extern "C" int __pidfd_getfd(int pidfd, int targetfd, unsigned int flags);
+
+int pidfd_open(pid_t pid, unsigned int flags) {
+  return FDTRACK_CREATE(__pidfd_open(pid, flags));
+}
+
+int pidfd_getfd(int pidfd, int targetfd, unsigned int flags) {
+  return FDTRACK_CREATE(__pidfd_getfd(pidfd, targetfd, flags));
+}
diff --git a/libc/include/sys/pidfd.h b/libc/include/sys/pidfd.h
new file mode 100644
index 0000000..6d0e809
--- /dev/null
+++ b/libc/include/sys/pidfd.h
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2021 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+#pragma once
+
+/**
+ * @file sys/pidfd.h
+ * @brief File descriptors representing processes.
+ */
+
+#include <sys/cdefs.h>
+#include <sys/types.h>
+
+#include <bits/signal_types.h>
+
+__BEGIN_DECLS
+
+/**
+ * [pidfd_open(2)](https://man7.org/linux/man-pages/man2/pidfd_open.2.html)
+ * opens a file descriptor that refers to a process. This file descriptor will
+ * have the close-on-exec flag set by default.
+ *
+ * Returns a new file descriptor on success and returns -1 and sets `errno` on
+ * failure.
+ *
+ * Available since API level 31.
+ */
+int pidfd_open(pid_t __pid, unsigned int __flags) __INTRODUCED_IN(31);
+
+/**
+ * [pidfd_getfd(2)](https://man7.org/linux/man-pages/man2/pidfd_open.2.html)
+ * dups a file descriptor from another process. This file descriptor will have
+ * the close-on-exec flag set by default.
+ *
+ * Returns a new file descriptor on success and returns -1 and sets `errno` on
+ * failure.
+ *
+ * Available since API level 31.
+ */
+int pidfd_getfd(int __pidfd, int __targetfd, unsigned int __flags) __INTRODUCED_IN(31);
+
+/**
+ * [pidfd_send_signal(2)](https://man7.org/linux/man-pages/man2/pidfd_send_signal.2.html)
+ * sends a signal to another process.
+ *
+ * Returns 0 on success and returns -1 and sets `errno` on failure.
+ *
+ * Available since API level 31.
+ */
+int pidfd_send_signal(int __pidfd, int __sig, siginfo_t *__info, unsigned int __flags) __INTRODUCED_IN(31);
+
+__END_DECLS
diff --git a/libc/libc.map.txt b/libc/libc.map.txt
index f4f35ac..51a1076 100644
--- a/libc/libc.map.txt
+++ b/libc/libc.map.txt
@@ -1558,6 +1558,9 @@
     __libc_register_dynamic_tls_listeners;
     ffsl;
     ffsll;
+    pidfd_getfd;
+    pidfd_open;
+    pidfd_send_signal;
     process_madvise;
 } LIBC_R;
 
diff --git a/libc/private/bionic_globals.h b/libc/private/bionic_globals.h
index 16f89bf..e105c18 100644
--- a/libc/private/bionic_globals.h
+++ b/libc/private/bionic_globals.h
@@ -95,9 +95,10 @@
   TlsModules tls_modules;
   BionicAllocator tls_allocator;
 
-  // Values passed from the HWASan runtime (via libc.so) to the loader.
+  // Values passed from libc.so to the loader.
   void (*load_hook)(ElfW(Addr) base, const ElfW(Phdr)* phdr, ElfW(Half) phnum) = nullptr;
   void (*unload_hook)(ElfW(Addr) base, const ElfW(Phdr)* phdr, ElfW(Half) phnum) = nullptr;
+  void (*set_target_sdk_version_hook)(int target) = nullptr;
 
   // Values passed from the linker to libc.so.
   const char* init_progname = nullptr;
@@ -108,6 +109,7 @@
 
   const char* scudo_stack_depot = nullptr;
   const char* scudo_region_info = nullptr;
+  const char* scudo_ring_buffer = nullptr;
 
   HeapTaggingLevel initial_heap_tagging_level = M_HEAP_TAGGING_LEVEL_NONE;
 };
diff --git a/libfdtrack/fdtrack.cpp b/libfdtrack/fdtrack.cpp
index 898bc43..fd56274 100644
--- a/libfdtrack/fdtrack.cpp
+++ b/libfdtrack/fdtrack.cpp
@@ -31,9 +31,12 @@
 
 #include <array>
 #include <mutex>
+#include <thread>
+#include <utility>
 #include <vector>
 
 #include <android/fdsan.h>
+#include <android/set_abort_message.h>
 #include <bionic/fdtrack.h>
 
 #include <android-base/no_destructor.h>
@@ -48,6 +51,7 @@
 };
 
 extern "C" void fdtrack_dump();
+extern "C" void fdtrack_dump_fatal();
 
 using fdtrack_callback_t = bool (*)(int fd, const char* const* function_names,
                                     const uint64_t* function_offsets, size_t count, void* arg);
@@ -74,7 +78,17 @@
     entry.backtrace.reserve(kStackDepth);
   }
 
-  signal(BIONIC_SIGNAL_FDTRACK, [](int) { fdtrack_dump(); });
+  struct sigaction sa = {};
+  sa.sa_sigaction = [](int, siginfo_t* siginfo, void*) {
+    if (siginfo->si_code == SI_QUEUE && siginfo->si_int == 1) {
+      fdtrack_dump_fatal();
+    } else {
+      fdtrack_dump();
+    }
+  };
+  sa.sa_flags = SA_SIGINFO | SA_ONSTACK;
+  sigaction(BIONIC_SIGNAL_FDTRACK, &sa, nullptr);
+
   if (Unwinder().Init()) {
     android_fdtrack_hook_t expected = nullptr;
     installed = android_fdtrack_compare_exchange_hook(&expected, &fd_hook);
@@ -156,16 +170,47 @@
   android_fdtrack_set_enabled(prev);
 }
 
-void fdtrack_dump() {
+static size_t hash_stack(const char* const* function_names, const uint64_t* function_offsets,
+                         size_t stack_depth) {
+  size_t hash = 0;
+  for (size_t i = 0; i < stack_depth; ++i) {
+    // To future maintainers: if a libc++ update ever makes this invalid, replace this with +.
+    hash = std::__hash_combine(hash, std::hash<std::string_view>()(function_names[i]));
+    hash = std::__hash_combine(hash, std::hash<uint64_t>()(function_offsets[i]));
+  }
+  return hash;
+}
+
+static void fdtrack_dump_impl(bool fatal) {
   if (!installed) {
     async_safe_format_log(ANDROID_LOG_INFO, "fdtrack", "fdtrack not installed");
   } else {
     async_safe_format_log(ANDROID_LOG_INFO, "fdtrack", "fdtrack dumping...");
   }
 
+  // If we're aborting, identify the most common stack in the hopes that it's the culprit,
+  // and emit that in the abort message so crash reporting can separate different fd leaks out.
+  // This is horrible and quadratic, but we need to avoid allocation since this can happen in
+  // response to a signal generated asynchronously. We're only going to dump 1k fds by default,
+  // and we're about to blow up the entire system, so this isn't too expensive.
+  struct StackInfo {
+    size_t hash = 0;
+    size_t count = 0;
+
+    size_t stack_depth = 0;
+    const char* function_names[kStackDepth - kStackFrameSkip];
+    uint64_t function_offsets[kStackDepth - kStackFrameSkip];
+  };
+  struct StackList {
+    size_t count = 0;
+    std::array<StackInfo, 128> data;
+  };
+  static StackList stacks;
+
   fdtrack_iterate(
-      [](int fd, const char* const* function_names, const uint64_t* function_offsets, size_t count,
-         void*) {
+      [](int fd, const char* const* function_names, const uint64_t* function_offsets,
+         size_t stack_depth, void* stacks_ptr) {
+        auto stacks = static_cast<StackList*>(stacks_ptr);
         uint64_t fdsan_owner = android_fdsan_get_owner_tag(fd);
         if (fdsan_owner != 0) {
           async_safe_format_log(ANDROID_LOG_INFO, "fdtrack", "fd %d: (owner = 0x%" PRIx64 ")", fd,
@@ -174,12 +219,81 @@
           async_safe_format_log(ANDROID_LOG_INFO, "fdtrack", "fd %d: (unowned)", fd);
         }
 
-        for (size_t i = 0; i < count; ++i) {
+        for (size_t i = 0; i < stack_depth; ++i) {
           async_safe_format_log(ANDROID_LOG_INFO, "fdtrack", "  %zu: %s+%" PRIu64, i,
                                 function_names[i], function_offsets[i]);
         }
 
+        if (stacks) {
+          size_t hash = hash_stack(function_names, function_offsets, stack_depth);
+          bool found_stack = false;
+          for (size_t i = 0; i < stacks->count; ++i) {
+            if (stacks->data[i].hash == hash) {
+              ++stacks->data[i].count;
+              found_stack = true;
+              break;
+            }
+          }
+
+          if (!found_stack) {
+            if (stacks->count < stacks->data.size()) {
+              auto& stack = stacks->data[stacks->count++];
+              stack.hash = hash;
+              stack.count = 1;
+              stack.stack_depth = stack_depth;
+              for (size_t i = 0; i < stack_depth; ++i) {
+                stack.function_names[i] = function_names[i];
+                stack.function_offsets[i] = function_offsets[i];
+              }
+            }
+          }
+        }
+
         return true;
       },
-      nullptr);
+      fatal ? &stacks : nullptr);
+
+  if (fatal) {
+    // Find the most common stack.
+    size_t max = 0;
+    StackInfo* stack = nullptr;
+    for (size_t i = 0; i < stacks.count; ++i) {
+      if (stacks.data[i].count > max) {
+        stack = &stacks.data[i];
+        max = stack->count;
+      }
+    }
+
+    static char buf[1024];
+
+    if (!stack) {
+      async_safe_format_buffer(buf, sizeof(buf),
+                               "aborting due to fd leak: failed to find most common stack");
+    } else {
+      char* p = buf;
+      p += async_safe_format_buffer(buf, sizeof(buf),
+                                    "aborting due to fd leak: most common stack =\n");
+
+      for (size_t i = 0; i < stack->stack_depth; ++i) {
+        ssize_t bytes_left = buf + sizeof(buf) - p;
+        if (bytes_left > 0) {
+          p += async_safe_format_buffer(p, buf + sizeof(buf) - p, "  %zu: %s+%" PRIu64 "\n", i,
+                                        stack->function_names[i], stack->function_offsets[i]);
+        }
+      }
+    }
+
+    android_set_abort_message(buf);
+
+    // Abort on a different thread to avoid ART dumping runtime stacks.
+    std::thread([]() { abort(); }).join();
+  }
+}
+
+void fdtrack_dump() {
+  fdtrack_dump_impl(false);
+}
+
+void fdtrack_dump_fatal() {
+  fdtrack_dump_impl(true);
 }
diff --git a/libfdtrack/libfdtrack.map.txt b/libfdtrack/libfdtrack.map.txt
index 7a23954..6c4015c 100644
--- a/libfdtrack/libfdtrack.map.txt
+++ b/libfdtrack/libfdtrack.map.txt
@@ -1,6 +1,7 @@
 LIBFDTRACK {
   global:
     fdtrack_dump;
+    fdtrack_dump_fatal;
     fdtrack_iterate;
   local:
     *;
diff --git a/linker/ldd.sh b/linker/ldd.sh
index 6bc49b4..56810bb 100755
--- a/linker/ldd.sh
+++ b/linker/ldd.sh
@@ -10,7 +10,7 @@
 
 [ $# -eq 1 ] || error "usage: ldd FILE"
 
-what=$(file -L "$1")
+what=$(LD_LIBRARY_PATH= file -L "$1")
 case "$what" in
   *32-bit*)
     linker --list "$1"
diff --git a/linker/linker_debuggerd_android.cpp b/linker/linker_debuggerd_android.cpp
index 203e441..cba6345 100644
--- a/linker/linker_debuggerd_android.cpp
+++ b/linker/linker_debuggerd_android.cpp
@@ -42,6 +42,7 @@
       .gwp_asan_metadata = __libc_shared_globals()->gwp_asan_metadata,
       .scudo_stack_depot = __libc_shared_globals()->scudo_stack_depot,
       .scudo_region_info = __libc_shared_globals()->scudo_region_info,
+      .scudo_ring_buffer = __libc_shared_globals()->scudo_ring_buffer,
   };
 }
 #endif
diff --git a/linker/linker_sdk_versions.cpp b/linker/linker_sdk_versions.cpp
index 29c0f4a..0d5796e 100644
--- a/linker/linker_sdk_versions.cpp
+++ b/linker/linker_sdk_versions.cpp
@@ -31,6 +31,8 @@
 #include <android/api-level.h>
 #include <android/fdsan.h>
 
+#include "private/bionic_globals.h"
+
 #include "linker.h"
 
 static std::atomic<int> g_target_sdk_version(__ANDROID_API__);
@@ -45,6 +47,9 @@
   if (target < 30) {
     android_fdsan_set_error_level_from_property(ANDROID_FDSAN_ERROR_LEVEL_WARN_ONCE);
   }
+  if (__libc_shared_globals()->set_target_sdk_version_hook) {
+    __libc_shared_globals()->set_target_sdk_version_hook(target);
+  }
 }
 
 int get_application_target_sdk_version() {
diff --git a/tests/Android.bp b/tests/Android.bp
index 9b7e6f5..02a33ee 100644
--- a/tests/Android.bp
+++ b/tests/Android.bp
@@ -375,6 +375,7 @@
         "netinet_ip_icmp_test.cpp",
         "netinet_udp_test.cpp",
         "nl_types_test.cpp",
+        "pidfd_test.cpp",
         "poll_test.cpp",
         "prio_ctor_test.cpp",
         "pthread_test.cpp",
diff --git a/tests/NOTICE b/tests/NOTICE
index 305e816..a58cf46 100644
--- a/tests/NOTICE
+++ b/tests/NOTICE
@@ -338,3 +338,19 @@
 
 -------------------------------------------------------------------
 
+Copyright (C) 2021 The Android Open Source Project
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+
+-------------------------------------------------------------------
+
diff --git a/tests/fdtrack_test.cpp b/tests/fdtrack_test.cpp
index 95758bf..13f1b2e 100644
--- a/tests/fdtrack_test.cpp
+++ b/tests/fdtrack_test.cpp
@@ -28,6 +28,8 @@
 #include <unistd.h>
 
 #if defined(__BIONIC__)
+#include <sys/pidfd.h>
+
 #include "platform/bionic/fdtrack.h"
 #include "platform/bionic/reserved_signals.h"
 #endif
@@ -61,9 +63,7 @@
   events.clear();
 
   android_fdtrack_hook_t previous = nullptr;
-  android_fdtrack_hook_t hook = [](android_fdtrack_event* event) {
-    events.push_back(*event);
-  };
+  android_fdtrack_hook_t hook = [](android_fdtrack_event* event) { events.push_back(*event); };
 
   if (!android_fdtrack_compare_exchange_hook(&previous, hook)) {
     errx(1, "failed to exchange hook: previous hook was %p", previous);
@@ -178,7 +178,7 @@
     static std::vector<int> expected_fds;                                                        \
     auto events = FdtrackRun([]() { SetFdResult(&expected_fds, expression); });                  \
     for (auto& fd : expected_fds) {                                                              \
-      ASSERT_NE(-1, fd);                                                                         \
+      ASSERT_NE(-1, fd) << strerror(errno);                                                      \
     }                                                                                            \
     if (events.size() != expected_fds.size()) {                                                  \
       fprintf(stderr, "too many events received: expected %zu, got %zu:\n", expected_fds.size(), \
@@ -211,6 +211,37 @@
 FDTRACK_TEST(openat, openat(AT_EMPTY_PATH, "/dev/null", O_WRONLY | O_CLOEXEC));
 FDTRACK_TEST(socket, socket(AF_UNIX, SOCK_STREAM, 0));
 
+FDTRACK_TEST(pidfd_open, ({
+  int rc = pidfd_open(getpid(), 0);
+  if (rc == -1) {
+    ASSERT_EQ(ENOSYS, errno);
+    GTEST_SKIP() << "pidfd_open not available";
+  }
+  rc;
+}));
+
+FDTRACK_TEST(pidfd_getfd, ({
+  android_fdtrack_set_enabled(false);
+  int pidfd_self = pidfd_open(getpid(), 0);
+  if (pidfd_self == -1) {
+    ASSERT_EQ(ENOSYS, errno);
+    GTEST_SKIP() << "pidfd_open not available";
+  }
+  android_fdtrack_set_enabled(true);
+
+  int rc = pidfd_getfd(pidfd_self, STDIN_FILENO, 0);
+  if (rc == -1) {
+    ASSERT_EQ(ENOSYS, errno);
+    GTEST_SKIP() << "pidfd_getfd not available";
+  }
+
+  android_fdtrack_set_enabled(false);
+  close(pidfd_self);
+  android_fdtrack_set_enabled(true);
+
+  rc;
+}));
+
 FDTRACK_TEST(dup, dup(STDOUT_FILENO));
 FDTRACK_TEST(dup2, dup2(STDOUT_FILENO, STDERR_FILENO));
 FDTRACK_TEST(dup3, dup3(STDOUT_FILENO, STDERR_FILENO, 0));
diff --git a/tests/malloc_test.cpp b/tests/malloc_test.cpp
index 3a09258..d73f243 100644
--- a/tests/malloc_test.cpp
+++ b/tests/malloc_test.cpp
@@ -46,6 +46,7 @@
 #if defined(__BIONIC__)
 
 #include "SignalUtils.h"
+#include "dlext_private.h"
 
 #include "platform/bionic/malloc.h"
 #include "platform/bionic/mte.h"
@@ -1351,3 +1352,22 @@
   GTEST_SKIP() << "bionic extension";
 #endif
 }
+
+TEST(malloc, allocation_slack) {
+#if defined(__BIONIC__)
+  bool allocator_scudo;
+  GetAllocatorVersion(&allocator_scudo);
+  if (!allocator_scudo) {
+    GTEST_SKIP() << "scudo allocator only test";
+  }
+
+  // Test that older target SDK levels let you access a few bytes off the end of
+  // a large allocation.
+  android_set_application_target_sdk_version(29);
+  auto p = std::make_unique<char[]>(131072);
+  volatile char *vp = p.get();
+  volatile char oob ATTRIBUTE_UNUSED = vp[131072];
+#else
+  GTEST_SKIP() << "bionic extension";
+#endif
+}
diff --git a/tests/pidfd_test.cpp b/tests/pidfd_test.cpp
new file mode 100644
index 0000000..7c691ef
--- /dev/null
+++ b/tests/pidfd_test.cpp
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2021 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <errno.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#if defined(__BIONIC__)
+#include <sys/pidfd.h>
+#endif
+
+#include <android-base/unique_fd.h>
+
+#include <gtest/gtest.h>
+
+#include "BionicDeathTest.h"
+
+using android::base::unique_fd;
+using namespace std::chrono_literals;
+
+using pidfd_DeathTest = BionicDeathTest;
+
+TEST(pidfd, pidfd_open) {
+#if defined(__BIONIC__)
+  pid_t child = fork();
+  ASSERT_NE(-1, child);
+  if (child == 0) {
+    _exit(42);
+  }
+
+  unique_fd pidfd(pidfd_open(child, 0));
+  if (pidfd.get() == -1) {
+    ASSERT_EQ(ENOSYS, errno);
+    GTEST_SKIP() << "pidfd_open not available";
+  }
+
+  siginfo_t siginfo;
+  int rc = waitid(P_PIDFD, pidfd.get(), &siginfo, WEXITED);
+  if (rc == -1) {
+    ASSERT_EQ(EINVAL, errno) << strerror(errno);
+    GTEST_SKIP() << "P_PIDFD not available";
+  }
+
+  ASSERT_EQ(child, siginfo.si_pid);
+#endif
+}
+
+TEST(pidfd, pidfd_getfd) {
+#if defined(__BIONIC__)
+  unique_fd r, w;
+  ASSERT_TRUE(android::base::Pipe(&r, &w));
+  unique_fd self(pidfd_open(getpid(), 0));
+  if (self.get() == -1) {
+    ASSERT_EQ(ENOSYS, errno);
+    GTEST_SKIP() << "pidfd_open not available";
+  }
+
+  unique_fd dup(pidfd_getfd(self.get(), r.get(), 0));
+  if (dup.get() == -1) {
+    ASSERT_EQ(ENOSYS, errno) << strerror(errno);
+    GTEST_SKIP() << "pidfd_getfd not available";
+  }
+
+  ASSERT_NE(r.get(), dup.get());
+  ASSERT_EQ(3, write(w.get(), "foo", 3));
+  char buf[4];
+  ASSERT_EQ(3, read(dup.get(), buf, sizeof(buf)));
+  ASSERT_EQ(0, memcmp(buf, "foo", 3));
+#endif
+}
+
+TEST_F(pidfd_DeathTest, pidfd_send_signal) {
+#if defined(__BIONIC__)
+  unique_fd self(pidfd_open(getpid(), 0));
+  if (self.get() == -1) {
+    ASSERT_EQ(ENOSYS, errno);
+    GTEST_SKIP() << "pidfd_open not available";
+  }
+
+  if (pidfd_send_signal(self.get(), 0, nullptr, 0) == -1) {
+    ASSERT_EQ(ENOSYS, errno);
+    GTEST_SKIP() << "pidfd_send_signal not available";
+  }
+
+  ASSERT_EXIT(({
+                // gtest will fork a child off for ASSERT_EXIT: `self` refers to the parent.
+                unique_fd child(pidfd_open(getpid(), 0));
+                pidfd_send_signal(child.get(), SIGINT, nullptr, 0);
+              }),
+              testing::KilledBySignal(SIGINT), "");
+
+#endif
+}
diff --git a/tests/stdlib_test.cpp b/tests/stdlib_test.cpp
index bb1fd7c..90ef861 100644
--- a/tests/stdlib_test.cpp
+++ b/tests/stdlib_test.cpp
@@ -489,6 +489,12 @@
   ASSERT_EQ(1, WEXITSTATUS(status));
 }
 
+TEST(stdlib, system_NULL) {
+  // "The system() function shall always return non-zero when command is NULL."
+  // http://pubs.opengroup.org/onlinepubs/9699919799/functions/system.html
+  ASSERT_NE(0, system(nullptr));
+}
+
 TEST(stdlib, atof) {
   ASSERT_DOUBLE_EQ(1.23, atof("1.23"));
 }
diff --git a/tests/sys_stat_test.cpp b/tests/sys_stat_test.cpp
index 8f1437b..f36007e 100644
--- a/tests/sys_stat_test.cpp
+++ b/tests/sys_stat_test.cpp
@@ -120,6 +120,11 @@
 #endif
 }
 
+TEST(sys_stat, fchmod_EBADF) {
+  ASSERT_EQ(-1, fchmod(-1, 0751));
+  ASSERT_EQ(EBADF, errno);
+}
+
 TEST(sys_stat, fchmodat_EFAULT_file) {
   ASSERT_EQ(-1, fchmodat(AT_FDCWD, (char *) 0x1, 0751, 0));
   ASSERT_EQ(EFAULT, errno);
diff --git a/tests/sys_xattr_test.cpp b/tests/sys_xattr_test.cpp
index 8f4a336..45cf379 100644
--- a/tests/sys_xattr_test.cpp
+++ b/tests/sys_xattr_test.cpp
@@ -55,13 +55,13 @@
   ASSERT_EQ(ERANGE, errno);
 }
 
-TEST(sys_xattr, fsetxattr_invalidfd) {
+TEST(sys_xattr, fsetxattr_invalid_fd) {
   char buf[10];
   errno = 0;
-  ASSERT_EQ(-1, fsetxattr(65535, "user.foo", "0123", 5, 0));
+  ASSERT_EQ(-1, fsetxattr(-1, "user.foo", "0123", 5, 0));
   ASSERT_EQ(EBADF, errno);
   errno = 0;
-  ASSERT_EQ(-1, fgetxattr(65535, "user.foo", buf, sizeof(buf)));
+  ASSERT_EQ(-1, fgetxattr(-1, "user.foo", buf, sizeof(buf)));
   ASSERT_EQ(EBADF, errno);
 }
 
@@ -127,3 +127,10 @@
 #endif
   close(fd);
 }
+
+TEST(sys_xattr, flistattr_invalid_fd) {
+  char buf[65536];  // 64kB is max possible xattr list size. See "man 7 xattr".
+  errno = 0;
+  ASSERT_EQ(-1, flistxattr(-1, buf, sizeof(buf)));
+  ASSERT_EQ(EBADF, errno);
+}