Merge "Whitelist reboot reasons related to userspace reboot failure"
diff --git a/adb/Android.bp b/adb/Android.bp
index 3e8da8a..7c5e3ea 100644
--- a/adb/Android.bp
+++ b/adb/Android.bp
@@ -114,6 +114,61 @@
     },
 }
 
+// libadbconnection
+// =========================================================
+// libadbconnection_client/server implement the socket handling for jdwp
+// forwarding and the track-jdwp service.
+cc_library {
+    name: "libadbconnection_server",
+    srcs: ["adbconnection/adbconnection_server.cpp"],
+
+    export_include_dirs: ["adbconnection/include"],
+
+    stl: "libc++_static",
+    shared_libs: ["liblog"],
+    static_libs: ["libbase"],
+
+    defaults: ["adbd_defaults", "host_adbd_supported"],
+
+    // Avoid getting duplicate symbol of android::build::getbuildnumber().
+    use_version_lib: false,
+
+    recovery_available: true,
+    compile_multilib: "both",
+}
+
+cc_library {
+    name: "libadbconnection_client",
+    srcs: ["adbconnection/adbconnection_client.cpp"],
+
+    export_include_dirs: ["adbconnection/include"],
+
+    stl: "libc++_static",
+    shared_libs: ["liblog"],
+    static_libs: ["libbase"],
+
+    defaults: ["adbd_defaults"],
+    visibility: [
+        "//art:__subpackages__",
+        "//system/core/adb/apex:__subpackages__",
+    ],
+    apex_available: [
+        "com.android.adbd",
+        "test_com.android.adbd",
+    ],
+
+    // libadbconnection_client doesn't need an embedded build number.
+    use_version_lib: false,
+
+    stubs: {
+        symbol_file: "adbconnection/libadbconnection_client.map.txt",
+        versions: ["1"],
+    },
+
+    host_supported: true,
+    compile_multilib: "both",
+}
+
 // libadb
 // =========================================================
 // These files are compiled for both the host and the device.
@@ -358,11 +413,11 @@
     generated_headers: ["platform_tools_version"],
 
     static_libs: [
+        "libadbconnection_server",
         "libdiagnose_usb",
     ],
 
     shared_libs: [
-        "libadbconnection_server",
         "libadbd_auth",
         "libasyncio",
         "libbase",
@@ -411,12 +466,12 @@
     ],
 
     static_libs: [
+        "libadbconnection_server",
         "libadbd_core",
         "libdiagnose_usb",
     ],
 
     shared_libs: [
-        "libadbconnection_server",
         "libadbd_auth",
         "libasyncio",
         "libbase",
@@ -452,7 +507,7 @@
     defaults: ["adbd_defaults", "host_adbd_supported"],
     recovery_available: true,
 
-    // Avoid getting duplicate symbol of android::build::GetBuildNumber().
+    // avoid getting duplicate symbol of android::build::getbuildnumber().
     use_version_lib: false,
 
     // libminadbd wants both, as it's used to build native tests.
@@ -460,11 +515,11 @@
 
     // libadbd doesn't build any additional source, but to expose libadbd_core as a shared library.
     whole_static_libs: [
+        "libadbconnection_server",
         "libadbd_core",
     ],
 
     shared_libs: [
-        "libadbconnection_server",
         "libadbd_auth",
         "libadbd_services",
         "libasyncio",
@@ -500,6 +555,7 @@
 
     stl: "libc++_static",
     static_libs: [
+        "libadbconnection_server",
         "libadbd",
         "libadbd_auth",
         "libadbd_services",
@@ -516,7 +572,6 @@
     ],
 
     shared_libs: [
-        "libadbconnection_server",
         "libcrypto",
     ],
 }
@@ -730,39 +785,3 @@
         "fastdeploy/testdata/sample.cd",
     ],
 }
-
-prebuilt_etc {
-    name: "com.android.adbd.ld.config.txt",
-    src: "apex/ld.config.txt",
-    filename: "ld.config.txt",
-    installable: false,
-}
-
-apex {
-    name: "com.android.adbd",
-    manifest: "apex/apex_manifest.json",
-
-    binaries: ["adbd"],
-    prebuilts: ["com.android.adbd.init.rc", "com.android.adbd.ld.config.txt"],
-
-    key: "com.android.adbd.key",
-    certificate: ":com.android.adbd.certificate",
-}
-
-apex_key {
-    name: "com.android.adbd.key",
-    public_key: "apex/com.android.adbd.avbpubkey",
-    private_key: "apex/com.android.adbd.pem",
-}
-
-android_app_certificate {
-    name: "com.android.adbd.certificate",
-    certificate: "apex/com.android.adbd",
-}
-
-prebuilt_etc {
-    name: "com.android.adbd.init.rc",
-    src: "apex/adbd.rc",
-    filename: "init.rc",
-    installable: false,
-}
diff --git a/adb/adbconnection/.clang-format b/adb/adbconnection/.clang-format
new file mode 120000
index 0000000..e545823
--- /dev/null
+++ b/adb/adbconnection/.clang-format
@@ -0,0 +1 @@
+../../.clang-format-2
\ No newline at end of file
diff --git a/adb/adbconnection/adbconnection_client.cpp b/adb/adbconnection/adbconnection_client.cpp
new file mode 100644
index 0000000..ee48abb
--- /dev/null
+++ b/adb/adbconnection/adbconnection_client.cpp
@@ -0,0 +1,148 @@
+/*
+ * Copyright (C) 2020 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 "adbconnection/client.h"
+
+#include <pwd.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+
+#include <memory>
+#include <optional>
+
+#include <android-base/cmsg.h>
+#include <android-base/logging.h>
+#include <android-base/unique_fd.h>
+
+using android::base::unique_fd;
+
+static constexpr char kJdwpControlName[] = "\0jdwp-control";
+
+struct AdbConnectionClientContext {
+  unique_fd control_socket_;
+};
+
+bool SocketPeerIsTrusted(int fd) {
+  ucred cr;
+  socklen_t cr_length = sizeof(cr);
+  if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_length) != 0) {
+    PLOG(ERROR) << "couldn't get socket credentials";
+    return false;
+  }
+
+  passwd* shell = getpwnam("shell");
+  if (cr.uid != 0 && cr.uid != shell->pw_uid) {
+    LOG(ERROR) << "untrusted uid " << cr.uid << " on other end of socket";
+    return false;
+  }
+
+  return true;
+}
+
+AdbConnectionClientContext* adbconnection_client_new(
+    const AdbConnectionClientInfo* const* info_elems, size_t info_count) {
+  auto ctx = std::make_unique<AdbConnectionClientContext>();
+
+  std::optional<uint64_t> pid;
+  std::optional<bool> debuggable;
+
+  for (size_t i = 0; i < info_count; ++i) {
+    auto info = info_elems[i];
+    switch (info->type) {
+      case AdbConnectionClientInfoType::pid:
+        if (pid) {
+          LOG(ERROR) << "multiple pid entries in AdbConnectionClientInfo, ignoring";
+          continue;
+        }
+        pid = info->data.pid;
+        break;
+
+      case AdbConnectionClientInfoType::debuggable:
+        if (debuggable) {
+          LOG(ERROR) << "multiple debuggable entries in AdbConnectionClientInfo, ignoring";
+          continue;
+        }
+        debuggable = info->data.pid;
+        break;
+    }
+  }
+
+  if (!pid) {
+    LOG(ERROR) << "AdbConnectionClientInfo missing required field pid";
+    return nullptr;
+  }
+
+  if (!debuggable) {
+    LOG(ERROR) << "AdbConnectionClientInfo missing required field debuggable";
+    return nullptr;
+  }
+
+  ctx->control_socket_.reset(socket(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0));
+  if (ctx->control_socket_ < 0) {
+    PLOG(ERROR) << "failed to create Unix domain socket";
+    return nullptr;
+  }
+
+  struct timeval timeout;
+  timeout.tv_sec = 1;
+  timeout.tv_usec = 0;
+  setsockopt(ctx->control_socket_.get(), SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
+
+  sockaddr_un addr = {};
+  addr.sun_family = AF_UNIX;
+  memcpy(addr.sun_path, kJdwpControlName, sizeof(kJdwpControlName));
+  size_t addr_len = offsetof(sockaddr_un, sun_path) + sizeof(kJdwpControlName) - 1;
+
+  int rc = connect(ctx->control_socket_.get(), reinterpret_cast<sockaddr*>(&addr), addr_len);
+  if (rc != 0) {
+    PLOG(ERROR) << "failed to connect to jdwp control socket";
+    return nullptr;
+  }
+
+  bool trusted = SocketPeerIsTrusted(ctx->control_socket_.get());
+  if (!trusted) {
+    LOG(ERROR) << "adb socket is not trusted, aborting connection";
+    return nullptr;
+  }
+
+  uint32_t pid_u32 = static_cast<uint32_t>(*pid);
+  rc = TEMP_FAILURE_RETRY(write(ctx->control_socket_.get(), &pid_u32, sizeof(pid_u32)));
+  if (rc != sizeof(pid_u32)) {
+    PLOG(ERROR) << "failed to send JDWP process pid to adbd";
+  }
+
+  return ctx.release();
+}
+
+void adbconnection_client_destroy(AdbConnectionClientContext* ctx) {
+  delete ctx;
+}
+
+int adbconnection_client_pollfd(AdbConnectionClientContext* ctx) {
+  return ctx->control_socket_.get();
+}
+
+int adbconnection_client_receive_jdwp_fd(AdbConnectionClientContext* ctx) {
+  char dummy;
+  unique_fd jdwp_fd;
+  ssize_t rc = android::base::ReceiveFileDescriptors(ctx->control_socket_, &dummy, 1, &jdwp_fd);
+  if (rc != 1) {
+    return rc;
+  }
+  return jdwp_fd.release();
+}
diff --git a/adb/adbconnection/adbconnection_server.cpp b/adb/adbconnection/adbconnection_server.cpp
new file mode 100644
index 0000000..939da2f
--- /dev/null
+++ b/adb/adbconnection/adbconnection_server.cpp
@@ -0,0 +1,129 @@
+/*
+ * Copyright (C) 2019 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 "adbconnection/server.h"
+
+#include <sys/epoll.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <unistd.h>
+
+#include <algorithm>
+#include <array>
+#include <vector>
+
+#include <android-base/logging.h>
+#include <android-base/unique_fd.h>
+
+using android::base::unique_fd;
+
+#define JDWP_CONTROL_NAME "\0jdwp-control"
+#define JDWP_CONTROL_NAME_LEN (sizeof(JDWP_CONTROL_NAME) - 1)
+
+static_assert(JDWP_CONTROL_NAME_LEN <= sizeof(reinterpret_cast<sockaddr_un*>(0)->sun_path));
+
+// Listen for incoming jdwp clients forever.
+void adbconnection_listen(void (*callback)(int fd, pid_t pid)) {
+  sockaddr_un addr = {};
+  socklen_t addrlen = JDWP_CONTROL_NAME_LEN + sizeof(addr.sun_family);
+
+  addr.sun_family = AF_UNIX;
+  memcpy(addr.sun_path, JDWP_CONTROL_NAME, JDWP_CONTROL_NAME_LEN);
+
+  unique_fd s(socket(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0));
+  if (s < 0) {
+    PLOG(ERROR) << "failed to create JDWP control socket";
+    return;
+  }
+
+  if (bind(s.get(), reinterpret_cast<sockaddr*>(&addr), addrlen) < 0) {
+    PLOG(ERROR) << "failed to bind JDWP control socket";
+    return;
+  }
+
+  if (listen(s.get(), 4) < 0) {
+    PLOG(ERROR) << "failed to listen on JDWP control socket";
+    return;
+  }
+
+  std::vector<unique_fd> pending_connections;
+
+  unique_fd epfd(epoll_create1(EPOLL_CLOEXEC));
+  std::array<epoll_event, 16> events;
+
+  events[0].events = EPOLLIN;
+  events[0].data.fd = -1;
+  if (epoll_ctl(epfd.get(), EPOLL_CTL_ADD, s.get(), &events[0]) != 0) {
+    LOG(FATAL) << "failed to register event with epoll fd";
+  }
+
+  while (true) {
+    int epoll_rc = TEMP_FAILURE_RETRY(epoll_wait(epfd.get(), events.data(), events.size(), -1));
+    if (epoll_rc == -1) {
+      PLOG(FATAL) << "epoll_wait failed";
+    }
+
+    for (int i = 0; i < epoll_rc; ++i) {
+      const epoll_event& event = events[i];
+      if (event.data.fd == -1) {
+        unique_fd client(
+            TEMP_FAILURE_RETRY(accept4(s.get(), nullptr, nullptr, SOCK_NONBLOCK | SOCK_CLOEXEC)));
+
+        if (client == -1) {
+          PLOG(WARNING) << "failed to accept client on JDWP control socket";
+          continue;
+        }
+
+        epoll_event register_event;
+        register_event.events = EPOLLIN;
+        register_event.data.fd = client.get();
+
+        if (epoll_ctl(epfd.get(), EPOLL_CTL_ADD, client.get(), &register_event) != 0) {
+          PLOG(FATAL) << "failed to register JDWP client with epoll";
+        }
+
+        pending_connections.emplace_back(std::move(client));
+      } else {
+        // n^2, but the backlog should be short.
+        auto it = std::find_if(pending_connections.begin(), pending_connections.end(),
+                               [&](const unique_fd& fd) { return fd.get() == event.data.fd; });
+
+        if (it == pending_connections.end()) {
+          LOG(FATAL) << "failed to find JDWP client (" << event.data.fd
+                     << ") in pending connections";
+        }
+
+        // Massively oversized buffer: we're expecting an int32_t from the other end.
+        char buf[32];
+        int rc = TEMP_FAILURE_RETRY(recv(it->get(), buf, sizeof(buf), MSG_DONTWAIT));
+        if (rc != 4) {
+          LOG(ERROR) << "received data of incorrect size from JDWP client: read " << rc
+                     << ", expected 4";
+        } else {
+          int32_t pid;
+          memcpy(&pid, buf, sizeof(pid));
+          callback(it->release(), static_cast<pid_t>(pid));
+        }
+
+        if (epoll_ctl(epfd.get(), EPOLL_CTL_DEL, event.data.fd, nullptr) != 0) {
+          LOG(FATAL) << "failed to delete fd from JDWP epoll fd";
+        }
+
+        pending_connections.erase(it);
+      }
+    }
+  }
+}
diff --git a/adb/adbconnection/include/adbconnection/client.h b/adb/adbconnection/include/adbconnection/client.h
new file mode 100644
index 0000000..692fea0
--- /dev/null
+++ b/adb/adbconnection/include/adbconnection/client.h
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#pragma once
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <android-base/unique_fd.h>
+
+extern "C" {
+
+struct AdbConnectionClientContext;
+
+enum AdbConnectionClientInfoType {
+  pid,
+  debuggable,
+};
+
+struct AdbConnectionClientInfo {
+  AdbConnectionClientInfoType type;
+  union {
+    uint64_t pid;
+    bool debuggable;
+  } data;
+};
+
+// Construct a context and connect to adbd.
+// Returns null if we fail to connect to adbd.
+AdbConnectionClientContext* adbconnection_client_new(
+    const AdbConnectionClientInfo* const* info_elems, size_t info_count);
+
+void adbconnection_client_destroy(AdbConnectionClientContext* ctx);
+
+// Get an fd which can be polled upon to detect when a jdwp socket is available.
+// You do not own this fd. Do not close it.
+int adbconnection_client_pollfd(AdbConnectionClientContext* ctx);
+
+// Receive a jdwp client fd.
+// Ownership is transferred to the caller of this function.
+int adbconnection_client_receive_jdwp_fd(AdbConnectionClientContext* ctx);
+}
diff --git a/adb/adbconnection/include/adbconnection/server.h b/adb/adbconnection/include/adbconnection/server.h
new file mode 100644
index 0000000..57ca6cd
--- /dev/null
+++ b/adb/adbconnection/include/adbconnection/server.h
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#pragma once
+
+#include <sys/types.h>
+
+#include <android-base/unique_fd.h>
+
+extern "C" {
+
+void adbconnection_listen(void (*callback)(int fd, pid_t pid));
+}
diff --git a/adb/adbconnection/libadbconnection_client.map.txt b/adb/adbconnection/libadbconnection_client.map.txt
new file mode 100644
index 0000000..153a0e4
--- /dev/null
+++ b/adb/adbconnection/libadbconnection_client.map.txt
@@ -0,0 +1,25 @@
+#
+# Copyright (C) 2019 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.
+#
+
+LIBADBCONNECTION_CLIENT_1 {
+  global:
+    adbconnection_client_new;
+    adbconnection_client_destroy;
+    adbconnection_client_pollfd;
+    adbconnection_client_receive_jdwp_fd;
+  local:
+    *;
+};
diff --git a/adb/apex/Android.bp b/adb/apex/Android.bp
new file mode 100644
index 0000000..75c4ed9
--- /dev/null
+++ b/adb/apex/Android.bp
@@ -0,0 +1,55 @@
+apex_defaults {
+    name: "com.android.adbd-defaults",
+
+    binaries: ["adbd"],
+    compile_multilib: "both",
+    multilib: {
+        both: {
+            native_shared_libs: ["libadbconnection_client"],
+        },
+    },
+    prebuilts: ["com.android.adbd.init.rc", "com.android.adbd.ld.config.txt"],
+
+    key: "com.android.adbd.key",
+    certificate: ":com.android.adbd.certificate",
+}
+
+apex {
+    name: "com.android.adbd",
+    defaults: ["com.android.adbd-defaults"],
+    manifest: "apex_manifest.json",
+}
+
+// adbd apex with INT_MAX version code, to allow for upgrade/rollback testing.
+apex {
+    name: "test_com.android.adbd",
+    defaults: ["com.android.adbd-defaults"],
+    manifest: "test_apex_manifest.json",
+    file_contexts: ":com.android.adbd-file_contexts",
+    installable: false,
+}
+
+prebuilt_etc {
+    name: "com.android.adbd.ld.config.txt",
+    src: "ld.config.txt",
+    filename: "ld.config.txt",
+    installable: false,
+}
+
+prebuilt_etc {
+    name: "com.android.adbd.init.rc",
+    src: "adbd.rc",
+    filename: "init.rc",
+    installable: false,
+}
+
+apex_key {
+    name: "com.android.adbd.key",
+    public_key: "com.android.adbd.avbpubkey",
+    private_key: "com.android.adbd.pem",
+}
+
+android_app_certificate {
+    name: "com.android.adbd.certificate",
+    certificate: "com.android.adbd",
+}
diff --git a/adb/apex/test_apex_manifest.json b/adb/apex/test_apex_manifest.json
new file mode 100644
index 0000000..7131977
--- /dev/null
+++ b/adb/apex/test_apex_manifest.json
@@ -0,0 +1,4 @@
+{
+  "name": "com.android.adbd",
+  "version": 2147483647
+}
diff --git a/adb/client/file_sync_client.cpp b/adb/client/file_sync_client.cpp
index fbfeb53..922f2ba 100644
--- a/adb/client/file_sync_client.cpp
+++ b/adb/client/file_sync_client.cpp
@@ -187,14 +187,13 @@
         const char* direction_str = (direction == TransferDirection::push) ? "pushed" : "pulled";
         std::stringstream ss;
         if (!name.empty()) {
-            ss << name << ": ";
+            std::string_view display_name(name);
+            char* out = getenv("ANDROID_PRODUCT_OUT");
+            if (out) android::base::ConsumePrefix(&display_name, out);
+            ss << display_name << ": ";
         }
         ss << files_transferred << " file" << ((files_transferred == 1) ? "" : "s") << " "
-           << direction_str << ".";
-        if (files_skipped > 0) {
-            ss << " " << files_skipped << " file" << ((files_skipped == 1) ? "" : "s")
-               << " skipped.";
-        }
+           << direction_str << ", " << files_skipped << " skipped.";
         ss << TransferRate();
 
         lp.Print(ss.str(), LinePrinter::LineType::INFO);
diff --git a/base/Android.bp b/base/Android.bp
index b25d0df..a32959b 100644
--- a/base/Android.bp
+++ b/base/Android.bp
@@ -33,6 +33,7 @@
 cc_library_headers {
     name: "libbase_headers",
     vendor_available: true,
+    ramdisk_available: true,
     recovery_available: true,
     host_supported: true,
     native_bridge_supported: true,
@@ -112,6 +113,7 @@
     name: "libbase",
     defaults: ["libbase_defaults"],
     vendor_available: true,
+    ramdisk_available: true,
     recovery_available: true,
     host_supported: true,
     native_bridge_supported: true,
diff --git a/base/include/android-base/errno_restorer.h b/base/include/android-base/errno_restorer.h
new file mode 100644
index 0000000..1c8597c
--- /dev/null
+++ b/base/include/android-base/errno_restorer.h
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2020 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.
+ */
+
+#pragma once
+
+#include "errno.h"
+
+#include "android-base/macros.h"
+
+namespace android {
+namespace base {
+
+class ErrnoRestorer {
+ public:
+  ErrnoRestorer() : saved_errno_(errno) {}
+
+  ~ErrnoRestorer() { errno = saved_errno_; }
+
+  // Allow this object to be used as part of && operation.
+  operator bool() const { return true; }
+
+ private:
+  const int saved_errno_;
+
+  DISALLOW_COPY_AND_ASSIGN(ErrnoRestorer);
+};
+
+}  // namespace base
+}  // namespace android
diff --git a/base/include/android-base/expected.h b/base/include/android-base/expected.h
index 030ef35e..b3f5adb 100644
--- a/base/include/android-base/expected.h
+++ b/base/include/android-base/expected.h
@@ -111,6 +111,7 @@
     !(!std::is_convertible_v<const U&, T> ||
      !std::is_convertible_v<const G&, E>) /* non-explicit */
   )>
+  // NOLINTNEXTLINE(google-explicit-constructor)
   constexpr expected(const expected<U, G>& rhs) {
     if (rhs.has_value()) var_ = rhs.value();
     else var_ = unexpected(rhs.error());
@@ -149,6 +150,7 @@
     !(!std::is_convertible_v<const U&, T> ||
      !std::is_convertible_v<const G&, E>) /* non-explicit */
   )>
+  // NOLINTNEXTLINE(google-explicit-constructor)
   constexpr expected(expected<U, G>&& rhs) {
     if (rhs.has_value()) var_ = std::move(rhs.value());
     else var_ = unexpected(std::move(rhs.error()));
@@ -180,6 +182,7 @@
                 !std::is_same_v<unexpected<E>, std::remove_cv_t<std::remove_reference_t<U>>> &&
                 std::is_convertible_v<U&&, T> /* non-explicit */
                 )>
+  // NOLINTNEXTLINE(google-explicit-constructor)
   constexpr expected(U&& v) : var_(std::in_place_index<0>, std::forward<U>(v)) {}
 
   template <class U = T _ENABLE_IF(
@@ -195,6 +198,7 @@
     std::is_constructible_v<E, const G&> &&
     std::is_convertible_v<const G&, E> /* non-explicit */
   )>
+  // NOLINTNEXTLINE(google-explicit-constructor)
   constexpr expected(const unexpected<G>& e)
   : var_(std::in_place_index<1>, e.value()) {}
 
@@ -209,6 +213,7 @@
     std::is_constructible_v<E, G&&> &&
     std::is_convertible_v<G&&, E> /* non-explicit */
   )>
+  // NOLINTNEXTLINE(google-explicit-constructor)
   constexpr expected(unexpected<G>&& e)
   : var_(std::in_place_index<1>, std::move(e.value())) {}
 
@@ -457,6 +462,7 @@
     std::is_void_v<U> &&
     std::is_convertible_v<const G&, E> /* non-explicit */
   )>
+  // NOLINTNEXTLINE(google-explicit-constructor)
   constexpr expected(const expected<U, G>& rhs) {
     if (!rhs.has_value()) var_ = unexpected(rhs.error());
   }
@@ -473,6 +479,7 @@
     std::is_void_v<U> &&
     std::is_convertible_v<const G&&, E> /* non-explicit */
   )>
+  // NOLINTNEXTLINE(google-explicit-constructor)
   constexpr expected(expected<U, G>&& rhs) {
     if (!rhs.has_value()) var_ = unexpected(std::move(rhs.error()));
   }
@@ -489,6 +496,7 @@
     std::is_constructible_v<E, const G&> &&
     std::is_convertible_v<const G&, E> /* non-explicit */
   )>
+  // NOLINTNEXTLINE(google-explicit-constructor)
   constexpr expected(const unexpected<G>& e)
   : var_(std::in_place_index<1>, e.value()) {}
 
@@ -503,6 +511,7 @@
     std::is_constructible_v<E, G&&> &&
     std::is_convertible_v<G&&, E> /* non-explicit */
   )>
+  // NOLINTNEXTLINE(google-explicit-constructor)
   constexpr expected(unexpected<G>&& e)
   : var_(std::in_place_index<1>, std::move(e.value())) {}
 
@@ -640,6 +649,7 @@
                 std::is_constructible_v<E, Err> &&
                 !std::is_same_v<std::remove_cv_t<std::remove_reference_t<E>>, std::in_place_t> &&
                 !std::is_same_v<std::remove_cv_t<std::remove_reference_t<E>>, unexpected>)>
+  // NOLINTNEXTLINE(google-explicit-constructor)
   constexpr unexpected(Err&& e) : val_(std::forward<Err>(e)) {}
 
   template<class U, class... Args _ENABLE_IF(
@@ -660,6 +670,7 @@
     !std::is_convertible_v<const unexpected<Err>, E> &&
     std::is_convertible_v<Err, E> /* non-explicit */
   )>
+  // NOLINTNEXTLINE(google-explicit-constructor)
   constexpr unexpected(const unexpected<Err>& rhs)
   : val_(rhs.value()) {}
 
@@ -690,6 +701,7 @@
     !std::is_convertible_v<const unexpected<Err>, E> &&
     std::is_convertible_v<Err, E> /* non-explicit */
   )>
+  // NOLINTNEXTLINE(google-explicit-constructor)
   constexpr unexpected(unexpected<Err>&& rhs)
   : val_(std::move(rhs.value())) {}
 
diff --git a/base/include/android-base/logging.h b/base/include/android-base/logging.h
index 7fd0182..accc225 100644
--- a/base/include/android-base/logging.h
+++ b/base/include/android-base/logging.h
@@ -64,6 +64,7 @@
 #include <memory>
 #include <ostream>
 
+#include "android-base/errno_restorer.h"
 #include "android-base/macros.h"
 
 // Note: DO NOT USE DIRECTLY. Use LOG_TAG instead.
@@ -115,7 +116,6 @@
 
 void DefaultAborter(const char* abort_message);
 
-std::string GetDefaultTag();
 void SetDefaultTag(const std::string& tag);
 
 // We expose this even though it is the default because a user that wants to
@@ -155,27 +155,6 @@
 // Replace the current aborter.
 void SetAborter(AbortFunction&& aborter);
 
-class ErrnoRestorer {
- public:
-  ErrnoRestorer()
-      : saved_errno_(errno) {
-  }
-
-  ~ErrnoRestorer() {
-    errno = saved_errno_;
-  }
-
-  // Allow this object to be used as part of && operation.
-  operator bool() const {
-    return true;
-  }
-
- private:
-  const int saved_errno_;
-
-  DISALLOW_COPY_AND_ASSIGN(ErrnoRestorer);
-};
-
 // A helper macro that produces an expression that accepts both a qualified name and an
 // unqualified name for a LogSeverity, and returns a LogSeverity value.
 // Note: DO NOT USE DIRECTLY. This is an implementation detail.
diff --git a/base/include/android-base/result.h b/base/include/android-base/result.h
index 1b763af..b6d26e7 100644
--- a/base/include/android-base/result.h
+++ b/base/include/android-base/result.h
@@ -90,6 +90,7 @@
   ResultError(T&& message, int code) : message_(std::forward<T>(message)), code_(code) {}
 
   template <typename T>
+  // NOLINTNEXTLINE(google-explicit-constructor)
   operator android::base::expected<T, ResultError>() {
     return android::base::unexpected(ResultError(message_, code_));
   }
@@ -118,9 +119,11 @@
 class Error {
  public:
   Error() : errno_(0), append_errno_(false) {}
+  // NOLINTNEXTLINE(google-explicit-constructor)
   Error(int errno_to_append) : errno_(errno_to_append), append_errno_(true) {}
 
   template <typename T>
+  // NOLINTNEXTLINE(google-explicit-constructor)
   operator android::base::expected<T, ResultError>() {
     return android::base::unexpected(ResultError(str(), errno_));
   }
diff --git a/base/liblog_symbols.cpp b/base/liblog_symbols.cpp
index d0e2eaa..d5dfcd2 100644
--- a/base/liblog_symbols.cpp
+++ b/base/liblog_symbols.cpp
@@ -50,6 +50,7 @@
     DLSYM(__android_log_default_aborter)
     DLSYM(__android_log_set_minimum_priority);
     DLSYM(__android_log_get_minimum_priority);
+    DLSYM(__android_log_set_default_tag);
 #undef DLSYM
 
     return real_liblog_functions;
@@ -72,6 +73,7 @@
         .__android_log_default_aborter = __android_log_default_aborter,
         .__android_log_set_minimum_priority = __android_log_set_minimum_priority,
         .__android_log_get_minimum_priority = __android_log_get_minimum_priority,
+        .__android_log_set_default_tag = __android_log_set_default_tag,
     };
   }();
   return liblog_functions;
diff --git a/base/liblog_symbols.h b/base/liblog_symbols.h
index c68fff6..d3134e9 100644
--- a/base/liblog_symbols.h
+++ b/base/liblog_symbols.h
@@ -38,6 +38,7 @@
   void (*__android_log_default_aborter)(const char* abort_message);
   int (*__android_log_set_minimum_priority)(int priority);
   int (*__android_log_get_minimum_priority)();
+  void (*__android_log_set_default_tag)(const char* tag);
 };
 
 const std::optional<LibLogFunctions>& GetLibLogFunctions();
diff --git a/base/logging.cpp b/base/logging.cpp
index 508871d..a868706 100644
--- a/base/logging.cpp
+++ b/base/logging.cpp
@@ -211,26 +211,27 @@
   return aborter;
 }
 
+// Only used for Q fallback.
 static std::recursive_mutex& TagLock() {
   static auto& tag_lock = *new std::recursive_mutex();
   return tag_lock;
 }
+// Only used for Q fallback.
 static std::string* gDefaultTag;
-std::string GetDefaultTag() {
-  std::lock_guard<std::recursive_mutex> lock(TagLock());
-  if (gDefaultTag == nullptr) {
-    return "";
-  }
-  return *gDefaultTag;
-}
+
 void SetDefaultTag(const std::string& tag) {
-  std::lock_guard<std::recursive_mutex> lock(TagLock());
-  if (gDefaultTag != nullptr) {
-    delete gDefaultTag;
-    gDefaultTag = nullptr;
-  }
-  if (!tag.empty()) {
-    gDefaultTag = new std::string(tag);
+  static auto& liblog_functions = GetLibLogFunctions();
+  if (liblog_functions) {
+    liblog_functions->__android_log_set_default_tag(tag.c_str());
+  } else {
+    std::lock_guard<std::recursive_mutex> lock(TagLock());
+    if (gDefaultTag != nullptr) {
+      delete gDefaultTag;
+      gDefaultTag = nullptr;
+    }
+    if (!tag.empty()) {
+      gDefaultTag = new std::string(tag);
+    }
   }
 }
 
@@ -574,24 +575,18 @@
                          const char* message) {
   static auto& liblog_functions = GetLibLogFunctions();
   auto priority = LogSeverityToPriority(severity);
-  if (tag == nullptr) {
-    std::lock_guard<std::recursive_mutex> lock(TagLock());
-    if (gDefaultTag == nullptr) {
-      gDefaultTag = new std::string(getprogname());
-    }
-
-    if (liblog_functions) {
-      __android_logger_data logger_data = {sizeof(__android_logger_data), LOG_ID_DEFAULT, priority,
-                                           gDefaultTag->c_str(),          file,           line};
-      __android_log_write_logger_data(&logger_data, message);
-    } else {
-      Logger()(DEFAULT, severity, gDefaultTag->c_str(), file, line, message);
-    }
+  if (liblog_functions) {
+    __android_logger_data logger_data = {
+        sizeof(__android_logger_data), LOG_ID_DEFAULT, priority, tag, file, line};
+    __android_log_write_logger_data(&logger_data, message);
   } else {
-    if (liblog_functions) {
-      __android_logger_data logger_data = {
-          sizeof(__android_logger_data), LOG_ID_DEFAULT, priority, tag, file, line};
-      __android_log_write_logger_data(&logger_data, message);
+    if (tag == nullptr) {
+      std::lock_guard<std::recursive_mutex> lock(TagLock());
+      if (gDefaultTag == nullptr) {
+        gDefaultTag = new std::string(getprogname());
+      }
+
+      Logger()(DEFAULT, severity, gDefaultTag->c_str(), file, line, message);
     } else {
       Logger()(DEFAULT, severity, tag, file, line, message);
     }
@@ -613,7 +608,6 @@
   // we need to fall back to using gMinimumLogSeverity, since __android_log_is_loggable() will not
   // take into consideration the value from SetMinimumLogSeverity().
   if (liblog_functions) {
-    // TODO: It is safe to pass nullptr for tag, but it will be better to use the default log tag.
     int priority = LogSeverityToPriority(severity);
     return __android_log_is_loggable(priority, tag, ANDROID_LOG_INFO);
   } else {
diff --git a/base/logging_test.cpp b/base/logging_test.cpp
index 8f46196..3a453e6 100644
--- a/base/logging_test.cpp
+++ b/base/logging_test.cpp
@@ -603,21 +603,6 @@
   LOG(ERROR) << "foobar";
 }
 
-TEST(logging, SetDefaultTag) {
-  constexpr const char* expected_tag = "test_tag";
-  constexpr const char* expected_msg = "foobar";
-  CapturedStderr cap;
-  {
-    std::string old_default_tag = android::base::GetDefaultTag();
-    android::base::SetDefaultTag(expected_tag);
-    android::base::ScopedLogSeverity sls(android::base::LogSeverity::INFO);
-    LOG(INFO) << expected_msg;
-    android::base::SetDefaultTag(old_default_tag);
-  }
-  ASSERT_NO_FATAL_FAILURE(
-      CheckMessage(cap, android::base::LogSeverity::INFO, expected_msg, expected_tag));
-}
-
 TEST(logging, StdioLogger) {
   CapturedStderr cap_err;
   CapturedStdout cap_out;
diff --git a/debuggerd/libdebuggerd/test/tombstone_test.cpp b/debuggerd/libdebuggerd/test/tombstone_test.cpp
index 9dea7ac..b33adf31 100644
--- a/debuggerd/libdebuggerd/test/tombstone_test.cpp
+++ b/debuggerd/libdebuggerd/test/tombstone_test.cpp
@@ -359,467 +359,3 @@
   dump_timestamp(&log_, 0);
   ASSERT_STREQ("Timestamp: 1970-01-01 00:00:00+0000\n", amfd_data_.c_str());
 }
-
-class MemoryPattern : public unwindstack::Memory {
- public:
-  MemoryPattern() = default;
-  virtual ~MemoryPattern() = default;
-
-  size_t Read(uint64_t, void* dst, size_t size) override {
-    uint8_t* data = reinterpret_cast<uint8_t*>(dst);
-    for (size_t i = 0; i < size; i++) {
-      data[i] = (i % 0xff);
-    }
-    return size;
-  }
-};
-
-TEST_F(TombstoneTest, dump_stack_single_frame) {
-  std::vector<unwindstack::FrameData> frames;
-  unwindstack::Maps maps;
-  MemoryPattern memory;
-
-  frames.push_back(
-      unwindstack::FrameData{.num = 0, .rel_pc = 0x1000, .pc = 0x301000, .sp = 0x2000});
-  dump_stack(&log_, frames, &maps, &memory);
-
-  std::string contents;
-  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
-  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &contents));
-
-  std::string expected =
-#if defined(__LP64__)
-      "         0000000000001f80  0706050403020100\n"
-      "         0000000000001f88  0f0e0d0c0b0a0908\n"
-      "         0000000000001f90  1716151413121110\n"
-      "         0000000000001f98  1f1e1d1c1b1a1918\n"
-      "         0000000000001fa0  2726252423222120\n"
-      "         0000000000001fa8  2f2e2d2c2b2a2928\n"
-      "         0000000000001fb0  3736353433323130\n"
-      "         0000000000001fb8  3f3e3d3c3b3a3938\n"
-      "         0000000000001fc0  4746454443424140\n"
-      "         0000000000001fc8  4f4e4d4c4b4a4948\n"
-      "         0000000000001fd0  5756555453525150\n"
-      "         0000000000001fd8  5f5e5d5c5b5a5958\n"
-      "         0000000000001fe0  6766656463626160\n"
-      "         0000000000001fe8  6f6e6d6c6b6a6968\n"
-      "         0000000000001ff0  7776757473727170\n"
-      "         0000000000001ff8  7f7e7d7c7b7a7978\n"
-      "    #00  0000000000002000  0706050403020100\n"
-      "         0000000000002008  0f0e0d0c0b0a0908\n"
-      "         0000000000002010  1716151413121110\n"
-      "         0000000000002018  1f1e1d1c1b1a1918\n"
-      "         0000000000002020  2726252423222120\n"
-      "         0000000000002028  2f2e2d2c2b2a2928\n"
-      "         0000000000002030  3736353433323130\n"
-      "         0000000000002038  3f3e3d3c3b3a3938\n"
-      "         0000000000002040  4746454443424140\n"
-      "         0000000000002048  4f4e4d4c4b4a4948\n"
-      "         0000000000002050  5756555453525150\n"
-      "         0000000000002058  5f5e5d5c5b5a5958\n"
-      "         0000000000002060  6766656463626160\n"
-      "         0000000000002068  6f6e6d6c6b6a6968\n"
-      "         0000000000002070  7776757473727170\n"
-      "         0000000000002078  7f7e7d7c7b7a7978\n";
-#else
-      "         00001fc0  03020100\n"
-      "         00001fc4  07060504\n"
-      "         00001fc8  0b0a0908\n"
-      "         00001fcc  0f0e0d0c\n"
-      "         00001fd0  13121110\n"
-      "         00001fd4  17161514\n"
-      "         00001fd8  1b1a1918\n"
-      "         00001fdc  1f1e1d1c\n"
-      "         00001fe0  23222120\n"
-      "         00001fe4  27262524\n"
-      "         00001fe8  2b2a2928\n"
-      "         00001fec  2f2e2d2c\n"
-      "         00001ff0  33323130\n"
-      "         00001ff4  37363534\n"
-      "         00001ff8  3b3a3938\n"
-      "         00001ffc  3f3e3d3c\n"
-      "    #00  00002000  03020100\n"
-      "         00002004  07060504\n"
-      "         00002008  0b0a0908\n"
-      "         0000200c  0f0e0d0c\n"
-      "         00002010  13121110\n"
-      "         00002014  17161514\n"
-      "         00002018  1b1a1918\n"
-      "         0000201c  1f1e1d1c\n"
-      "         00002020  23222120\n"
-      "         00002024  27262524\n"
-      "         00002028  2b2a2928\n"
-      "         0000202c  2f2e2d2c\n"
-      "         00002030  33323130\n"
-      "         00002034  37363534\n"
-      "         00002038  3b3a3938\n"
-      "         0000203c  3f3e3d3c\n";
-#endif
-  EXPECT_EQ(expected, contents);
-}
-
-TEST_F(TombstoneTest, dump_stack_multiple_frames_same_sp) {
-  std::vector<unwindstack::FrameData> frames;
-  unwindstack::Maps maps;
-  MemoryPattern memory;
-
-  frames.push_back(
-      unwindstack::FrameData{.num = 0, .rel_pc = 0x1000, .pc = 0x301000, .sp = 0x2000});
-  frames.push_back(
-      unwindstack::FrameData{.num = 0, .rel_pc = 0x1400, .pc = 0x301400, .sp = 0x2000});
-  dump_stack(&log_, frames, &maps, &memory);
-
-  std::string contents;
-  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
-  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &contents));
-
-  std::string expected =
-#if defined(__LP64__)
-      "         0000000000001f80  0706050403020100\n"
-      "         0000000000001f88  0f0e0d0c0b0a0908\n"
-      "         0000000000001f90  1716151413121110\n"
-      "         0000000000001f98  1f1e1d1c1b1a1918\n"
-      "         0000000000001fa0  2726252423222120\n"
-      "         0000000000001fa8  2f2e2d2c2b2a2928\n"
-      "         0000000000001fb0  3736353433323130\n"
-      "         0000000000001fb8  3f3e3d3c3b3a3938\n"
-      "         0000000000001fc0  4746454443424140\n"
-      "         0000000000001fc8  4f4e4d4c4b4a4948\n"
-      "         0000000000001fd0  5756555453525150\n"
-      "         0000000000001fd8  5f5e5d5c5b5a5958\n"
-      "         0000000000001fe0  6766656463626160\n"
-      "         0000000000001fe8  6f6e6d6c6b6a6968\n"
-      "         0000000000001ff0  7776757473727170\n"
-      "         0000000000001ff8  7f7e7d7c7b7a7978\n"
-      "    #00  0000000000002000  0706050403020100\n"
-      "         ................  ................\n"
-      "    #01  0000000000002000  0706050403020100\n"
-      "         0000000000002008  0f0e0d0c0b0a0908\n"
-      "         0000000000002010  1716151413121110\n"
-      "         0000000000002018  1f1e1d1c1b1a1918\n"
-      "         0000000000002020  2726252423222120\n"
-      "         0000000000002028  2f2e2d2c2b2a2928\n"
-      "         0000000000002030  3736353433323130\n"
-      "         0000000000002038  3f3e3d3c3b3a3938\n"
-      "         0000000000002040  4746454443424140\n"
-      "         0000000000002048  4f4e4d4c4b4a4948\n"
-      "         0000000000002050  5756555453525150\n"
-      "         0000000000002058  5f5e5d5c5b5a5958\n"
-      "         0000000000002060  6766656463626160\n"
-      "         0000000000002068  6f6e6d6c6b6a6968\n"
-      "         0000000000002070  7776757473727170\n"
-      "         0000000000002078  7f7e7d7c7b7a7978\n";
-#else
-      "         00001fc0  03020100\n"
-      "         00001fc4  07060504\n"
-      "         00001fc8  0b0a0908\n"
-      "         00001fcc  0f0e0d0c\n"
-      "         00001fd0  13121110\n"
-      "         00001fd4  17161514\n"
-      "         00001fd8  1b1a1918\n"
-      "         00001fdc  1f1e1d1c\n"
-      "         00001fe0  23222120\n"
-      "         00001fe4  27262524\n"
-      "         00001fe8  2b2a2928\n"
-      "         00001fec  2f2e2d2c\n"
-      "         00001ff0  33323130\n"
-      "         00001ff4  37363534\n"
-      "         00001ff8  3b3a3938\n"
-      "         00001ffc  3f3e3d3c\n"
-      "    #00  00002000  03020100\n"
-      "         ........  ........\n"
-      "    #01  00002000  03020100\n"
-      "         00002004  07060504\n"
-      "         00002008  0b0a0908\n"
-      "         0000200c  0f0e0d0c\n"
-      "         00002010  13121110\n"
-      "         00002014  17161514\n"
-      "         00002018  1b1a1918\n"
-      "         0000201c  1f1e1d1c\n"
-      "         00002020  23222120\n"
-      "         00002024  27262524\n"
-      "         00002028  2b2a2928\n"
-      "         0000202c  2f2e2d2c\n"
-      "         00002030  33323130\n"
-      "         00002034  37363534\n"
-      "         00002038  3b3a3938\n"
-      "         0000203c  3f3e3d3c\n";
-#endif
-  EXPECT_EQ(expected, contents);
-}
-
-TEST_F(TombstoneTest, dump_stack_multiple_frames) {
-  std::vector<unwindstack::FrameData> frames;
-  unwindstack::Maps maps;
-  MemoryPattern memory;
-
-  frames.push_back(
-      unwindstack::FrameData{.num = 0, .rel_pc = 0x1000, .pc = 0x301000, .sp = 0x2000});
-  frames.push_back(
-      unwindstack::FrameData{.num = 0, .rel_pc = 0x1400, .pc = 0x301400, .sp = 0x2010});
-  frames.push_back(
-      unwindstack::FrameData{.num = 0, .rel_pc = 0x1400, .pc = 0x301400, .sp = 0x2100});
-  dump_stack(&log_, frames, &maps, &memory);
-
-  std::string contents;
-  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
-  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &contents));
-
-  std::string expected =
-#if defined(__LP64__)
-      "         0000000000001f80  0706050403020100\n"
-      "         0000000000001f88  0f0e0d0c0b0a0908\n"
-      "         0000000000001f90  1716151413121110\n"
-      "         0000000000001f98  1f1e1d1c1b1a1918\n"
-      "         0000000000001fa0  2726252423222120\n"
-      "         0000000000001fa8  2f2e2d2c2b2a2928\n"
-      "         0000000000001fb0  3736353433323130\n"
-      "         0000000000001fb8  3f3e3d3c3b3a3938\n"
-      "         0000000000001fc0  4746454443424140\n"
-      "         0000000000001fc8  4f4e4d4c4b4a4948\n"
-      "         0000000000001fd0  5756555453525150\n"
-      "         0000000000001fd8  5f5e5d5c5b5a5958\n"
-      "         0000000000001fe0  6766656463626160\n"
-      "         0000000000001fe8  6f6e6d6c6b6a6968\n"
-      "         0000000000001ff0  7776757473727170\n"
-      "         0000000000001ff8  7f7e7d7c7b7a7978\n"
-      "    #00  0000000000002000  0706050403020100\n"
-      "         0000000000002008  0f0e0d0c0b0a0908\n"
-      "    #01  0000000000002010  0706050403020100\n"
-      "         0000000000002018  0f0e0d0c0b0a0908\n"
-      "         0000000000002020  1716151413121110\n"
-      "         0000000000002028  1f1e1d1c1b1a1918\n"
-      "         0000000000002030  2726252423222120\n"
-      "         0000000000002038  2f2e2d2c2b2a2928\n"
-      "         0000000000002040  3736353433323130\n"
-      "         0000000000002048  3f3e3d3c3b3a3938\n"
-      "         0000000000002050  4746454443424140\n"
-      "         0000000000002058  4f4e4d4c4b4a4948\n"
-      "         0000000000002060  5756555453525150\n"
-      "         0000000000002068  5f5e5d5c5b5a5958\n"
-      "         0000000000002070  6766656463626160\n"
-      "         0000000000002078  6f6e6d6c6b6a6968\n"
-      "         0000000000002080  7776757473727170\n"
-      "         0000000000002088  7f7e7d7c7b7a7978\n"
-      "         ................  ................\n"
-      "    #02  0000000000002100  0706050403020100\n"
-      "         0000000000002108  0f0e0d0c0b0a0908\n"
-      "         0000000000002110  1716151413121110\n"
-      "         0000000000002118  1f1e1d1c1b1a1918\n"
-      "         0000000000002120  2726252423222120\n"
-      "         0000000000002128  2f2e2d2c2b2a2928\n"
-      "         0000000000002130  3736353433323130\n"
-      "         0000000000002138  3f3e3d3c3b3a3938\n"
-      "         0000000000002140  4746454443424140\n"
-      "         0000000000002148  4f4e4d4c4b4a4948\n"
-      "         0000000000002150  5756555453525150\n"
-      "         0000000000002158  5f5e5d5c5b5a5958\n"
-      "         0000000000002160  6766656463626160\n"
-      "         0000000000002168  6f6e6d6c6b6a6968\n"
-      "         0000000000002170  7776757473727170\n"
-      "         0000000000002178  7f7e7d7c7b7a7978\n";
-#else
-      "         00001fc0  03020100\n"
-      "         00001fc4  07060504\n"
-      "         00001fc8  0b0a0908\n"
-      "         00001fcc  0f0e0d0c\n"
-      "         00001fd0  13121110\n"
-      "         00001fd4  17161514\n"
-      "         00001fd8  1b1a1918\n"
-      "         00001fdc  1f1e1d1c\n"
-      "         00001fe0  23222120\n"
-      "         00001fe4  27262524\n"
-      "         00001fe8  2b2a2928\n"
-      "         00001fec  2f2e2d2c\n"
-      "         00001ff0  33323130\n"
-      "         00001ff4  37363534\n"
-      "         00001ff8  3b3a3938\n"
-      "         00001ffc  3f3e3d3c\n"
-      "    #00  00002000  03020100\n"
-      "         00002004  07060504\n"
-      "         00002008  0b0a0908\n"
-      "         0000200c  0f0e0d0c\n"
-      "    #01  00002010  03020100\n"
-      "         00002014  07060504\n"
-      "         00002018  0b0a0908\n"
-      "         0000201c  0f0e0d0c\n"
-      "         00002020  13121110\n"
-      "         00002024  17161514\n"
-      "         00002028  1b1a1918\n"
-      "         0000202c  1f1e1d1c\n"
-      "         00002030  23222120\n"
-      "         00002034  27262524\n"
-      "         00002038  2b2a2928\n"
-      "         0000203c  2f2e2d2c\n"
-      "         00002040  33323130\n"
-      "         00002044  37363534\n"
-      "         00002048  3b3a3938\n"
-      "         0000204c  3f3e3d3c\n"
-      "         ........  ........\n"
-      "    #02  00002100  03020100\n"
-      "         00002104  07060504\n"
-      "         00002108  0b0a0908\n"
-      "         0000210c  0f0e0d0c\n"
-      "         00002110  13121110\n"
-      "         00002114  17161514\n"
-      "         00002118  1b1a1918\n"
-      "         0000211c  1f1e1d1c\n"
-      "         00002120  23222120\n"
-      "         00002124  27262524\n"
-      "         00002128  2b2a2928\n"
-      "         0000212c  2f2e2d2c\n"
-      "         00002130  33323130\n"
-      "         00002134  37363534\n"
-      "         00002138  3b3a3938\n"
-      "         0000213c  3f3e3d3c\n";
-#endif
-  EXPECT_EQ(expected, contents);
-}
-
-TEST_F(TombstoneTest, dump_stack_multiple_frames_disjoint_frames) {
-  std::vector<unwindstack::FrameData> frames;
-  unwindstack::Maps maps;
-  MemoryPattern memory;
-
-  frames.push_back(
-      unwindstack::FrameData{.num = 0, .rel_pc = 0x1000, .pc = 0x301000, .sp = 0x2000});
-  frames.push_back(
-      unwindstack::FrameData{.num = 0, .rel_pc = 0x1400, .pc = 0x301400, .sp = 0x2010});
-  frames.push_back(
-      unwindstack::FrameData{.num = 0, .rel_pc = 0x1400, .pc = 0x301400, .sp = 0x1000});
-  frames.push_back(
-      unwindstack::FrameData{.num = 0, .rel_pc = 0x1400, .pc = 0x301400, .sp = 0x1030});
-  dump_stack(&log_, frames, &maps, &memory);
-
-  std::string contents;
-  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
-  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &contents));
-
-  std::string expected =
-#if defined(__LP64__)
-      "         0000000000001f80  0706050403020100\n"
-      "         0000000000001f88  0f0e0d0c0b0a0908\n"
-      "         0000000000001f90  1716151413121110\n"
-      "         0000000000001f98  1f1e1d1c1b1a1918\n"
-      "         0000000000001fa0  2726252423222120\n"
-      "         0000000000001fa8  2f2e2d2c2b2a2928\n"
-      "         0000000000001fb0  3736353433323130\n"
-      "         0000000000001fb8  3f3e3d3c3b3a3938\n"
-      "         0000000000001fc0  4746454443424140\n"
-      "         0000000000001fc8  4f4e4d4c4b4a4948\n"
-      "         0000000000001fd0  5756555453525150\n"
-      "         0000000000001fd8  5f5e5d5c5b5a5958\n"
-      "         0000000000001fe0  6766656463626160\n"
-      "         0000000000001fe8  6f6e6d6c6b6a6968\n"
-      "         0000000000001ff0  7776757473727170\n"
-      "         0000000000001ff8  7f7e7d7c7b7a7978\n"
-      "    #00  0000000000002000  0706050403020100\n"
-      "         0000000000002008  0f0e0d0c0b0a0908\n"
-      "    #01  0000000000002010  0706050403020100\n"
-      "         0000000000002018  0f0e0d0c0b0a0908\n"
-      "         0000000000002020  1716151413121110\n"
-      "         0000000000002028  1f1e1d1c1b1a1918\n"
-      "         0000000000002030  2726252423222120\n"
-      "         0000000000002038  2f2e2d2c2b2a2928\n"
-      "         0000000000002040  3736353433323130\n"
-      "         0000000000002048  3f3e3d3c3b3a3938\n"
-      "         0000000000002050  4746454443424140\n"
-      "         0000000000002058  4f4e4d4c4b4a4948\n"
-      "         0000000000002060  5756555453525150\n"
-      "         0000000000002068  5f5e5d5c5b5a5958\n"
-      "         0000000000002070  6766656463626160\n"
-      "         0000000000002078  6f6e6d6c6b6a6968\n"
-      "         0000000000002080  7776757473727170\n"
-      "         0000000000002088  7f7e7d7c7b7a7978\n"
-      "         ................  ................\n"
-      "    #02  0000000000001000  0706050403020100\n"
-      "         0000000000001008  0f0e0d0c0b0a0908\n"
-      "         0000000000001010  1716151413121110\n"
-      "         0000000000001018  1f1e1d1c1b1a1918\n"
-      "         0000000000001020  2726252423222120\n"
-      "         0000000000001028  2f2e2d2c2b2a2928\n"
-      "    #03  0000000000001030  0706050403020100\n"
-      "         0000000000001038  0f0e0d0c0b0a0908\n"
-      "         0000000000001040  1716151413121110\n"
-      "         0000000000001048  1f1e1d1c1b1a1918\n"
-      "         0000000000001050  2726252423222120\n"
-      "         0000000000001058  2f2e2d2c2b2a2928\n"
-      "         0000000000001060  3736353433323130\n"
-      "         0000000000001068  3f3e3d3c3b3a3938\n"
-      "         0000000000001070  4746454443424140\n"
-      "         0000000000001078  4f4e4d4c4b4a4948\n"
-      "         0000000000001080  5756555453525150\n"
-      "         0000000000001088  5f5e5d5c5b5a5958\n"
-      "         0000000000001090  6766656463626160\n"
-      "         0000000000001098  6f6e6d6c6b6a6968\n"
-      "         00000000000010a0  7776757473727170\n"
-      "         00000000000010a8  7f7e7d7c7b7a7978\n";
-#else
-      "         00001fc0  03020100\n"
-      "         00001fc4  07060504\n"
-      "         00001fc8  0b0a0908\n"
-      "         00001fcc  0f0e0d0c\n"
-      "         00001fd0  13121110\n"
-      "         00001fd4  17161514\n"
-      "         00001fd8  1b1a1918\n"
-      "         00001fdc  1f1e1d1c\n"
-      "         00001fe0  23222120\n"
-      "         00001fe4  27262524\n"
-      "         00001fe8  2b2a2928\n"
-      "         00001fec  2f2e2d2c\n"
-      "         00001ff0  33323130\n"
-      "         00001ff4  37363534\n"
-      "         00001ff8  3b3a3938\n"
-      "         00001ffc  3f3e3d3c\n"
-      "    #00  00002000  03020100\n"
-      "         00002004  07060504\n"
-      "         00002008  0b0a0908\n"
-      "         0000200c  0f0e0d0c\n"
-      "    #01  00002010  03020100\n"
-      "         00002014  07060504\n"
-      "         00002018  0b0a0908\n"
-      "         0000201c  0f0e0d0c\n"
-      "         00002020  13121110\n"
-      "         00002024  17161514\n"
-      "         00002028  1b1a1918\n"
-      "         0000202c  1f1e1d1c\n"
-      "         00002030  23222120\n"
-      "         00002034  27262524\n"
-      "         00002038  2b2a2928\n"
-      "         0000203c  2f2e2d2c\n"
-      "         00002040  33323130\n"
-      "         00002044  37363534\n"
-      "         00002048  3b3a3938\n"
-      "         0000204c  3f3e3d3c\n"
-      "         ........  ........\n"
-      "    #02  00001000  03020100\n"
-      "         00001004  07060504\n"
-      "         00001008  0b0a0908\n"
-      "         0000100c  0f0e0d0c\n"
-      "         00001010  13121110\n"
-      "         00001014  17161514\n"
-      "         00001018  1b1a1918\n"
-      "         0000101c  1f1e1d1c\n"
-      "         00001020  23222120\n"
-      "         00001024  27262524\n"
-      "         00001028  2b2a2928\n"
-      "         0000102c  2f2e2d2c\n"
-      "    #03  00001030  03020100\n"
-      "         00001034  07060504\n"
-      "         00001038  0b0a0908\n"
-      "         0000103c  0f0e0d0c\n"
-      "         00001040  13121110\n"
-      "         00001044  17161514\n"
-      "         00001048  1b1a1918\n"
-      "         0000104c  1f1e1d1c\n"
-      "         00001050  23222120\n"
-      "         00001054  27262524\n"
-      "         00001058  2b2a2928\n"
-      "         0000105c  2f2e2d2c\n"
-      "         00001060  33323130\n"
-      "         00001064  37363534\n"
-      "         00001068  3b3a3938\n"
-      "         0000106c  3f3e3d3c\n";
-#endif
-  EXPECT_EQ(expected, contents);
-}
diff --git a/debuggerd/libdebuggerd/tombstone.cpp b/debuggerd/libdebuggerd/tombstone.cpp
index b64e260..4e7f35c 100644
--- a/debuggerd/libdebuggerd/tombstone.cpp
+++ b/debuggerd/libdebuggerd/tombstone.cpp
@@ -188,106 +188,6 @@
   _LOG(log, logtype::HEADER, "uid: %d\n", thread_info.uid);
 }
 
-static void dump_stack_segment(log_t* log, unwindstack::Maps* maps, unwindstack::Memory* memory,
-                               uint64_t* sp, size_t words, int label) {
-  // Read the data all at once.
-  word_t stack_data[words];
-
-  // TODO: Do we need to word align this for crashes caused by a misaligned sp?
-  //       The process_vm_readv implementation of Memory should handle this appropriately?
-  size_t bytes_read = memory->Read(*sp, stack_data, sizeof(word_t) * words);
-  words = bytes_read / sizeof(word_t);
-  std::string line;
-  for (size_t i = 0; i < words; i++) {
-    line = "    ";
-    if (i == 0 && label >= 0) {
-      // Print the label once.
-      line += StringPrintf("#%02d  ", label);
-    } else {
-      line += "     ";
-    }
-    line += StringPrintf("%" PRIPTR "  %" PRIPTR, *sp, static_cast<uint64_t>(stack_data[i]));
-
-    unwindstack::MapInfo* map_info = maps->Find(stack_data[i]);
-    if (map_info != nullptr && !map_info->name.empty()) {
-      line += "  " + map_info->name;
-      std::string func_name;
-      uint64_t func_offset = 0;
-      if (map_info->GetFunctionName(stack_data[i], &func_name, &func_offset)) {
-        line += " (" + func_name;
-        if (func_offset) {
-          line += StringPrintf("+%" PRIu64, func_offset);
-        }
-        line += ')';
-      }
-    }
-    _LOG(log, logtype::STACK, "%s\n", line.c_str());
-
-    *sp += sizeof(word_t);
-  }
-}
-
-static void dump_stack(log_t* log, const std::vector<unwindstack::FrameData>& frames,
-                       unwindstack::Maps* maps, unwindstack::Memory* memory) {
-  size_t first = 0, last;
-  for (size_t i = 0; i < frames.size(); i++) {
-    if (frames[i].sp) {
-      if (!first) {
-        first = i+1;
-      }
-      last = i;
-    }
-  }
-
-  if (!first) {
-    return;
-  }
-  first--;
-
-  // Dump a few words before the first frame.
-  uint64_t sp = frames[first].sp - STACK_WORDS * sizeof(word_t);
-  dump_stack_segment(log, maps, memory, &sp, STACK_WORDS, -1);
-
-#if defined(__LP64__)
-  static constexpr const char delimiter[] = "         ................  ................\n";
-#else
-  static constexpr const char delimiter[] = "         ........  ........\n";
-#endif
-
-  // Dump a few words from all successive frames.
-  for (size_t i = first; i <= last; i++) {
-    auto* frame = &frames[i];
-    if (sp != frame->sp) {
-      _LOG(log, logtype::STACK, delimiter);
-      sp = frame->sp;
-    }
-    if (i != last) {
-      // Print stack data up to the stack from the next frame.
-      size_t words;
-      uint64_t next_sp = frames[i + 1].sp;
-      if (next_sp < sp) {
-        // The next frame is probably using a completely different stack,
-        // so dump the max from this stack.
-        words = STACK_WORDS;
-      } else {
-        words = (next_sp - sp) / sizeof(word_t);
-        if (words == 0) {
-          // The sp is the same as the next frame, print at least
-          // one line for this frame.
-          words = 1;
-        } else if (words > STACK_WORDS) {
-          words = STACK_WORDS;
-        }
-      }
-      dump_stack_segment(log, maps, memory, &sp, words, i);
-    } else {
-      // Print some number of words past the last stack frame since we
-      // don't know how large the stack is.
-      dump_stack_segment(log, maps, memory, &sp, STACK_WORDS, i);
-    }
-  }
-}
-
 static std::string get_addr_string(uint64_t addr) {
   std::string addr_str;
 #if defined(__LP64__)
@@ -499,9 +399,6 @@
   } else {
     _LOG(log, logtype::BACKTRACE, "\nbacktrace:\n");
     log_backtrace(log, unwinder, "    ");
-
-    _LOG(log, logtype::STACK, "\nstack:\n");
-    dump_stack(log, unwinder->frames(), unwinder->GetMaps(), unwinder->GetProcessMemory().get());
   }
 
   if (primary_thread) {
diff --git a/fastboot/Android.mk b/fastboot/Android.mk
index 17ec392..fd009e7 100644
--- a/fastboot/Android.mk
+++ b/fastboot/Android.mk
@@ -18,9 +18,9 @@
 # Package fastboot-related executables.
 #
 
-my_dist_files := $(HOST_OUT_EXECUTABLES)/mke2fs
-my_dist_files += $(HOST_OUT_EXECUTABLES)/e2fsdroid
-my_dist_files += $(HOST_OUT_EXECUTABLES)/make_f2fs
-my_dist_files += $(HOST_OUT_EXECUTABLES)/sload_f2fs
+my_dist_files := $(SOONG_HOST_OUT_EXECUTABLES)/mke2fs
+my_dist_files += $(SOONG_HOST_OUT_EXECUTABLES)/e2fsdroid
+my_dist_files += $(SOONG_HOST_OUT_EXECUTABLES)/make_f2fs
+my_dist_files += $(SOONG_HOST_OUT_EXECUTABLES)/sload_f2fs
 $(call dist-for-goals,dist_files sdk win_sdk,$(my_dist_files))
 my_dist_files :=
diff --git a/fastboot/constants.h b/fastboot/constants.h
index 5a554a0..aefd448 100644
--- a/fastboot/constants.h
+++ b/fastboot/constants.h
@@ -47,6 +47,8 @@
 #define FB_VAR_VERSION "version"
 #define FB_VAR_VERSION_BOOTLOADER "version-bootloader"
 #define FB_VAR_VERSION_BASEBAND "version-baseband"
+#define FB_VAR_VERSION_OS "version-os"
+#define FB_VAR_VERSION_VNDK "version-vndk"
 #define FB_VAR_PRODUCT "product"
 #define FB_VAR_SERIALNO "serialno"
 #define FB_VAR_SECURE "secure"
@@ -69,3 +71,9 @@
 #define FB_VAR_SUPER_PARTITION_NAME "super-partition-name"
 #define FB_VAR_SNAPSHOT_UPDATE_STATUS "snapshot-update-status"
 #define FB_VAR_CPU_ABI "cpu-abi"
+#define FB_VAR_SYSTEM_FINGERPRINT "system-fingerprint"
+#define FB_VAR_VENDOR_FINGERPRINT "vendor-fingerprint"
+#define FB_VAR_DYNAMIC_PARTITION "dynamic-partition"
+#define FB_VAR_FIRST_API_LEVEL "first-api-level"
+#define FB_VAR_SECURITY_PATCH_LEVEL "security-patch-level"
+#define FB_VAR_TREBLE_ENABLED "treble-enabled"
diff --git a/fastboot/device/commands.cpp b/fastboot/device/commands.cpp
index b7263d9..2c9dec9 100644
--- a/fastboot/device/commands.cpp
+++ b/fastboot/device/commands.cpp
@@ -106,6 +106,8 @@
             {FB_VAR_VERSION, {GetVersion, nullptr}},
             {FB_VAR_VERSION_BOOTLOADER, {GetBootloaderVersion, nullptr}},
             {FB_VAR_VERSION_BASEBAND, {GetBasebandVersion, nullptr}},
+            {FB_VAR_VERSION_OS, {GetOsVersion, nullptr}},
+            {FB_VAR_VERSION_VNDK, {GetVndkVersion, nullptr}},
             {FB_VAR_PRODUCT, {GetProduct, nullptr}},
             {FB_VAR_SERIALNO, {GetSerial, nullptr}},
             {FB_VAR_VARIANT, {GetVariant, nullptr}},
@@ -127,7 +129,13 @@
             {FB_VAR_HW_REVISION, {GetHardwareRevision, nullptr}},
             {FB_VAR_SUPER_PARTITION_NAME, {GetSuperPartitionName, nullptr}},
             {FB_VAR_SNAPSHOT_UPDATE_STATUS, {GetSnapshotUpdateStatus, nullptr}},
-            {FB_VAR_CPU_ABI, {GetCpuAbi, nullptr}}};
+            {FB_VAR_CPU_ABI, {GetCpuAbi, nullptr}},
+            {FB_VAR_SYSTEM_FINGERPRINT, {GetSystemFingerprint, nullptr}},
+            {FB_VAR_VENDOR_FINGERPRINT, {GetVendorFingerprint, nullptr}},
+            {FB_VAR_DYNAMIC_PARTITION, {GetDynamicPartition, nullptr}},
+            {FB_VAR_FIRST_API_LEVEL, {GetFirstApiLevel, nullptr}},
+            {FB_VAR_SECURITY_PATCH_LEVEL, {GetSecurityPatchLevel, nullptr}},
+            {FB_VAR_TREBLE_ENABLED, {GetTrebleEnabled, nullptr}}};
 
     if (args.size() < 2) {
         return device->WriteFail("Missing argument");
diff --git a/fastboot/device/variables.cpp b/fastboot/device/variables.cpp
index 10eac01..e7d8bc3 100644
--- a/fastboot/device/variables.cpp
+++ b/fastboot/device/variables.cpp
@@ -62,6 +62,18 @@
     return true;
 }
 
+bool GetOsVersion(FastbootDevice* /* device */, const std::vector<std::string>& /* args */,
+                  std::string* message) {
+    *message = android::base::GetProperty("ro.build.version.release", "");
+    return true;
+}
+
+bool GetVndkVersion(FastbootDevice* /* device */, const std::vector<std::string>& /* args */,
+                    std::string* message) {
+    *message = android::base::GetProperty("ro.vndk.version", "");
+    return true;
+}
+
 bool GetProduct(FastbootDevice* /* device */, const std::vector<std::string>& /* args */,
                 std::string* message) {
     *message = android::base::GetProperty("ro.product.device", "");
@@ -458,3 +470,42 @@
     *message = android::base::GetProperty("ro.product.cpu.abi", "");
     return true;
 }
+
+bool GetSystemFingerprint(FastbootDevice* /* device */, const std::vector<std::string>& /* args */,
+                          std::string* message) {
+    *message = android::base::GetProperty("ro.system.build.fingerprint", "");
+    if (message->empty()) {
+        *message = android::base::GetProperty("ro.build.fingerprint", "");
+    }
+    return true;
+}
+
+bool GetVendorFingerprint(FastbootDevice* /* device */, const std::vector<std::string>& /* args */,
+                          std::string* message) {
+    *message = android::base::GetProperty("ro.vendor.build.fingerprint", "");
+    return true;
+}
+
+bool GetDynamicPartition(FastbootDevice* /* device */, const std::vector<std::string>& /* args */,
+                         std::string* message) {
+    *message = android::base::GetProperty("ro.boot.dynamic_partitions", "");
+    return true;
+}
+
+bool GetFirstApiLevel(FastbootDevice* /* device */, const std::vector<std::string>& /* args */,
+                      std::string* message) {
+    *message = android::base::GetProperty("ro.product.first_api_level", "");
+    return true;
+}
+
+bool GetSecurityPatchLevel(FastbootDevice* /* device */, const std::vector<std::string>& /* args */,
+                           std::string* message) {
+    *message = android::base::GetProperty("ro.build.version.security_patch", "");
+    return true;
+}
+
+bool GetTrebleEnabled(FastbootDevice* /* device */, const std::vector<std::string>& /* args */,
+                      std::string* message) {
+    *message = android::base::GetProperty("ro.treble.enabled", "");
+    return true;
+}
diff --git a/fastboot/device/variables.h b/fastboot/device/variables.h
index 90840d6..c11e472 100644
--- a/fastboot/device/variables.h
+++ b/fastboot/device/variables.h
@@ -26,6 +26,10 @@
                           std::string* message);
 bool GetBasebandVersion(FastbootDevice* device, const std::vector<std::string>& args,
                         std::string* message);
+bool GetOsVersion(FastbootDevice* device, const std::vector<std::string>& args,
+                  std::string* message);
+bool GetVndkVersion(FastbootDevice* device, const std::vector<std::string>& args,
+                    std::string* message);
 bool GetProduct(FastbootDevice* device, const std::vector<std::string>& args, std::string* message);
 bool GetSerial(FastbootDevice* device, const std::vector<std::string>& args, std::string* message);
 bool GetSecure(FastbootDevice* device, const std::vector<std::string>& args, std::string* message);
@@ -64,6 +68,18 @@
 bool GetSnapshotUpdateStatus(FastbootDevice* device, const std::vector<std::string>& args,
                              std::string* message);
 bool GetCpuAbi(FastbootDevice* device, const std::vector<std::string>& args, std::string* message);
+bool GetSystemFingerprint(FastbootDevice* device, const std::vector<std::string>& args,
+                          std::string* message);
+bool GetVendorFingerprint(FastbootDevice* device, const std::vector<std::string>& args,
+                          std::string* message);
+bool GetDynamicPartition(FastbootDevice* device, const std::vector<std::string>& args,
+                         std::string* message);
+bool GetFirstApiLevel(FastbootDevice* device, const std::vector<std::string>& args,
+                      std::string* message);
+bool GetSecurityPatchLevel(FastbootDevice* device, const std::vector<std::string>& args,
+                           std::string* message);
+bool GetTrebleEnabled(FastbootDevice* device, const std::vector<std::string>& args,
+                      std::string* message);
 
 // Helpers for getvar all.
 std::vector<std::vector<std::string>> GetAllPartitionArgsWithSlot(FastbootDevice* device);
diff --git a/fs_mgr/Android.bp b/fs_mgr/Android.bp
index 34c64d2..7a88aa3 100644
--- a/fs_mgr/Android.bp
+++ b/fs_mgr/Android.bp
@@ -91,6 +91,7 @@
     },
     header_libs: [
         "libfiemap_headers",
+        "libstorage_literals_headers",
     ],
     export_header_lib_headers: [
         "libfiemap_headers",
@@ -165,7 +166,7 @@
         "libcrypto",
         "libext4_utils",
         "libfec",
-        "libfs_mgr",
+        "libfs_mgr_binder",
         "liblog",
         "liblp",
         "libselinux",
@@ -187,4 +188,26 @@
             ],
         },
     },
+    required: [
+        "clean_scratch_files",
+    ],
+}
+
+cc_binary {
+    name: "clean_scratch_files",
+    defaults: ["fs_mgr_defaults"],
+    shared_libs: [
+        "libbase",
+        "libfs_mgr_binder",
+    ],
+    srcs: [
+        "clean_scratch_files.cpp",
+    ],
+    product_variables: {
+        debuggable: {
+            init_rc: [
+                "clean_scratch_files.rc",
+            ],
+        },
+    },
 }
diff --git a/fs_mgr/clean_scratch_files.cpp b/fs_mgr/clean_scratch_files.cpp
new file mode 100644
index 0000000..42fe35a
--- /dev/null
+++ b/fs_mgr/clean_scratch_files.cpp
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2020 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 <fs_mgr_overlayfs.h>
+
+int main() {
+    android::fs_mgr::CleanupOldScratchFiles();
+    return 0;
+}
diff --git a/fs_mgr/clean_scratch_files.rc b/fs_mgr/clean_scratch_files.rc
new file mode 100644
index 0000000..738d1aa
--- /dev/null
+++ b/fs_mgr/clean_scratch_files.rc
@@ -0,0 +1,2 @@
+on post-fs-data && property:ro.debuggable=1
+    exec_background - root root -- clean_scratch_files
diff --git a/fs_mgr/fs_mgr.cpp b/fs_mgr/fs_mgr.cpp
index ed82066..9180a06 100644
--- a/fs_mgr/fs_mgr.cpp
+++ b/fs_mgr/fs_mgr.cpp
@@ -86,6 +86,7 @@
 #define ZRAM_BACK_DEV   "/sys/block/zram0/backing_dev"
 
 #define SYSFS_EXT4_VERITY "/sys/fs/ext4/features/verity"
+#define SYSFS_EXT4_CASEFOLD "/sys/fs/ext4/features/casefold"
 
 // FIXME: this should be in system/extras
 #define EXT4_FEATURE_COMPAT_STABLE_INODES 0x0800
@@ -100,6 +101,7 @@
 using android::base::unique_fd;
 using android::dm::DeviceMapper;
 using android::dm::DmDeviceState;
+using android::dm::DmTargetLinear;
 
 // Realistically, this file should be part of the android::fs_mgr namespace;
 using namespace android::fs_mgr;
@@ -123,6 +125,7 @@
     FS_STAT_SET_RESERVED_BLOCKS_FAILED = 0x20000,
     FS_STAT_ENABLE_ENCRYPTION_FAILED = 0x40000,
     FS_STAT_ENABLE_VERITY_FAILED = 0x80000,
+    FS_STAT_ENABLE_CASEFOLD_FAILED = 0x100000,
 };
 
 static void log_fs_stat(const std::string& blk_device, int fs_stat) {
@@ -344,6 +347,7 @@
                        const struct ext4_super_block* sb, int* fs_stat) {
     bool has_quota = (sb->s_feature_ro_compat & cpu_to_le32(EXT4_FEATURE_RO_COMPAT_QUOTA)) != 0;
     bool want_quota = entry.fs_mgr_flags.quota;
+    bool want_projid = android::base::GetBoolProperty("ro.emulated_storage.projid", false);
 
     if (has_quota == want_quota) {
         return;
@@ -360,12 +364,16 @@
     if (want_quota) {
         LINFO << "Enabling quotas on " << blk_device;
         argv[1] = "-Oquota";
-        argv[2] = "-Qusrquota,grpquota";
+        // Once usr/grp unneeded, make just prjquota to save overhead
+        if (want_projid)
+            argv[2] = "-Qusrquota,grpquota,prjquota";
+        else
+            argv[2] = "-Qusrquota,grpquota";
         *fs_stat |= FS_STAT_QUOTA_ENABLED;
     } else {
         LINFO << "Disabling quotas on " << blk_device;
         argv[1] = "-O^quota";
-        argv[2] = "-Q^usrquota,^grpquota";
+        argv[2] = "-Q^usrquota,^grpquota,^prjquota";
     }
 
     if (!run_tune2fs(argv, ARRAY_SIZE(argv))) {
@@ -498,6 +506,42 @@
     }
 }
 
+// Enable casefold if needed.
+static void tune_casefold(const std::string& blk_device, const struct ext4_super_block* sb,
+                          int* fs_stat) {
+    bool has_casefold =
+            (sb->s_feature_ro_compat & cpu_to_le32(EXT4_FEATURE_INCOMPAT_CASEFOLD)) != 0;
+    bool wants_casefold = android::base::GetBoolProperty("ro.emulated_storage.casefold", false);
+
+    if (!wants_casefold || has_casefold) return;
+
+    std::string casefold_support;
+    if (!android::base::ReadFileToString(SYSFS_EXT4_CASEFOLD, &casefold_support)) {
+        LERROR << "Failed to open " << SYSFS_EXT4_CASEFOLD;
+        return;
+    }
+
+    if (!(android::base::Trim(casefold_support) == "supported")) {
+        LERROR << "Current ext4 casefolding not supported by kernel";
+        return;
+    }
+
+    if (!tune2fs_available()) {
+        LERROR << "Unable to enable ext4 casefold on " << blk_device
+               << " because " TUNE2FS_BIN " is missing";
+        return;
+    }
+
+    LINFO << "Enabling ext4 casefold on " << blk_device;
+
+    const char* argv[] = {TUNE2FS_BIN, "-O", "casefold", "-E", "encoding=utf8", blk_device.c_str()};
+    if (!run_tune2fs(argv, ARRAY_SIZE(argv))) {
+        LERROR << "Failed to run " TUNE2FS_BIN " to enable "
+               << "ext4 casefold on " << blk_device;
+        *fs_stat |= FS_STAT_ENABLE_CASEFOLD_FAILED;
+    }
+}
+
 // Read the primary superblock from an f2fs filesystem.  On failure return
 // false.  If it's not an f2fs filesystem, also set FS_STAT_INVALID_MAGIC.
 #define F2FS_BLKSIZE 4096
@@ -595,6 +639,7 @@
             tune_reserved_size(blk_device, entry, &sb, &fs_stat);
             tune_encrypt(blk_device, entry, &sb, &fs_stat);
             tune_verity(blk_device, entry, &sb, &fs_stat);
+            tune_casefold(blk_device, &sb, &fs_stat);
         }
     }
 
@@ -1070,6 +1115,83 @@
     }
 }
 
+static constexpr const char* kUserdataWrapperName = "userdata-wrapper";
+
+static void WrapUserdata(FstabEntry* entry, dev_t dev, const std::string& block_device) {
+    DeviceMapper& dm = DeviceMapper::Instance();
+    if (dm.GetState(kUserdataWrapperName) != DmDeviceState::INVALID) {
+        // This will report failure for us. If we do fail to get the path,
+        // we leave the device unwrapped.
+        dm.GetDmDevicePathByName(kUserdataWrapperName, &entry->blk_device);
+        return;
+    }
+
+    unique_fd fd(open(block_device.c_str(), O_RDONLY | O_CLOEXEC));
+    if (fd < 0) {
+        PLOG(ERROR) << "open failed: " << entry->blk_device;
+        return;
+    }
+
+    auto dev_str = android::base::StringPrintf("%u:%u", major(dev), minor(dev));
+    uint64_t sectors = get_block_device_size(fd) / 512;
+
+    android::dm::DmTable table;
+    table.Emplace<DmTargetLinear>(0, sectors, dev_str, 0);
+
+    std::string dm_path;
+    if (!dm.CreateDevice(kUserdataWrapperName, table, &dm_path, 20s)) {
+        LOG(ERROR) << "Failed to create userdata wrapper device";
+        return;
+    }
+    entry->blk_device = dm_path;
+}
+
+// When using Virtual A/B, partitions can be backed by /data and mapped with
+// device-mapper in first-stage init. This can happen when merging an OTA or
+// when using adb remount to house "scratch". In this case, /data cannot be
+// mounted directly off the userdata block device, and e2fsck will refuse to
+// scan it, because the kernel reports the block device as in-use.
+//
+// As a workaround, when mounting /data, we create a trivial dm-linear wrapper
+// if the underlying block device already has dependencies. Note that we make
+// an exception for metadata-encrypted devices, since dm-default-key is already
+// a wrapper.
+static void WrapUserdataIfNeeded(FstabEntry* entry, const std::string& actual_block_device = {}) {
+    const auto& block_device =
+            actual_block_device.empty() ? entry->blk_device : actual_block_device;
+    if (entry->mount_point != "/data" || !entry->key_dir.empty() ||
+        android::base::StartsWith(block_device, "/dev/block/dm-")) {
+        return;
+    }
+
+    struct stat st;
+    if (stat(block_device.c_str(), &st) < 0) {
+        PLOG(ERROR) << "stat failed: " << block_device;
+        return;
+    }
+
+    std::string path = android::base::StringPrintf("/sys/dev/block/%u:%u/holders",
+                                                   major(st.st_rdev), minor(st.st_rdev));
+    std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(path.c_str()), closedir);
+    if (!dir) {
+        PLOG(ERROR) << "opendir failed: " << path;
+        return;
+    }
+
+    struct dirent* d;
+    bool has_holders = false;
+    while ((d = readdir(dir.get())) != nullptr) {
+        if (strcmp(d->d_name, ".") != 0 && strcmp(d->d_name, "..") != 0) {
+            has_holders = true;
+            break;
+        }
+    }
+
+    if (has_holders) {
+        WrapUserdata(entry, st.st_rdev, block_device);
+    }
+}
+
 static bool IsMountPointMounted(const std::string& mount_point) {
     // Check if this is already mounted.
     Fstab fstab;
@@ -1149,6 +1271,8 @@
             }
         }
 
+        WrapUserdataIfNeeded(&current_entry);
+
         if (!checkpoint_manager.Update(&current_entry)) {
             continue;
         }
@@ -1419,6 +1543,9 @@
     }
     std::string block_device;
     if (auto entry = GetEntryForMountPoint(&proc_mounts, "/data"); entry != nullptr) {
+        // Note: we don't care about a userdata wrapper here, since it's safe
+        // to remount on top of the bow device instead, there will be no
+        // conflicts.
         block_device = entry->blk_device;
     } else {
         LERROR << "/data is not mounted";
@@ -1537,6 +1664,8 @@
             }
         }
 
+        WrapUserdataIfNeeded(&fstab_entry, n_blk_device);
+
         if (!checkpoint_manager.Update(&fstab_entry, n_blk_device)) {
             LERROR << "Could not set up checkpoint partition, skipping!";
             continue;
diff --git a/fs_mgr/fs_mgr_overlayfs.cpp b/fs_mgr/fs_mgr_overlayfs.cpp
index c043754..2bc53d3 100644
--- a/fs_mgr/fs_mgr_overlayfs.cpp
+++ b/fs_mgr/fs_mgr_overlayfs.cpp
@@ -48,15 +48,21 @@
 #include <fs_mgr_overlayfs.h>
 #include <fstab/fstab.h>
 #include <libdm/dm.h>
+#include <libfiemap/image_manager.h>
 #include <libgsi/libgsi.h>
 #include <liblp/builder.h>
 #include <liblp/liblp.h>
+#include <storage_literals/storage_literals.h>
 
 #include "fs_mgr_priv.h"
+#include "libfiemap/utility.h"
 
 using namespace std::literals;
 using namespace android::dm;
 using namespace android::fs_mgr;
+using namespace android::storage_literals;
+using android::fiemap::FilesystemHasReliablePinning;
+using android::fiemap::IImageManager;
 
 namespace {
 
@@ -104,6 +110,14 @@
     return false;
 }
 
+namespace android {
+namespace fs_mgr {
+
+void MapScratchPartitionIfNeeded(Fstab*,
+                                 const std::function<bool(const std::set<std::string>&)>&) {}
+}  // namespace fs_mgr
+}  // namespace android
+
 #else  // ALLOW_ADBD_DISABLE_VERITY == 0
 
 namespace {
@@ -153,6 +167,12 @@
 }
 
 const auto kPhysicalDevice = "/dev/block/by-name/"s;
+constexpr char kScratchImageMetadata[] = "/metadata/gsi/remount/lp_metadata";
+
+// Note: this is meant only for recovery/first-stage init.
+bool ScratchIsOnData() {
+    return fs_mgr_access(kScratchImageMetadata);
+}
 
 bool fs_mgr_update_blk_device(FstabEntry* entry) {
     if (entry->fs_mgr_flags.logical) {
@@ -443,20 +463,37 @@
 bool fs_mgr_overlayfs_teardown_scratch(const std::string& overlay, bool* change) {
     // umount and delete kScratchMountPoint storage if we have logical partitions
     if (overlay != kScratchMountPoint) return true;
-    auto slot_number = fs_mgr_overlayfs_slot_number();
-    auto super_device = fs_mgr_overlayfs_super_device(slot_number);
-    if (!fs_mgr_rw_access(super_device)) return true;
 
     auto save_errno = errno;
     if (fs_mgr_overlayfs_already_mounted(kScratchMountPoint, false)) {
         fs_mgr_overlayfs_umount_scratch();
     }
+
+    const auto partition_name = android::base::Basename(kScratchMountPoint);
+
+    auto images = IImageManager::Open("remount", 10s);
+    if (images && images->BackingImageExists(partition_name)) {
+#if defined __ANDROID_RECOVERY__
+        if (!images->DisableImage(partition_name)) {
+            return false;
+        }
+#else
+        if (!images->UnmapImageIfExists(partition_name) ||
+            !images->DeleteBackingImage(partition_name)) {
+            return false;
+        }
+#endif
+    }
+
+    auto slot_number = fs_mgr_overlayfs_slot_number();
+    auto super_device = fs_mgr_overlayfs_super_device(slot_number);
+    if (!fs_mgr_rw_access(super_device)) return true;
+
     auto builder = MetadataBuilder::New(super_device, slot_number);
     if (!builder) {
         errno = save_errno;
         return true;
     }
-    const auto partition_name = android::base::Basename(kScratchMountPoint);
     if (builder->FindPartition(partition_name) == nullptr) {
         errno = save_errno;
         return true;
@@ -836,7 +873,8 @@
 // This returns the scratch device that was detected during early boot (first-
 // stage init). If the device was created later, for example during setup for
 // the adb remount command, it can return an empty string since it does not
-// query ImageManager.
+// query ImageManager. (Note that ImageManager in first-stage init will always
+// use device-mapper, since /data is not available to use loop devices.)
 static std::string GetBootScratchDevice() {
     auto& dm = DeviceMapper::Instance();
 
@@ -992,12 +1030,66 @@
     return true;
 }
 
-static bool CanUseSuperPartition(const Fstab& fstab) {
+static bool CreateScratchOnData(std::string* scratch_device, bool* partition_exists, bool* change) {
+    *partition_exists = false;
+    *change = false;
+
+    auto images = IImageManager::Open("remount", 10s);
+    if (!images) {
+        return false;
+    }
+
+    auto partition_name = android::base::Basename(kScratchMountPoint);
+    if (images->GetMappedImageDevice(partition_name, scratch_device)) {
+        *partition_exists = true;
+        return true;
+    }
+
+    BlockDeviceInfo info;
+    PartitionOpener opener;
+    if (!opener.GetInfo(fs_mgr_get_super_partition_name(), &info)) {
+        LERROR << "could not get block device info for super";
+        return false;
+    }
+
+    *change = true;
+
+    // Note: calling RemoveDisabledImages here ensures that we do not race with
+    // clean_scratch_files and accidentally try to map an image that will be
+    // deleted.
+    if (!images->RemoveDisabledImages()) {
+        return false;
+    }
+    if (!images->BackingImageExists(partition_name)) {
+        static constexpr uint64_t kMinimumSize = 16_MiB;
+        static constexpr uint64_t kMaximumSize = 2_GiB;
+
+        uint64_t size = std::clamp(info.size / 2, kMinimumSize, kMaximumSize);
+        auto flags = IImageManager::CREATE_IMAGE_DEFAULT;
+
+        if (!images->CreateBackingImage(partition_name, size, flags)) {
+            LERROR << "could not create scratch image of " << size << " bytes";
+            return false;
+        }
+    }
+    if (!images->MapImageDevice(partition_name, 10s, scratch_device)) {
+        LERROR << "could not map scratch image";
+        return false;
+    }
+    return true;
+}
+
+static bool CanUseSuperPartition(const Fstab& fstab, bool* is_virtual_ab) {
     auto slot_number = fs_mgr_overlayfs_slot_number();
     auto super_device = fs_mgr_overlayfs_super_device(slot_number);
     if (!fs_mgr_rw_access(super_device) || !fs_mgr_overlayfs_has_logical(fstab)) {
         return false;
     }
+    auto metadata = ReadMetadata(super_device, slot_number);
+    if (!metadata) {
+        return false;
+    }
+    *is_virtual_ab = !!(metadata->header.flags & LP_HEADER_FLAG_VIRTUAL_AB_DEVICE);
     return true;
 }
 
@@ -1011,7 +1103,12 @@
     }
 
     // If that fails, see if we can land on super.
-    if (CanUseSuperPartition(fstab)) {
+    bool is_virtual_ab;
+    if (CanUseSuperPartition(fstab, &is_virtual_ab)) {
+        bool can_use_data = false;
+        if (is_virtual_ab && FilesystemHasReliablePinning("/data", &can_use_data) && can_use_data) {
+            return CreateScratchOnData(scratch_device, partition_exists, change);
+        }
         return CreateDynamicScratch(scratch_device, partition_exists, change);
     }
 
@@ -1053,19 +1150,6 @@
     return fs_mgr_overlayfs_mount_scratch(scratch_device, mnt_type);
 }
 
-bool fs_mgr_overlayfs_scratch_can_be_mounted(const std::string& scratch_device) {
-    if (scratch_device.empty()) return false;
-    if (fs_mgr_overlayfs_already_mounted(kScratchMountPoint, false)) return false;
-    if (android::base::StartsWith(scratch_device, kPhysicalDevice)) return true;
-    if (fs_mgr_rw_access(scratch_device)) return true;
-    auto slot_number = fs_mgr_overlayfs_slot_number();
-    auto super_device = fs_mgr_overlayfs_super_device(slot_number);
-    if (!fs_mgr_rw_access(super_device)) return false;
-    auto builder = MetadataBuilder::New(super_device, slot_number);
-    if (!builder) return false;
-    return builder->FindPartition(android::base::Basename(kScratchMountPoint)) != nullptr;
-}
-
 bool fs_mgr_overlayfs_invalid() {
     if (fs_mgr_overlayfs_valid() == OverlayfsValidResult::kNotSupported) return true;
 
@@ -1114,7 +1198,7 @@
     // if verity is still disabled, i.e. no reboot occurred), and skips calling
     // fs_mgr_overlayfs_mount_all().
     auto scratch_device = GetBootScratchDevice();
-    if (!fs_mgr_overlayfs_scratch_can_be_mounted(scratch_device)) {
+    if (!fs_mgr_rw_access(scratch_device)) {
         return;
     }
     if (!WaitForFile(scratch_device, 10s)) {
@@ -1152,35 +1236,6 @@
     return ret;
 }
 
-std::vector<std::string> fs_mgr_overlayfs_required_devices(Fstab* fstab) {
-    if (fs_mgr_overlayfs_invalid()) return {};
-
-    if (GetEntryForMountPoint(fstab, kScratchMountPoint) != nullptr) {
-        return {};
-    }
-
-    bool want_scratch = false;
-    for (const auto& entry : fs_mgr_overlayfs_candidate_list(*fstab)) {
-        if (fs_mgr_is_verity_enabled(entry)) {
-            continue;
-        }
-        if (fs_mgr_overlayfs_already_mounted(fs_mgr_mount_point(entry.mount_point))) {
-            continue;
-        }
-        want_scratch = true;
-        break;
-    }
-    if (!want_scratch) {
-        return {};
-    }
-
-    auto device = GetBootScratchDevice();
-    if (!device.empty()) {
-        return {device};
-    }
-    return {};
-}
-
 // Returns false if setup not permitted, errno set to last error.
 // If something is altered, set *change.
 bool fs_mgr_overlayfs_setup(const char* backing, const char* mount_point, bool* change,
@@ -1246,13 +1301,27 @@
     return ret;
 }
 
-static bool GetAndMapScratchDeviceIfNeeded(std::string* device, bool* mapped) {
+static bool EnsureScratchMapped(std::string* device, bool* mapped) {
     *mapped = false;
     *device = GetBootScratchDevice();
     if (!device->empty()) {
         return true;
     }
 
+    auto partition_name = android::base::Basename(kScratchMountPoint);
+
+    // Check for scratch on /data first, before looking for a modified super
+    // partition. We should only reach this code in recovery, because scratch
+    // would otherwise always be mapped.
+    auto images = IImageManager::Open("remount", 10s);
+    if (images && images->BackingImageExists(partition_name)) {
+        if (!images->MapImageDevice(partition_name, 10s, device)) {
+            return false;
+        }
+        *mapped = true;
+        return true;
+    }
+
     // Avoid uart spam by first checking for a scratch partition.
     auto metadata_slot = fs_mgr_overlayfs_slot_number();
     auto super_device = fs_mgr_overlayfs_super_device(metadata_slot);
@@ -1261,7 +1330,6 @@
         return false;
     }
 
-    auto partition_name = android::base::Basename(kScratchMountPoint);
     auto partition = FindPartition(*metadata.get(), partition_name);
     if (!partition) {
         return false;
@@ -1281,6 +1349,12 @@
     return true;
 }
 
+static void UnmapScratchDevice() {
+    // This should only be reachable in recovery, where scratch is not
+    // automatically mapped and therefore can be unmapped.
+    DestroyLogicalPartition(android::base::Basename(kScratchMountPoint));
+}
+
 // Returns false if teardown not permitted, errno set to last error.
 // If something is altered, set *change.
 bool fs_mgr_overlayfs_teardown(const char* mount_point, bool* change) {
@@ -1293,7 +1367,7 @@
     bool unmap = false;
     if ((mount_point != nullptr) && !fs_mgr_overlayfs_already_mounted(kScratchMountPoint, false)) {
         std::string scratch_device;
-        if (GetAndMapScratchDeviceIfNeeded(&scratch_device, &unmap)) {
+        if (EnsureScratchMapped(&scratch_device, &unmap)) {
             mount_scratch = fs_mgr_overlayfs_mount_scratch(scratch_device,
                                                            fs_mgr_overlayfs_scratch_mount_type());
         }
@@ -1319,7 +1393,7 @@
         fs_mgr_overlayfs_umount_scratch();
     }
     if (unmap) {
-        DestroyLogicalPartition(android::base::Basename(kScratchMountPoint));
+        UnmapScratchDevice();
     }
     return ret;
 }
@@ -1338,6 +1412,59 @@
     return false;
 }
 
+namespace android {
+namespace fs_mgr {
+
+void MapScratchPartitionIfNeeded(Fstab* fstab,
+                                 const std::function<bool(const std::set<std::string>&)>& init) {
+    if (fs_mgr_overlayfs_invalid()) {
+        return;
+    }
+    if (GetEntryForMountPoint(fstab, kScratchMountPoint) != nullptr) {
+        return;
+    }
+
+    bool want_scratch = false;
+    for (const auto& entry : fs_mgr_overlayfs_candidate_list(*fstab)) {
+        if (fs_mgr_is_verity_enabled(entry)) {
+            continue;
+        }
+        if (fs_mgr_overlayfs_already_mounted(fs_mgr_mount_point(entry.mount_point))) {
+            continue;
+        }
+        want_scratch = true;
+        break;
+    }
+    if (!want_scratch) {
+        return;
+    }
+
+    if (ScratchIsOnData()) {
+        if (auto images = IImageManager::Open("remount", 0ms)) {
+            images->MapAllImages(init);
+        }
+    }
+
+    // Physical or logical partitions will have already been mapped here,
+    // so just ensure /dev/block symlinks exist.
+    auto device = GetBootScratchDevice();
+    if (!device.empty()) {
+        init({android::base::Basename(device)});
+    }
+}
+
+void CleanupOldScratchFiles() {
+    if (!ScratchIsOnData()) {
+        return;
+    }
+    if (auto images = IImageManager::Open("remount", 0ms)) {
+        images->RemoveDisabledImages();
+    }
+}
+
+}  // namespace fs_mgr
+}  // namespace android
+
 #endif  // ALLOW_ADBD_DISABLE_VERITY != 0
 
 bool fs_mgr_has_shared_blocks(const std::string& mount_point, const std::string& dev) {
diff --git a/fs_mgr/include/fs_mgr_overlayfs.h b/fs_mgr/include/fs_mgr_overlayfs.h
index 9a7381f..34aded9 100644
--- a/fs_mgr/include/fs_mgr_overlayfs.h
+++ b/fs_mgr/include/fs_mgr_overlayfs.h
@@ -16,8 +16,11 @@
 
 #pragma once
 
+#include <functional>
+
 #include <fstab/fstab.h>
 
+#include <set>
 #include <string>
 #include <vector>
 
@@ -38,3 +41,13 @@
     kOverrideCredsRequired,
 };
 OverlayfsValidResult fs_mgr_overlayfs_valid();
+
+namespace android {
+namespace fs_mgr {
+
+void MapScratchPartitionIfNeeded(Fstab* fstab,
+                                 const std::function<bool(const std::set<std::string>&)>& init);
+void CleanupOldScratchFiles();
+
+}  // namespace fs_mgr
+}  // namespace android
diff --git a/fs_mgr/libfiemap/image_manager.cpp b/fs_mgr/libfiemap/image_manager.cpp
index 280318e..0195716 100644
--- a/fs_mgr/libfiemap/image_manager.cpp
+++ b/fs_mgr/libfiemap/image_manager.cpp
@@ -124,7 +124,7 @@
     return images;
 }
 
-bool ImageManager::PartitionExists(const std::string& name) {
+bool ImageManager::BackingImageExists(const std::string& name) {
     if (!MetadataExists(metadata_dir_)) {
         return false;
     }
@@ -135,11 +135,6 @@
     return !!FindPartition(*metadata.get(), name);
 }
 
-bool ImageManager::BackingImageExists(const std::string& name) {
-    auto header_file = GetImageHeaderPath(name);
-    return access(header_file.c_str(), F_OK) == 0;
-}
-
 static bool IsUnreliablePinningAllowed(const std::string& path) {
     return android::base::StartsWith(path, "/data/gsi/dsu/") ||
            android::base::StartsWith(path, "/data/gsi/test/") ||
@@ -261,6 +256,10 @@
         return false;
     }
 
+#if defined __ANDROID_RECOVERY__
+    LOG(ERROR) << "Cannot remove images backed by /data in recovery";
+    return false;
+#else
     std::string message;
     auto header_file = GetImageHeaderPath(name);
     if (!SplitFiemap::RemoveSplitFiles(header_file, &message)) {
@@ -274,6 +273,7 @@
         LOG(ERROR) << "Error removing " << status_file << ": " << message;
     }
     return RemoveImageMetadata(metadata_dir_, name);
+#endif
 }
 
 // Create a block device for an image file, using its extents in its
@@ -507,6 +507,7 @@
 
     auto image_header = GetImageHeaderPath(name);
 
+#if !defined __ANDROID_RECOVERY__
     // If there is a device-mapper node wrapping the block device, then we're
     // able to create another node around it; the dm layer does not carry the
     // exclusion lock down the stack when a mount occurs.
@@ -530,6 +531,13 @@
     } else if (!MapWithLoopDevice(name, timeout_ms, path)) {
         return false;
     }
+#else
+    // In recovery, we can *only* use device-mapper, since partitions aren't
+    // mounted. That also means we cannot call GetBlockDeviceForFile.
+    if (!MapWithDmLinear(*partition_opener_.get(), name, timeout_ms, path)) {
+        return false;
+    }
+#endif
 
     // Set a property so we remember this is mapped.
     auto prop_name = GetStatusPropertyName(name);
diff --git a/fs_mgr/libfiemap/include/libfiemap/image_manager.h b/fs_mgr/libfiemap/include/libfiemap/image_manager.h
index 2c13229..60b98dc 100644
--- a/fs_mgr/libfiemap/include/libfiemap/image_manager.h
+++ b/fs_mgr/libfiemap/include/libfiemap/image_manager.h
@@ -76,7 +76,9 @@
     // Unmap a block device previously mapped with mapBackingImage.
     virtual bool UnmapImageDevice(const std::string& name) = 0;
 
-    // Returns true whether the named backing image exists.
+    // Returns true whether the named backing image exists. This does not check
+    // consistency with the /data partition, so that it can return true in
+    // recovery.
     virtual bool BackingImageExists(const std::string& name) = 0;
 
     // Returns true if the specified image is mapped to a device.
@@ -154,10 +156,6 @@
 
     std::vector<std::string> GetAllBackingImages();
 
-    // Returns true if the named partition exists. This does not check the
-    // consistency of the backing image/data file.
-    bool PartitionExists(const std::string& name);
-
     // Validates that all images still have pinned extents. This will be removed
     // once b/134588268 is fixed.
     bool Validate();
diff --git a/fs_mgr/libsnapshot/Android.bp b/fs_mgr/libsnapshot/Android.bp
index c67e33d..ad48b82 100644
--- a/fs_mgr/libsnapshot/Android.bp
+++ b/fs_mgr/libsnapshot/Android.bp
@@ -24,14 +24,13 @@
     ],
     shared_libs: [
         "libbase",
+        "libcutils",
         "liblog",
         "liblp",
     ],
     static_libs: [
-        "libcutils",
         "libdm",
         "libfstab",
-        "liblp",
         "update_metadata-protos",
     ],
     whole_static_libs: [
@@ -146,8 +145,8 @@
     ],
     static_libs: [
         "libfs_mgr",
-        "libgtest",
         "libgmock",
+        "libgtest",
     ],
 }
 
@@ -155,33 +154,33 @@
     name: "libsnapshot_test",
     defaults: ["libsnapshot_defaults"],
     srcs: [
-        "snapshot_test.cpp",
         "partition_cow_creator_test.cpp",
         "snapshot_metadata_updater_test.cpp",
-        "test_helpers.cpp",
+        "snapshot_test.cpp",
     ],
     shared_libs: [
-        "libbinder",
-        "libcrypto",
-        "libhidlbase",
-        "libprotobuf-cpp-lite",
-        "libutils",
-    ],
-    static_libs: [
         "android.hardware.boot@1.0",
         "android.hardware.boot@1.1",
+        "libbinder",
+        "libcrypto",
         "libfs_mgr",
-        "libgmock",
         "libgsi",
+        "libhidlbase",
         "liblp",
+        "libprotobuf-cpp-lite",
+        "libsparse",
+        "libutils",
+        "libz",
+    ],
+    static_libs: [
+        "libgmock",
         "libsnapshot",
         "libsnapshot_test_helpers",
-        "libsparse",
-        "libz",
     ],
     header_libs: [
         "libstorage_literals_headers",
     ],
+    require_root: true,
 }
 
 cc_binary {
@@ -191,7 +190,6 @@
     ],
     static_libs: [
         "libdm",
-        "libext2_uuid",
         "libfstab",
         "libsnapshot",
     ],
@@ -201,6 +199,7 @@
         "libbase",
         "libbinder",
         "libbinderthreadstate",
+        "libext2_uuid",
         "libext4_utils",
         "libfs_mgr_binder",
         "libhidlbase",
diff --git a/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h b/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h
index 959d8a7..e786bc9 100644
--- a/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h
+++ b/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h
@@ -213,7 +213,8 @@
 
     // Perform first-stage mapping of snapshot targets. This replaces init's
     // call to CreateLogicalPartitions when snapshots are present.
-    bool CreateLogicalAndSnapshotPartitions(const std::string& super_device);
+    bool CreateLogicalAndSnapshotPartitions(const std::string& super_device,
+                                            const std::chrono::milliseconds& timeout_ms = {});
 
     // This method should be called preceding any wipe or flash of metadata or
     // userdata. It is only valid in recovery or fastbootd, and it ensures that
diff --git a/fs_mgr/libsnapshot/snapshot.cpp b/fs_mgr/libsnapshot/snapshot.cpp
index 912087c..88731df 100644
--- a/fs_mgr/libsnapshot/snapshot.cpp
+++ b/fs_mgr/libsnapshot/snapshot.cpp
@@ -828,7 +828,8 @@
                 cancelled = true;
                 break;
             default:
-                LOG(ERROR) << "Unknown merge status: " << static_cast<uint32_t>(snapshot_state);
+                LOG(ERROR) << "Unknown merge status for \"" << snapshot << "\": "
+                           << "\"" << snapshot_state << "\"";
                 failed = true;
                 break;
         }
@@ -1218,7 +1219,8 @@
         if (!UnmapPartitionWithSnapshot(lock, name) || !DeleteSnapshot(lock, name)) {
             // Remember whether or not we were able to unmap the cow image.
             auto cow_image_device = GetCowImageDeviceName(name);
-            has_mapped_cow_images |= images_->IsImageMapped(cow_image_device);
+            has_mapped_cow_images |=
+                    (EnsureImageManager() && images_->IsImageMapped(cow_image_device));
 
             ok = false;
         }
@@ -1344,7 +1346,8 @@
     }
 }
 
-bool SnapshotManager::CreateLogicalAndSnapshotPartitions(const std::string& super_device) {
+bool SnapshotManager::CreateLogicalAndSnapshotPartitions(
+        const std::string& super_device, const std::chrono::milliseconds& timeout_ms) {
     LOG(INFO) << "Creating logical partitions with snapshots as needed";
 
     auto lock = LockExclusive();
@@ -1370,6 +1373,7 @@
                 .metadata = metadata.get(),
                 .partition = &partition,
                 .partition_opener = &opener,
+                .timeout_ms = timeout_ms,
         };
         std::string ignore_path;
         if (!MapPartitionWithSnapshot(lock.get(), std::move(params), &ignore_path)) {
@@ -1706,7 +1710,7 @@
     } else if (contents == "merge-failed") {
         return UpdateState::MergeFailed;
     } else {
-        LOG(ERROR) << "Unknown merge state in update state file";
+        LOG(ERROR) << "Unknown merge state in update state file: \"" << contents << "\"";
         return UpdateState::None;
     }
 }
@@ -1728,7 +1732,7 @@
         case UpdateState::MergeFailed:
             return os << "merge-failed";
         default:
-            LOG(ERROR) << "Unknown update state";
+            LOG(ERROR) << "Unknown update state: " << static_cast<uint32_t>(state);
             return os;
     }
 }
diff --git a/fs_mgr/libsnapshot/snapshot_metadata_updater_test.cpp b/fs_mgr/libsnapshot/snapshot_metadata_updater_test.cpp
index 337be4f..5530e59 100644
--- a/fs_mgr/libsnapshot/snapshot_metadata_updater_test.cpp
+++ b/fs_mgr/libsnapshot/snapshot_metadata_updater_test.cpp
@@ -19,6 +19,7 @@
 #include <memory>
 #include <string>
 
+#include <android-base/properties.h>
 #include <gmock/gmock.h>
 #include <gtest/gtest.h>
 #include <liblp/builder.h>
@@ -42,6 +43,10 @@
 
 class SnapshotMetadataUpdaterTest : public ::testing::TestWithParam<uint32_t> {
   public:
+    SnapshotMetadataUpdaterTest() {
+        is_virtual_ab_ = android::base::GetBoolProperty("ro.virtual_ab.enabled", false);
+    }
+
     void SetUp() override {
         target_slot_ = GetParam();
         target_suffix_ = SlotSuffixForSlotNumber(target_slot_);
@@ -122,6 +127,7 @@
                                   << ".";
     }
 
+    bool is_virtual_ab_;
     std::unique_ptr<MetadataBuilder> builder_;
     uint32_t target_slot_;
     std::string target_suffix_;
diff --git a/fs_mgr/libsnapshot/snapshot_test.cpp b/fs_mgr/libsnapshot/snapshot_test.cpp
index 47ac474..634e0b4 100644
--- a/fs_mgr/libsnapshot/snapshot_test.cpp
+++ b/fs_mgr/libsnapshot/snapshot_test.cpp
@@ -78,7 +78,9 @@
 
 class SnapshotTest : public ::testing::Test {
   public:
-    SnapshotTest() : dm_(DeviceMapper::Instance()) {}
+    SnapshotTest() : dm_(DeviceMapper::Instance()) {
+        is_virtual_ab_ = android::base::GetBoolProperty("ro.virtual_ab.enabled", false);
+    }
 
     // This is exposed for main.
     void Cleanup() {
@@ -88,6 +90,8 @@
 
   protected:
     void SetUp() override {
+        if (!is_virtual_ab_) GTEST_SKIP() << "Test for Virtual A/B devices only";
+
         SnapshotTestPropertyFetcher::SetUp();
         InitializeState();
         CleanupTestArtifacts();
@@ -97,6 +101,8 @@
     }
 
     void TearDown() override {
+        if (!is_virtual_ab_) return;
+
         lock_ = nullptr;
 
         CleanupTestArtifacts();
@@ -329,6 +335,7 @@
         return AssertionSuccess();
     }
 
+    bool is_virtual_ab_;
     DeviceMapper& dm_;
     std::unique_ptr<SnapshotManager::LockedFile> lock_;
     android::fiemap::IImageManager* image_manager_ = nullptr;
@@ -754,6 +761,8 @@
 class SnapshotUpdateTest : public SnapshotTest {
   public:
     void SetUp() override {
+        if (!is_virtual_ab_) GTEST_SKIP() << "Test for Virtual A/B devices only";
+
         SnapshotTest::SetUp();
         Cleanup();
 
@@ -813,6 +822,8 @@
         }
     }
     void TearDown() override {
+        if (!is_virtual_ab_) return;
+
         Cleanup();
         SnapshotTest::TearDown();
     }
@@ -999,7 +1010,7 @@
     auto init = SnapshotManager::NewForFirstStageMount(new TestDeviceInfo(fake_super, "_b"));
     ASSERT_NE(init, nullptr);
     ASSERT_TRUE(init->NeedSnapshotsInFirstStageMount());
-    ASSERT_TRUE(init->CreateLogicalAndSnapshotPartitions("super"));
+    ASSERT_TRUE(init->CreateLogicalAndSnapshotPartitions("super", 1s));
 
     // Check that the target partitions have the same content.
     for (const auto& name : {"sys_b", "vnd_b", "prd_b"}) {
@@ -1127,7 +1138,7 @@
     auto init = SnapshotManager::NewForFirstStageMount(new TestDeviceInfo(fake_super, "_b"));
     ASSERT_NE(init, nullptr);
     ASSERT_TRUE(init->NeedSnapshotsInFirstStageMount());
-    ASSERT_TRUE(init->CreateLogicalAndSnapshotPartitions("super"));
+    ASSERT_TRUE(init->CreateLogicalAndSnapshotPartitions("super", 1s));
 
     // Check that the target partitions have the same content.
     for (const auto& name : {"sys_b", "vnd_b", "prd_b"}) {
@@ -1139,7 +1150,7 @@
     init = SnapshotManager::NewForFirstStageMount(new TestDeviceInfo(fake_super, "_a"));
     ASSERT_NE(init, nullptr);
     ASSERT_FALSE(init->NeedSnapshotsInFirstStageMount());
-    ASSERT_TRUE(init->CreateLogicalAndSnapshotPartitions("super"));
+    ASSERT_TRUE(init->CreateLogicalAndSnapshotPartitions("super", 1s));
 
     // Assert that the source partitions aren't affected.
     for (const auto& name : {"sys_a", "vnd_a", "prd_a"}) {
@@ -1516,7 +1527,7 @@
     auto init = SnapshotManager::NewForFirstStageMount(new TestDeviceInfo(fake_super, "_b"));
     ASSERT_NE(init, nullptr);
     ASSERT_TRUE(init->NeedSnapshotsInFirstStageMount());
-    ASSERT_TRUE(init->CreateLogicalAndSnapshotPartitions("super"));
+    ASSERT_TRUE(init->CreateLogicalAndSnapshotPartitions("super", 1s));
 
     // Check that the target partition have the same content. Hashtree and FEC extents
     // should be accounted for.
@@ -1625,6 +1636,8 @@
 };
 
 TEST_P(FlashAfterUpdateTest, FlashSlotAfterUpdate) {
+    if (!is_virtual_ab_) GTEST_SKIP() << "Test for Virtual A/B devices only";
+
     // OTA client blindly unmaps all partitions that are possibly mapped.
     for (const auto& name : {"sys_b", "vnd_b", "prd_b"}) {
         ASSERT_TRUE(sm->UnmapUpdateSnapshot(name));
@@ -1639,7 +1652,8 @@
     // Simulate shutting down the device.
     ASSERT_TRUE(UnmapAll());
 
-    if (std::get<1>(GetParam()) /* merge */) {
+    bool after_merge = std::get<1>(GetParam());
+    if (after_merge) {
         ASSERT_TRUE(InitiateMerge("_b"));
         // Simulate shutting down the device after merge has initiated.
         ASSERT_TRUE(UnmapAll());
@@ -1688,21 +1702,11 @@
     auto init = SnapshotManager::NewForFirstStageMount(
             new TestDeviceInfo(fake_super, flashed_slot_suffix));
     ASSERT_NE(init, nullptr);
-    if (init->NeedSnapshotsInFirstStageMount()) {
-        ASSERT_TRUE(init->CreateLogicalAndSnapshotPartitions("super"));
-    } else {
-        for (const auto& name : {"sys", "vnd"}) {
-            ASSERT_TRUE(CreateLogicalPartition(
-                    CreateLogicalPartitionParams{
-                            .block_device = fake_super,
-                            .metadata_slot = flashed_slot,
-                            .partition_name = name + flashed_slot_suffix,
-                            .timeout_ms = 1s,
-                            .partition_opener = opener_.get(),
-                    },
-                    &path));
-        }
+
+    if (flashed_slot && after_merge) {
+        ASSERT_TRUE(init->NeedSnapshotsInFirstStageMount());
     }
+    ASSERT_TRUE(init->CreateLogicalAndSnapshotPartitions("super", 1s));
 
     // Check that the target partitions have the same content.
     for (const auto& name : {"sys", "vnd"}) {
@@ -1727,13 +1731,17 @@
 // Test behavior of ImageManager::Create on low space scenario. These tests assumes image manager
 // uses /data as backup device.
 class ImageManagerTest : public SnapshotTest, public WithParamInterface<uint64_t> {
-  public:
+  protected:
     void SetUp() override {
+        if (!is_virtual_ab_) GTEST_SKIP() << "Test for Virtual A/B devices only";
+
         SnapshotTest::SetUp();
         userdata_ = std::make_unique<LowSpaceUserdata>();
         ASSERT_TRUE(userdata_->Init(GetParam()));
     }
     void TearDown() override {
+        if (!is_virtual_ab_) return;
+
         EXPECT_TRUE(!image_manager_->BackingImageExists(kImageName) ||
                     image_manager_->DeleteBackingImage(kImageName));
     }
diff --git a/fs_mgr/libstorage_literals/Android.bp b/fs_mgr/libstorage_literals/Android.bp
index 11611dd..beb18ef 100644
--- a/fs_mgr/libstorage_literals/Android.bp
+++ b/fs_mgr/libstorage_literals/Android.bp
@@ -2,5 +2,6 @@
 cc_library_headers {
     name: "libstorage_literals_headers",
     host_supported: true,
+    recovery_available: true,
     export_include_dirs: ["."],
 }
diff --git a/fs_mgr/tests/adb-remount-test.sh b/fs_mgr/tests/adb-remount-test.sh
index 4226e95..c66f307 100755
--- a/fs_mgr/tests/adb-remount-test.sh
+++ b/fs_mgr/tests/adb-remount-test.sh
@@ -1160,13 +1160,16 @@
 ret=${?}
 uses_dynamic_scratch=false
 scratch_partition=
+virtual_ab=`get_property ro.virtual_ab.enabled`
 if ${overlayfs_needed}; then
   if [ ${ret} != 0 ]; then
     die -t ${T} "overlay takeover failed"
   fi
   echo "${D}" | grep "^overlay .* /system\$" >/dev/null ||
    echo "${ORANGE}[  WARNING ]${NORMAL} overlay takeover not complete" >&2
-  scratch_partition=scratch
+  if [ -z "${virtual_ab}" ]; then
+    scratch_partition=scratch
+  fi
   if echo "${D}" | grep " /mnt/scratch" >/dev/null; then
     echo "${BLUE}[     INFO ]${NORMAL} using ${scratch_partition} dynamic partition for overrides" >&2
   fi
diff --git a/healthd/BatteryMonitor.cpp b/healthd/BatteryMonitor.cpp
index bdf4aac..7caf468 100644
--- a/healthd/BatteryMonitor.cpp
+++ b/healthd/BatteryMonitor.cpp
@@ -126,6 +126,26 @@
     return *ret;
 }
 
+BatteryCapacityLevel getBatteryCapacityLevel(const char* capacityLevel) {
+    static SysfsStringEnumMap<BatteryCapacityLevel> batteryCapacityLevelMap[] = {
+            {"Unknown", BatteryCapacityLevel::UNKNOWN},
+            {"Critical", BatteryCapacityLevel::CRITICAL},
+            {"Low", BatteryCapacityLevel::LOW},
+            {"Normal", BatteryCapacityLevel::NORMAL},
+            {"High", BatteryCapacityLevel::HIGH},
+            {"Full", BatteryCapacityLevel::FULL},
+            {NULL, BatteryCapacityLevel::UNKNOWN},
+    };
+
+    auto ret = mapSysfsString(capacityLevel, batteryCapacityLevelMap);
+    if (!ret) {
+        KLOG_WARNING(LOG_TAG, "Unknown battery capacity level '%s'\n", capacityLevel);
+        *ret = BatteryCapacityLevel::UNKNOWN;
+    }
+
+    return *ret;
+}
+
 BatteryHealth getBatteryHealth(const char* status) {
     static SysfsStringEnumMap<BatteryHealth> batteryHealthMap[] = {
             {"Unknown", BatteryHealth::UNKNOWN},
@@ -241,9 +261,10 @@
         mHealthInfo->legacy.batteryCurrentAverage =
                 getIntField(mHealthdConfig->batteryCurrentAvgPath);
 
-    // TODO(b/142260281): Retrieve these values correctly.
-    mHealthInfo->batteryCapacityLevel = BatteryCapacityLevel::UNKNOWN;
-    mHealthInfo->batteryChargeTimeToFullNowSeconds = 0;
+    if (!mHealthdConfig->batteryChargeTimeToFullNowPath.isEmpty())
+        mHealthInfo->batteryChargeTimeToFullNowSeconds =
+                getIntField(mHealthdConfig->batteryChargeTimeToFullNowPath);
+
     mHealthInfo->batteryFullCapacityUah = props.batteryFullCharge;
 
     props.batteryTemperature = mBatteryFixedTemperature ?
@@ -252,6 +273,9 @@
 
     std::string buf;
 
+    if (readFromFile(mHealthdConfig->batteryCapacityLevelPath, &buf) > 0)
+        mHealthInfo->batteryCapacityLevel = getBatteryCapacityLevel(buf.c_str());
+
     if (readFromFile(mHealthdConfig->batteryStatusPath, &buf) > 0)
         props.batteryStatus = getBatteryStatus(buf.c_str());
 
@@ -585,6 +609,19 @@
                         mHealthdConfig->batteryCycleCountPath = path;
                 }
 
+                if (mHealthdConfig->batteryCapacityLevelPath.isEmpty()) {
+                    path.clear();
+                    path.appendFormat("%s/%s/capacity_level", POWER_SUPPLY_SYSFS_PATH, name);
+                    if (access(path, R_OK) == 0) mHealthdConfig->batteryCapacityLevelPath = path;
+                }
+
+                if (mHealthdConfig->batteryChargeTimeToFullNowPath.isEmpty()) {
+                    path.clear();
+                    path.appendFormat("%s/%s/time_to_full_now", POWER_SUPPLY_SYSFS_PATH, name);
+                    if (access(path, R_OK) == 0)
+                        mHealthdConfig->batteryChargeTimeToFullNowPath = path;
+                }
+
                 if (mHealthdConfig->batteryCurrentAvgPath.isEmpty()) {
                     path.clear();
                     path.appendFormat("%s/%s/current_avg",
@@ -653,6 +690,10 @@
             KLOG_WARNING(LOG_TAG, "BatteryFullChargePath not found\n");
         if (mHealthdConfig->batteryCycleCountPath.isEmpty())
             KLOG_WARNING(LOG_TAG, "BatteryCycleCountPath not found\n");
+        if (mHealthdConfig->batteryCapacityLevelPath.isEmpty())
+            KLOG_WARNING(LOG_TAG, "batteryCapacityLevelPath not found\n");
+        if (mHealthdConfig->batteryChargeTimeToFullNowPath.isEmpty())
+            KLOG_WARNING(LOG_TAG, "batteryChargeTimeToFullNowPath. not found\n");
     }
 
     if (property_get("ro.boot.fake_battery", pval, NULL) > 0
diff --git a/healthd/include/healthd/healthd.h b/healthd/include/healthd/healthd.h
index a900071..8ffb114 100644
--- a/healthd/include/healthd/healthd.h
+++ b/healthd/include/healthd/healthd.h
@@ -69,6 +69,8 @@
     android::String8 batteryChargeCounterPath;
     android::String8 batteryFullChargePath;
     android::String8 batteryCycleCountPath;
+    android::String8 batteryCapacityLevelPath;
+    android::String8 batteryChargeTimeToFullNowPath;
 
     int (*energyCounter)(int64_t *);
     int boot_min_cap;
diff --git a/init/first_stage_mount.cpp b/init/first_stage_mount.cpp
index 9da32e4..d8c4843 100644
--- a/init/first_stage_mount.cpp
+++ b/init/first_stage_mount.cpp
@@ -591,14 +591,18 @@
     }
 
     // heads up for instantiating required device(s) for overlayfs logic
-    const auto devices = fs_mgr_overlayfs_required_devices(&fstab_);
-    for (auto const& device : devices) {
-        if (android::base::StartsWith(device, "/dev/block/by-name/")) {
-            InitRequiredDevices({basename(device.c_str())});
-        } else {
-            InitMappedDevice(device);
+    auto init_devices = [this](std::set<std::string> devices) -> bool {
+        for (auto iter = devices.begin(); iter != devices.end();) {
+            if (android::base::StartsWith(*iter, "/dev/block/dm-")) {
+                if (!InitMappedDevice(*iter)) return false;
+                iter = devices.erase(iter);
+            } else {
+                iter++;
+            }
         }
-    }
+        return InitRequiredDevices(std::move(devices));
+    };
+    MapScratchPartitionIfNeeded(&fstab_, init_devices);
 
     fs_mgr_overlayfs_mount_all(&fstab_);
 
diff --git a/init/reboot.cpp b/init/reboot.cpp
index 2b593ea..8b239fe 100644
--- a/init/reboot.cpp
+++ b/init/reboot.cpp
@@ -741,12 +741,15 @@
     });
     // Triggering userspace-reboot-requested will result in a bunch of setprop
     // actions. We should make sure, that all of them are propagated before
-    // proceeding with userspace reboot. Synchronously setting kUserspaceRebootInProgress property
-    // is not perfect, but it should do the trick.
+    // proceeding with userspace reboot. Synchronously setting sys.init.userspace_reboot.in_progress
+    // property is not perfect, but it should do the trick.
     if (!android::sysprop::InitProperties::userspace_reboot_in_progress(true)) {
         return Error() << "Failed to set sys.init.userspace_reboot.in_progress property";
     }
     EnterShutdown();
+    if (!SetProperty("sys.powerctl", "")) {
+        return Error() << "Failed to reset sys.powerctl property";
+    }
     std::vector<Service*> stop_first;
     // Remember the services that were enabled. We will need to manually enable them again otherwise
     // triggers like class_start won't restart them.
diff --git a/libcutils/fs_config.cpp b/libcutils/fs_config.cpp
index 65c59bd..fd9a3eb 100644
--- a/libcutils/fs_config.cpp
+++ b/libcutils/fs_config.cpp
@@ -196,6 +196,7 @@
     { 00750, AID_ROOT,      AID_SHELL,     CAP_MASK_LONG(CAP_SETUID) |
                                            CAP_MASK_LONG(CAP_SETGID),
                                               "system/bin/simpleperf_app_runner" },
+    { 00755, AID_ROOT,      AID_ROOT,      0, "first_stage_ramdisk/system/bin/e2fsck" },
     // generic defaults
     { 00755, AID_ROOT,      AID_ROOT,      0, "bin/*" },
     { 00640, AID_ROOT,      AID_SHELL,     0, "fstab.*" },
diff --git a/libcutils/include/private/android_filesystem_config.h b/libcutils/include/private/android_filesystem_config.h
index f9a3df9..ff6b036 100644
--- a/libcutils/include/private/android_filesystem_config.h
+++ b/libcutils/include/private/android_filesystem_config.h
@@ -130,6 +130,7 @@
 #define AID_GSID 1074            /* GSI service daemon */
 #define AID_FSVERITY_CERT 1075   /* fs-verity key ownership in keystore */
 #define AID_CREDSTORE 1076       /* identity credential manager service */
+#define AID_EXTERNAL_STORAGE 1077 /* Full external storage access including USB OTG volumes */
 /* Changes to this file must be made in AOSP, *not* in internal branches. */
 
 #define AID_SHELL 2000 /* adb and debug shell user */
diff --git a/liblog/Android.bp b/liblog/Android.bp
index 58c96b6..2cf60e0 100644
--- a/liblog/Android.bp
+++ b/liblog/Android.bp
@@ -21,14 +21,11 @@
     "logger_read.cpp",
     "logger_write.cpp",
     "logprint.cpp",
-]
-liblog_host_sources = [
-    "fake_log_device.cpp",
+    "properties.cpp",
 ]
 liblog_target_sources = [
     "event_tag_map.cpp",
     "log_time.cpp",
-    "properties.cpp",
     "pmsg_reader.cpp",
     "pmsg_writer.cpp",
     "logd_reader.cpp",
@@ -39,6 +36,7 @@
     name: "liblog_headers",
     host_supported: true,
     vendor_available: true,
+    ramdisk_available: true,
     recovery_available: true,
     native_bridge_supported: true,
     export_include_dirs: ["include"],
@@ -62,15 +60,12 @@
 cc_library {
     name: "liblog",
     host_supported: true,
+    ramdisk_available: true,
     recovery_available: true,
     native_bridge_supported: true,
     srcs: liblog_sources,
 
     target: {
-        host: {
-            srcs: liblog_host_sources,
-            cflags: ["-DFAKE_LOG_DEVICE=1"],
-        },
         android: {
             version_script: "liblog.map.txt",
             srcs: liblog_target_sources,
diff --git a/liblog/fake_log_device.cpp b/liblog/fake_log_device.cpp
deleted file mode 100644
index cd4c11e..0000000
--- a/liblog/fake_log_device.cpp
+++ /dev/null
@@ -1,533 +0,0 @@
-/*
- * Copyright (C) 2008-2014 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.
- */
-/*
- * Intercepts log messages intended for the Android log device.
- * Messages are printed to stderr.
- */
-
-#include "fake_log_device.h"
-
-#include <ctype.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <time.h>
-
-#include <mutex>
-
-#include <android-base/no_destructor.h>
-#include <android/log.h>
-#include <log/log_id.h>
-#include <log/logprint.h>
-
-#include "logger.h"
-
-#define kMaxTagLen 16 /* from the long-dead utils/Log.cpp */
-
-#define kTagSetSize 16 /* arbitrary */
-
-#if 0
-#define TRACE(...) printf("fake_log_device: " __VA_ARGS__)
-#else
-#define TRACE(...) ((void)0)
-#endif
-
-typedef struct LogState {
-  bool initialized = false;
-  /* global minimum priority */
-  int global_min_priority;
-
-  /* output format */
-  AndroidLogPrintFormat output_format;
-
-  /* tags and priorities */
-  struct {
-    char tag[kMaxTagLen];
-    int minPriority;
-  } tagSet[kTagSetSize];
-} LogState;
-
-static LogState log_state;
-static android::base::NoDestructor<std::mutex> fake_log_mutex;
-
-/*
- * Configure logging based on ANDROID_LOG_TAGS environment variable.  We
- * need to parse a string that looks like
- *
- *   *:v jdwp:d dalvikvm:d dalvikvm-gc:i dalvikvmi:i
- *
- * The tag (or '*' for the global level) comes first, followed by a colon
- * and a letter indicating the minimum priority level we're expected to log.
- * This can be used to reveal or conceal logs with specific tags.
- *
- * We also want to check ANDROID_PRINTF_LOG to determine how the output
- * will look.
- */
-void InitializeLogStateLocked() {
-  log_state.initialized = true;
-
-  /* global min priority defaults to "info" level */
-  log_state.global_min_priority = ANDROID_LOG_INFO;
-
-  /*
-   * This is based on the the long-dead utils/Log.cpp code.
-   */
-  const char* tags = getenv("ANDROID_LOG_TAGS");
-  TRACE("Found ANDROID_LOG_TAGS='%s'\n", tags);
-  if (tags != NULL) {
-    int entry = 0;
-
-    while (*tags != '\0') {
-      char tagName[kMaxTagLen];
-      int i, minPrio;
-
-      while (isspace(*tags)) tags++;
-
-      i = 0;
-      while (*tags != '\0' && !isspace(*tags) && *tags != ':' && i < kMaxTagLen) {
-        tagName[i++] = *tags++;
-      }
-      if (i == kMaxTagLen) {
-        TRACE("ERROR: env tag too long (%d chars max)\n", kMaxTagLen - 1);
-        return;
-      }
-      tagName[i] = '\0';
-
-      /* default priority, if there's no ":" part; also zero out '*' */
-      minPrio = ANDROID_LOG_VERBOSE;
-      if (tagName[0] == '*' && tagName[1] == '\0') {
-        minPrio = ANDROID_LOG_DEBUG;
-        tagName[0] = '\0';
-      }
-
-      if (*tags == ':') {
-        tags++;
-        if (*tags >= '0' && *tags <= '9') {
-          if (*tags >= ('0' + ANDROID_LOG_SILENT))
-            minPrio = ANDROID_LOG_VERBOSE;
-          else
-            minPrio = *tags - '\0';
-        } else {
-          switch (*tags) {
-            case 'v':
-              minPrio = ANDROID_LOG_VERBOSE;
-              break;
-            case 'd':
-              minPrio = ANDROID_LOG_DEBUG;
-              break;
-            case 'i':
-              minPrio = ANDROID_LOG_INFO;
-              break;
-            case 'w':
-              minPrio = ANDROID_LOG_WARN;
-              break;
-            case 'e':
-              minPrio = ANDROID_LOG_ERROR;
-              break;
-            case 'f':
-              minPrio = ANDROID_LOG_FATAL;
-              break;
-            case 's':
-              minPrio = ANDROID_LOG_SILENT;
-              break;
-            default:
-              minPrio = ANDROID_LOG_DEFAULT;
-              break;
-          }
-        }
-
-        tags++;
-        if (*tags != '\0' && !isspace(*tags)) {
-          TRACE("ERROR: garbage in tag env; expected whitespace\n");
-          TRACE("       env='%s'\n", tags);
-          return;
-        }
-      }
-
-      if (tagName[0] == 0) {
-        log_state.global_min_priority = minPrio;
-        TRACE("+++ global min prio %d\n", logState->globalMinPriority);
-      } else {
-        log_state.tagSet[entry].minPriority = minPrio;
-        strcpy(log_state.tagSet[entry].tag, tagName);
-        TRACE("+++ entry %d: %s:%d\n", entry, logState->tagSet[entry].tag,
-              logState->tagSet[entry].minPriority);
-        entry++;
-      }
-    }
-  }
-
-  /*
-   * Taken from the long-dead utils/Log.cpp
-   */
-  const char* fstr = getenv("ANDROID_PRINTF_LOG");
-  AndroidLogPrintFormat format;
-  if (fstr == NULL) {
-    format = FORMAT_BRIEF;
-  } else {
-    if (strcmp(fstr, "brief") == 0)
-      format = FORMAT_BRIEF;
-    else if (strcmp(fstr, "process") == 0)
-      format = FORMAT_PROCESS;
-    else if (strcmp(fstr, "tag") == 0)
-      format = FORMAT_PROCESS;
-    else if (strcmp(fstr, "thread") == 0)
-      format = FORMAT_PROCESS;
-    else if (strcmp(fstr, "raw") == 0)
-      format = FORMAT_PROCESS;
-    else if (strcmp(fstr, "time") == 0)
-      format = FORMAT_PROCESS;
-    else if (strcmp(fstr, "long") == 0)
-      format = FORMAT_PROCESS;
-    else
-      format = (AndroidLogPrintFormat)atoi(fstr);  // really?!
-  }
-
-  log_state.output_format = format;
-}
-
-/*
- * Return a human-readable string for the priority level.  Always returns
- * a valid string.
- */
-static const char* getPriorityString(int priority) {
-  /* the first character of each string should be unique */
-  static const char* priorityStrings[] = {"Verbose", "Debug", "Info", "Warn", "Error", "Assert"};
-  int idx;
-
-  idx = (int)priority - (int)ANDROID_LOG_VERBOSE;
-  if (idx < 0 || idx >= (int)(sizeof(priorityStrings) / sizeof(priorityStrings[0])))
-    return "?unknown?";
-  return priorityStrings[idx];
-}
-
-#if defined(_WIN32)
-/*
- * WIN32 does not have writev().
- * Make up something to replace it.
- */
-static ssize_t fake_writev(int fd, const struct iovec* iov, int iovcnt) {
-  ssize_t result = 0;
-  const struct iovec* end = iov + iovcnt;
-  for (; iov < end; iov++) {
-    ssize_t w = write(fd, iov->iov_base, iov->iov_len);
-    if (w != (ssize_t)iov->iov_len) {
-      if (w < 0) return w;
-      return result + w;
-    }
-    result += w;
-  }
-  return result;
-}
-
-#define writev fake_writev
-#endif
-
-/*
- * Write a filtered log message to stderr.
- *
- * Log format parsing taken from the long-dead utils/Log.cpp.
- */
-static void ShowLog(int logPrio, const char* tag, const char* msg) {
-#if !defined(_WIN32)
-  struct tm tmBuf;
-#endif
-  struct tm* ptm;
-  char timeBuf[32];
-  char prefixBuf[128], suffixBuf[128];
-  char priChar;
-  time_t when;
-#if !defined(_WIN32)
-  pid_t pid, tid;
-#else
-  uint32_t pid, tid;
-#endif
-
-  TRACE("LOG %d: %s %s", logPrio, tag, msg);
-
-  priChar = getPriorityString(logPrio)[0];
-  when = time(NULL);
-  pid = tid = getpid();  // find gettid()?
-
-/*
- * Get the current date/time in pretty form
- *
- * It's often useful when examining a log with "less" to jump to
- * a specific point in the file by searching for the date/time stamp.
- * For this reason it's very annoying to have regexp meta characters
- * in the time stamp.  Don't use forward slashes, parenthesis,
- * brackets, asterisks, or other special chars here.
- */
-#if !defined(_WIN32)
-  ptm = localtime_r(&when, &tmBuf);
-#else
-  ptm = localtime(&when);
-#endif
-  // strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%d %H:%M:%S", ptm);
-  strftime(timeBuf, sizeof(timeBuf), "%m-%d %H:%M:%S", ptm);
-
-  /*
-   * Construct a buffer containing the log header and log message.
-   */
-  size_t prefixLen, suffixLen;
-
-  switch (log_state.output_format) {
-    case FORMAT_TAG:
-      prefixLen = snprintf(prefixBuf, sizeof(prefixBuf), "%c/%-8s: ", priChar, tag);
-      strcpy(suffixBuf, "\n");
-      suffixLen = 1;
-      break;
-    case FORMAT_PROCESS:
-      prefixLen = snprintf(prefixBuf, sizeof(prefixBuf), "%c(%5d) ", priChar, pid);
-      suffixLen = snprintf(suffixBuf, sizeof(suffixBuf), "  (%s)\n", tag);
-      break;
-    case FORMAT_THREAD:
-      prefixLen = snprintf(prefixBuf, sizeof(prefixBuf), "%c(%5d:%5d) ", priChar, pid, tid);
-      strcpy(suffixBuf, "\n");
-      suffixLen = 1;
-      break;
-    case FORMAT_RAW:
-      prefixBuf[0] = 0;
-      prefixLen = 0;
-      strcpy(suffixBuf, "\n");
-      suffixLen = 1;
-      break;
-    case FORMAT_TIME:
-      prefixLen = snprintf(prefixBuf, sizeof(prefixBuf), "%s %-8s\n\t", timeBuf, tag);
-      strcpy(suffixBuf, "\n");
-      suffixLen = 1;
-      break;
-    case FORMAT_THREADTIME:
-      prefixLen = snprintf(prefixBuf, sizeof(prefixBuf), "%s %5d %5d %c %-8s \n\t", timeBuf, pid,
-                           tid, priChar, tag);
-      strcpy(suffixBuf, "\n");
-      suffixLen = 1;
-      break;
-    case FORMAT_LONG:
-      prefixLen = snprintf(prefixBuf, sizeof(prefixBuf), "[ %s %5d:%5d %c/%-8s ]\n", timeBuf, pid,
-                           tid, priChar, tag);
-      strcpy(suffixBuf, "\n\n");
-      suffixLen = 2;
-      break;
-    default:
-      prefixLen = snprintf(prefixBuf, sizeof(prefixBuf), "%c/%-8s(%5d): ", priChar, tag, pid);
-      strcpy(suffixBuf, "\n");
-      suffixLen = 1;
-      break;
-  }
-
-  /*
-   * Figure out how many lines there will be.
-   */
-  const char* end = msg + strlen(msg);
-  size_t numLines = 0;
-  const char* p = msg;
-  while (p < end) {
-    if (*p++ == '\n') numLines++;
-  }
-  if (p > msg && *(p - 1) != '\n') {
-    numLines++;
-  }
-
-  /*
-   * Create an array of iovecs large enough to write all of
-   * the lines with a prefix and a suffix.
-   */
-  const size_t INLINE_VECS = 64;
-  const size_t MAX_LINES = ((size_t)~0) / (3 * sizeof(struct iovec*));
-  struct iovec stackVec[INLINE_VECS];
-  struct iovec* vec = stackVec;
-  size_t numVecs;
-
-  if (numLines > MAX_LINES) numLines = MAX_LINES;
-
-  numVecs = numLines * 3;  // 3 iovecs per line.
-  if (numVecs > INLINE_VECS) {
-    vec = (struct iovec*)malloc(sizeof(struct iovec) * numVecs);
-    if (vec == NULL) {
-      msg = "LOG: write failed, no memory";
-      numVecs = INLINE_VECS;
-      numLines = numVecs / 3;
-      vec = stackVec;
-    }
-  }
-
-  /*
-   * Fill in the iovec pointers.
-   */
-  p = msg;
-  struct iovec* v = vec;
-  int totalLen = 0;
-  while (numLines > 0 && p < end) {
-    if (prefixLen > 0) {
-      v->iov_base = prefixBuf;
-      v->iov_len = prefixLen;
-      totalLen += prefixLen;
-      v++;
-    }
-    const char* start = p;
-    while (p < end && *p != '\n') {
-      p++;
-    }
-    if ((p - start) > 0) {
-      v->iov_base = (void*)start;
-      v->iov_len = p - start;
-      totalLen += p - start;
-      v++;
-    }
-    if (*p == '\n') p++;
-    if (suffixLen > 0) {
-      v->iov_base = suffixBuf;
-      v->iov_len = suffixLen;
-      totalLen += suffixLen;
-      v++;
-    }
-    numLines -= 1;
-  }
-
-  /*
-   * Write the entire message to the log file with a single writev() call.
-   * We need to use this rather than a collection of printf()s on a FILE*
-   * because of multi-threading and multi-process issues.
-   *
-   * If the file was not opened with O_APPEND, this will produce interleaved
-   * output when called on the same file from multiple processes.
-   *
-   * If the file descriptor is actually a network socket, the writev()
-   * call may return with a partial write.  Putting the writev() call in
-   * a loop can result in interleaved data.  This can be alleviated
-   * somewhat by wrapping the writev call in the Mutex.
-   */
-
-  for (;;) {
-    int cc = writev(fileno(stderr), vec, v - vec);
-
-    if (cc == totalLen) break;
-
-    if (cc < 0) {
-      if (errno == EINTR) continue;
-
-      /* can't really log the failure; for now, throw out a stderr */
-      fprintf(stderr, "+++ LOG: write failed (errno=%d)\n", errno);
-      break;
-    } else {
-      /* shouldn't happen when writing to file or tty */
-      fprintf(stderr, "+++ LOG: write partial (%d of %d)\n", cc, totalLen);
-      break;
-    }
-  }
-
-  /* if we allocated storage for the iovecs, free it */
-  if (vec != stackVec) free(vec);
-}
-
-/*
- * Receive a log message.  We happen to know that "vector" has three parts:
- *
- *  priority (1 byte)
- *  tag (N bytes -- null-terminated ASCII string)
- *  message (N bytes -- null-terminated ASCII string)
- */
-int FakeWrite(log_id_t log_id, struct timespec*, struct iovec* vector, size_t count) {
-  /* Make sure that no-one frees the LogState while we're using it.
-   * Also guarantees that only one thread is in showLog() at a given
-   * time (if it matters).
-   */
-  auto lock = std::lock_guard{*fake_log_mutex};
-
-  if (!log_state.initialized) {
-    InitializeLogStateLocked();
-  }
-
-  if (log_id == LOG_ID_EVENTS || log_id == LOG_ID_STATS || log_id == LOG_ID_SECURITY) {
-    TRACE("%s: ignoring binary log\n", android_log_id_to_name(log_id));
-    int len = 0;
-    for (size_t i = 0; i < count; ++i) {
-      len += vector[i].iov_len;
-    }
-    return len;
-  }
-
-  if (count != 3) {
-    TRACE("%s: writevLog with count=%d not expected\n", android_log_id_to_name(log_id), count);
-    return -1;
-  }
-
-  /* pull out the three fields */
-  int logPrio = *(const char*)vector[0].iov_base;
-  const char* tag = (const char*)vector[1].iov_base;
-  const char* msg = (const char*)vector[2].iov_base;
-
-  /* see if this log tag is configured */
-  int minPrio = log_state.global_min_priority;
-  for (size_t i = 0; i < kTagSetSize; i++) {
-    if (log_state.tagSet[i].minPriority == ANDROID_LOG_UNKNOWN)
-      break; /* reached end of configured values */
-
-    if (strcmp(log_state.tagSet[i].tag, tag) == 0) {
-      minPrio = log_state.tagSet[i].minPriority;
-      break;
-    }
-  }
-
-  if (logPrio >= minPrio) {
-    ShowLog(logPrio, tag, msg);
-  }
-
-  int len = 0;
-  for (size_t i = 0; i < count; ++i) {
-    len += vector[i].iov_len;
-  }
-  return len;
-}
-
-/*
- * Reset out state.
- *
- * The logger API has no means or need to 'stop' or 'close' using the logs,
- * and as such, there is no way for that 'stop' or 'close' to translate into
- * a close operation to the fake log handler. fakeLogClose is provided for
- * completeness only.
- *
- * We have no intention of adding a log close operation as it would complicate
- * every user of the logging API with no gain since the only valid place to
- * call is in the exit handler. Logging can continue in the exit handler to
- * help debug HOST tools ...
- */
-void FakeClose() {
-  auto lock = std::lock_guard{*fake_log_mutex};
-
-  memset(&log_state, 0, sizeof(log_state));
-}
-
-int __android_log_is_loggable(int prio, const char*, int) {
-  int minimum_priority = __android_log_get_minimum_priority();
-  if (minimum_priority == ANDROID_LOG_DEFAULT) {
-    minimum_priority = ANDROID_LOG_INFO;
-  }
-  return prio >= minimum_priority;
-}
-
-int __android_log_is_loggable_len(int prio, const char*, size_t, int def) {
-  return __android_log_is_loggable(prio, nullptr, def);
-}
-
-int __android_log_is_debuggable() {
-  return 1;
-}
diff --git a/liblog/fake_log_device.h b/liblog/fake_log_device.h
deleted file mode 100644
index 53f1b41..0000000
--- a/liblog/fake_log_device.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2013 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.
- */
-
-#pragma once
-
-#include <sys/cdefs.h>
-#include <sys/types.h>
-
-#include <android/log.h>
-
-__BEGIN_DECLS
-
-void FakeClose();
-int FakeWrite(log_id_t log_id, struct timespec* ts, struct iovec* vec, size_t nr);
-
-int __android_log_is_loggable(int prio, const char*, int def);
-int __android_log_is_loggable_len(int prio, const char*, size_t, int def);
-int __android_log_is_debuggable();
-
-__END_DECLS
diff --git a/liblog/include/android/log.h b/liblog/include/android/log.h
index 00aafaa..c84ddf7 100644
--- a/liblog/include/android/log.h
+++ b/liblog/include/android/log.h
@@ -276,6 +276,13 @@
  */
 int __android_log_get_minimum_priority();
 
+/**
+ * Sets the default tag if no tag is provided when writing a log message.  Defaults to
+ * getprogname().  This truncates tag to the maximum log message size, though appropriate tags
+ * should be much smaller.
+ */
+void __android_log_set_default_tag(const char* tag);
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/liblog/liblog.map.txt b/liblog/liblog.map.txt
index 62b9805..198cdae 100644
--- a/liblog/liblog.map.txt
+++ b/liblog/liblog.map.txt
@@ -73,6 +73,7 @@
     __android_log_logd_logger;
     __android_log_security_bswrite; # apex
     __android_log_set_aborter;
+    __android_log_set_default_tag;
     __android_log_set_logger;
     __android_log_set_minimum_priority;
     __android_log_stderr_logger;
diff --git a/liblog/logger_read.cpp b/liblog/logger_read.cpp
index e0598de..a0c526b 100644
--- a/liblog/logger_read.cpp
+++ b/liblog/logger_read.cpp
@@ -97,7 +97,7 @@
 
   int ret = 0;
 
-#if (FAKE_LOG_DEVICE == 0)
+#ifdef __ANDROID__
   if (logger_list->mode & ANDROID_LOG_PSTORE) {
     ret = PmsgRead(logger_list, log_msg);
   } else {
@@ -135,7 +135,7 @@
     return;
   }
 
-#if (FAKE_LOG_DEVICE == 0)
+#ifdef __ANDROID__
   if (logger_list->mode & ANDROID_LOG_PSTORE) {
     PmsgClose(logger_list);
   } else {
diff --git a/liblog/logger_write.cpp b/liblog/logger_write.cpp
index 1783854..cf82e0f 100644
--- a/liblog/logger_write.cpp
+++ b/liblog/logger_write.cpp
@@ -14,8 +14,11 @@
  * limitations under the License.
  */
 
+#include "logger_write.h"
+
 #include <errno.h>
 #include <inttypes.h>
+#include <libgen.h>
 #include <stdlib.h>
 #include <string.h>
 #include <sys/time.h>
@@ -26,20 +29,20 @@
 
 #include <shared_mutex>
 
+#include <android-base/errno_restorer.h>
 #include <android-base/macros.h>
 #include <private/android_filesystem_config.h>
 #include <private/android_logger.h>
 
 #include "android/log.h"
+#include "log/log_read.h"
 #include "logger.h"
 #include "rwlock.h"
 #include "uio.h"
 
-#if (FAKE_LOG_DEVICE == 0)
+#ifdef __ANDROID__
 #include "logd_writer.h"
 #include "pmsg_writer.h"
-#else
-#include "fake_log_device.h"
 #endif
 
 #if defined(__APPLE__)
@@ -50,6 +53,8 @@
 #include <windows.h>
 #endif
 
+using android::base::ErrnoRestorer;
+
 #define LOG_BUF_SIZE 1024
 
 #if defined(__ANDROID__)
@@ -98,14 +103,51 @@
  * Release any logger resources. A new log write will immediately re-acquire.
  */
 void __android_log_close() {
-#if (FAKE_LOG_DEVICE == 0)
+#ifdef __ANDROID__
   LogdClose();
   PmsgClose();
-#else
-  FakeClose();
 #endif
 }
 
+#if defined(__GLIBC__) || defined(_WIN32)
+static const char* getprogname() {
+#if defined(__GLIBC__)
+  return program_invocation_short_name;
+#elif defined(_WIN32)
+  static bool first = true;
+  static char progname[MAX_PATH] = {};
+
+  if (first) {
+    char path[PATH_MAX + 1];
+    DWORD result = GetModuleFileName(nullptr, path, sizeof(path) - 1);
+    if (result == 0 || result == sizeof(path) - 1) return "";
+    path[PATH_MAX - 1] = 0;
+
+    char* path_basename = basename(path);
+
+    snprintf(progname, sizeof(progname), "%s", path_basename);
+    first = false;
+  }
+
+  return progname;
+#endif
+}
+#endif
+
+// It's possible for logging to happen during static initialization before our globals are
+// initialized, so we place this std::string in a function such that it is initialized on the first
+// call.
+std::string& GetDefaultTag() {
+  static std::string default_tag = getprogname();
+  return default_tag;
+}
+RwLock default_tag_lock;
+
+void __android_log_set_default_tag(const char* tag) {
+  auto lock = std::unique_lock{default_tag_lock};
+  GetDefaultTag().assign(tag, 0, LOGGER_ENTRY_MAX_PAYLOAD);
+}
+
 static int minimum_log_priority = ANDROID_LOG_DEFAULT;
 int __android_log_set_minimum_priority(int priority) {
   int old_minimum_log_priority = minimum_log_priority;
@@ -153,11 +195,9 @@
 
 #ifdef __ANDROID__
 static int write_to_log(log_id_t log_id, struct iovec* vec, size_t nr) {
-  int ret, save_errno;
+  int ret;
   struct timespec ts;
 
-  save_errno = errno;
-
   if (log_id == LOG_ID_KERNEL) {
     return -EINVAL;
   }
@@ -166,23 +206,19 @@
 
   if (log_id == LOG_ID_SECURITY) {
     if (vec[0].iov_len < 4) {
-      errno = save_errno;
       return -EINVAL;
     }
 
     ret = check_log_uid_permissions();
     if (ret < 0) {
-      errno = save_errno;
       return ret;
     }
     if (!__android_log_security()) {
       /* If only we could reset downstream logd counter */
-      errno = save_errno;
       return -EPERM;
     }
   } else if (log_id == LOG_ID_EVENTS || log_id == LOG_ID_STATS) {
     if (vec[0].iov_len < 4) {
-      errno = save_errno;
       return -EINVAL;
     }
   }
@@ -190,7 +226,6 @@
   ret = LogdWrite(log_id, &ts, vec, nr);
   PmsgWrite(log_id, &ts, vec, nr);
 
-  errno = save_errno;
   return ret;
 }
 #else
@@ -270,7 +305,19 @@
 }
 
 void __android_log_write_logger_data(__android_logger_data* logger_data, const char* msg) {
-  if (logger_data->tag == nullptr) logger_data->tag = "";
+  ErrnoRestorer errno_restorer;
+
+  if (logger_data->buffer_id != LOG_ID_DEFAULT && logger_data->buffer_id != LOG_ID_MAIN &&
+      logger_data->buffer_id != LOG_ID_SYSTEM && logger_data->buffer_id != LOG_ID_RADIO &&
+      logger_data->buffer_id != LOG_ID_CRASH) {
+    return;
+  }
+
+  auto tag_lock = std::shared_lock{default_tag_lock, std::defer_lock};
+  if (logger_data->tag == nullptr) {
+    tag_lock.lock();
+    logger_data->tag = GetDefaultTag().c_str();
+  }
 
 #if __BIONIC__
   if (logger_data->priority == ANDROID_LOG_FATAL) {
@@ -283,6 +330,8 @@
 }
 
 int __android_log_buf_write(int bufID, int prio, const char* tag, const char* msg) {
+  ErrnoRestorer errno_restorer;
+
   if (!__android_log_is_loggable(prio, tag, ANDROID_LOG_VERBOSE)) {
     return 0;
   }
@@ -293,6 +342,8 @@
 }
 
 int __android_log_vprint(int prio, const char* tag, const char* fmt, va_list ap) {
+  ErrnoRestorer errno_restorer;
+
   if (!__android_log_is_loggable(prio, tag, ANDROID_LOG_VERBOSE)) {
     return 0;
   }
@@ -308,6 +359,8 @@
 }
 
 int __android_log_print(int prio, const char* tag, const char* fmt, ...) {
+  ErrnoRestorer errno_restorer;
+
   if (!__android_log_is_loggable(prio, tag, ANDROID_LOG_VERBOSE)) {
     return 0;
   }
@@ -326,6 +379,8 @@
 }
 
 int __android_log_buf_print(int bufID, int prio, const char* tag, const char* fmt, ...) {
+  ErrnoRestorer errno_restorer;
+
   if (!__android_log_is_loggable(prio, tag, ANDROID_LOG_VERBOSE)) {
     return 0;
   }
@@ -372,6 +427,8 @@
 }
 
 int __android_log_bwrite(int32_t tag, const void* payload, size_t len) {
+  ErrnoRestorer errno_restorer;
+
   struct iovec vec[2];
 
   vec[0].iov_base = &tag;
@@ -383,6 +440,8 @@
 }
 
 int __android_log_stats_bwrite(int32_t tag, const void* payload, size_t len) {
+  ErrnoRestorer errno_restorer;
+
   struct iovec vec[2];
 
   vec[0].iov_base = &tag;
@@ -394,6 +453,8 @@
 }
 
 int __android_log_security_bwrite(int32_t tag, const void* payload, size_t len) {
+  ErrnoRestorer errno_restorer;
+
   struct iovec vec[2];
 
   vec[0].iov_base = &tag;
@@ -410,6 +471,8 @@
  * handy if we just want to dump an integer into the log.
  */
 int __android_log_btwrite(int32_t tag, char type, const void* payload, size_t len) {
+  ErrnoRestorer errno_restorer;
+
   struct iovec vec[3];
 
   vec[0].iov_base = &tag;
@@ -427,6 +490,8 @@
  * event log.
  */
 int __android_log_bswrite(int32_t tag, const char* payload) {
+  ErrnoRestorer errno_restorer;
+
   struct iovec vec[4];
   char type = EVENT_TYPE_STRING;
   uint32_t len = strlen(payload);
@@ -448,6 +513,8 @@
  * security log.
  */
 int __android_log_security_bswrite(int32_t tag, const char* payload) {
+  ErrnoRestorer errno_restorer;
+
   struct iovec vec[4];
   char type = EVENT_TYPE_STRING;
   uint32_t len = strlen(payload);
diff --git a/liblog/logger_write.h b/liblog/logger_write.h
new file mode 100644
index 0000000..065fd55
--- /dev/null
+++ b/liblog/logger_write.h
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2020 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.
+ */
+
+#pragma once
+
+#include <string>
+
+#include "rwlock.h"
+
+std::string& GetDefaultTag();  // Must read lock default_tag_lock
+extern RwLock default_tag_lock;
\ No newline at end of file
diff --git a/liblog/logprint.cpp b/liblog/logprint.cpp
index 0745a1e..e32878a 100644
--- a/liblog/logprint.cpp
+++ b/liblog/logprint.cpp
@@ -1520,12 +1520,7 @@
  * This code is Android specific, bionic guarantees that
  * calls to non-reentrant getpwuid() are thread safe.
  */
-#if !defined(__MINGW32__)
-#if (FAKE_LOG_DEVICE == 0)
-#ifndef __BIONIC__
-#warning "This code assumes that getpwuid is thread safe, only true with Bionic!"
-#endif
-#endif
+#ifdef __ANDROID__
       struct passwd* pwd = getpwuid(entry->uid);
       if (pwd && (strlen(pwd->pw_name) <= 5)) {
         snprintf(uid, sizeof(uid), "%5s:", pwd->pw_name);
diff --git a/liblog/properties.cpp b/liblog/properties.cpp
index a53c92b..f30058a 100644
--- a/liblog/properties.cpp
+++ b/liblog/properties.cpp
@@ -20,14 +20,19 @@
 #include <pthread.h>
 #include <stdlib.h>
 #include <string.h>
-#define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
-#include <sys/_system_properties.h>
 #include <unistd.h>
 
 #include <algorithm>
+#include <shared_mutex>
 
 #include <private/android_logger.h>
 
+#include "logger_write.h"
+
+#ifdef __ANDROID__
+#define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
+#include <sys/_system_properties.h>
+
 static pthread_mutex_t lock_loggable = PTHREAD_MUTEX_INITIALIZER;
 
 static int lock() {
@@ -93,10 +98,17 @@
   /* sizeof() is used on this array below */
   static const char log_namespace[] = "persist.log.tag.";
   static const size_t base_offset = 8; /* skip "persist." */
-  /* calculate the size of our key temporary buffer */
-  const size_t taglen = tag ? len : 0;
+
+  auto tag_lock = std::shared_lock{default_tag_lock, std::defer_lock};
+  if (tag == nullptr || len == 0) {
+    tag_lock.lock();
+    auto& tag_string = GetDefaultTag();
+    tag = tag_string.c_str();
+    len = tag_string.size();
+  }
+
   /* sizeof(log_namespace) = strlen(log_namespace) + 1 */
-  char key[sizeof(log_namespace) + taglen];
+  char key[sizeof(log_namespace) + len];
   char* kp;
   size_t i;
   char c = 0;
@@ -146,7 +158,7 @@
     }
   }
 
-  if (taglen) {
+  if (len) {
     int local_change_detected = change_detected;
     if (!not_locked) {
       if (!last_tag || !last_tag[0] || (last_tag[0] != tag[0]) ||
@@ -637,3 +649,23 @@
 
   return property_size;
 }
+
+#else
+
+int __android_log_is_loggable(int prio, const char*, int) {
+  int minimum_priority = __android_log_get_minimum_priority();
+  if (minimum_priority == ANDROID_LOG_DEFAULT) {
+    minimum_priority = ANDROID_LOG_INFO;
+  }
+  return prio >= minimum_priority;
+}
+
+int __android_log_is_loggable_len(int prio, const char*, size_t, int def) {
+  return __android_log_is_loggable(prio, nullptr, def);
+}
+
+int __android_log_is_debuggable() {
+  return 1;
+}
+
+#endif
\ No newline at end of file
diff --git a/liblog/tests/Android.bp b/liblog/tests/Android.bp
index 3288954..b4bb77f 100644
--- a/liblog/tests/Android.bp
+++ b/liblog/tests/Android.bp
@@ -54,6 +54,7 @@
     ],
     srcs: [
         "libc_test.cpp",
+        "liblog_default_tag.cpp",
         "liblog_global_state.cpp",
         "liblog_test.cpp",
         "log_id_test.cpp",
@@ -103,6 +104,11 @@
     name: "liblog-host-test",
     static_libs: ["liblog"],
     shared_libs: ["libbase"],
-    srcs: ["liblog_host_test.cpp"],
+    srcs: [
+        "liblog_host_test.cpp",
+        "liblog_default_tag.cpp",
+        "liblog_global_state.cpp",
+        "rwlock_test.cpp",
+    ],
     isolated: true,
 }
diff --git a/liblog/tests/liblog_default_tag.cpp b/liblog/tests/liblog_default_tag.cpp
new file mode 100644
index 0000000..31b7467
--- /dev/null
+++ b/liblog/tests/liblog_default_tag.cpp
@@ -0,0 +1,160 @@
+/*
+ * Copyright (C) 2020 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.
+ */
+
+// LOG_TAG must be unset for android-base's logging to use a default tag.
+#undef LOG_TAG
+
+#include <stdlib.h>
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/properties.h>
+#include <android-base/scopeguard.h>
+#include <android/log.h>
+
+#include <gtest/gtest.h>
+
+#ifndef __ANDROID__
+static const char* getprogname() {
+  return program_invocation_short_name;
+}
+#endif
+
+TEST(liblog_default_tag, no_default_tag_libbase_write_first) {
+  using namespace android::base;
+  bool message_seen = false;
+  std::string expected_tag = "";
+  SetLogger([&](LogId, LogSeverity, const char* tag, const char*, unsigned int, const char*) {
+    message_seen = true;
+    EXPECT_EQ(expected_tag, tag);
+  });
+
+  expected_tag = getprogname();
+  LOG(WARNING) << "message";
+  EXPECT_TRUE(message_seen);
+  message_seen = false;
+
+  __android_log_buf_write(LOG_ID_MAIN, ANDROID_LOG_WARN, nullptr, "message");
+  EXPECT_TRUE(message_seen);
+}
+
+TEST(liblog_default_tag, no_default_tag_liblog_write_first) {
+  using namespace android::base;
+  bool message_seen = false;
+  std::string expected_tag = "";
+  SetLogger([&](LogId, LogSeverity, const char* tag, const char*, unsigned int, const char*) {
+    message_seen = true;
+    EXPECT_EQ(expected_tag, tag);
+  });
+
+  expected_tag = getprogname();
+  __android_log_buf_write(LOG_ID_MAIN, ANDROID_LOG_WARN, nullptr, "message");
+  EXPECT_TRUE(message_seen);
+  message_seen = false;
+
+  LOG(WARNING) << "message";
+  EXPECT_TRUE(message_seen);
+}
+
+TEST(liblog_default_tag, libbase_sets_default_tag) {
+  using namespace android::base;
+  bool message_seen = false;
+  std::string expected_tag = "libbase_test_tag";
+  SetLogger([&](LogId, LogSeverity, const char* tag, const char*, unsigned int, const char*) {
+    message_seen = true;
+    EXPECT_EQ(expected_tag, tag);
+  });
+  SetDefaultTag(expected_tag);
+
+  __android_log_buf_write(LOG_ID_MAIN, ANDROID_LOG_WARN, nullptr, "message");
+  EXPECT_TRUE(message_seen);
+  message_seen = false;
+
+  LOG(WARNING) << "message";
+  EXPECT_TRUE(message_seen);
+}
+
+TEST(liblog_default_tag, liblog_sets_default_tag) {
+  using namespace android::base;
+  bool message_seen = false;
+  std::string expected_tag = "liblog_test_tag";
+  SetLogger([&](LogId, LogSeverity, const char* tag, const char*, unsigned int, const char*) {
+    message_seen = true;
+    EXPECT_EQ(expected_tag, tag);
+  });
+  __android_log_set_default_tag(expected_tag.c_str());
+
+  __android_log_buf_write(LOG_ID_MAIN, ANDROID_LOG_WARN, nullptr, "message");
+  EXPECT_TRUE(message_seen);
+  message_seen = false;
+
+  LOG(WARNING) << "message";
+  EXPECT_TRUE(message_seen);
+}
+
+TEST(liblog_default_tag, default_tag_plus_log_severity) {
+#ifdef __ANDROID__
+  using namespace android::base;
+  bool message_seen = false;
+  std::string expected_tag = "liblog_test_tag";
+  SetLogger([&](LogId, LogSeverity, const char* tag, const char*, unsigned int, const char*) {
+    message_seen = true;
+    EXPECT_EQ(expected_tag, tag);
+  });
+  __android_log_set_default_tag(expected_tag.c_str());
+
+  auto log_tag_property = "log.tag." + expected_tag;
+  SetProperty(log_tag_property, "V");
+  auto reset_tag_property_guard = make_scope_guard([=] { SetProperty(log_tag_property, ""); });
+
+  __android_log_buf_write(LOG_ID_MAIN, ANDROID_LOG_VERBOSE, nullptr, "message");
+  EXPECT_TRUE(message_seen);
+  message_seen = false;
+
+  LOG(VERBOSE) << "message";
+  EXPECT_TRUE(message_seen);
+#else
+  GTEST_SKIP() << "No log tag properties on host";
+#endif
+}
+
+TEST(liblog_default_tag, generated_default_tag_plus_log_severity) {
+#ifdef __ANDROID__
+  using namespace android::base;
+  bool message_seen = false;
+  std::string expected_tag = getprogname();
+  SetLogger([&](LogId, LogSeverity, const char* tag, const char*, unsigned int, const char*) {
+    message_seen = true;
+    EXPECT_EQ(expected_tag, tag);
+  });
+
+  // Even without any calls to SetDefaultTag(), the first message that attempts to log, will
+  // generate a default tag from getprogname() and check log.tag.<default tag> for loggability. This
+  // case checks that we can log a Verbose message when log.tag.<getprogname()> is set to 'V'.
+  auto log_tag_property = "log.tag." + expected_tag;
+  SetProperty(log_tag_property, "V");
+  auto reset_tag_property_guard = make_scope_guard([=] { SetProperty(log_tag_property, ""); });
+
+  __android_log_buf_write(LOG_ID_MAIN, ANDROID_LOG_VERBOSE, nullptr, "message");
+  EXPECT_TRUE(message_seen);
+  message_seen = false;
+
+  LOG(VERBOSE) << "message";
+  EXPECT_TRUE(message_seen);
+#else
+  GTEST_SKIP() << "No log tag properties on host";
+#endif
+}
\ No newline at end of file
diff --git a/liblog/tests/liblog_global_state.cpp b/liblog/tests/liblog_global_state.cpp
index 8d73bb8..9a181ef 100644
--- a/liblog/tests/liblog_global_state.cpp
+++ b/liblog/tests/liblog_global_state.cpp
@@ -188,6 +188,7 @@
 }
 
 TEST(liblog_global_state, is_loggable_tag_log_priority_only) {
+#ifdef __ANDROID__
   EXPECT_EQ(0, __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG, ANDROID_LOG_INFO));
   EXPECT_EQ(1, __android_log_is_loggable(ANDROID_LOG_INFO, LOG_TAG, ANDROID_LOG_INFO));
   EXPECT_EQ(1, __android_log_is_loggable(ANDROID_LOG_WARN, LOG_TAG, ANDROID_LOG_INFO));
@@ -204,9 +205,13 @@
   EXPECT_EQ(1, __android_log_is_loggable(ANDROID_LOG_WARN, LOG_TAG, ANDROID_LOG_INFO));
 
   android::base::SetProperty(log_tag_property, "");
+#else
+  GTEST_SKIP() << "No log tag properties on host";
+#endif
 }
 
 TEST(liblog_global_state, is_loggable_both_set) {
+#ifdef __ANDROID__
   EXPECT_EQ(0, __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG, ANDROID_LOG_INFO));
   EXPECT_EQ(1, __android_log_is_loggable(ANDROID_LOG_INFO, LOG_TAG, ANDROID_LOG_INFO));
   EXPECT_EQ(1, __android_log_is_loggable(ANDROID_LOG_WARN, LOG_TAG, ANDROID_LOG_INFO));
@@ -240,4 +245,7 @@
   EXPECT_EQ(1, __android_log_is_loggable(ANDROID_LOG_WARN, LOG_TAG, ANDROID_LOG_INFO));
 
   android::base::SetProperty(log_tag_property, "");
+#else
+  GTEST_SKIP() << "No log tag properties on host";
+#endif
 }
diff --git a/liblog/tests/liblog_host_test.cpp b/liblog/tests/liblog_host_test.cpp
index 377550f..ec186d4 100644
--- a/liblog/tests/liblog_host_test.cpp
+++ b/liblog/tests/liblog_host_test.cpp
@@ -20,15 +20,37 @@
 #include <stdlib.h>
 #include <unistd.h>
 
+#include <regex>
+#include <string>
+
+#include <android-base/logging.h>
+#include <android-base/macros.h>
 #include <android-base/stringprintf.h>
-#include <android-base/strings.h>
 #include <android-base/test_utils.h>
 #include <gtest/gtest.h>
 
+using android::base::InitLogging;
+using android::base::StderrLogger;
 using android::base::StringPrintf;
-using android::base::StringReplace;
 
-void GenerateLogContent() {
+static std::string MakeLogPattern(int priority, const char* tag, const char* message) {
+  static const char log_characters[] = "XXVDIWEF";
+  static_assert(arraysize(log_characters) - 1 == ANDROID_LOG_SILENT,
+                "Mismatch in size of log_characters and values in android_LogPriority");
+  priority = priority > ANDROID_LOG_SILENT ? ANDROID_LOG_FATAL : priority;
+  char log_char = log_characters[priority];
+
+  return StringPrintf("%s %c \\d+-\\d+ \\d+:\\d+:\\d+ \\s*\\d+ \\s*\\d+ %s", tag, log_char,
+                      message);
+}
+
+static void CheckMessage(bool expected, const std::string& output, int priority, const char* tag,
+                         const char* message) {
+  std::regex message_regex(MakeLogPattern(priority, tag, message));
+  EXPECT_EQ(expected, std::regex_search(output, message_regex)) << message;
+}
+
+static void GenerateLogContent() {
   __android_log_buf_print(LOG_ID_MAIN, ANDROID_LOG_VERBOSE, "tag", "verbose main");
   __android_log_buf_print(LOG_ID_MAIN, ANDROID_LOG_INFO, "tag", "info main");
   __android_log_buf_print(LOG_ID_MAIN, ANDROID_LOG_ERROR, "tag", "error main");
@@ -52,137 +74,86 @@
 }
 
 TEST(liblog, default_write) {
-  setenv("ANDROID_PRINTF_LOG", "brief", true);
   CapturedStderr captured_stderr;
+  InitLogging(nullptr, StderrLogger);
 
   GenerateLogContent();
 
-  std::string expected_output = StringReplace(R"init(I/tag     (<pid>): info main
-E/tag     (<pid>): error main
-I/tag     (<pid>): info radio
-E/tag     (<pid>): error radio
-I/tag     (<pid>): info system
-E/tag     (<pid>): error system
-I/tag     (<pid>): info crash
-E/tag     (<pid>): error crash
-)init",
-                                              "<pid>", GetPidString(), true);
+  CheckMessage(false, captured_stderr.str(), ANDROID_LOG_VERBOSE, "tag", "verbose main");
+  CheckMessage(true, captured_stderr.str(), ANDROID_LOG_INFO, "tag", "info main");
+  CheckMessage(true, captured_stderr.str(), ANDROID_LOG_ERROR, "tag", "error main");
 
-  EXPECT_EQ(expected_output, captured_stderr.str());
+  CheckMessage(false, captured_stderr.str(), ANDROID_LOG_VERBOSE, "tag", "verbose radio");
+  CheckMessage(true, captured_stderr.str(), ANDROID_LOG_INFO, "tag", "info radio");
+  CheckMessage(true, captured_stderr.str(), ANDROID_LOG_ERROR, "tag", "error radio");
+
+  CheckMessage(false, captured_stderr.str(), ANDROID_LOG_VERBOSE, "tag", "verbose system");
+  CheckMessage(true, captured_stderr.str(), ANDROID_LOG_INFO, "tag", "info system");
+  CheckMessage(true, captured_stderr.str(), ANDROID_LOG_ERROR, "tag", "error system");
+
+  CheckMessage(false, captured_stderr.str(), ANDROID_LOG_VERBOSE, "tag", "verbose crash");
+  CheckMessage(true, captured_stderr.str(), ANDROID_LOG_INFO, "tag", "info crash");
+  CheckMessage(true, captured_stderr.str(), ANDROID_LOG_ERROR, "tag", "error crash");
 }
 
-TEST(liblog, format) {
-  setenv("ANDROID_PRINTF_LOG", "process", true);
+TEST(liblog, verbose_write) {
+  setenv("ANDROID_LOG_TAGS", "*:v", true);
   CapturedStderr captured_stderr;
+  InitLogging(nullptr, StderrLogger);
 
   GenerateLogContent();
 
-  std::string expected_output = StringReplace(R"init(I(<pid>) info main  (tag)
-E(<pid>) error main  (tag)
-I(<pid>) info radio  (tag)
-E(<pid>) error radio  (tag)
-I(<pid>) info system  (tag)
-E(<pid>) error system  (tag)
-I(<pid>) info crash  (tag)
-E(<pid>) error crash  (tag)
-)init",
-                                              "<pid>", GetPidString(), true);
+  CheckMessage(true, captured_stderr.str(), ANDROID_LOG_VERBOSE, "tag", "verbose main");
+  CheckMessage(true, captured_stderr.str(), ANDROID_LOG_INFO, "tag", "info main");
+  CheckMessage(true, captured_stderr.str(), ANDROID_LOG_ERROR, "tag", "error main");
 
-  EXPECT_EQ(expected_output, captured_stderr.str());
-  captured_stderr.Stop();
-  captured_stderr.Reset();
-  captured_stderr.Start();
+  CheckMessage(true, captured_stderr.str(), ANDROID_LOG_VERBOSE, "tag", "verbose radio");
+  CheckMessage(true, captured_stderr.str(), ANDROID_LOG_INFO, "tag", "info radio");
+  CheckMessage(true, captured_stderr.str(), ANDROID_LOG_ERROR, "tag", "error radio");
 
-  // Changing the environment after starting writing doesn't change the format.
-  setenv("ANDROID_PRINTF_LOG", "brief", true);
-  GenerateLogContent();
-  EXPECT_EQ(expected_output, captured_stderr.str());
-  captured_stderr.Stop();
-  captured_stderr.Reset();
-  captured_stderr.Start();
+  CheckMessage(true, captured_stderr.str(), ANDROID_LOG_VERBOSE, "tag", "verbose system");
+  CheckMessage(true, captured_stderr.str(), ANDROID_LOG_INFO, "tag", "info system");
+  CheckMessage(true, captured_stderr.str(), ANDROID_LOG_ERROR, "tag", "error system");
 
-  // However calling __android_log_close() does reset logging and allow changing the format.
-  __android_log_close();
-  GenerateLogContent();
-
-  expected_output = StringReplace(R"init(I/tag     (<pid>): info main
-E/tag     (<pid>): error main
-I/tag     (<pid>): info radio
-E/tag     (<pid>): error radio
-I/tag     (<pid>): info system
-E/tag     (<pid>): error system
-I/tag     (<pid>): info crash
-E/tag     (<pid>): error crash
-)init",
-                                  "<pid>", GetPidString(), true);
-
-  EXPECT_EQ(expected_output, captured_stderr.str());
+  CheckMessage(true, captured_stderr.str(), ANDROID_LOG_VERBOSE, "tag", "verbose crash");
+  CheckMessage(true, captured_stderr.str(), ANDROID_LOG_INFO, "tag", "info crash");
+  CheckMessage(true, captured_stderr.str(), ANDROID_LOG_ERROR, "tag", "error crash");
 }
 
-TEST(liblog, filter) {
-  setenv("ANDROID_PRINTF_LOG", "brief", true);
-  setenv("ANDROID_LOG_TAGS", "*:w verbose_tag:v debug_tag:d", true);
-  CapturedStderr captured_stderr;
-
-  auto generate_logs = [](log_id_t log_id) {
-    // Check that we show verbose logs when requesting for a given tag.
-    __android_log_buf_print(log_id, ANDROID_LOG_VERBOSE, "verbose_tag", "verbose verbose_tag");
-    __android_log_buf_print(log_id, ANDROID_LOG_ERROR, "verbose_tag", "error verbose_tag");
-
-    // Check that we don't show verbose logs when explicitly requesting debug+ for a given tag.
-    __android_log_buf_print(log_id, ANDROID_LOG_VERBOSE, "debug_tag", "verbose debug_tag");
-    __android_log_buf_print(log_id, ANDROID_LOG_DEBUG, "debug_tag", "debug debug_tag");
-    __android_log_buf_print(log_id, ANDROID_LOG_ERROR, "debug_tag", "error debug_tag");
-
-    // Check that we don't show info logs when requesting globally warn+.
-    __android_log_buf_print(log_id, ANDROID_LOG_INFO, "default_tag", "info default_tag");
-    __android_log_buf_print(log_id, ANDROID_LOG_WARN, "default_tag", "warn default_tag");
-    __android_log_buf_print(log_id, ANDROID_LOG_ERROR, "default_tag", "error default_tag");
-  };
-
-  auto expected_output = StringReplace(R"init(V/verbose_tag(<pid>): verbose verbose_tag
-E/verbose_tag(<pid>): error verbose_tag
-D/debug_tag(<pid>): debug debug_tag
-E/debug_tag(<pid>): error debug_tag
-W/default_tag(<pid>): warn default_tag
-E/default_tag(<pid>): error default_tag
-)init",
-                                       "<pid>", GetPidString(), true);
-
-  auto test_all_logs = [&] {
-    for (auto log_id : {LOG_ID_MAIN, LOG_ID_SYSTEM, LOG_ID_RADIO, LOG_ID_CRASH}) {
-      generate_logs(log_id);
-      EXPECT_EQ(expected_output, captured_stderr.str());
-      captured_stderr.Stop();
-      captured_stderr.Reset();
-      captured_stderr.Start();
-    }
-  };
-
-  test_all_logs();
-
-  // Changing the environment after starting writing doesn't change the filter.
+TEST(liblog, error_write) {
   setenv("ANDROID_LOG_TAGS", "*:e", true);
-  test_all_logs();
+  CapturedStderr captured_stderr;
+  InitLogging(nullptr, StderrLogger);
 
-  // However calling __android_log_close() does reset logging and allow changing the format.
-  __android_log_close();
-  expected_output = StringReplace(R"init(E/verbose_tag(<pid>): error verbose_tag
-E/debug_tag(<pid>): error debug_tag
-E/default_tag(<pid>): error default_tag
-)init",
-                                  "<pid>", GetPidString(), true);
-  test_all_logs();
+  GenerateLogContent();
+
+  CheckMessage(false, captured_stderr.str(), ANDROID_LOG_VERBOSE, "tag", "verbose main");
+  CheckMessage(false, captured_stderr.str(), ANDROID_LOG_INFO, "tag", "info main");
+  CheckMessage(true, captured_stderr.str(), ANDROID_LOG_ERROR, "tag", "error main");
+
+  CheckMessage(false, captured_stderr.str(), ANDROID_LOG_VERBOSE, "tag", "verbose radio");
+  CheckMessage(false, captured_stderr.str(), ANDROID_LOG_INFO, "tag", "info radio");
+  CheckMessage(true, captured_stderr.str(), ANDROID_LOG_ERROR, "tag", "error radio");
+
+  CheckMessage(false, captured_stderr.str(), ANDROID_LOG_VERBOSE, "tag", "verbose system");
+  CheckMessage(false, captured_stderr.str(), ANDROID_LOG_INFO, "tag", "info system");
+  CheckMessage(true, captured_stderr.str(), ANDROID_LOG_ERROR, "tag", "error system");
+
+  CheckMessage(false, captured_stderr.str(), ANDROID_LOG_VERBOSE, "tag", "verbose crash");
+  CheckMessage(false, captured_stderr.str(), ANDROID_LOG_INFO, "tag", "info crash");
+  CheckMessage(true, captured_stderr.str(), ANDROID_LOG_ERROR, "tag", "error crash");
 }
 
 TEST(liblog, kernel_no_write) {
   CapturedStderr captured_stderr;
+  InitLogging(nullptr, StderrLogger);
   __android_log_buf_print(LOG_ID_KERNEL, ANDROID_LOG_ERROR, "tag", "kernel error");
   EXPECT_EQ("", captured_stderr.str());
 }
 
 TEST(liblog, binary_no_write) {
   CapturedStderr captured_stderr;
+  InitLogging(nullptr, StderrLogger);
   __android_log_buf_print(LOG_ID_EVENTS, ANDROID_LOG_ERROR, "tag", "error events");
   __android_log_buf_print(LOG_ID_STATS, ANDROID_LOG_ERROR, "tag", "error stats");
   __android_log_buf_print(LOG_ID_SECURITY, ANDROID_LOG_ERROR, "tag", "error security");
diff --git a/libnetutils/ifc_utils.c b/libnetutils/ifc_utils.c
index 8212eba..5999e39 100644
--- a/libnetutils/ifc_utils.c
+++ b/libnetutils/ifc_utils.c
@@ -257,8 +257,8 @@
  *
  * Returns zero on success and negative errno on failure.
  */
-int ifc_act_on_address(int action, const char *name, const char *address,
-                       int prefixlen) {
+int ifc_act_on_address(int action, const char* name, const char* address, int prefixlen,
+                       bool nodad) {
     int ifindex, s, len, ret;
     struct sockaddr_storage ss;
     int saved_errno;
@@ -311,6 +311,7 @@
 
     // Interface address message header.
     req.r.ifa_family = ss.ss_family;
+    req.r.ifa_flags = nodad ? IFA_F_NODAD : 0;
     req.r.ifa_prefixlen = prefixlen;
     req.r.ifa_index = ifindex;
 
@@ -363,12 +364,12 @@
 
 // Returns zero on success and negative errno on failure.
 int ifc_add_address(const char *name, const char *address, int prefixlen) {
-    return ifc_act_on_address(RTM_NEWADDR, name, address, prefixlen);
+    return ifc_act_on_address(RTM_NEWADDR, name, address, prefixlen, /*nodad*/ false);
 }
 
 // Returns zero on success and negative errno on failure.
 int ifc_del_address(const char *name, const char * address, int prefixlen) {
-    return ifc_act_on_address(RTM_DELADDR, name, address, prefixlen);
+    return ifc_act_on_address(RTM_DELADDR, name, address, prefixlen, /*nodad*/ false);
 }
 
 /*
diff --git a/libnetutils/include/netutils/ifc.h b/libnetutils/include/netutils/ifc.h
index 3b27234..ee896ac 100644
--- a/libnetutils/include/netutils/ifc.h
+++ b/libnetutils/include/netutils/ifc.h
@@ -17,8 +17,9 @@
 #ifndef _NETUTILS_IFC_H_
 #define _NETUTILS_IFC_H_
 
-#include <sys/cdefs.h>
 #include <arpa/inet.h>
+#include <stdbool.h>
+#include <sys/cdefs.h>
 
 __BEGIN_DECLS
 
@@ -42,6 +43,8 @@
 
 extern int ifc_get_addr(const char *name, in_addr_t *addr);
 extern int ifc_set_addr(const char *name, in_addr_t addr);
+extern int ifc_act_on_address(int action, const char* name, const char* address, int prefixlen,
+                              bool nodad);
 extern int ifc_add_address(const char *name, const char *address,
                            int prefixlen);
 extern int ifc_del_address(const char *name, const char *address,
diff --git a/libprocessgroup/cgroup_map.cpp b/libprocessgroup/cgroup_map.cpp
index 20ae2be..2fc920b 100644
--- a/libprocessgroup/cgroup_map.cpp
+++ b/libprocessgroup/cgroup_map.cpp
@@ -71,7 +71,12 @@
     if (!HasValue()) return false;
 
     if (state_ == UNKNOWN) {
-        state_ = access(GetProcsFilePath("", 0, 0).c_str(), F_OK) == 0 ? USABLE : MISSING;
+        if (ACgroupController_getFlags != nullptr) {
+            uint32_t flags = ACgroupController_getFlags(controller_);
+            state_ = (flags & CGROUPRC_CONTROLLER_FLAG_MOUNTED) != 0 ? USABLE : MISSING;
+        } else {
+            state_ = access(GetProcsFilePath("", 0, 0).c_str(), F_OK) == 0 ? USABLE : MISSING;
+        }
     }
 
     return state_ == USABLE;
@@ -161,9 +166,16 @@
     auto controller_count = ACgroupFile_getControllerCount();
     for (uint32_t i = 0; i < controller_count; ++i) {
         const ACgroupController* controller = ACgroupFile_getController(i);
-        LOG(INFO) << "\t" << ACgroupController_getName(controller) << " ver "
-                  << ACgroupController_getVersion(controller) << " path "
-                  << ACgroupController_getPath(controller);
+        if (ACgroupController_getFlags != nullptr) {
+            LOG(INFO) << "\t" << ACgroupController_getName(controller) << " ver "
+                      << ACgroupController_getVersion(controller) << " path "
+                      << ACgroupController_getPath(controller) << " flags "
+                      << ACgroupController_getFlags(controller);
+        } else {
+            LOG(INFO) << "\t" << ACgroupController_getName(controller) << " ver "
+                      << ACgroupController_getVersion(controller) << " path "
+                      << ACgroupController_getPath(controller);
+        }
     }
 }
 
diff --git a/libprocessgroup/cgrouprc/cgroup_controller.cpp b/libprocessgroup/cgrouprc/cgroup_controller.cpp
index d064d31..5a326e5 100644
--- a/libprocessgroup/cgrouprc/cgroup_controller.cpp
+++ b/libprocessgroup/cgrouprc/cgroup_controller.cpp
@@ -27,6 +27,11 @@
     return controller->version();
 }
 
+uint32_t ACgroupController_getFlags(const ACgroupController* controller) {
+    CHECK(controller != nullptr);
+    return controller->flags();
+}
+
 const char* ACgroupController_getName(const ACgroupController* controller) {
     CHECK(controller != nullptr);
     return controller->name();
diff --git a/libprocessgroup/cgrouprc/include/android/cgrouprc.h b/libprocessgroup/cgrouprc/include/android/cgrouprc.h
index 0f6a9cd..0ce5123 100644
--- a/libprocessgroup/cgrouprc/include/android/cgrouprc.h
+++ b/libprocessgroup/cgrouprc/include/android/cgrouprc.h
@@ -66,10 +66,21 @@
         __INTRODUCED_IN(29);
 
 /**
- * Flag bitmask to be used when ACgroupController_getFlags can be exported
+ * Flag bitmask used in ACgroupController_getFlags
  */
 #define CGROUPRC_CONTROLLER_FLAG_MOUNTED 0x1
 
+#if __ANDROID_API__ >= __ANDROID_API_R__
+
+/**
+ * Returns the flags bitmask of the given controller.
+ * If the given controller is null, return 0.
+ */
+__attribute__((warn_unused_result, weak)) uint32_t ACgroupController_getFlags(
+        const ACgroupController*) __INTRODUCED_IN(30);
+
+#endif
+
 /**
  * Returns the name of the given controller.
  * If the given controller is null, return nullptr.
diff --git a/libprocessgroup/cgrouprc/libcgrouprc.llndk.txt b/libprocessgroup/cgrouprc/libcgrouprc.llndk.txt
index 91df392..ce5c419 100644
--- a/libprocessgroup/cgrouprc/libcgrouprc.llndk.txt
+++ b/libprocessgroup/cgrouprc/libcgrouprc.llndk.txt
@@ -9,3 +9,10 @@
   local:
     *;
 };
+
+LIBCGROUPRC_30 { # introduced=30
+  global:
+    ACgroupController_getFlags;
+  local:
+    *;
+};
diff --git a/libprocessgroup/sched_policy.cpp b/libprocessgroup/sched_policy.cpp
index 16339d3..698e74d 100644
--- a/libprocessgroup/sched_policy.cpp
+++ b/libprocessgroup/sched_policy.cpp
@@ -138,8 +138,17 @@
     return enabled;
 }
 
+static bool schedtune_enabled() {
+    return (CgroupMap::GetInstance().FindController("schedtune").IsUsable());
+}
+
+static bool cpuctl_enabled() {
+    return (CgroupMap::GetInstance().FindController("cpu").IsUsable());
+}
+
 bool schedboost_enabled() {
-    static bool enabled = (CgroupMap::GetInstance().FindController("schedtune").IsUsable());
+    static bool enabled = schedtune_enabled() || cpuctl_enabled();
+
     return enabled;
 }
 
@@ -162,7 +171,9 @@
 
     std::string group;
     if (schedboost_enabled()) {
-        if (getCGroupSubsys(tid, "schedtune", group) < 0) return -1;
+        if ((getCGroupSubsys(tid, "schedtune", group) < 0) &&
+            (getCGroupSubsys(tid, "cpu", group) < 0))
+		return -1;
     }
     if (group.empty() && cpusets_enabled()) {
         if (getCGroupSubsys(tid, "cpuset", group) < 0) return -1;
diff --git a/libprocessgroup/task_profiles.cpp b/libprocessgroup/task_profiles.cpp
index 9447f86..72f01af 100644
--- a/libprocessgroup/task_profiles.cpp
+++ b/libprocessgroup/task_profiles.cpp
@@ -288,6 +288,11 @@
     return true;
 }
 
+void TaskProfile::MoveTo(TaskProfile* profile) {
+    profile->elements_ = std::move(elements_);
+    profile->res_cached_ = res_cached_;
+}
+
 bool TaskProfile::ExecuteForProcess(uid_t uid, pid_t pid) const {
     for (const auto& element : elements_) {
         if (!element->ExecuteForProcess(uid, pid)) {
@@ -458,7 +463,15 @@
                 LOG(WARNING) << "Unknown profile action: " << action_name;
             }
         }
-        profiles_[profile_name] = profile;
+        auto iter = profiles_.find(profile_name);
+        if (iter == profiles_.end()) {
+            profiles_[profile_name] = profile;
+        } else {
+            // Move the content rather that replace the profile because old profile might be
+            // referenced from an aggregate profile if vendor overrides task profiles
+            profile->MoveTo(iter->second.get());
+            profile.reset();
+        }
     }
 
     const Json::Value& aggregateprofiles_val = root["AggregateProfiles"];
diff --git a/libprocessgroup/task_profiles.h b/libprocessgroup/task_profiles.h
index 9f2308c..a64ca50 100644
--- a/libprocessgroup/task_profiles.h
+++ b/libprocessgroup/task_profiles.h
@@ -143,6 +143,7 @@
     TaskProfile() : res_cached_(false) {}
 
     void Add(std::unique_ptr<ProfileAction> e) { elements_.push_back(std::move(e)); }
+    void MoveTo(TaskProfile* profile);
 
     bool ExecuteForProcess(uid_t uid, pid_t pid) const;
     bool ExecuteForTask(int tid) const;
diff --git a/libsparse/Android.bp b/libsparse/Android.bp
index 88146e9..135904b 100644
--- a/libsparse/Android.bp
+++ b/libsparse/Android.bp
@@ -3,6 +3,7 @@
 cc_library {
     name: "libsparse",
     host_supported: true,
+    ramdisk_available: true,
     recovery_available: true,
     unique_host_soname: true,
     srcs: [
diff --git a/libstats/socket/Android.bp b/libstats/socket/Android.bp
index 3b6efbb..9fd9fbc 100644
--- a/libstats/socket/Android.bp
+++ b/libstats/socket/Android.bp
@@ -75,3 +75,22 @@
         "libgtest_prod",
     ],
 }
+
+cc_test {
+    name: "libstatssocket_test",
+    srcs: ["tests/stats_event_test.cpp"],
+    cflags: [
+        "-Wall",
+        "-Werror",
+    ],
+    static_libs: [
+        "libgmock",
+        "libstatssocket",
+    ],
+    shared_libs: [
+        "libcutils",
+        "liblog",
+        "libutils",
+    ],
+    test_suites: ["device_tests"],
+}
diff --git a/libstats/socket/tests/stats_event_test.cpp b/libstats/socket/tests/stats_event_test.cpp
new file mode 100644
index 0000000..cf0592c
--- /dev/null
+++ b/libstats/socket/tests/stats_event_test.cpp
@@ -0,0 +1,344 @@
+/*
+ * Copyright (C) 2019 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 "stats_event.h"
+#include <gtest/gtest.h>
+#include <utils/SystemClock.h>
+
+using std::string;
+using std::vector;
+
+// Side-effect: this function moves the start of the buffer past the read value
+template <class T>
+T readNext(uint8_t** buffer) {
+    T value = *(T*)(*buffer);
+    *buffer += sizeof(T);
+    return value;
+}
+
+void checkTypeHeader(uint8_t** buffer, uint8_t typeId, uint8_t numAnnotations = 0) {
+    uint8_t typeHeader = (numAnnotations << 4) | typeId;
+    EXPECT_EQ(readNext<uint8_t>(buffer), typeHeader);
+}
+
+template <class T>
+void checkScalar(uint8_t** buffer, T expectedValue) {
+    EXPECT_EQ(readNext<T>(buffer), expectedValue);
+}
+
+void checkString(uint8_t** buffer, const string& expectedString) {
+    uint32_t size = readNext<uint32_t>(buffer);
+    string parsedString((char*)(*buffer), size);
+    EXPECT_EQ(parsedString, expectedString);
+    *buffer += size;  // move buffer past string we just read
+}
+
+void checkByteArray(uint8_t** buffer, const vector<uint8_t>& expectedByteArray) {
+    uint32_t size = readNext<uint32_t>(buffer);
+    vector<uint8_t> parsedByteArray(*buffer, *buffer + size);
+    EXPECT_EQ(parsedByteArray, expectedByteArray);
+    *buffer += size;  // move buffer past byte array we just read
+}
+
+template <class T>
+void checkAnnotation(uint8_t** buffer, uint8_t annotationId, uint8_t typeId, T annotationValue) {
+    EXPECT_EQ(readNext<uint8_t>(buffer), annotationId);
+    EXPECT_EQ(readNext<uint8_t>(buffer), typeId);
+    checkScalar<T>(buffer, annotationValue);
+}
+
+void checkMetadata(uint8_t** buffer, uint8_t numElements, int64_t startTime, int64_t endTime,
+                   uint32_t atomId) {
+    // All events start with OBJECT_TYPE id.
+    checkTypeHeader(buffer, OBJECT_TYPE);
+
+    // We increment by 2 because the number of elements listed in the
+    // serialization accounts for the timestamp and atom id as well.
+    checkScalar(buffer, static_cast<uint8_t>(numElements + 2));
+
+    // Check timestamp
+    checkTypeHeader(buffer, INT64_TYPE);
+    int64_t timestamp = readNext<int64_t>(buffer);
+    EXPECT_GE(timestamp, startTime);
+    EXPECT_LE(timestamp, endTime);
+
+    // Check atom id
+    checkTypeHeader(buffer, INT32_TYPE);
+    checkScalar(buffer, atomId);
+}
+
+TEST(StatsEventTest, TestScalars) {
+    uint32_t atomId = 100;
+    int32_t int32Value = -5;
+    int64_t int64Value = -2 * android::elapsedRealtimeNano();
+    float floatValue = 2.0;
+    bool boolValue = false;
+
+    int64_t startTime = android::elapsedRealtimeNano();
+    struct stats_event* event = stats_event_obtain();
+    stats_event_set_atom_id(event, atomId);
+    stats_event_write_int32(event, int32Value);
+    stats_event_write_int64(event, int64Value);
+    stats_event_write_float(event, floatValue);
+    stats_event_write_bool(event, boolValue);
+    stats_event_build(event);
+    int64_t endTime = android::elapsedRealtimeNano();
+
+    size_t bufferSize;
+    uint8_t* buffer = stats_event_get_buffer(event, &bufferSize);
+    uint8_t* bufferEnd = buffer + bufferSize;
+
+    checkMetadata(&buffer, /*numElements=*/4, startTime, endTime, atomId);
+
+    // check int32 element
+    checkTypeHeader(&buffer, INT32_TYPE);
+    checkScalar(&buffer, int32Value);
+
+    // check int64 element
+    checkTypeHeader(&buffer, INT64_TYPE);
+    checkScalar(&buffer, int64Value);
+
+    // check float element
+    checkTypeHeader(&buffer, FLOAT_TYPE);
+    checkScalar(&buffer, floatValue);
+
+    // check bool element
+    checkTypeHeader(&buffer, BOOL_TYPE);
+    checkScalar(&buffer, boolValue);
+
+    EXPECT_EQ(buffer, bufferEnd);  // ensure that we have read the entire buffer
+    EXPECT_EQ(stats_event_get_errors(event), 0);
+    stats_event_release(event);
+}
+
+TEST(StatsEventTest, TestStrings) {
+    uint32_t atomId = 100;
+    string str = "test_string";
+
+    int64_t startTime = android::elapsedRealtimeNano();
+    struct stats_event* event = stats_event_obtain();
+    stats_event_set_atom_id(event, atomId);
+    stats_event_write_string8(event, str.c_str());
+    stats_event_build(event);
+    int64_t endTime = android::elapsedRealtimeNano();
+
+    size_t bufferSize;
+    uint8_t* buffer = stats_event_get_buffer(event, &bufferSize);
+    uint8_t* bufferEnd = buffer + bufferSize;
+
+    checkMetadata(&buffer, /*numElements=*/1, startTime, endTime, atomId);
+
+    checkTypeHeader(&buffer, STRING_TYPE);
+    checkString(&buffer, str);
+
+    EXPECT_EQ(buffer, bufferEnd);  // ensure that we have read the entire buffer
+    EXPECT_EQ(stats_event_get_errors(event), 0);
+    stats_event_release(event);
+}
+
+TEST(StatsEventTest, TestByteArrays) {
+    uint32_t atomId = 100;
+    vector<uint8_t> message = {'b', 'y', 't', '\0', 'e', 's'};
+
+    int64_t startTime = android::elapsedRealtimeNano();
+    struct stats_event* event = stats_event_obtain();
+    stats_event_set_atom_id(event, atomId);
+    stats_event_write_byte_array(event, message.data(), message.size());
+    stats_event_build(event);
+    int64_t endTime = android::elapsedRealtimeNano();
+
+    size_t bufferSize;
+    uint8_t* buffer = stats_event_get_buffer(event, &bufferSize);
+    uint8_t* bufferEnd = buffer + bufferSize;
+
+    checkMetadata(&buffer, /*numElements=*/1, startTime, endTime, atomId);
+
+    checkTypeHeader(&buffer, BYTE_ARRAY_TYPE);
+    checkByteArray(&buffer, message);
+
+    EXPECT_EQ(buffer, bufferEnd);  // ensure that we have read the entire buffer
+    EXPECT_EQ(stats_event_get_errors(event), 0);
+    stats_event_release(event);
+}
+
+TEST(StatsEventTest, TestAttributionChains) {
+    uint32_t atomId = 100;
+
+    uint8_t numNodes = 50;
+    uint32_t uids[numNodes];
+    vector<string> tags(numNodes);  // storage that cTag elements point to
+    const char* cTags[numNodes];
+    for (int i = 0; i < (int)numNodes; i++) {
+        uids[i] = i;
+        tags.push_back("test" + std::to_string(i));
+        cTags[i] = tags[i].c_str();
+    }
+
+    int64_t startTime = android::elapsedRealtimeNano();
+    struct stats_event* event = stats_event_obtain();
+    stats_event_set_atom_id(event, atomId);
+    stats_event_write_attribution_chain(event, uids, cTags, numNodes);
+    stats_event_build(event);
+    int64_t endTime = android::elapsedRealtimeNano();
+
+    size_t bufferSize;
+    uint8_t* buffer = stats_event_get_buffer(event, &bufferSize);
+    uint8_t* bufferEnd = buffer + bufferSize;
+
+    checkMetadata(&buffer, /*numElements=*/1, startTime, endTime, atomId);
+
+    checkTypeHeader(&buffer, ATTRIBUTION_CHAIN_TYPE);
+    checkScalar(&buffer, numNodes);
+    for (int i = 0; i < numNodes; i++) {
+        checkScalar(&buffer, uids[i]);
+        checkString(&buffer, tags[i]);
+    }
+
+    EXPECT_EQ(buffer, bufferEnd);  // ensure that we have read the entire buffer
+    EXPECT_EQ(stats_event_get_errors(event), 0);
+    stats_event_release(event);
+}
+
+TEST(StatsEventTest, TestKeyValuePairs) {
+    uint32_t atomId = 100;
+
+    uint8_t numPairs = 4;
+    struct key_value_pair pairs[numPairs];
+    pairs[0] = {.key = 0, .valueType = INT32_TYPE, .int32Value = -1};
+    pairs[1] = {.key = 1, .valueType = INT64_TYPE, .int64Value = 0x123456789};
+    pairs[2] = {.key = 2, .valueType = FLOAT_TYPE, .floatValue = 5.5};
+    string str = "test_key_value_pair_string";
+    pairs[3] = {.key = 3, .valueType = STRING_TYPE, .stringValue = str.c_str()};
+
+    int64_t startTime = android::elapsedRealtimeNano();
+    struct stats_event* event = stats_event_obtain();
+    stats_event_set_atom_id(event, atomId);
+    stats_event_write_key_value_pairs(event, pairs, numPairs);
+    stats_event_build(event);
+    int64_t endTime = android::elapsedRealtimeNano();
+
+    size_t bufferSize;
+    uint8_t* buffer = stats_event_get_buffer(event, &bufferSize);
+    uint8_t* bufferEnd = buffer + bufferSize;
+
+    checkMetadata(&buffer, /*numElements=*/1, startTime, endTime, atomId);
+
+    checkTypeHeader(&buffer, KEY_VALUE_PAIRS_TYPE);
+    checkScalar(&buffer, numPairs);
+
+    // first pair
+    checkScalar(&buffer, pairs[0].key);
+    checkTypeHeader(&buffer, pairs[0].valueType);
+    checkScalar(&buffer, pairs[0].int32Value);
+
+    // second pair
+    checkScalar(&buffer, pairs[1].key);
+    checkTypeHeader(&buffer, pairs[1].valueType);
+    checkScalar(&buffer, pairs[1].int64Value);
+
+    // third pair
+    checkScalar(&buffer, pairs[2].key);
+    checkTypeHeader(&buffer, pairs[2].valueType);
+    checkScalar(&buffer, pairs[2].floatValue);
+
+    // fourth pair
+    checkScalar(&buffer, pairs[3].key);
+    checkTypeHeader(&buffer, pairs[3].valueType);
+    checkString(&buffer, str);
+
+    EXPECT_EQ(buffer, bufferEnd);  // ensure that we have read the entire buffer
+    EXPECT_EQ(stats_event_get_errors(event), 0);
+    stats_event_release(event);
+}
+
+TEST(StatsEventTest, TestAnnotations) {
+    uint32_t atomId = 100;
+
+    // first element information
+    bool boolValue = false;
+    uint8_t boolAnnotation1Id = 1;
+    uint8_t boolAnnotation2Id = 2;
+    bool boolAnnotation1Value = true;
+    int32_t boolAnnotation2Value = 3;
+
+    // second element information
+    float floatValue = -5.0;
+    uint8_t floatAnnotation1Id = 3;
+    uint8_t floatAnnotation2Id = 4;
+    int32_t floatAnnotation1Value = 8;
+    bool floatAnnotation2Value = false;
+
+    int64_t startTime = android::elapsedRealtimeNano();
+    struct stats_event* event = stats_event_obtain();
+    stats_event_set_atom_id(event, 100);
+    stats_event_write_bool(event, boolValue);
+    stats_event_add_bool_annotation(event, boolAnnotation1Id, boolAnnotation1Value);
+    stats_event_add_int32_annotation(event, boolAnnotation2Id, boolAnnotation2Value);
+    stats_event_write_float(event, floatValue);
+    stats_event_add_int32_annotation(event, floatAnnotation1Id, floatAnnotation1Value);
+    stats_event_add_bool_annotation(event, floatAnnotation2Id, floatAnnotation2Value);
+    stats_event_build(event);
+    int64_t endTime = android::elapsedRealtimeNano();
+
+    size_t bufferSize;
+    uint8_t* buffer = stats_event_get_buffer(event, &bufferSize);
+    uint8_t* bufferEnd = buffer + bufferSize;
+
+    checkMetadata(&buffer, /*numElements=*/2, startTime, endTime, atomId);
+
+    // check first element
+    checkTypeHeader(&buffer, BOOL_TYPE, /*numAnnotations=*/2);
+    checkScalar(&buffer, boolValue);
+    checkAnnotation(&buffer, boolAnnotation1Id, BOOL_TYPE, boolAnnotation1Value);
+    checkAnnotation(&buffer, boolAnnotation2Id, INT32_TYPE, boolAnnotation2Value);
+
+    // check second element
+    checkTypeHeader(&buffer, FLOAT_TYPE, /*numAnnotations=*/2);
+    checkScalar(&buffer, floatValue);
+    checkAnnotation(&buffer, floatAnnotation1Id, INT32_TYPE, floatAnnotation1Value);
+    checkAnnotation(&buffer, floatAnnotation2Id, BOOL_TYPE, floatAnnotation2Value);
+
+    EXPECT_EQ(buffer, bufferEnd);  // ensure that we have read the entire buffer
+    EXPECT_EQ(stats_event_get_errors(event), 0);
+    stats_event_release(event);
+}
+
+TEST(StatsEventTest, TestNoAtomIdError) {
+    struct stats_event* event = stats_event_obtain();
+    // Don't set the atom id in order to trigger the error.
+    stats_event_build(event);
+
+    uint32_t errors = stats_event_get_errors(event);
+    EXPECT_NE(errors | ERROR_NO_ATOM_ID, 0);
+
+    stats_event_release(event);
+}
+
+TEST(StatsEventTest, TestOverflowError) {
+    struct stats_event* event = stats_event_obtain();
+    stats_event_set_atom_id(event, 100);
+    // Add 1000 int32s to the event. Each int32 takes 5 bytes so this will
+    // overflow the 4068 byte buffer.
+    for (int i = 0; i < 1000; i++) {
+        stats_event_write_int32(event, 0);
+    }
+    stats_event_build(event);
+
+    uint32_t errors = stats_event_get_errors(event);
+    EXPECT_NE(errors | ERROR_OVERFLOW, 0);
+
+    stats_event_release(event);
+}
diff --git a/libunwindstack/Android.bp b/libunwindstack/Android.bp
index 9cd3d65..3695f72 100644
--- a/libunwindstack/Android.bp
+++ b/libunwindstack/Android.bp
@@ -240,6 +240,7 @@
         "tests/files/offline/debug_frame_load_bias_arm/*",
         "tests/files/offline/eh_frame_bias_x86/*",
         "tests/files/offline/eh_frame_hdr_begin_x86_64/*",
+        "tests/files/offline/empty_arm64/*",
         "tests/files/offline/invalid_elf_offset_arm/*",
         "tests/files/offline/jit_debug_arm/*",
         "tests/files/offline/jit_debug_x86/*",
diff --git a/libunwindstack/MapInfo.cpp b/libunwindstack/MapInfo.cpp
index f2dad84..31f3144 100644
--- a/libunwindstack/MapInfo.cpp
+++ b/libunwindstack/MapInfo.cpp
@@ -37,12 +37,12 @@
 bool MapInfo::InitFileMemoryFromPreviousReadOnlyMap(MemoryFileAtOffset* memory) {
   // One last attempt, see if the previous map is read-only with the
   // same name and stretches across this map.
-  if (prev_map == nullptr || prev_map->flags != PROT_READ) {
+  if (prev_real_map == nullptr || prev_real_map->flags != PROT_READ) {
     return false;
   }
 
-  uint64_t map_size = end - prev_map->end;
-  if (!memory->Init(name, prev_map->offset, map_size)) {
+  uint64_t map_size = end - prev_real_map->end;
+  if (!memory->Init(name, prev_real_map->offset, map_size)) {
     return false;
   }
 
@@ -51,12 +51,12 @@
     return false;
   }
 
-  if (!memory->Init(name, prev_map->offset, max_size)) {
+  if (!memory->Init(name, prev_real_map->offset, max_size)) {
     return false;
   }
 
-  elf_offset = offset - prev_map->offset;
-  elf_start_offset = prev_map->offset;
+  elf_offset = offset - prev_real_map->offset;
+  elf_start_offset = prev_real_map->offset;
   return true;
 }
 
@@ -112,8 +112,8 @@
     // Need to check how to set the elf start offset. If this map is not
     // the r-x map of a r-- map, then use the real offset value. Otherwise,
     // use 0.
-    if (prev_map == nullptr || prev_map->offset != 0 || prev_map->flags != PROT_READ ||
-        prev_map->name != name) {
+    if (prev_real_map == nullptr || prev_real_map->offset != 0 ||
+        prev_real_map->flags != PROT_READ || prev_real_map->name != name) {
       elf_start_offset = offset;
     }
     return memory.release();
@@ -172,20 +172,20 @@
   // doesn't guarantee that this invariant will always be true. However,
   // if that changes, there is likely something else that will change and
   // break something.
-  if (offset == 0 || name.empty() || prev_map == nullptr || prev_map->name != name ||
-      prev_map->offset >= offset) {
+  if (offset == 0 || name.empty() || prev_real_map == nullptr || prev_real_map->name != name ||
+      prev_real_map->offset >= offset) {
     return nullptr;
   }
 
   // Make sure that relative pc values are corrected properly.
-  elf_offset = offset - prev_map->offset;
+  elf_offset = offset - prev_real_map->offset;
   // Use this as the elf start offset, otherwise, you always get offsets into
   // the r-x section, which is not quite the right information.
-  elf_start_offset = prev_map->offset;
+  elf_start_offset = prev_real_map->offset;
 
   MemoryRanges* ranges = new MemoryRanges;
-  ranges->Insert(
-      new MemoryRange(process_memory, prev_map->start, prev_map->end - prev_map->start, 0));
+  ranges->Insert(new MemoryRange(process_memory, prev_real_map->start,
+                                 prev_real_map->end - prev_real_map->start, 0));
   ranges->Insert(new MemoryRange(process_memory, start, end - start, elf_offset));
 
   memory_backed_elf = true;
@@ -236,15 +236,15 @@
 
   if (!elf->valid()) {
     elf_start_offset = offset;
-  } else if (prev_map != nullptr && elf_start_offset != offset &&
-             prev_map->offset == elf_start_offset && prev_map->name == name) {
+  } else if (prev_real_map != nullptr && elf_start_offset != offset &&
+             prev_real_map->offset == elf_start_offset && prev_real_map->name == name) {
     // If there is a read-only map then a read-execute map that represents the
     // same elf object, make sure the previous map is using the same elf
     // object if it hasn't already been set.
-    std::lock_guard<std::mutex> guard(prev_map->mutex_);
-    if (prev_map->elf.get() == nullptr) {
-      prev_map->elf = elf;
-      prev_map->memory_backed_elf = memory_backed_elf;
+    std::lock_guard<std::mutex> guard(prev_real_map->mutex_);
+    if (prev_real_map->elf.get() == nullptr) {
+      prev_real_map->elf = elf;
+      prev_real_map->memory_backed_elf = memory_backed_elf;
     }
   }
   return elf.get();
diff --git a/libunwindstack/Maps.cpp b/libunwindstack/Maps.cpp
index 0ab68db..8f49ad9 100644
--- a/libunwindstack/Maps.cpp
+++ b/libunwindstack/Maps.cpp
@@ -60,6 +60,8 @@
 }
 
 bool Maps::Parse() {
+  MapInfo* prev_map = nullptr;
+  MapInfo* prev_real_map = nullptr;
   return android::procinfo::ReadMapFile(
       GetMapsFile(),
       [&](uint64_t start, uint64_t end, uint16_t flags, uint64_t pgoff, ino_t, const char* name) {
@@ -67,17 +69,24 @@
         if (strncmp(name, "/dev/", 5) == 0 && strncmp(name + 5, "ashmem/", 7) != 0) {
           flags |= unwindstack::MAPS_FLAGS_DEVICE_MAP;
         }
-        maps_.emplace_back(
-            new MapInfo(maps_.empty() ? nullptr : maps_.back().get(), start, end, pgoff,
-                        flags, name));
+        maps_.emplace_back(new MapInfo(prev_map, prev_real_map, start, end, pgoff, flags, name));
+        prev_map = maps_.back().get();
+        if (!prev_map->IsBlank()) {
+          prev_real_map = prev_map;
+        }
       });
 }
 
 void Maps::Add(uint64_t start, uint64_t end, uint64_t offset, uint64_t flags,
                const std::string& name, uint64_t load_bias) {
+  MapInfo* prev_map = maps_.empty() ? nullptr : maps_.back().get();
+  MapInfo* prev_real_map = prev_map;
+  while (prev_real_map != nullptr && prev_real_map->IsBlank()) {
+    prev_real_map = prev_real_map->prev_map;
+  }
+
   auto map_info =
-      std::make_unique<MapInfo>(maps_.empty() ? nullptr : maps_.back().get(), start, end, offset,
-                                flags, name);
+      std::make_unique<MapInfo>(prev_map, prev_real_map, start, end, offset, flags, name);
   map_info->load_bias = load_bias;
   maps_.emplace_back(std::move(map_info));
 }
@@ -89,14 +98,21 @@
 
   // Set the prev_map values on the info objects.
   MapInfo* prev_map = nullptr;
+  MapInfo* prev_real_map = nullptr;
   for (const auto& map_info : maps_) {
     map_info->prev_map = prev_map;
+    map_info->prev_real_map = prev_real_map;
     prev_map = map_info.get();
+    if (!prev_map->IsBlank()) {
+      prev_real_map = prev_map;
+    }
   }
 }
 
 bool BufferMaps::Parse() {
   std::string content(buffer_);
+  MapInfo* prev_map = nullptr;
+  MapInfo* prev_real_map = nullptr;
   return android::procinfo::ReadMapFileContent(
       &content[0],
       [&](uint64_t start, uint64_t end, uint16_t flags, uint64_t pgoff, ino_t, const char* name) {
@@ -104,9 +120,11 @@
         if (strncmp(name, "/dev/", 5) == 0 && strncmp(name + 5, "ashmem/", 7) != 0) {
           flags |= unwindstack::MAPS_FLAGS_DEVICE_MAP;
         }
-        maps_.emplace_back(
-            new MapInfo(maps_.empty() ? nullptr : maps_.back().get(), start, end, pgoff,
-                        flags, name));
+        maps_.emplace_back(new MapInfo(prev_map, prev_real_map, start, end, pgoff, flags, name));
+        prev_map = maps_.back().get();
+        if (!prev_map->IsBlank()) {
+          prev_real_map = prev_map;
+        }
       });
 }
 
diff --git a/libunwindstack/RegsArm64.cpp b/libunwindstack/RegsArm64.cpp
index 1df1dff..00b3367 100644
--- a/libunwindstack/RegsArm64.cpp
+++ b/libunwindstack/RegsArm64.cpp
@@ -100,8 +100,8 @@
   fn("x27", regs_[ARM64_REG_R27]);
   fn("x28", regs_[ARM64_REG_R28]);
   fn("x29", regs_[ARM64_REG_R29]);
-  fn("sp", regs_[ARM64_REG_SP]);
   fn("lr", regs_[ARM64_REG_LR]);
+  fn("sp", regs_[ARM64_REG_SP]);
   fn("pc", regs_[ARM64_REG_PC]);
   fn("pst", regs_[ARM64_REG_PSTATE]);
 }
@@ -110,10 +110,10 @@
   arm64_user_regs* user = reinterpret_cast<arm64_user_regs*>(remote_data);
 
   RegsArm64* regs = new RegsArm64();
-  memcpy(regs->RawData(), &user->regs[0], (ARM64_REG_R31 + 1) * sizeof(uint64_t));
+  memcpy(regs->RawData(), &user->regs[0], (ARM64_REG_R30 + 1) * sizeof(uint64_t));
   uint64_t* reg_data = reinterpret_cast<uint64_t*>(regs->RawData());
-  reg_data[ARM64_REG_PC] = user->pc;
   reg_data[ARM64_REG_SP] = user->sp;
+  reg_data[ARM64_REG_PC] = user->pc;
   reg_data[ARM64_REG_PSTATE] = user->pstate;
   return regs;
 }
diff --git a/libunwindstack/TEST_MAPPING b/libunwindstack/TEST_MAPPING
index 55771c0..909f897 100644
--- a/libunwindstack/TEST_MAPPING
+++ b/libunwindstack/TEST_MAPPING
@@ -2,6 +2,9 @@
   "presubmit": [
     {
       "name": "libunwindstack_unit_test"
+    },
+    {
+      "name": "CtsSimpleperfTestCases"
     }
   ]
 }
diff --git a/libunwindstack/include/unwindstack/MapInfo.h b/libunwindstack/include/unwindstack/MapInfo.h
index 8f0c516..052e79f 100644
--- a/libunwindstack/include/unwindstack/MapInfo.h
+++ b/libunwindstack/include/unwindstack/MapInfo.h
@@ -31,24 +31,26 @@
 class MemoryFileAtOffset;
 
 struct MapInfo {
-  MapInfo(MapInfo* map_info, uint64_t start, uint64_t end, uint64_t offset, uint64_t flags,
-          const char* name)
+  MapInfo(MapInfo* prev_map, MapInfo* prev_real_map, uint64_t start, uint64_t end, uint64_t offset,
+          uint64_t flags, const char* name)
       : start(start),
         end(end),
         offset(offset),
         flags(flags),
         name(name),
-        prev_map(map_info),
+        prev_map(prev_map),
+        prev_real_map(prev_real_map),
         load_bias(INT64_MAX),
         build_id(0) {}
-  MapInfo(MapInfo* map_info, uint64_t start, uint64_t end, uint64_t offset, uint64_t flags,
-          const std::string& name)
+  MapInfo(MapInfo* prev_map, MapInfo* prev_real_map, uint64_t start, uint64_t end, uint64_t offset,
+          uint64_t flags, const std::string& name)
       : start(start),
         end(end),
         offset(offset),
         flags(flags),
         name(name),
-        prev_map(map_info),
+        prev_map(prev_map),
+        prev_real_map(prev_real_map),
         load_bias(INT64_MAX),
         build_id(0) {}
   ~MapInfo();
@@ -71,6 +73,14 @@
   uint64_t elf_start_offset = 0;
 
   MapInfo* prev_map = nullptr;
+  // This is the previous map that is not empty with a 0 offset. For
+  // example, this set of maps:
+  //  1000-2000  r--p 000000 00:00 0 libc.so
+  //  2000-3000  ---p 000000 00:00 0 libc.so
+  //  3000-4000  r-xp 003000 00:00 0 libc.so
+  // The last map's prev_map would point to the 2000-3000 map, while the
+  // prev_real_map would point to the 1000-2000 map.
+  MapInfo* prev_real_map = nullptr;
 
   std::atomic_int64_t load_bias;
 
@@ -97,6 +107,8 @@
   // Returns the printable version of the build id (hex dump of raw data).
   std::string GetPrintableBuildID();
 
+  inline bool IsBlank() { return offset == 0 && flags == 0 && name.empty(); }
+
  private:
   MapInfo(const MapInfo&) = delete;
   void operator=(const MapInfo&) = delete;
diff --git a/libunwindstack/tests/DexFileTest.cpp b/libunwindstack/tests/DexFileTest.cpp
index 0149a42..1b54da6 100644
--- a/libunwindstack/tests/DexFileTest.cpp
+++ b/libunwindstack/tests/DexFileTest.cpp
@@ -105,7 +105,7 @@
             static_cast<size_t>(TEMP_FAILURE_RETRY(write(tf.fd, kDexData, sizeof(kDexData)))));
 
   MemoryFake memory;
-  MapInfo info(nullptr, 0, 0x10000, 0, 0x5, tf.path);
+  MapInfo info(nullptr, nullptr, 0, 0x10000, 0, 0x5, tf.path);
   EXPECT_TRUE(DexFile::Create(0x500, &memory, &info) != nullptr);
 }
 
@@ -118,7 +118,7 @@
             static_cast<size_t>(TEMP_FAILURE_RETRY(write(tf.fd, kDexData, sizeof(kDexData)))));
 
   MemoryFake memory;
-  MapInfo info(nullptr, 0x100, 0x10000, 0, 0x5, tf.path);
+  MapInfo info(nullptr, nullptr, 0x100, 0x10000, 0, 0x5, tf.path);
   EXPECT_TRUE(DexFile::Create(0x600, &memory, &info) != nullptr);
 }
 
@@ -131,21 +131,21 @@
             static_cast<size_t>(TEMP_FAILURE_RETRY(write(tf.fd, kDexData, sizeof(kDexData)))));
 
   MemoryFake memory;
-  MapInfo info(nullptr, 0x100, 0x10000, 0x200, 0x5, tf.path);
+  MapInfo info(nullptr, nullptr, 0x100, 0x10000, 0x200, 0x5, tf.path);
   EXPECT_TRUE(DexFile::Create(0x400, &memory, &info) != nullptr);
 }
 
 TEST(DexFileTest, create_using_memory_empty_file) {
   MemoryFake memory;
   memory.SetMemory(0x4000, kDexData, sizeof(kDexData));
-  MapInfo info(nullptr, 0x100, 0x10000, 0x200, 0x5, "");
+  MapInfo info(nullptr, nullptr, 0x100, 0x10000, 0x200, 0x5, "");
   EXPECT_TRUE(DexFile::Create(0x4000, &memory, &info) != nullptr);
 }
 
 TEST(DexFileTest, create_using_memory_file_does_not_exist) {
   MemoryFake memory;
   memory.SetMemory(0x4000, kDexData, sizeof(kDexData));
-  MapInfo info(nullptr, 0x100, 0x10000, 0x200, 0x5, "/does/not/exist");
+  MapInfo info(nullptr, nullptr, 0x100, 0x10000, 0x200, 0x5, "/does/not/exist");
   EXPECT_TRUE(DexFile::Create(0x4000, &memory, &info) != nullptr);
 }
 
@@ -158,7 +158,7 @@
 
   MemoryFake memory;
   memory.SetMemory(0x4000, kDexData, sizeof(kDexData));
-  MapInfo info(nullptr, 0x4000, 0x10000, 0x200, 0x5, "/does/not/exist");
+  MapInfo info(nullptr, nullptr, 0x4000, 0x10000, 0x200, 0x5, "/does/not/exist");
   std::unique_ptr<DexFile> dex_file = DexFile::Create(0x4000, &memory, &info);
   ASSERT_TRUE(dex_file != nullptr);
 
@@ -171,7 +171,7 @@
 TEST(DexFileTest, get_method) {
   MemoryFake memory;
   memory.SetMemory(0x4000, kDexData, sizeof(kDexData));
-  MapInfo info(nullptr, 0x100, 0x10000, 0x200, 0x5, "");
+  MapInfo info(nullptr, nullptr, 0x100, 0x10000, 0x200, 0x5, "");
   std::unique_ptr<DexFile> dex_file(DexFile::Create(0x4000, &memory, &info));
   ASSERT_TRUE(dex_file != nullptr);
 
@@ -189,7 +189,7 @@
 TEST(DexFileTest, get_method_empty) {
   MemoryFake memory;
   memory.SetMemory(0x4000, kDexData, sizeof(kDexData));
-  MapInfo info(nullptr, 0x100, 0x10000, 0x200, 0x5, "");
+  MapInfo info(nullptr, nullptr, 0x100, 0x10000, 0x200, 0x5, "");
   std::unique_ptr<DexFile> dex_file(DexFile::Create(0x4000, &memory, &info));
   ASSERT_TRUE(dex_file != nullptr);
 
diff --git a/libunwindstack/tests/ElfCacheTest.cpp b/libunwindstack/tests/ElfCacheTest.cpp
index 5735858..5f13546 100644
--- a/libunwindstack/tests/ElfCacheTest.cpp
+++ b/libunwindstack/tests/ElfCacheTest.cpp
@@ -78,8 +78,8 @@
 
   uint64_t start = 0x1000;
   uint64_t end = 0x20000;
-  MapInfo info1(nullptr, start, end, 0, 0x5, tf.path);
-  MapInfo info2(nullptr, start, end, 0, 0x5, tf.path);
+  MapInfo info1(nullptr, nullptr, start, end, 0, 0x5, tf.path);
+  MapInfo info2(nullptr, nullptr, start, end, 0, 0x5, tf.path);
 
   Elf* elf1 = info1.GetElf(memory_, ARCH_ARM);
   ASSERT_TRUE(elf1->valid());
@@ -119,17 +119,17 @@
   uint64_t start = 0x1000;
   uint64_t end = 0x20000;
   // Will have an elf at offset 0 in file.
-  MapInfo info0_1(nullptr, start, end, 0, 0x5, tf.path);
-  MapInfo info0_2(nullptr, start, end, 0, 0x5, tf.path);
+  MapInfo info0_1(nullptr, nullptr, start, end, 0, 0x5, tf.path);
+  MapInfo info0_2(nullptr, nullptr, start, end, 0, 0x5, tf.path);
   // Will have an elf at offset 0x100 in file.
-  MapInfo info100_1(nullptr, start, end, 0x100, 0x5, tf.path);
-  MapInfo info100_2(nullptr, start, end, 0x100, 0x5, tf.path);
+  MapInfo info100_1(nullptr, nullptr, start, end, 0x100, 0x5, tf.path);
+  MapInfo info100_2(nullptr, nullptr, start, end, 0x100, 0x5, tf.path);
   // Will have an elf at offset 0x200 in file.
-  MapInfo info200_1(nullptr, start, end, 0x200, 0x5, tf.path);
-  MapInfo info200_2(nullptr, start, end, 0x200, 0x5, tf.path);
+  MapInfo info200_1(nullptr, nullptr, start, end, 0x200, 0x5, tf.path);
+  MapInfo info200_2(nullptr, nullptr, start, end, 0x200, 0x5, tf.path);
   // Will have an elf at offset 0 in file.
-  MapInfo info300_1(nullptr, start, end, 0x300, 0x5, tf.path);
-  MapInfo info300_2(nullptr, start, end, 0x300, 0x5, tf.path);
+  MapInfo info300_1(nullptr, nullptr, start, end, 0x300, 0x5, tf.path);
+  MapInfo info300_2(nullptr, nullptr, start, end, 0x300, 0x5, tf.path);
 
   Elf* elf0_1 = info0_1.GetElf(memory_, ARCH_ARM);
   ASSERT_TRUE(elf0_1->valid());
@@ -216,10 +216,10 @@
   uint64_t start = 0x1000;
   uint64_t end = 0x20000;
   // Multiple info sections at different offsets will have non-zero elf offsets.
-  MapInfo info300_1(nullptr, start, end, 0x300, 0x5, tf.path);
-  MapInfo info300_2(nullptr, start, end, 0x300, 0x5, tf.path);
-  MapInfo info400_1(nullptr, start, end, 0x400, 0x5, tf.path);
-  MapInfo info400_2(nullptr, start, end, 0x400, 0x5, tf.path);
+  MapInfo info300_1(nullptr, nullptr, start, end, 0x300, 0x5, tf.path);
+  MapInfo info300_2(nullptr, nullptr, start, end, 0x300, 0x5, tf.path);
+  MapInfo info400_1(nullptr, nullptr, start, end, 0x400, 0x5, tf.path);
+  MapInfo info400_2(nullptr, nullptr, start, end, 0x400, 0x5, tf.path);
 
   Elf* elf300_1 = info300_1.GetElf(memory_, ARCH_ARM);
   ASSERT_TRUE(elf300_1->valid());
diff --git a/libunwindstack/tests/ElfTest.cpp b/libunwindstack/tests/ElfTest.cpp
index 4866345..1f3ed81 100644
--- a/libunwindstack/tests/ElfTest.cpp
+++ b/libunwindstack/tests/ElfTest.cpp
@@ -275,7 +275,7 @@
   elf.FakeSetInterface(interface);
 
   elf.FakeSetValid(true);
-  MapInfo map_info(nullptr, 0x1000, 0x2000, 0, 0, "");
+  MapInfo map_info(nullptr, nullptr, 0x1000, 0x2000, 0, 0, "");
 
   ASSERT_EQ(0x101U, elf.GetRelPc(0x1101, &map_info));
 
diff --git a/libunwindstack/tests/MapInfoCreateMemoryTest.cpp b/libunwindstack/tests/MapInfoCreateMemoryTest.cpp
index 6c1cfa2..6d8d58e 100644
--- a/libunwindstack/tests/MapInfoCreateMemoryTest.cpp
+++ b/libunwindstack/tests/MapInfoCreateMemoryTest.cpp
@@ -89,7 +89,7 @@
 };
 
 TEST_F(MapInfoCreateMemoryTest, end_le_start) {
-  MapInfo info(nullptr, 0x100, 0x100, 0, 0, elf_.path);
+  MapInfo info(nullptr, nullptr, 0x100, 0x100, 0, 0, elf_.path);
 
   std::unique_ptr<Memory> memory(info.CreateMemory(process_memory_));
   ASSERT_TRUE(memory.get() == nullptr);
@@ -108,7 +108,7 @@
 // Verify that if the offset is non-zero but there is no elf at the offset,
 // that the full file is used.
 TEST_F(MapInfoCreateMemoryTest, file_backed_non_zero_offset_full_file) {
-  MapInfo info(nullptr, 0x100, 0x200, 0x100, 0, elf_.path);
+  MapInfo info(nullptr, nullptr, 0x100, 0x200, 0x100, 0, elf_.path);
 
   std::unique_ptr<Memory> memory(info.CreateMemory(process_memory_));
   ASSERT_TRUE(memory.get() != nullptr);
@@ -129,8 +129,9 @@
 
   // Now verify the elf start offset is set correctly based on the previous
   // info.
-  MapInfo prev_info(nullptr, 0, 0x100, 0x10, 0, "");
+  MapInfo prev_info(nullptr, nullptr, 0, 0x100, 0x10, 0, "");
   info.prev_map = &prev_info;
+  info.prev_real_map = &prev_info;
 
   // No preconditions met, change each one until it should set the elf start
   // offset to zero.
@@ -177,7 +178,7 @@
 // Verify that if the offset is non-zero and there is an elf at that
 // offset, that only part of the file is used.
 TEST_F(MapInfoCreateMemoryTest, file_backed_non_zero_offset_partial_file) {
-  MapInfo info(nullptr, 0x100, 0x200, 0x1000, 0, elf_at_1000_.path);
+  MapInfo info(nullptr, nullptr, 0x100, 0x200, 0x1000, 0, elf_at_1000_.path);
 
   std::unique_ptr<Memory> memory(info.CreateMemory(process_memory_));
   ASSERT_TRUE(memory.get() != nullptr);
@@ -202,7 +203,7 @@
 // embedded elf is bigger than the initial map, the new object is larger
 // than the original map size. Do this for a 32 bit elf and a 64 bit elf.
 TEST_F(MapInfoCreateMemoryTest, file_backed_non_zero_offset_partial_file_whole_elf32) {
-  MapInfo info(nullptr, 0x5000, 0x6000, 0x1000, 0, elf32_at_map_.path);
+  MapInfo info(nullptr, nullptr, 0x5000, 0x6000, 0x1000, 0, elf32_at_map_.path);
 
   std::unique_ptr<Memory> memory(info.CreateMemory(process_memory_));
   ASSERT_TRUE(memory.get() != nullptr);
@@ -220,7 +221,7 @@
 }
 
 TEST_F(MapInfoCreateMemoryTest, file_backed_non_zero_offset_partial_file_whole_elf64) {
-  MapInfo info(nullptr, 0x7000, 0x8000, 0x2000, 0, elf64_at_map_.path);
+  MapInfo info(nullptr, nullptr, 0x7000, 0x8000, 0x2000, 0, elf64_at_map_.path);
 
   std::unique_ptr<Memory> memory(info.CreateMemory(process_memory_));
   ASSERT_TRUE(memory.get() != nullptr);
@@ -243,14 +244,14 @@
   // be returned if the file mapping fails, but the device check is incorrect.
   std::vector<uint8_t> buffer(1024);
   uint64_t start = reinterpret_cast<uint64_t>(buffer.data());
-  MapInfo info(nullptr, start, start + buffer.size(), 0, 0x8000, "/dev/something");
+  MapInfo info(nullptr, nullptr, start, start + buffer.size(), 0, 0x8000, "/dev/something");
 
   std::unique_ptr<Memory> memory(info.CreateMemory(process_memory_));
   ASSERT_TRUE(memory.get() == nullptr);
 }
 
 TEST_F(MapInfoCreateMemoryTest, process_memory) {
-  MapInfo info(nullptr, 0x2000, 0x3000, 0, PROT_READ, "");
+  MapInfo info(nullptr, nullptr, 0x2000, 0x3000, 0, PROT_READ, "");
 
   Elf32_Ehdr ehdr = {};
   TestInitEhdr<Elf32_Ehdr>(&ehdr, ELFCLASS32, EM_ARM);
diff --git a/libunwindstack/tests/MapInfoGetBuildIDTest.cpp b/libunwindstack/tests/MapInfoGetBuildIDTest.cpp
index 16451d1..6953e26 100644
--- a/libunwindstack/tests/MapInfoGetBuildIDTest.cpp
+++ b/libunwindstack/tests/MapInfoGetBuildIDTest.cpp
@@ -50,7 +50,8 @@
     elf_interface_ = new ElfInterfaceFake(memory_);
     elf_->FakeSetInterface(elf_interface_);
     elf_container_.reset(elf_);
-    map_info_.reset(new MapInfo(nullptr, 0x1000, 0x20000, 0, PROT_READ | PROT_WRITE, tf_->path));
+    map_info_.reset(
+        new MapInfo(nullptr, nullptr, 0x1000, 0x20000, 0, PROT_READ | PROT_WRITE, tf_->path));
   }
 
   void MultipleThreadTest(std::string expected_build_id);
@@ -64,7 +65,7 @@
 };
 
 TEST_F(MapInfoGetBuildIDTest, no_elf_and_no_valid_elf_in_memory) {
-  MapInfo info(nullptr, 0x1000, 0x2000, 0, PROT_READ, "");
+  MapInfo info(nullptr, nullptr, 0x1000, 0x2000, 0, PROT_READ, "");
 
   EXPECT_EQ("", info.GetBuildID());
   EXPECT_EQ("", info.GetPrintableBuildID());
diff --git a/libunwindstack/tests/MapInfoGetElfTest.cpp b/libunwindstack/tests/MapInfoGetElfTest.cpp
index d60b8b1..7f97814 100644
--- a/libunwindstack/tests/MapInfoGetElfTest.cpp
+++ b/libunwindstack/tests/MapInfoGetElfTest.cpp
@@ -68,7 +68,7 @@
 };
 
 TEST_F(MapInfoGetElfTest, invalid) {
-  MapInfo info(nullptr, 0x1000, 0x2000, 0, PROT_READ, "");
+  MapInfo info(nullptr, nullptr, 0x1000, 0x2000, 0, PROT_READ, "");
 
   // The map is empty, but this should still create an invalid elf object.
   Elf* elf = info.GetElf(process_memory_, ARCH_ARM);
@@ -77,7 +77,7 @@
 }
 
 TEST_F(MapInfoGetElfTest, valid32) {
-  MapInfo info(nullptr, 0x3000, 0x4000, 0, PROT_READ, "");
+  MapInfo info(nullptr, nullptr, 0x3000, 0x4000, 0, PROT_READ, "");
 
   Elf32_Ehdr ehdr;
   TestInitEhdr<Elf32_Ehdr>(&ehdr, ELFCLASS32, EM_ARM);
@@ -97,7 +97,7 @@
 }
 
 TEST_F(MapInfoGetElfTest, valid64) {
-  MapInfo info(nullptr, 0x8000, 0x9000, 0, PROT_READ, "");
+  MapInfo info(nullptr, nullptr, 0x8000, 0x9000, 0, PROT_READ, "");
 
   Elf64_Ehdr ehdr;
   TestInitEhdr<Elf64_Ehdr>(&ehdr, ELFCLASS64, EM_AARCH64);
@@ -111,7 +111,7 @@
 }
 
 TEST_F(MapInfoGetElfTest, invalid_arch_mismatch) {
-  MapInfo info(nullptr, 0x3000, 0x4000, 0, PROT_READ, "");
+  MapInfo info(nullptr, nullptr, 0x3000, 0x4000, 0, PROT_READ, "");
 
   Elf32_Ehdr ehdr;
   TestInitEhdr<Elf32_Ehdr>(&ehdr, ELFCLASS32, EM_ARM);
@@ -123,7 +123,7 @@
 }
 
 TEST_F(MapInfoGetElfTest, gnu_debugdata_init32) {
-  MapInfo info(nullptr, 0x2000, 0x3000, 0, PROT_READ, "");
+  MapInfo info(nullptr, nullptr, 0x2000, 0x3000, 0, PROT_READ, "");
 
   TestInitGnuDebugdata<Elf32_Ehdr, Elf32_Shdr>(ELFCLASS32, EM_ARM, true,
                                                [&](uint64_t offset, const void* ptr, size_t size) {
@@ -139,7 +139,7 @@
 }
 
 TEST_F(MapInfoGetElfTest, gnu_debugdata_init64) {
-  MapInfo info(nullptr, 0x5000, 0x8000, 0, PROT_READ, "");
+  MapInfo info(nullptr, nullptr, 0x5000, 0x8000, 0, PROT_READ, "");
 
   TestInitGnuDebugdata<Elf64_Ehdr, Elf64_Shdr>(ELFCLASS64, EM_AARCH64, true,
                                                [&](uint64_t offset, const void* ptr, size_t size) {
@@ -155,7 +155,7 @@
 }
 
 TEST_F(MapInfoGetElfTest, end_le_start) {
-  MapInfo info(nullptr, 0x1000, 0x1000, 0, PROT_READ, elf_.path);
+  MapInfo info(nullptr, nullptr, 0x1000, 0x1000, 0, PROT_READ, elf_.path);
 
   Elf32_Ehdr ehdr;
   TestInitEhdr<Elf32_Ehdr>(&ehdr, ELFCLASS32, EM_ARM);
@@ -182,7 +182,7 @@
 // Verify that if the offset is non-zero but there is no elf at the offset,
 // that the full file is used.
 TEST_F(MapInfoGetElfTest, file_backed_non_zero_offset_full_file) {
-  MapInfo info(nullptr, 0x1000, 0x2000, 0x100, PROT_READ, elf_.path);
+  MapInfo info(nullptr, nullptr, 0x1000, 0x2000, 0x100, PROT_READ, elf_.path);
 
   std::vector<uint8_t> buffer(0x1000);
   memset(buffer.data(), 0, buffer.size());
@@ -211,7 +211,7 @@
 // Verify that if the offset is non-zero and there is an elf at that
 // offset, that only part of the file is used.
 TEST_F(MapInfoGetElfTest, file_backed_non_zero_offset_partial_file) {
-  MapInfo info(nullptr, 0x1000, 0x2000, 0x2000, PROT_READ, elf_.path);
+  MapInfo info(nullptr, nullptr, 0x1000, 0x2000, 0x2000, PROT_READ, elf_.path);
 
   std::vector<uint8_t> buffer(0x4000);
   memset(buffer.data(), 0, buffer.size());
@@ -241,7 +241,7 @@
 // embedded elf is bigger than the initial map, the new object is larger
 // than the original map size. Do this for a 32 bit elf and a 64 bit elf.
 TEST_F(MapInfoGetElfTest, file_backed_non_zero_offset_partial_file_whole_elf32) {
-  MapInfo info(nullptr, 0x5000, 0x6000, 0x1000, PROT_READ, elf_.path);
+  MapInfo info(nullptr, nullptr, 0x5000, 0x6000, 0x1000, PROT_READ, elf_.path);
 
   std::vector<uint8_t> buffer(0x4000);
   memset(buffer.data(), 0, buffer.size());
@@ -269,7 +269,7 @@
 }
 
 TEST_F(MapInfoGetElfTest, file_backed_non_zero_offset_partial_file_whole_elf64) {
-  MapInfo info(nullptr, 0x7000, 0x8000, 0x1000, PROT_READ, elf_.path);
+  MapInfo info(nullptr, nullptr, 0x7000, 0x8000, 0x1000, PROT_READ, elf_.path);
 
   std::vector<uint8_t> buffer(0x4000);
   memset(buffer.data(), 0, buffer.size());
@@ -297,7 +297,7 @@
 }
 
 TEST_F(MapInfoGetElfTest, check_device_maps) {
-  MapInfo info(nullptr, 0x7000, 0x8000, 0x1000, PROT_READ | MAPS_FLAGS_DEVICE_MAP,
+  MapInfo info(nullptr, nullptr, 0x7000, 0x8000, 0x1000, PROT_READ | MAPS_FLAGS_DEVICE_MAP,
                "/dev/something");
 
   // Create valid elf data in process memory for this to verify that only
@@ -343,7 +343,7 @@
   wait = true;
   // Create all of the threads and have them do the GetElf at the same time
   // to make it likely that a race will occur.
-  MapInfo info(nullptr, 0x7000, 0x8000, 0x1000, PROT_READ, "");
+  MapInfo info(nullptr, nullptr, 0x7000, 0x8000, 0x1000, PROT_READ, "");
   for (size_t i = 0; i < kNumConcurrentThreads; i++) {
     std::thread* thread = new std::thread([i, this, &wait, &info, &elf_in_threads]() {
       while (wait)
@@ -373,8 +373,8 @@
 
 // Verify that previous maps don't automatically get the same elf object.
 TEST_F(MapInfoGetElfTest, prev_map_elf_not_set) {
-  MapInfo info1(nullptr, 0x1000, 0x2000, 0, PROT_READ, "/not/present");
-  MapInfo info2(&info1, 0x2000, 0x3000, 0, PROT_READ, elf_.path);
+  MapInfo info1(nullptr, nullptr, 0x1000, 0x2000, 0, PROT_READ, "/not/present");
+  MapInfo info2(&info1, &info1, 0x2000, 0x3000, 0, PROT_READ, elf_.path);
 
   Elf32_Ehdr ehdr;
   TestInitEhdr<Elf32_Ehdr>(&ehdr, ELFCLASS32, EM_ARM);
@@ -389,8 +389,25 @@
 // Verify that a read-only map followed by a read-execute map will result
 // in the same elf object in both maps.
 TEST_F(MapInfoGetElfTest, read_only_followed_by_read_exec_share_elf) {
-  MapInfo r_info(nullptr, 0x1000, 0x2000, 0, PROT_READ, elf_.path);
-  MapInfo rw_info(&r_info, 0x2000, 0x3000, 0x1000, PROT_READ | PROT_EXEC, elf_.path);
+  MapInfo r_info(nullptr, nullptr, 0x1000, 0x2000, 0, PROT_READ, elf_.path);
+  MapInfo rw_info(&r_info, &r_info, 0x2000, 0x3000, 0x1000, PROT_READ | PROT_EXEC, elf_.path);
+
+  Elf32_Ehdr ehdr;
+  TestInitEhdr<Elf32_Ehdr>(&ehdr, ELFCLASS32, EM_ARM);
+  memory_->SetMemory(0x1000, &ehdr, sizeof(ehdr));
+  Elf* elf = rw_info.GetElf(process_memory_, ARCH_ARM);
+  ASSERT_TRUE(elf != nullptr);
+  ASSERT_TRUE(elf->valid());
+
+  ASSERT_EQ(elf, r_info.GetElf(process_memory_, ARCH_ARM));
+}
+
+// Verify that a read-only map followed by an empty map, then followed by
+// a read-execute map will result in the same elf object in both maps.
+TEST_F(MapInfoGetElfTest, read_only_followed_by_empty_then_read_exec_share_elf) {
+  MapInfo r_info(nullptr, nullptr, 0x1000, 0x2000, 0, PROT_READ, elf_.path);
+  MapInfo empty(&r_info, &r_info, 0x2000, 0x3000, 0, 0, "");
+  MapInfo rw_info(&empty, &r_info, 0x3000, 0x4000, 0x2000, PROT_READ | PROT_EXEC, elf_.path);
 
   Elf32_Ehdr ehdr;
   TestInitEhdr<Elf32_Ehdr>(&ehdr, ELFCLASS32, EM_ARM);
diff --git a/libunwindstack/tests/MapInfoGetLoadBiasTest.cpp b/libunwindstack/tests/MapInfoGetLoadBiasTest.cpp
index da3dbf2..971d452 100644
--- a/libunwindstack/tests/MapInfoGetLoadBiasTest.cpp
+++ b/libunwindstack/tests/MapInfoGetLoadBiasTest.cpp
@@ -50,7 +50,7 @@
     process_memory_.reset(memory_);
     elf_ = new ElfFake(new MemoryFake);
     elf_container_.reset(elf_);
-    map_info_.reset(new MapInfo(nullptr, 0x1000, 0x20000, 0, PROT_READ | PROT_WRITE, ""));
+    map_info_.reset(new MapInfo(nullptr, nullptr, 0x1000, 0x20000, 0, PROT_READ | PROT_WRITE, ""));
   }
 
   void MultipleThreadTest(uint64_t expected_load_bias);
@@ -63,7 +63,7 @@
 };
 
 TEST_F(MapInfoGetLoadBiasTest, no_elf_and_no_valid_elf_in_memory) {
-  MapInfo info(nullptr, 0x1000, 0x2000, 0, PROT_READ, "");
+  MapInfo info(nullptr, nullptr, 0x1000, 0x2000, 0, PROT_READ, "");
 
   EXPECT_EQ(0U, info.GetLoadBias(process_memory_));
 }
diff --git a/libunwindstack/tests/MapInfoTest.cpp b/libunwindstack/tests/MapInfoTest.cpp
index ef76b1b..98edc0e 100644
--- a/libunwindstack/tests/MapInfoTest.cpp
+++ b/libunwindstack/tests/MapInfoTest.cpp
@@ -26,8 +26,8 @@
 namespace unwindstack {
 
 TEST(MapInfoTest, maps_constructor_const_char) {
-  MapInfo prev_map(nullptr, 0, 0, 0, 0, "");
-  MapInfo map_info(&prev_map, 1, 2, 3, 4, "map");
+  MapInfo prev_map(nullptr, nullptr, 0, 0, 0, 0, "");
+  MapInfo map_info(&prev_map, &prev_map, 1, 2, 3, 4, "map");
 
   EXPECT_EQ(&prev_map, map_info.prev_map);
   EXPECT_EQ(1UL, map_info.start);
@@ -42,8 +42,8 @@
 
 TEST(MapInfoTest, maps_constructor_string) {
   std::string name("string_map");
-  MapInfo prev_map(nullptr, 0, 0, 0, 0, "");
-  MapInfo map_info(&prev_map, 1, 2, 3, 4, name);
+  MapInfo prev_map(nullptr, nullptr, 0, 0, 0, 0, "");
+  MapInfo map_info(&prev_map, &prev_map, 1, 2, 3, 4, name);
 
   EXPECT_EQ(&prev_map, map_info.prev_map);
   EXPECT_EQ(1UL, map_info.start);
@@ -62,7 +62,7 @@
   elf->FakeSetInterface(interface);
   interface->FakePushFunctionData(FunctionData("function", 1000));
 
-  MapInfo map_info(nullptr, 1, 2, 3, 4, "");
+  MapInfo map_info(nullptr, nullptr, 1, 2, 3, 4, "");
   map_info.elf.reset(elf);
 
   std::string name;
diff --git a/libunwindstack/tests/MapsTest.cpp b/libunwindstack/tests/MapsTest.cpp
index 9e7a6ab..724eeb5 100644
--- a/libunwindstack/tests/MapsTest.cpp
+++ b/libunwindstack/tests/MapsTest.cpp
@@ -82,7 +82,7 @@
 }
 
 TEST(MapsTest, verify_parse_line) {
-  MapInfo info(nullptr, 0, 0, 0, 0, "");
+  MapInfo info(nullptr, nullptr, 0, 0, 0, 0, "");
 
   VerifyLine("01-02 rwxp 03 04:05 06\n", &info);
   EXPECT_EQ(1U, info.start);
@@ -155,7 +155,7 @@
 }
 
 TEST(MapsTest, verify_large_values) {
-  MapInfo info(nullptr, 0, 0, 0, 0, "");
+  MapInfo info(nullptr, nullptr, 0, 0, 0, 0, "");
 #if defined(__LP64__)
   VerifyLine("fabcdef012345678-f12345678abcdef8 rwxp f0b0d0f010305070 00:00 0\n", &info);
   EXPECT_EQ(0xfabcdef012345678UL, info.start);
diff --git a/libunwindstack/tests/RegsIterateTest.cpp b/libunwindstack/tests/RegsIterateTest.cpp
index bc95851..47e605a 100644
--- a/libunwindstack/tests/RegsIterateTest.cpp
+++ b/libunwindstack/tests/RegsIterateTest.cpp
@@ -111,8 +111,8 @@
   result.push_back({"x27", ARM64_REG_R27});
   result.push_back({"x28", ARM64_REG_R28});
   result.push_back({"x29", ARM64_REG_R29});
-  result.push_back({"sp", ARM64_REG_SP});
   result.push_back({"lr", ARM64_REG_LR});
+  result.push_back({"sp", ARM64_REG_SP});
   result.push_back({"pc", ARM64_REG_PC});
   result.push_back({"pst", ARM64_REG_PSTATE});
   return result;
diff --git a/libunwindstack/tests/RegsTest.cpp b/libunwindstack/tests/RegsTest.cpp
index 472d1cf..0a33e2f 100644
--- a/libunwindstack/tests/RegsTest.cpp
+++ b/libunwindstack/tests/RegsTest.cpp
@@ -182,7 +182,7 @@
   RegsX86_64 regs_x86_64;
   RegsMips regs_mips;
   RegsMips64 regs_mips64;
-  MapInfo map_info(nullptr, 0x1000, 0x2000, 0, 0, "");
+  MapInfo map_info(nullptr, nullptr, 0x1000, 0x2000, 0, 0, "");
   Elf* invalid_elf = new Elf(nullptr);
   map_info.elf.reset(invalid_elf);
 
diff --git a/libunwindstack/tests/UnwindOfflineTest.cpp b/libunwindstack/tests/UnwindOfflineTest.cpp
index 364101a..c2bd836 100644
--- a/libunwindstack/tests/UnwindOfflineTest.cpp
+++ b/libunwindstack/tests/UnwindOfflineTest.cpp
@@ -169,15 +169,18 @@
 };
 
 std::unordered_map<std::string, uint32_t> UnwindOfflineTest::arm64_regs_ = {
-    {"x0", ARM64_REG_R0},   {"x1", ARM64_REG_R1},   {"x2", ARM64_REG_R2},   {"x3", ARM64_REG_R3},
-    {"x4", ARM64_REG_R4},   {"x5", ARM64_REG_R5},   {"x6", ARM64_REG_R6},   {"x7", ARM64_REG_R7},
-    {"x8", ARM64_REG_R8},   {"x9", ARM64_REG_R9},   {"x10", ARM64_REG_R10}, {"x11", ARM64_REG_R11},
-    {"x12", ARM64_REG_R12}, {"x13", ARM64_REG_R13}, {"x14", ARM64_REG_R14}, {"x15", ARM64_REG_R15},
-    {"x16", ARM64_REG_R16}, {"x17", ARM64_REG_R17}, {"x18", ARM64_REG_R18}, {"x19", ARM64_REG_R19},
-    {"x20", ARM64_REG_R20}, {"x21", ARM64_REG_R21}, {"x22", ARM64_REG_R22}, {"x23", ARM64_REG_R23},
-    {"x24", ARM64_REG_R24}, {"x25", ARM64_REG_R25}, {"x26", ARM64_REG_R26}, {"x27", ARM64_REG_R27},
-    {"x28", ARM64_REG_R28}, {"x29", ARM64_REG_R29}, {"sp", ARM64_REG_SP},   {"lr", ARM64_REG_LR},
-    {"pc", ARM64_REG_PC},
+    {"x0", ARM64_REG_R0},      {"x1", ARM64_REG_R1},   {"x2", ARM64_REG_R2},
+    {"x3", ARM64_REG_R3},      {"x4", ARM64_REG_R4},   {"x5", ARM64_REG_R5},
+    {"x6", ARM64_REG_R6},      {"x7", ARM64_REG_R7},   {"x8", ARM64_REG_R8},
+    {"x9", ARM64_REG_R9},      {"x10", ARM64_REG_R10}, {"x11", ARM64_REG_R11},
+    {"x12", ARM64_REG_R12},    {"x13", ARM64_REG_R13}, {"x14", ARM64_REG_R14},
+    {"x15", ARM64_REG_R15},    {"x16", ARM64_REG_R16}, {"x17", ARM64_REG_R17},
+    {"x18", ARM64_REG_R18},    {"x19", ARM64_REG_R19}, {"x20", ARM64_REG_R20},
+    {"x21", ARM64_REG_R21},    {"x22", ARM64_REG_R22}, {"x23", ARM64_REG_R23},
+    {"x24", ARM64_REG_R24},    {"x25", ARM64_REG_R25}, {"x26", ARM64_REG_R26},
+    {"x27", ARM64_REG_R27},    {"x28", ARM64_REG_R28}, {"x29", ARM64_REG_R29},
+    {"sp", ARM64_REG_SP},      {"lr", ARM64_REG_LR},   {"pc", ARM64_REG_PC},
+    {"pst", ARM64_REG_PSTATE},
 };
 
 std::unordered_map<std::string, uint32_t> UnwindOfflineTest::x86_regs_ = {
@@ -1697,4 +1700,40 @@
   EXPECT_EQ(0xffe67d10ULL, unwinder.frames()[16].sp);
 }
 
+TEST_F(UnwindOfflineTest, empty_arm64) {
+  ASSERT_NO_FATAL_FAILURE(Init("empty_arm64/", ARCH_ARM64));
+
+  Unwinder unwinder(128, maps_.get(), regs_.get(), process_memory_);
+  unwinder.Unwind();
+
+  std::string frame_info(DumpFrames(unwinder));
+  ASSERT_EQ(7U, unwinder.NumFrames()) << "Unwind:\n" << frame_info;
+  EXPECT_EQ(
+      "  #00 pc 00000000000963a4  libc.so (__ioctl+4)\n"
+      "  #01 pc 000000000005344c  libc.so (ioctl+140)\n"
+      "  #02 pc 0000000000050ce4  libbinder.so "
+      "(android::IPCThreadState::talkWithDriver(bool)+308)\n"
+      "  #03 pc 0000000000050e98  libbinder.so "
+      "(android::IPCThreadState::getAndExecuteCommand()+24)\n"
+      "  #04 pc 00000000000516ac  libbinder.so (android::IPCThreadState::joinThreadPool(bool)+60)\n"
+      "  #05 pc 00000000000443b0  netd (main+1056)\n"
+      "  #06 pc 0000000000045594  libc.so (__libc_init+108)\n",
+      frame_info);
+
+  EXPECT_EQ(0x72a02203a4U, unwinder.frames()[0].pc);
+  EXPECT_EQ(0x7ffb6c0b50U, unwinder.frames()[0].sp);
+  EXPECT_EQ(0x72a01dd44cU, unwinder.frames()[1].pc);
+  EXPECT_EQ(0x7ffb6c0b50U, unwinder.frames()[1].sp);
+  EXPECT_EQ(0x729f759ce4U, unwinder.frames()[2].pc);
+  EXPECT_EQ(0x7ffb6c0c50U, unwinder.frames()[2].sp);
+  EXPECT_EQ(0x729f759e98U, unwinder.frames()[3].pc);
+  EXPECT_EQ(0x7ffb6c0ce0U, unwinder.frames()[3].sp);
+  EXPECT_EQ(0x729f75a6acU, unwinder.frames()[4].pc);
+  EXPECT_EQ(0x7ffb6c0d10U, unwinder.frames()[4].sp);
+  EXPECT_EQ(0x5d478af3b0U, unwinder.frames()[5].pc);
+  EXPECT_EQ(0x7ffb6c0d40U, unwinder.frames()[5].sp);
+  EXPECT_EQ(0x72a01cf594U, unwinder.frames()[6].pc);
+  EXPECT_EQ(0x7ffb6c0f30U, unwinder.frames()[6].sp);
+}
+
 }  // namespace unwindstack
diff --git a/libunwindstack/tests/files/offline/empty_arm64/libbinder.so b/libunwindstack/tests/files/offline/empty_arm64/libbinder.so
new file mode 100644
index 0000000..f30384c
--- /dev/null
+++ b/libunwindstack/tests/files/offline/empty_arm64/libbinder.so
Binary files differ
diff --git a/libunwindstack/tests/files/offline/empty_arm64/libc.so b/libunwindstack/tests/files/offline/empty_arm64/libc.so
new file mode 100644
index 0000000..b05dcaf
--- /dev/null
+++ b/libunwindstack/tests/files/offline/empty_arm64/libc.so
Binary files differ
diff --git a/libunwindstack/tests/files/offline/empty_arm64/maps.txt b/libunwindstack/tests/files/offline/empty_arm64/maps.txt
new file mode 100644
index 0000000..edb83c6
--- /dev/null
+++ b/libunwindstack/tests/files/offline/empty_arm64/maps.txt
@@ -0,0 +1,9 @@
+5d4786b000-5d47893000 r--p 0 00:00 0   netd
+5d47893000-5d47894000 ---p 0 00:00 0
+5d47894000-5d47901000 --xp 29000 00:00 0   netd
+729f709000-729f750000 r--p 0 00:00 0   libbinder.so
+729f750000-729f751000 ---p 0 00:00 0
+729f751000-729f794000 --xp 48000 00:00 0   libbinder.so
+72a018a000-72a01c2000 r--p 0 00:00 0   libc.so
+72a01c2000-72a01c3000 ---p 0 00:00 0
+72a01c3000-72a023b000 --xp 39000 00:00 0   libc.so
diff --git a/libunwindstack/tests/files/offline/empty_arm64/netd b/libunwindstack/tests/files/offline/empty_arm64/netd
new file mode 100644
index 0000000..8a72e94
--- /dev/null
+++ b/libunwindstack/tests/files/offline/empty_arm64/netd
Binary files differ
diff --git a/libunwindstack/tests/files/offline/empty_arm64/regs.txt b/libunwindstack/tests/files/offline/empty_arm64/regs.txt
new file mode 100644
index 0000000..3d4279f
--- /dev/null
+++ b/libunwindstack/tests/files/offline/empty_arm64/regs.txt
@@ -0,0 +1,34 @@
+x0: 1d
+x1: c0306201
+x2: 7ffb6c0c50
+x3: 0
+x4: 0
+x5: 0
+x6: 0
+x7: 0
+x8: 1d
+x9: 7ffb6c0c00
+x10: 7ffb6c0c50
+x11: 7ffb6c0bd0
+x12: ffffff80ffffffd0
+x13: 0
+x14: 72a0240ce2
+x15: 20
+x16: 729f7a54e8
+x17: 72a01dd3c0
+x18: 72a0ac2000
+x19: 72a0666000
+x20: 719769b610
+x21: 719769b730
+x22: c0306201
+x23: fffffff7
+x24: 72a0666000
+x25: 0
+x26: 0
+x27: 0
+x28: 0
+x29: 7ffb6c0c30
+sp: 7ffb6c0b50
+lr: 72a01dd450
+pc: 72a02203a4
+pst: a0000000
diff --git a/libunwindstack/tests/files/offline/empty_arm64/stack.data b/libunwindstack/tests/files/offline/empty_arm64/stack.data
new file mode 100644
index 0000000..6d6108c
--- /dev/null
+++ b/libunwindstack/tests/files/offline/empty_arm64/stack.data
Binary files differ
diff --git a/logcat/logcat.cpp b/logcat/logcat.cpp
index 7b18438..08e3d22 100644
--- a/logcat/logcat.cpp
+++ b/logcat/logcat.cpp
@@ -110,7 +110,7 @@
 #endif
 
 static int openLogFile(const char* pathname, size_t sizeKB) {
-    int fd = open(pathname, O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR);
+    int fd = open(pathname, O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR | S_IRGRP);
     if (fd < 0) {
         return fd;
     }
diff --git a/logcat/logcatd b/logcat/logcatd
index 622e567..5a1415d 100755
--- a/logcat/logcatd
+++ b/logcat/logcatd
@@ -4,6 +4,10 @@
 # first reads the 'last' logcat to persistent storage with `-L` then run logcat again without
 # `-L` to read the current logcat buffers to persistent storage.
 
+# init sets the umask to 077 for forked processes. logpersist needs to create files that are group
+# readable. So relax the umask to only disallow group wx and world rwx.
+umask 037
+
 has_last="false"
 for arg in "$@"; do
   if [ "$arg" == "-L" -o "$arg" == "--last" ]; then
diff --git a/logcat/logcatd.rc b/logcat/logcatd.rc
index e986184..64d5500 100644
--- a/logcat/logcatd.rc
+++ b/logcat/logcatd.rc
@@ -30,8 +30,8 @@
     setprop logd.logpersistd.enable true
 
 on property:logd.logpersistd.enable=true && property:logd.logpersistd=logcatd
-    # all exec/services are called with umask(077), so no gain beyond 0700
-    mkdir /data/misc/logd 0700 logd log
+    # log group should be able to read persisted logs
+    mkdir /data/misc/logd 0750 logd log
     start logcatd
 
 # stop logcatd service and clear data
diff --git a/logd/logtagd.rc b/logd/logtagd.rc
index 46aa8c1..248a78c 100644
--- a/logd/logtagd.rc
+++ b/logd/logtagd.rc
@@ -2,7 +2,7 @@
 # logtagd event log tag service (debug only)
 #
 on post-fs-data
-    mkdir /data/misc/logd 0700 logd log
+    mkdir /data/misc/logd 0750 logd log
     write /data/misc/logd/event-log-tags ""
     chown logd log /data/misc/logd/event-log-tags
     chmod 0600 /data/misc/logd/event-log-tags
diff --git a/property_service/libpropertyinfoparser/Android.bp b/property_service/libpropertyinfoparser/Android.bp
index ac802b5..108d15a 100644
--- a/property_service/libpropertyinfoparser/Android.bp
+++ b/property_service/libpropertyinfoparser/Android.bp
@@ -2,6 +2,7 @@
     name: "libpropertyinfoparser",
     host_supported: true,
     vendor_available: true,
+    ramdisk_available: true,
     recovery_available: true,
     native_bridge_supported: true,
     srcs: ["property_info_parser.cpp"],
diff --git a/rootdir/Android.mk b/rootdir/Android.mk
index 5821379..a9d0ed0 100644
--- a/rootdir/Android.mk
+++ b/rootdir/Android.mk
@@ -67,6 +67,11 @@
   EXPORT_GLOBAL_GCOV_OPTIONS := export GCOV_PREFIX /data/misc/trace
 endif
 
+EXPORT_GLOBAL_CLANG_COVERAGE_OPTIONS :=
+ifeq ($(CLANG_COVERAGE),true)
+  EXPORT_GLOBAL_CLANG_COVERAGE_OPTIONS := export LLVM_PROFILE_FILE /data/misc/trace/clang-%p-%m.profraw
+endif
+
 # Put it here instead of in init.rc module definition,
 # because init.rc is conditionally included.
 #
@@ -147,6 +152,7 @@
 	$(hide) sed -i -e 's?%SYSTEMSERVERCLASSPATH%?$(PRODUCT_SYSTEM_SERVER_CLASSPATH)?g' $@
 	$(hide) sed -i -e 's?%EXPORT_GLOBAL_ASAN_OPTIONS%?$(EXPORT_GLOBAL_ASAN_OPTIONS)?g' $@
 	$(hide) sed -i -e 's?%EXPORT_GLOBAL_GCOV_OPTIONS%?$(EXPORT_GLOBAL_GCOV_OPTIONS)?g' $@
+	$(hide) sed -i -e 's?%EXPORT_GLOBAL_CLANG_COVERAGE_OPTIONS%?$(EXPORT_GLOBAL_CLANG_COVERAGE_OPTIONS)?g' $@
 	$(hide) sed -i -e 's?%EXPORT_GLOBAL_HWASAN_OPTIONS%?$(EXPORT_GLOBAL_HWASAN_OPTIONS)?g' $@
 
 # Append PLATFORM_VNDK_VERSION to base name.
diff --git a/rootdir/init.environ.rc.in b/rootdir/init.environ.rc.in
index 50005d9..fdaaf1a 100644
--- a/rootdir/init.environ.rc.in
+++ b/rootdir/init.environ.rc.in
@@ -15,4 +15,5 @@
     export SYSTEMSERVERCLASSPATH %SYSTEMSERVERCLASSPATH%
     %EXPORT_GLOBAL_ASAN_OPTIONS%
     %EXPORT_GLOBAL_GCOV_OPTIONS%
+    %EXPORT_GLOBAL_CLANG_COVERAGE_OPTIONS%
     %EXPORT_GLOBAL_HWASAN_OPTIONS%
diff --git a/rootdir/init.rc b/rootdir/init.rc
index 6a6169c..5f4b8c3 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -165,7 +165,7 @@
     mkdir /mnt/secure/asec 0700 root root
     mkdir /mnt/asec 0755 root system
     mkdir /mnt/obb 0755 root system
-    mkdir /mnt/media_rw 0750 root media_rw
+    mkdir /mnt/media_rw 0750 root external_storage
     mkdir /mnt/user 0755 root root
     mkdir /mnt/user/0 0755 root root
     mkdir /mnt/user/0/self 0755 root root
@@ -173,7 +173,7 @@
     mkdir /mnt/user/0/emulated/0 0755 root root
 
     # Prepare directories for pass through processes
-    mkdir /mnt/pass_through 0755 root root
+    mkdir /mnt/pass_through 0700 root root
     mkdir /mnt/pass_through/0 0755 root root
     mkdir /mnt/pass_through/0/self 0755 root root
     mkdir /mnt/pass_through/0/emulated 0755 root root
@@ -489,6 +489,7 @@
 on late-fs
     # Ensure that tracefs has the correct permissions.
     # This does not work correctly if it is called in post-fs.
+    chmod 0755 /sys/kernel/tracing
     chmod 0755 /sys/kernel/debug/tracing
 
     # HALs required before storage encryption can get unlocked (FBE/FDE)
@@ -1012,6 +1013,7 @@
   setprop apexd.status ""
   setprop sys.user.0.ce_available ""
   setprop sys.shutdown.requested ""
+  setprop service.bootanim.exit ""
 
 on userspace-reboot-fs-remount
   # Make sure that vold is running.
@@ -1021,6 +1023,7 @@
   exec - system system -- /system/bin/vdc checkpoint resetCheckpoint
   exec - system system -- /system/bin/vdc checkpoint markBootAttempt
   remount_userdata
+  start bootanim
 
 on userspace-reboot-resume
   trigger userspace-reboot-fs-remount
diff --git a/set-verity-state/Android.bp b/set-verity-state/Android.bp
index cd8c8c5..da112c9 100644
--- a/set-verity-state/Android.bp
+++ b/set-verity-state/Android.bp
@@ -9,8 +9,9 @@
         "libcrypto_utils",
         "libcutils",
         "libfec",
-        "libfs_mgr",
+        "libfs_mgr_binder",
         "liblog",
+        "libutils",
     ],
     static_libs: [
         "libavb_user",