Merge "ld.config for com.android.neuralnetworks APEX."
diff --git a/adb/client/usb_linux.cpp b/adb/client/usb_linux.cpp
index 81b8306..17b4db1 100644
--- a/adb/client/usb_linux.cpp
+++ b/adb/client/usb_linux.cpp
@@ -324,7 +324,7 @@
 
     h->urb_out_busy = true;
     while (true) {
-        auto now = std::chrono::system_clock::now();
+        auto now = std::chrono::steady_clock::now();
         if (h->cv.wait_until(lock, now + 5s) == std::cv_status::timeout || h->dead) {
             // TODO: call USBDEVFS_DISCARDURB?
             errno = ETIMEDOUT;
diff --git a/debuggerd/client/debuggerd_client.cpp b/debuggerd/client/debuggerd_client.cpp
index 60eb241..1a5b435 100644
--- a/debuggerd/client/debuggerd_client.cpp
+++ b/debuggerd/client/debuggerd_client.cpp
@@ -22,9 +22,11 @@
 #include <sys/poll.h>
 #include <sys/stat.h>
 #include <sys/types.h>
+#include <time.h>
 #include <unistd.h>
 
 #include <chrono>
+#include <iomanip>
 
 #include <android-base/cmsg.h>
 #include <android-base/file.h>
@@ -42,8 +44,10 @@
 
 using namespace std::chrono_literals;
 
+using android::base::ReadFileToString;
 using android::base::SendFileDescriptors;
 using android::base::unique_fd;
+using android::base::WriteStringToFd;
 
 static bool send_signal(pid_t pid, const DebuggerdDumpType dump_type) {
   const int signal = (dump_type == kDebuggerdJavaBacktrace) ? SIGQUIT : DEBUGGER_SIGNAL;
@@ -65,6 +69,76 @@
   tv->tv_usec = static_cast<long>(microseconds.count());
 }
 
+static void get_wchan_header(pid_t pid, std::stringstream& buffer) {
+  struct tm now;
+  time_t t = time(nullptr);
+  localtime_r(&t, &now);
+  char timestamp[32];
+  strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", &now);
+  std::string time_now(timestamp);
+
+  std::string path = "/proc/" + std::to_string(pid) + "/cmdline";
+
+  char proc_name_buf[1024];
+  const char* proc_name = nullptr;
+  std::unique_ptr<FILE, decltype(&fclose)> fp(fopen(path.c_str(), "r"), &fclose);
+
+  if (fp) {
+    proc_name = fgets(proc_name_buf, sizeof(proc_name_buf), fp.get());
+  }
+
+  if (!proc_name) {
+    proc_name = "<unknown>";
+  }
+
+  buffer << "\n----- Waiting Channels: pid " << pid << " at " << time_now << " -----\n"
+         << "Cmd line: " << proc_name << "\n";
+}
+
+static void get_wchan_footer(pid_t pid, std::stringstream& buffer) {
+  buffer << "----- end " << std::to_string(pid) << " -----\n";
+}
+
+/**
+ * Returns the wchan data for each thread in the process,
+ * or empty string if unable to obtain any data.
+ */
+static std::string get_wchan_data(pid_t pid) {
+  std::stringstream buffer;
+  std::vector<pid_t> tids;
+
+  if (!android::procinfo::GetProcessTids(pid, &tids)) {
+    LOG(WARNING) << "libdebuggerd_client: Failed to get process tids";
+    return buffer.str();
+  }
+
+  std::stringstream data;
+  for (int tid : tids) {
+    std::string path = "/proc/" + std::to_string(pid) + "/task/" + std::to_string(tid) + "/wchan";
+    std::string wchan_str;
+    if (!ReadFileToString(path, &wchan_str, true)) {
+      PLOG(WARNING) << "libdebuggerd_client: Failed to read \"" << path << "\"";
+      continue;
+    }
+    data << "sysTid=" << std::left << std::setw(10) << tid << wchan_str << "\n";
+  }
+
+  if (std::string str = data.str(); !str.empty()) {
+    get_wchan_header(pid, buffer);
+    buffer << "\n" << str << "\n";
+    get_wchan_footer(pid, buffer);
+    buffer << "\n";
+  }
+
+  return buffer.str();
+}
+
+static void dump_wchan_data(const std::string& data, int fd, pid_t pid) {
+  if (!WriteStringToFd(data, fd)) {
+    LOG(WARNING) << "libdebuggerd_client: Failed to dump wchan data for pid: " << pid;
+  }
+}
+
 bool debuggerd_trigger_dump(pid_t tid, DebuggerdDumpType dump_type, unsigned int timeout_ms,
                             unique_fd output_fd) {
   pid_t pid = tid;
@@ -261,6 +335,17 @@
   if (copy == -1) {
     return -1;
   }
+
+  // debuggerd_trigger_dump results in every thread in the process being interrupted
+  // by a signal, so we need to fetch the wchan data before calling that.
+  std::string wchan_data = get_wchan_data(tid);
+
   int timeout_ms = timeout_secs > 0 ? timeout_secs * 1000 : 0;
-  return debuggerd_trigger_dump(tid, dump_type, timeout_ms, std::move(copy)) ? 0 : -1;
+  int ret = debuggerd_trigger_dump(tid, dump_type, timeout_ms, std::move(copy)) ? 0 : -1;
+
+  // Dump wchan data, since only privileged processes (CAP_SYS_ADMIN) can read
+  // kernel stack traces (/proc/*/stack).
+  dump_wchan_data(wchan_data, fd, tid);
+
+  return ret;
 }
diff --git a/debuggerd/debuggerd_test.cpp b/debuggerd/debuggerd_test.cpp
index 1f0e420..fbc8b97 100644
--- a/debuggerd/debuggerd_test.cpp
+++ b/debuggerd/debuggerd_test.cpp
@@ -1099,3 +1099,30 @@
   // This should be good enough, though...
   ASSERT_LT(diff, 10) << "too many new tombstones; is something crashing in the background?";
 }
+
+static __attribute__((__noinline__)) void overflow_stack(void* p) {
+  void* buf[1];
+  buf[0] = p;
+  static volatile void* global = buf;
+  if (global) {
+    global = buf;
+    overflow_stack(&buf);
+  }
+}
+
+TEST_F(CrasherTest, stack_overflow) {
+  int intercept_result;
+  unique_fd output_fd;
+  StartProcess([]() { overflow_stack(nullptr); });
+
+  StartIntercept(&output_fd);
+  FinishCrasher();
+  AssertDeath(SIGSEGV);
+  FinishIntercept(&intercept_result);
+
+  ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
+
+  std::string result;
+  ConsumeFd(std::move(output_fd), &result);
+  ASSERT_MATCH(result, R"(Cause: stack pointer[^\n]*stack overflow.\n)");
+}
diff --git a/debuggerd/libdebuggerd/tombstone.cpp b/debuggerd/libdebuggerd/tombstone.cpp
index d246722..da2ba58 100644
--- a/debuggerd/libdebuggerd/tombstone.cpp
+++ b/debuggerd/libdebuggerd/tombstone.cpp
@@ -86,7 +86,39 @@
   _LOG(log, logtype::HEADER, "Timestamp: %s\n", buf);
 }
 
-static void dump_probable_cause(log_t* log, const siginfo_t* si, unwindstack::Maps* maps) {
+static std::string get_stack_overflow_cause(uint64_t fault_addr, uint64_t sp,
+                                            unwindstack::Maps* maps) {
+  static constexpr uint64_t kMaxDifferenceBytes = 256;
+  uint64_t difference;
+  if (sp >= fault_addr) {
+    difference = sp - fault_addr;
+  } else {
+    difference = fault_addr - sp;
+  }
+  if (difference <= kMaxDifferenceBytes) {
+    // The faulting address is close to the current sp, check if the sp
+    // indicates a stack overflow.
+    // On arm, the sp does not get updated when the instruction faults.
+    // In this case, the sp will still be in a valid map, which is the
+    // last case below.
+    // On aarch64, the sp does get updated when the instruction faults.
+    // In this case, the sp will be in either an invalid map if triggered
+    // on the main thread, or in a guard map if in another thread, which
+    // will be the first case or second case from below.
+    unwindstack::MapInfo* map_info = maps->Find(sp);
+    if (map_info == nullptr) {
+      return "stack pointer is in a non-existent map; likely due to stack overflow.";
+    } else if ((map_info->flags & (PROT_READ | PROT_WRITE)) != (PROT_READ | PROT_WRITE)) {
+      return "stack pointer is not in a rw map; likely due to stack overflow.";
+    } else if ((sp - map_info->start) <= kMaxDifferenceBytes) {
+      return "stack pointer is close to top of stack; likely stack overflow.";
+    }
+  }
+  return "";
+}
+
+static void dump_probable_cause(log_t* log, const siginfo_t* si, unwindstack::Maps* maps,
+                                unwindstack::Regs* regs) {
   std::string cause;
   if (si->si_signo == SIGSEGV && si->si_code == SEGV_MAPERR) {
     if (si->si_addr < reinterpret_cast<void*>(4096)) {
@@ -101,11 +133,16 @@
       cause = "call to kuser_memory_barrier";
     } else if (si->si_addr == reinterpret_cast<void*>(0xffff0f60)) {
       cause = "call to kuser_cmpxchg64";
+    } else {
+      cause = get_stack_overflow_cause(reinterpret_cast<uint64_t>(si->si_addr), regs->sp(), maps);
     }
   } else if (si->si_signo == SIGSEGV && si->si_code == SEGV_ACCERR) {
-    unwindstack::MapInfo* map_info = maps->Find(reinterpret_cast<uint64_t>(si->si_addr));
+    uint64_t fault_addr = reinterpret_cast<uint64_t>(si->si_addr);
+    unwindstack::MapInfo* map_info = maps->Find(fault_addr);
     if (map_info != nullptr && map_info->flags == PROT_EXEC) {
       cause = "execute-only (no-read) memory access error; likely due to data in .text.";
+    } else {
+      cause = get_stack_overflow_cause(fault_addr, regs->sp(), maps);
     }
   } else if (si->si_signo == SIGSYS && si->si_code == SYS_SECCOMP) {
     cause = StringPrintf("seccomp prevented call to disallowed %s system call %d", ABI_STRING,
@@ -447,7 +484,7 @@
 
   if (thread_info.siginfo) {
     dump_signal_info(log, thread_info, unwinder->GetProcessMemory().get());
-    dump_probable_cause(log, thread_info.siginfo, unwinder->GetMaps());
+    dump_probable_cause(log, thread_info.siginfo, unwinder->GetMaps(), thread_info.registers.get());
   }
 
   if (primary_thread) {
diff --git a/demangle/.clang-format b/demangle/.clang-format
deleted file mode 120000
index fd0645f..0000000
--- a/demangle/.clang-format
+++ /dev/null
@@ -1 +0,0 @@
-../.clang-format-2
\ No newline at end of file
diff --git a/demangle/Android.bp b/demangle/Android.bp
deleted file mode 100644
index fd79cf8..0000000
--- a/demangle/Android.bp
+++ /dev/null
@@ -1,87 +0,0 @@
-//
-// Copyright (C) 2017 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.
-//
-
-cc_defaults {
-    name: "libdemangle_defaults",
-
-    host_supported: true,
-
-    cflags: [
-        "-Wall",
-        "-Werror",
-        "-Wextra",
-    ],
-
-    target: {
-        linux_bionic: {
-            enabled: true,
-        },
-    },
-}
-
-cc_library {
-    name: "libdemangle",
-    defaults: ["libdemangle_defaults"],
-    vendor_available: true,
-    recovery_available: true,
-
-    srcs: [
-        "Demangler.cpp",
-    ],
-
-    local_include_dirs: [
-        "include",
-    ],
-
-    export_include_dirs: [
-        "include",
-    ],
-}
-
-cc_binary {
-    name: "demangle",
-    defaults: ["libdemangle_defaults"],
-    srcs: ["demangle.cpp"],
-    host_supported: true,
-
-    shared_libs: ["libdemangle"],
-}
-
-//-------------------------------------------------------------------------
-// Unit Tests
-//-------------------------------------------------------------------------
-cc_test {
-    name: "libdemangle_test",
-    defaults: ["libdemangle_defaults"],
-
-    srcs: [
-        "DemangleTest.cpp",
-    ],
-
-    cflags: [
-        "-O0",
-        "-g",
-    ],
-
-    shared_libs: [
-        "libdemangle",
-    ],
-
-    test_suites: ["device-tests"],
-    required: [
-        "libdemangle",
-    ],
-}
diff --git a/demangle/Android.mk b/demangle/Android.mk
deleted file mode 100644
index d8082a9..0000000
--- a/demangle/Android.mk
+++ /dev/null
@@ -1,31 +0,0 @@
-#
-# Copyright (C) 2017 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.
-#
-
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := demangle_fuzzer
-LOCAL_SRC_FILES := \
-    Demangler.cpp \
-    demangle_fuzzer.cpp \
-
-LOCAL_CFLAGS := \
-    -Wall \
-    -Werror \
-    -Wextra \
-
-include $(BUILD_FUZZ_TEST)
diff --git a/demangle/DemangleTest.cpp b/demangle/DemangleTest.cpp
deleted file mode 100644
index 1787031..0000000
--- a/demangle/DemangleTest.cpp
+++ /dev/null
@@ -1,555 +0,0 @@
-/*
- * Copyright (C) 2017 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 <stdlib.h>
-
-#include <gtest/gtest.h>
-
-#include <demangle.h>
-
-#include "Demangler.h"
-
-TEST(DemangleTest, IllegalArgumentModifiers) {
-  Demangler demangler;
-
-  ASSERT_EQ("_Zpp4FUNKK", demangler.Parse("_Zpp4FUNKK"));
-  ASSERT_EQ("_Zpp4FUNVV", demangler.Parse("_Zpp4FUNVV"));
-}
-
-TEST(DemangleTest, VoidArgument) {
-  Demangler demangler;
-
-  ASSERT_EQ("func()", demangler.Parse("_ZN4funcEv"));
-  ASSERT_EQ("func(void&)", demangler.Parse("_ZN4funcERv"));
-  ASSERT_EQ("func(void, void)", demangler.Parse("_ZN4funcEvv"));
-  ASSERT_EQ("func(void*)", demangler.Parse("_ZN4funcEPv"));
-  ASSERT_EQ("func(void const)", demangler.Parse("_ZN4funcEKv"));
-  ASSERT_EQ("func(void volatile)", demangler.Parse("_ZN4funcEVv"));
-}
-
-TEST(DemangleTest, ArgumentModifiers) {
-  Demangler demangler;
-
-  ASSERT_EQ("func(char)", demangler.Parse("_ZN4funcEc"));
-  ASSERT_EQ("func(char*)", demangler.Parse("_ZN4funcEPc"));
-  ASSERT_EQ("func(char**)", demangler.Parse("_ZN4funcEPPc"));
-  ASSERT_EQ("func(char***)", demangler.Parse("_ZN4funcEPPPc"));
-  ASSERT_EQ("func(char&)", demangler.Parse("_ZN4funcERc"));
-  ASSERT_EQ("func(char*&)", demangler.Parse("_ZN4funcERPc"));
-  ASSERT_EQ("func(char&)", demangler.Parse("_ZN4funcERRc"));
-  ASSERT_EQ("func(char*&*)", demangler.Parse("_ZN4funcEPRPc"));
-  ASSERT_EQ("func(char**&)", demangler.Parse("_ZN4funcERRPPc"));
-  ASSERT_EQ("func(char const)", demangler.Parse("_ZN4funcEKc"));
-  ASSERT_EQ("func(char volatile)", demangler.Parse("_ZN4funcEVc"));
-  ASSERT_EQ("func(char volatile const)", demangler.Parse("_ZN4funcEKVc"));
-  ASSERT_EQ("func(char const volatile)", demangler.Parse("_ZN4funcEVKc"));
-  ASSERT_EQ("func(char const* volatile&)", demangler.Parse("_ZN4funcERVPKc"));
-  ASSERT_EQ("func(void, char, short)", demangler.Parse("_ZN4funcEvcs"));
-  ASSERT_EQ("func(void*, char&, short&*)", demangler.Parse("_ZN4funcEPvRcPRs"));
-}
-
-TEST(DemangleTest, FunctionModifiers) {
-  Demangler demangler;
-
-  ASSERT_EQ("func() const", demangler.Parse("_ZNK4funcEv"));
-  ASSERT_EQ("func() volatile", demangler.Parse("_ZNV4funcEv"));
-  ASSERT_EQ("func() volatile const", demangler.Parse("_ZNKV4funcEv"));
-  ASSERT_EQ("func() const volatile", demangler.Parse("_ZNVK4funcEv"));
-}
-
-TEST(DemangleTest, MultiplePartsInName) {
-  Demangler demangler;
-
-  ASSERT_EQ("one::two()", demangler.Parse("_ZN3one3twoEv"));
-  ASSERT_EQ("one::two::three()", demangler.Parse("_ZN3one3two5threeEv"));
-  ASSERT_EQ("one::two::three::four()", demangler.Parse("_ZN3one3two5three4fourEv"));
-  ASSERT_EQ("one::two::three::four::five()", demangler.Parse("_ZN3one3two5three4four4fiveEv"));
-  ASSERT_EQ("one(two::three::four::five)", demangler.Parse("_ZN3oneEN3two5three4four4fiveE"));
-}
-
-TEST(DemangleTest, AnonymousNamespace) {
-  Demangler demangler;
-
-  ASSERT_EQ("(anonymous namespace)::two()", demangler.Parse("_ZN12_GLOBAL__N_13twoEv"));
-  ASSERT_EQ("one::two((anonymous namespace))", demangler.Parse("_ZN3one3twoE12_GLOBAL__N_1"));
-}
-
-TEST(DemangleTest, DestructorValues) {
-  Demangler demangler;
-
-  ASSERT_EQ("one::two::~two()", demangler.Parse("_ZN3one3twoD0Ev"));
-  ASSERT_EQ("one::two::~two()", demangler.Parse("_ZN3one3twoD1Ev"));
-  ASSERT_EQ("one::two::~two()", demangler.Parse("_ZN3one3twoD2Ev"));
-  ASSERT_EQ("one::two::~two()", demangler.Parse("_ZN3one3twoD5Ev"));
-  ASSERT_EQ("one::two::three::~three()", demangler.Parse("_ZN3one3two5threeD0Ev"));
-
-  ASSERT_EQ("_ZN3one3twoD3Ev", demangler.Parse("_ZN3one3twoD3Ev"));
-  ASSERT_EQ("_ZN3one3twoD4Ev", demangler.Parse("_ZN3one3twoD4Ev"));
-  ASSERT_EQ("_ZN3one3twoD6Ev", demangler.Parse("_ZN3one3twoD6Ev"));
-  ASSERT_EQ("_ZN3one3twoD7Ev", demangler.Parse("_ZN3one3twoD7Ev"));
-  ASSERT_EQ("_ZN3one3twoD8Ev", demangler.Parse("_ZN3one3twoD8Ev"));
-  ASSERT_EQ("_ZN3one3twoD9Ev", demangler.Parse("_ZN3one3twoD9Ev"));
-
-  ASSERT_EQ("one::two<three::four>::~two()", demangler.Parse("_ZN3one3twoIN5three4fourEED2Ev"));
-}
-
-TEST(DemangleTest, ConstructorValues) {
-  Demangler demangler;
-
-  ASSERT_EQ("one::two::two()", demangler.Parse("_ZN3one3twoC1Ev"));
-  ASSERT_EQ("one::two::two()", demangler.Parse("_ZN3one3twoC2Ev"));
-  ASSERT_EQ("one::two::two()", demangler.Parse("_ZN3one3twoC3Ev"));
-  ASSERT_EQ("one::two::two()", demangler.Parse("_ZN3one3twoC5Ev"));
-  ASSERT_EQ("one::two::three::three()", demangler.Parse("_ZN3one3two5threeC1Ev"));
-
-  ASSERT_EQ("_ZN3one3twoC0Ev", demangler.Parse("_ZN3one3twoC0Ev"));
-  ASSERT_EQ("_ZN3one3twoC4Ev", demangler.Parse("_ZN3one3twoC4Ev"));
-  ASSERT_EQ("_ZN3one3twoC6Ev", demangler.Parse("_ZN3one3twoC6Ev"));
-  ASSERT_EQ("_ZN3one3twoC7Ev", demangler.Parse("_ZN3one3twoC7Ev"));
-  ASSERT_EQ("_ZN3one3twoC8Ev", demangler.Parse("_ZN3one3twoC8Ev"));
-  ASSERT_EQ("_ZN3one3twoC9Ev", demangler.Parse("_ZN3one3twoC9Ev"));
-
-  ASSERT_EQ("one::two<three::four>::two()", demangler.Parse("_ZN3one3twoIN5three4fourEEC1Ev"));
-}
-
-TEST(DemangleTest, OperatorValues) {
-  Demangler demangler;
-
-  ASSERT_EQ("operator&&()", demangler.Parse("_Zaav"));
-  ASSERT_EQ("operator&()", demangler.Parse("_Zadv"));
-  ASSERT_EQ("operator&()", demangler.Parse("_Zanv"));
-  ASSERT_EQ("operator&=()", demangler.Parse("_ZaNv"));
-  ASSERT_EQ("operator=()", demangler.Parse("_ZaSv"));
-  ASSERT_EQ("operator()()", demangler.Parse("_Zclv"));
-  ASSERT_EQ("operator,()", demangler.Parse("_Zcmv"));
-  ASSERT_EQ("operator~()", demangler.Parse("_Zcov"));
-  ASSERT_EQ("operator delete[]()", demangler.Parse("_Zdav"));
-  ASSERT_EQ("operator*()", demangler.Parse("_Zdev"));
-  ASSERT_EQ("operator delete()", demangler.Parse("_Zdlv"));
-  ASSERT_EQ("operator/()", demangler.Parse("_Zdvv"));
-  ASSERT_EQ("operator/=()", demangler.Parse("_ZdVv"));
-  ASSERT_EQ("operator^()", demangler.Parse("_Zeov"));
-  ASSERT_EQ("operator^=()", demangler.Parse("_ZeOv"));
-  ASSERT_EQ("operator==()", demangler.Parse("_Zeqv"));
-  ASSERT_EQ("operator>=()", demangler.Parse("_Zgev"));
-  ASSERT_EQ("operator>()", demangler.Parse("_Zgtv"));
-  ASSERT_EQ("operator[]()", demangler.Parse("_Zixv"));
-  ASSERT_EQ("operator<=()", demangler.Parse("_Zlev"));
-  ASSERT_EQ("operator<<()", demangler.Parse("_Zlsv"));
-  ASSERT_EQ("operator<<=()", demangler.Parse("_ZlSv"));
-  ASSERT_EQ("operator<()", demangler.Parse("_Zltv"));
-  ASSERT_EQ("operator-()", demangler.Parse("_Zmiv"));
-  ASSERT_EQ("operator-=()", demangler.Parse("_ZmIv"));
-  ASSERT_EQ("operator*()", demangler.Parse("_Zmlv"));
-  ASSERT_EQ("operator*=()", demangler.Parse("_ZmLv"));
-  ASSERT_EQ("operator--()", demangler.Parse("_Zmmv"));
-  ASSERT_EQ("operator new[]()", demangler.Parse("_Znav"));
-  ASSERT_EQ("operator!=()", demangler.Parse("_Znev"));
-  ASSERT_EQ("operator-()", demangler.Parse("_Zngv"));
-  ASSERT_EQ("operator!()", demangler.Parse("_Zntv"));
-  ASSERT_EQ("operator new()", demangler.Parse("_Znwv"));
-  ASSERT_EQ("operator||()", demangler.Parse("_Zoov"));
-  ASSERT_EQ("operator|()", demangler.Parse("_Zorv"));
-  ASSERT_EQ("operator|=()", demangler.Parse("_ZoRv"));
-  ASSERT_EQ("operator->*()", demangler.Parse("_Zpmv"));
-  ASSERT_EQ("operator+()", demangler.Parse("_Zplv"));
-  ASSERT_EQ("operator+=()", demangler.Parse("_ZpLv"));
-  ASSERT_EQ("operator++()", demangler.Parse("_Zppv"));
-  ASSERT_EQ("operator+()", demangler.Parse("_Zpsv"));
-  ASSERT_EQ("operator->()", demangler.Parse("_Zptv"));
-  ASSERT_EQ("operator?()", demangler.Parse("_Zquv"));
-  ASSERT_EQ("operator%()", demangler.Parse("_Zrmv"));
-  ASSERT_EQ("operator%=()", demangler.Parse("_ZrMv"));
-  ASSERT_EQ("operator>>()", demangler.Parse("_Zrsv"));
-  ASSERT_EQ("operator>>=()", demangler.Parse("_ZrSv"));
-
-  // Spot check using an operator as part of function name.
-  ASSERT_EQ("operator&&()", demangler.Parse("_ZNaaEv"));
-  ASSERT_EQ("operator++()", demangler.Parse("_ZNppEv"));
-  ASSERT_EQ("one::operator++()", demangler.Parse("_ZN3oneppEv"));
-
-  // Spot check using an operator in an argument name.
-  ASSERT_EQ("operator+(operator|=)", demangler.Parse("_ZNpsENoRE"));
-  ASSERT_EQ("operator==()", demangler.Parse("_Zeqv"));
-  ASSERT_EQ("one(arg1::operator|=, arg2::operator==)",
-            demangler.Parse("_ZN3oneEN4arg1oREN4arg2eqE"));
-}
-
-TEST(DemangleTest, FunctionStartsWithNumber) {
-  Demangler demangler;
-
-  ASSERT_EQ("value(char, int)", demangler.Parse("_Z5valueci"));
-  ASSERT_EQ("abcdefjklmn(signed char)", demangler.Parse("_Z11abcdefjklmna"));
-  ASSERT_EQ("value(one, signed char)", demangler.Parse("_Z5value3onea"));
-}
-
-TEST(DemangleTest, FunctionStartsWithLPlusNumber) {
-  Demangler demangler;
-
-  ASSERT_EQ("value(char, int)", demangler.Parse("_ZL5valueci"));
-  ASSERT_EQ("abcdefjklmn(signed char)", demangler.Parse("_ZL11abcdefjklmna"));
-  ASSERT_EQ("value(one, signed char)", demangler.Parse("_ZL5value3onea"));
-}
-
-TEST(DemangleTest, StdTypes) {
-  Demangler demangler;
-
-  ASSERT_EQ("std::one", demangler.Parse("_ZNSt3oneE"));
-  ASSERT_EQ("std::one(std::two)", demangler.Parse("_ZNSt3oneESt3two"));
-  ASSERT_EQ("std::std::one(std::two)", demangler.Parse("_ZNStSt3oneESt3two"));
-  ASSERT_EQ("std()", demangler.Parse("_ZNStEv"));
-  ASSERT_EQ("one::std::std::two::~two(one::std::std::two)",
-            demangler.Parse("_ZN3oneStSt3twoD0ES0_"));
-
-  ASSERT_EQ("std::allocator", demangler.Parse("_ZNSaE"));
-  ASSERT_EQ("std::basic_string", demangler.Parse("_ZNSbE"));
-  ASSERT_EQ("_ZNScE", demangler.Parse("_ZNScE"));
-  ASSERT_EQ("std::iostream", demangler.Parse("_ZNSdE"));
-  ASSERT_EQ("_ZNSeE", demangler.Parse("_ZNSeE"));
-  ASSERT_EQ("_ZNSfE", demangler.Parse("_ZNSfE"));
-  ASSERT_EQ("_ZNSgE", demangler.Parse("_ZNSgE"));
-  ASSERT_EQ("_ZNShE", demangler.Parse("_ZNShE"));
-  ASSERT_EQ("std::istream", demangler.Parse("_ZNSiE"));
-  ASSERT_EQ("_ZNSjE", demangler.Parse("_ZNSjE"));
-  ASSERT_EQ("_ZNSkE", demangler.Parse("_ZNSkE"));
-  ASSERT_EQ("_ZNSlE", demangler.Parse("_ZNSlE"));
-  ASSERT_EQ("_ZNSmE", demangler.Parse("_ZNSmE"));
-  ASSERT_EQ("_ZNSnE", demangler.Parse("_ZNSnE"));
-  ASSERT_EQ("std::ostream", demangler.Parse("_ZNSoE"));
-  ASSERT_EQ("_ZNSpE", demangler.Parse("_ZNSpE"));
-  ASSERT_EQ("_ZNSqE", demangler.Parse("_ZNSqE"));
-  ASSERT_EQ("_ZNSrE", demangler.Parse("_ZNSrE"));
-  ASSERT_EQ("std::string", demangler.Parse("_ZNSsE"));
-  ASSERT_EQ("_ZNSuE", demangler.Parse("_ZNSuE"));
-  ASSERT_EQ("_ZNSvE", demangler.Parse("_ZNSvE"));
-  ASSERT_EQ("_ZNSwE", demangler.Parse("_ZNSwE"));
-  ASSERT_EQ("_ZNSxE", demangler.Parse("_ZNSxE"));
-  ASSERT_EQ("_ZNSyE", demangler.Parse("_ZNSyE"));
-  ASSERT_EQ("_ZNSzE", demangler.Parse("_ZNSzE"));
-}
-
-TEST(DemangleTest, SingleLetterArguments) {
-  Demangler demangler;
-
-  ASSERT_EQ("func(signed char)", demangler.Parse("_ZN4funcEa"));
-  ASSERT_EQ("func(bool)", demangler.Parse("_ZN4funcEb"));
-  ASSERT_EQ("func(char)", demangler.Parse("_ZN4funcEc"));
-  ASSERT_EQ("func(double)", demangler.Parse("_ZN4funcEd"));
-  ASSERT_EQ("func(long double)", demangler.Parse("_ZN4funcEe"));
-  ASSERT_EQ("func(float)", demangler.Parse("_ZN4funcEf"));
-  ASSERT_EQ("func(__float128)", demangler.Parse("_ZN4funcEg"));
-  ASSERT_EQ("func(unsigned char)", demangler.Parse("_ZN4funcEh"));
-  ASSERT_EQ("func(int)", demangler.Parse("_ZN4funcEi"));
-  ASSERT_EQ("func(unsigned int)", demangler.Parse("_ZN4funcEj"));
-  ASSERT_EQ("_ZN4funcEk", demangler.Parse("_ZN4funcEk"));
-  ASSERT_EQ("func(long)", demangler.Parse("_ZN4funcEl"));
-  ASSERT_EQ("func(unsigned long)", demangler.Parse("_ZN4funcEm"));
-  ASSERT_EQ("func(__int128)", demangler.Parse("_ZN4funcEn"));
-  ASSERT_EQ("func(unsigned __int128)", demangler.Parse("_ZN4funcEo"));
-  ASSERT_EQ("_ZN4funcEp", demangler.Parse("_ZN4funcEp"));
-  ASSERT_EQ("_ZN4funcEq", demangler.Parse("_ZN4funcEq"));
-  ASSERT_EQ("_ZN4funcEr", demangler.Parse("_ZN4funcEr"));
-  ASSERT_EQ("func(short)", demangler.Parse("_ZN4funcEs"));
-  ASSERT_EQ("func(unsigned short)", demangler.Parse("_ZN4funcEt"));
-  ASSERT_EQ("_ZN4funcEu", demangler.Parse("_ZN4funcEu"));
-  ASSERT_EQ("func()", demangler.Parse("_ZN4funcEv"));
-  ASSERT_EQ("func(wchar_t)", demangler.Parse("_ZN4funcEw"));
-  ASSERT_EQ("func(long long)", demangler.Parse("_ZN4funcEx"));
-  ASSERT_EQ("func(unsigned long long)", demangler.Parse("_ZN4funcEy"));
-  ASSERT_EQ("func(...)", demangler.Parse("_ZN4funcEz"));
-}
-
-TEST(DemangleTest, DArguments) {
-  Demangler demangler;
-
-  ASSERT_EQ("func(auto)", demangler.Parse("_ZN4funcEDa"));
-  ASSERT_EQ("_ZN4funcEDb", demangler.Parse("_ZN4funcEDb"));
-  ASSERT_EQ("_ZN4funcEDc", demangler.Parse("_ZN4funcEDc"));
-  ASSERT_EQ("func(decimal64)", demangler.Parse("_ZN4funcEDd"));
-  ASSERT_EQ("func(decimal128)", demangler.Parse("_ZN4funcEDe"));
-  ASSERT_EQ("func(decimal32)", demangler.Parse("_ZN4funcEDf"));
-  ASSERT_EQ("_ZN4funcEDg", demangler.Parse("_ZN4funcEDg"));
-  ASSERT_EQ("func(half)", demangler.Parse("_ZN4funcEDh"));
-  ASSERT_EQ("func(char32_t)", demangler.Parse("_ZN4funcEDi"));
-  ASSERT_EQ("_ZN4funcEDj", demangler.Parse("_ZN4funcEDj"));
-  ASSERT_EQ("_ZN4funcEDk", demangler.Parse("_ZN4funcEDk"));
-  ASSERT_EQ("_ZN4funcEDl", demangler.Parse("_ZN4funcEDl"));
-  ASSERT_EQ("_ZN4funcEDm", demangler.Parse("_ZN4funcEDm"));
-  ASSERT_EQ("func(decltype(nullptr))", demangler.Parse("_ZN4funcEDn"));
-  ASSERT_EQ("_ZN4funcEDo", demangler.Parse("_ZN4funcEDo"));
-  ASSERT_EQ("_ZN4funcEDp", demangler.Parse("_ZN4funcEDp"));
-  ASSERT_EQ("_ZN4funcEDq", demangler.Parse("_ZN4funcEDq"));
-  ASSERT_EQ("_ZN4funcEDr", demangler.Parse("_ZN4funcEDr"));
-  ASSERT_EQ("func(char16_t)", demangler.Parse("_ZN4funcEDs"));
-  ASSERT_EQ("_ZN4funcEDt", demangler.Parse("_ZN4funcEDt"));
-  ASSERT_EQ("_ZN4funcEDu", demangler.Parse("_ZN4funcEDu"));
-  ASSERT_EQ("_ZN4funcEDv", demangler.Parse("_ZN4funcEDv"));
-  ASSERT_EQ("_ZN4funcEDw", demangler.Parse("_ZN4funcEDw"));
-  ASSERT_EQ("_ZN4funcEDx", demangler.Parse("_ZN4funcEDx"));
-  ASSERT_EQ("_ZN4funcEDy", demangler.Parse("_ZN4funcEDy"));
-  ASSERT_EQ("_ZN4funcEDz", demangler.Parse("_ZN4funcEDz"));
-}
-
-TEST(DemangleTest, FunctionArguments) {
-  Demangler demangler;
-
-  ASSERT_EQ("func(char ())", demangler.Parse("_ZN4funcEFcvE"));
-  ASSERT_EQ("func(char (*)())", demangler.Parse("_ZN4funcEPFcvE"));
-  ASSERT_EQ("func(char (&)())", demangler.Parse("_ZN4funcERFcvE"));
-  ASSERT_EQ("func(char (&)())", demangler.Parse("_ZN4funcERFcvE"));
-  ASSERT_EQ("func(char (*&)())", demangler.Parse("_ZN4funcERPFcvE"));
-  ASSERT_EQ("func(char (*)(int) const)", demangler.Parse("_ZN4funcEPKFciE"));
-  ASSERT_EQ("func(char (&)() const)", demangler.Parse("_ZN4funcERKFcvE"));
-  ASSERT_EQ("func(char (&)() volatile)", demangler.Parse("_ZN4funcERVFcvE"));
-  ASSERT_EQ("func(char (&)() volatile const)", demangler.Parse("_ZN4funcERKVFcvE"));
-  ASSERT_EQ("func(char (&)() const volatile)", demangler.Parse("_ZN4funcERVKFcvE"));
-  ASSERT_EQ("func(char (&)(int, signed char) const)", demangler.Parse("_ZN4funcERKFciaE"));
-  ASSERT_EQ("fake(char (&* volatile const)(void, void, signed char), signed char)",
-            demangler.Parse("_ZN4fakeEKVPRFcvvaEa"));
-}
-
-TEST(DemangleTest, TemplateFunction) {
-  Demangler demangler;
-
-  ASSERT_EQ("one<char>", demangler.Parse("_ZN3oneIcEE"));
-  ASSERT_EQ("one<void>", demangler.Parse("_ZN3oneIvEE"));
-  ASSERT_EQ("one<void*>", demangler.Parse("_ZN3oneIPvEE"));
-  ASSERT_EQ("one<void const>", demangler.Parse("_ZN3oneIKvEE"));
-  ASSERT_EQ("one<char, int, bool>", demangler.Parse("_ZN3oneIcibEE"));
-  ASSERT_EQ("one::two<three>", demangler.Parse("_ZN3one3twoIN5threeEEE"));
-  ASSERT_EQ("one<char, int, two::three>", demangler.Parse("_ZN3oneIciN3two5threeEEE"));
-  // Template within templates.
-  ASSERT_EQ("one::two<three<char, int>>", demangler.Parse("_ZN3one3twoIN5threeIciEEEE"));
-  ASSERT_EQ("one::two<three<char, four<int>>>", demangler.Parse("_ZN3one3twoIN5threeIcN4fourIiEEEEEE"));
-
-  ASSERT_EQ("one<char>", demangler.Parse("_Z3oneIcE"));
-  ASSERT_EQ("one<void>", demangler.Parse("_Z3oneIvE"));
-  ASSERT_EQ("one<void*>", demangler.Parse("_Z3oneIPvE"));
-  ASSERT_EQ("one<void const>", demangler.Parse("_Z3oneIKvE"));
-  ASSERT_EQ("one<char, int, bool>", demangler.Parse("_Z3oneIcibE"));
-  ASSERT_EQ("one(two<three>)", demangler.Parse("_Z3one3twoIN5threeEE"));
-  ASSERT_EQ("one<char, int, two::three>", demangler.Parse("_Z3oneIciN3two5threeEE"));
-  // Template within templates.
-  ASSERT_EQ("one(two<three<char, int>>)", demangler.Parse("_Z3one3twoIN5threeIciEEE"));
-  ASSERT_EQ("one(two<three<char, four<int>>>)",
-            demangler.Parse("_Z3one3twoIN5threeIcN4fourIiEEEEE"));
-}
-
-TEST(DemangleTest, TemplateFunctionWithReturnType) {
-  Demangler demangler;
-
-  ASSERT_EQ("char one<int>(char)", demangler.Parse("_Z3oneIiEcc"));
-  ASSERT_EQ("void one<int>()", demangler.Parse("_Z3oneIiEvv"));
-  ASSERT_EQ("char one<int>()", demangler.Parse("_Z3oneIiEcv"));
-  ASSERT_EQ("char one<int>(void, void)", demangler.Parse("_Z3oneIiEcvv"));
-  ASSERT_EQ("char one<int>()", demangler.Parse("_ZN3oneIiEEcv"));
-  ASSERT_EQ("char one<int>(void, void)", demangler.Parse("_ZN3oneIiEEcvv"));
-}
-
-TEST(DemangleTest, TemplateArguments) {
-  Demangler demangler;
-
-  ASSERT_EQ("one(two<char>)", demangler.Parse("_ZN3oneE3twoIcE"));
-  ASSERT_EQ("one(two<char, void>)", demangler.Parse("_ZN3oneE3twoIcvE"));
-  ASSERT_EQ("one(two<char, void, three<four, int>>)",
-            demangler.Parse("_ZN3oneE3twoIcv5threeI4fouriEE"));
-}
-
-TEST(DemangleTest, SubstitutionUnderscore) {
-  Demangler demangler;
-
-  ASSERT_EQ("a::a", demangler.Parse("_ZN1aS_E"));
-  ASSERT_EQ("one::one", demangler.Parse("_ZN3oneS_E"));
-  ASSERT_EQ("one::two::one", demangler.Parse("_ZN3one3twoS_E"));
-  ASSERT_EQ("one::two::three::one", demangler.Parse("_ZN3one3two5threeS_E"));
-  ASSERT_EQ("one::two(one)", demangler.Parse("_ZN3one3twoES_"));
-  ASSERT_EQ("one::two(three::one)", demangler.Parse("_ZN3one3twoEN5threeS_E"));
-
-  // Special case that St is part of the saved value used in the substitution.
-  ASSERT_EQ("std::one::std::one", demangler.Parse("_ZNSt3oneS_E"));
-
-  // Multiple substitutions in the string.
-  ASSERT_EQ("one::one(one, one)", demangler.Parse("_ZN3oneS_ES_S_"));
-  ASSERT_EQ("std::one::two::std::one(std::one)", demangler.Parse("_ZNSt3one3twoS_ES_"));
-}
-
-TEST(DemangleTest, SubstitutionByNumber) {
-  Demangler demangler;
-
-  // Basic substitution.
-  ASSERT_EQ("a::b::c(a::b)", demangler.Parse("_ZN1a1b1cES0_"));
-  ASSERT_EQ("_ZN1a1b1cES1_", demangler.Parse("_ZN1a1b1cES1_"));
-  ASSERT_EQ("a::b::c::d(a::b::c)", demangler.Parse("_ZN1a1b1c1dES1_"));
-  ASSERT_EQ("a::b::c::d::e::f::g::h::i::j::k::l::m::n::o::p::q(a::b::c::d::e::f::g::h::i::j::k::l)",
-            demangler.Parse("_ZN1a1b1c1d1e1f1g1h1i1j1k1l1m1n1o1p1qESA_"));
-  ASSERT_EQ("a::b::c::d::e::f::g::h::i::j::k::l::m::n::o::p::q(a::b::c::d::e::f::g::h::i::j::k::l::m)",
-            demangler.Parse("_ZN1a1b1c1d1e1f1g1h1i1j1k1l1m1n1o1p1qESB_"));
-
-  // Verify argument modifiers are included in substitution list.
-  ASSERT_EQ("one::two(char&* volatile const, char&)", demangler.Parse("_ZN3one3twoEKVPRcS0_"));
-  ASSERT_EQ("one::two(char&* volatile const, char&*)", demangler.Parse("_ZN3one3twoEKVPRcS1_"));
-  ASSERT_EQ("one::two(char&* volatile const, char&* volatile const)",
-            demangler.Parse("_ZN3one3twoEKVPRcS2_"));
-  ASSERT_EQ("one::two(int&* volatile* const, int&)", demangler.Parse("_ZN3one3twoEKPVPRiS0_"));
-  ASSERT_EQ("one::two(int&* volatile const, int&*)", demangler.Parse("_ZN3one3twoEKVPRiS1_"));
-  ASSERT_EQ("one::two(int&* volatile const, int&* volatile const)",
-            demangler.Parse("_ZN3one3twoEKVPRiS2_"));
-
-  // Verify Constructor/Destructor does properly save from function name.
-  ASSERT_EQ("_ZN1a1bES0_", demangler.Parse("_ZN1a1bES0_"));
-  ASSERT_EQ("a::b::b(a::b)", demangler.Parse("_ZN1a1bC1ES0_"));
-  ASSERT_EQ("a::b::~b(a::b)", demangler.Parse("_ZN1a1bD0ES0_"));
-
-  // Make sure substitution values are not saved.
-  ASSERT_EQ("a::b::b(a::b, char*, char*)", demangler.Parse("_ZN1a1bC1ES0_PcS1_"));
-}
-
-TEST(DemangleTest, ComplexSubstitution) {
-  Demangler demangler;
-
-  ASSERT_EQ("one::two<one::three>::two()", demangler.Parse("_ZN3one3twoINS_5threeEEC1Ev"));
-  ASSERT_EQ("one::two::two(one::two const&, bool, one::three*)",
-            demangler.Parse("_ZN3one3twoC2ERKS0_bPNS_5threeE"));
-  ASSERT_EQ("one::two::three::four<one::five>::~four(one::two*)",
-            demangler.Parse("_ZN3one3two5three4fourINS_4fiveEED2EPS0_"));
-  ASSERT_EQ("one::two::three::four<one::five>::~four(one::two::three*)",
-            demangler.Parse("_ZN3one3two5three4fourINS_4fiveEED2EPS1_"));
-  ASSERT_EQ("one::two::three::four<one::five>::~four(one::two::three::four*)",
-            demangler.Parse("_ZN3one3two5three4fourINS_4fiveEED2EPS2_"));
-  ASSERT_EQ("one::two::three::four<one::five>::~four(one::five*)",
-            demangler.Parse("_ZN3one3two5three4fourINS_4fiveEED2EPS3_"));
-}
-
-TEST(DemangleTest, TemplateSubstitution) {
-  Demangler demangler;
-
-  ASSERT_EQ("void one<int, double>(int)", demangler.Parse("_ZN3oneIidEEvT_"));
-  ASSERT_EQ("void one<int, double>(double)", demangler.Parse("_ZN3oneIidEEvT0_"));
-  ASSERT_EQ("void one<int, double, char, void>(char)", demangler.Parse("_ZN3oneIidcvEEvT1_"));
-
-  ASSERT_EQ("void one<int, double>(int)", demangler.Parse("_Z3oneIidEvT_"));
-  ASSERT_EQ("void one<int, double>(double)", demangler.Parse("_Z3oneIidEvT0_"));
-  ASSERT_EQ("void one<int, double, char, void>(char)", demangler.Parse("_Z3oneIidcvEvT1_"));
-
-  ASSERT_EQ("void one<a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r>(l)",
-            demangler.Parse("_ZN3oneI1a1b1c1d1e1f1g1h1i1j1k1l1m1n1o1p1q1rEEvT10_"));
-  ASSERT_EQ("void one<a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r>(m)",
-            demangler.Parse("_ZN3oneI1a1b1c1d1e1f1g1h1i1j1k1l1m1n1o1p1q1rEEvT11_"));
-
-  ASSERT_EQ("void one<a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r>(l)",
-            demangler.Parse("_Z3oneI1a1b1c1d1e1f1g1h1i1j1k1l1m1n1o1p1q1rEvT10_"));
-  ASSERT_EQ("void one<a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r>(m)",
-            demangler.Parse("_Z3oneI1a1b1c1d1e1f1g1h1i1j1k1l1m1n1o1p1q1rEvT11_"));
-}
-
-TEST(DemangleTest, StringTooLong) {
-  Demangler demangler;
-
-  ASSERT_EQ("_ZN3one3twoC2ERKS0_bPNS_5threeE",
-            demangler.Parse("_ZN3one3twoC2ERKS0_bPNS_5threeE", 10));
-  ASSERT_EQ("_ZN3one3twoC2ERKS0_bPNS_5threeE",
-            demangler.Parse("_ZN3one3twoC2ERKS0_bPNS_5threeE", 30));
-  ASSERT_EQ("one::two::two(one::two const&, bool, one::three*)",
-            demangler.Parse("_ZN3one3twoC2ERKS0_bPNS_5threeE", 31));
-
-  // Check the length check only occurs after the two letter value
-  // has been processed.
-  ASSERT_EQ("one::two(auto)", demangler.Parse("_ZN3one3twoEDa", 15));
-  ASSERT_EQ("one::two(auto)", demangler.Parse("_ZN3one3twoEDa", 14));
-  ASSERT_EQ("one::two(auto)", demangler.Parse("_ZN3one3twoEDa", 13));
-  ASSERT_EQ("_ZN3one3twoEDa", demangler.Parse("_ZN3one3twoEDa", 12));
-}
-
-TEST(DemangleTest, BooleanLiterals) {
-  Demangler demangler;
-
-  ASSERT_EQ("one<true>", demangler.Parse("_ZN3oneILb1EEE"));
-  ASSERT_EQ("one<false>", demangler.Parse("_ZN3oneILb0EEE"));
-  ASSERT_EQ("one<false, true>", demangler.Parse("_ZN3oneILb0ELb1EEE"));
-
-  ASSERT_EQ("one<true>", demangler.Parse("_Z3oneILb1EE"));
-  ASSERT_EQ("one<false>", demangler.Parse("_Z3oneILb0EE"));
-  ASSERT_EQ("one<false, true>", demangler.Parse("_Z3oneILb0ELb1EE"));
-
-  ASSERT_EQ("one(two<three<four>, false, true>)",
-            demangler.Parse("_ZN3oneE3twoI5threeI4fourELb0ELb1EE"));
-}
-
-TEST(DemangleTest, non_virtual_thunk) {
-  Demangler demangler;
-
-  ASSERT_EQ("non-virtual thunk to one", demangler.Parse("_ZThn0_N3oneE"));
-  ASSERT_EQ("non-virtual thunk to two", demangler.Parse("_ZThn0_3two"));
-  ASSERT_EQ("non-virtual thunk to three", demangler.Parse("_ZTh0_5three"));
-  ASSERT_EQ("non-virtual thunk to four", demangler.Parse("_ZTh_4four"));
-  ASSERT_EQ("non-virtual thunk to five", demangler.Parse("_ZTh0123456789_4five"));
-  ASSERT_EQ("non-virtual thunk to six", demangler.Parse("_ZThn0123456789_3six"));
-
-  ASSERT_EQ("_ZThn0N3oneE", demangler.Parse("_ZThn0N3oneE"));
-  ASSERT_EQ("_ZThn03two", demangler.Parse("_ZThn03two"));
-  ASSERT_EQ("_ZTh05three", demangler.Parse("_ZTh05three"));
-  ASSERT_EQ("_ZTh4four", demangler.Parse("_ZTh4four"));
-  ASSERT_EQ("_ZTh01234567894five", demangler.Parse("_ZTh01234567894five"));
-  ASSERT_EQ("_ZThn01234567893six", demangler.Parse("_ZThn01234567893six"));
-  ASSERT_EQ("_ZT_N3oneE", demangler.Parse("_ZT_N3oneE"));
-  ASSERT_EQ("_ZT0_N3oneE", demangler.Parse("_ZT0_N3oneE"));
-  ASSERT_EQ("_ZTH_N3oneE", demangler.Parse("_ZTH_N3oneE"));
-}
-
-TEST(DemangleTest, r_value_reference) {
-  Demangler demangler;
-  ASSERT_EQ(
-      "android::SurfaceComposerClient::Transaction::merge(android::SurfaceComposerClient::"
-      "Transaction&&)",
-      demangler.Parse("_ZN7android21SurfaceComposerClient11Transaction5mergeEOS1_"));
-}
-
-TEST(DemangleTest, initial_St) {
-  Demangler demangler;
-  EXPECT_EQ("std::state", demangler.Parse("_ZSt5state"));
-  EXPECT_EQ("std::_In::ward", demangler.Parse("_ZNSt3_In4wardE"));
-  EXPECT_EQ("std::__terminate(void (*)())", demangler.Parse("_ZSt11__terminatePFvvE"));
-}
-
-TEST(DemangleTest, cfi) {
-  Demangler demangler;
-  EXPECT_EQ("nfa_sys_ptim_timer_update(tPTIM_CB*)",
-            demangler.Parse("_Z25nfa_sys_ptim_timer_updateP8tPTIM_CB"));
-  EXPECT_EQ("nfa_sys_ptim_timer_update(tPTIM_CB*) [clone .cfi]",
-            demangler.Parse("_Z25nfa_sys_ptim_timer_updateP8tPTIM_CB.cfi"));
-}
-
-TEST(DemangleTest, demangle) {
-  std::string str;
-
-  str = demangle("_ZN1a1b1cES0_");
-  ASSERT_EQ("a::b::c(a::b)", str);
-
-  str = demangle("_");
-  ASSERT_EQ("_", str);
-
-  str = demangle("_Z");
-  ASSERT_EQ("_Z", str);
-
-  str = demangle("_Za");
-  ASSERT_EQ("_Za", str);
-
-  str = demangle("_Zaa");
-  ASSERT_EQ("operator&&", str);
-
-  str = demangle("Xa");
-  ASSERT_EQ("Xa", str);
-}
diff --git a/demangle/Demangler.cpp b/demangle/Demangler.cpp
deleted file mode 100644
index 7bae356..0000000
--- a/demangle/Demangler.cpp
+++ /dev/null
@@ -1,925 +0,0 @@
-/*
- * Copyright (C) 2017 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 <assert.h>
-#include <string.h>
-
-#include <cctype>
-#include <stack>
-#include <string>
-#include <vector>
-
-#include "Demangler.h"
-
-constexpr const char* Demangler::kTypes[];
-constexpr const char* Demangler::kDTypes[];
-constexpr const char* Demangler::kSTypes[];
-
-void Demangler::Save(const std::string& str, bool is_name) {
-  saves_.push_back(str);
-  last_save_name_ = is_name;
-}
-
-std::string Demangler::GetArgumentsString() {
-  size_t num_args = cur_state_.args.size();
-  std::string arg_str;
-  if (num_args > 0) {
-    arg_str = cur_state_.args[0];
-    for (size_t i = 1; i < num_args; i++) {
-      arg_str += ", " + cur_state_.args[i];
-    }
-  }
-  return arg_str;
-}
-
-const char* Demangler::AppendOperatorString(const char* name) {
-  const char* oper = nullptr;
-  switch (*name) {
-  case 'a':
-    name++;
-    switch (*name) {
-    case 'a':
-      oper = "operator&&";
-      break;
-    case 'd':
-    case 'n':
-      oper = "operator&";
-      break;
-    case 'N':
-      oper = "operator&=";
-      break;
-    case 'S':
-      oper = "operator=";
-      break;
-    }
-    break;
-  case 'c':
-    name++;
-    switch (*name) {
-    case 'l':
-      oper = "operator()";
-      break;
-    case 'm':
-      oper = "operator,";
-      break;
-    case 'o':
-      oper = "operator~";
-      break;
-    }
-    break;
-  case 'd':
-    name++;
-    switch (*name) {
-    case 'a':
-      oper = "operator delete[]";
-      break;
-    case 'e':
-      oper = "operator*";
-      break;
-    case 'l':
-      oper = "operator delete";
-      break;
-    case 'v':
-      oper = "operator/";
-      break;
-    case 'V':
-      oper = "operator/=";
-      break;
-    }
-    break;
-  case 'e':
-    name++;
-    switch (*name) {
-    case 'o':
-      oper = "operator^";
-      break;
-    case 'O':
-      oper = "operator^=";
-      break;
-    case 'q':
-      oper = "operator==";
-      break;
-    }
-    break;
-  case 'g':
-    name++;
-    switch (*name) {
-    case 'e':
-      oper = "operator>=";
-      break;
-    case 't':
-      oper = "operator>";
-      break;
-    }
-    break;
-  case 'i':
-    name++;
-    switch (*name) {
-    case 'x':
-      oper = "operator[]";
-      break;
-    }
-    break;
-  case 'l':
-    name++;
-    switch (*name) {
-    case 'e':
-      oper = "operator<=";
-      break;
-    case 's':
-      oper = "operator<<";
-      break;
-    case 'S':
-      oper = "operator<<=";
-      break;
-    case 't':
-      oper = "operator<";
-      break;
-    }
-    break;
-  case 'm':
-    name++;
-    switch (*name) {
-    case 'i':
-      oper = "operator-";
-      break;
-    case 'I':
-      oper = "operator-=";
-      break;
-    case 'l':
-      oper = "operator*";
-      break;
-    case 'L':
-      oper = "operator*=";
-      break;
-    case 'm':
-      oper = "operator--";
-      break;
-    }
-    break;
-  case 'n':
-    name++;
-    switch (*name) {
-    case 'a':
-      oper = "operator new[]";
-      break;
-    case 'e':
-      oper = "operator!=";
-      break;
-    case 'g':
-      oper = "operator-";
-      break;
-    case 't':
-      oper = "operator!";
-      break;
-    case 'w':
-      oper = "operator new";
-      break;
-    }
-    break;
-  case 'o':
-    name++;
-    switch (*name) {
-    case 'o':
-      oper = "operator||";
-      break;
-    case 'r':
-      oper = "operator|";
-      break;
-    case 'R':
-      oper = "operator|=";
-      break;
-    }
-    break;
-  case 'p':
-    name++;
-    switch (*name) {
-    case 'm':
-      oper = "operator->*";
-      break;
-    case 'l':
-      oper = "operator+";
-      break;
-    case 'L':
-      oper = "operator+=";
-      break;
-    case 'p':
-      oper = "operator++";
-      break;
-    case 's':
-      oper = "operator+";
-      break;
-    case 't':
-      oper = "operator->";
-      break;
-    }
-    break;
-  case 'q':
-    name++;
-    switch (*name) {
-    case 'u':
-      oper = "operator?";
-      break;
-    }
-    break;
-  case 'r':
-    name++;
-    switch (*name) {
-    case 'm':
-      oper = "operator%";
-      break;
-    case 'M':
-      oper = "operator%=";
-      break;
-    case 's':
-      oper = "operator>>";
-      break;
-    case 'S':
-      oper = "operator>>=";
-      break;
-    }
-    break;
-  }
-  if (oper == nullptr) {
-    return nullptr;
-  }
-  AppendCurrent(oper);
-  cur_state_.last_save = oper;
-  return name + 1;
-}
-
-const char* Demangler::GetStringFromLength(const char* name, std::string* str) {
-  assert(std::isdigit(*name));
-
-  size_t length = *name - '0';
-  name++;
-  while (*name != '\0' && std::isdigit(*name)) {
-    length = length * 10 + *name - '0';
-    name++;
-  }
-
-  std::string read_str;
-  while (*name != '\0' && length != 0) {
-    read_str += *name;
-    name++;
-    length--;
-  }
-  if (length != 0) {
-    return nullptr;
-  }
-  // Special replacement of _GLOBAL__N_1 to (anonymous namespace).
-  if (read_str == "_GLOBAL__N_1") {
-    *str += "(anonymous namespace)";
-  } else {
-    *str += read_str;
-  }
-  return name;
-}
-
-void Demangler::AppendCurrent(const std::string& str) {
-  if (!cur_state_.str.empty()) {
-    cur_state_.str += "::";
-  }
-  cur_state_.str += str;
-}
-
-void Demangler::AppendCurrent(const char* str) {
-  if (!cur_state_.str.empty()) {
-    cur_state_.str += "::";
-  }
-  cur_state_.str += str;
-}
-
-const char* Demangler::ParseS(const char* name) {
-  if (std::islower(*name)) {
-    const char* type = kSTypes[*name - 'a'];
-    if (type == nullptr) {
-      return nullptr;
-    }
-    AppendCurrent(type);
-    return name + 1;
-  }
-
-  if (saves_.empty()) {
-    return nullptr;
-  }
-
-  if (*name == '_') {
-    last_save_name_ = false;
-    AppendCurrent(saves_[0]);
-    return name + 1;
-  }
-
-  bool isdigit = std::isdigit(*name);
-  if (!isdigit && !std::isupper(*name)) {
-    return nullptr;
-  }
-
-  size_t index;
-  if (isdigit) {
-    index = *name - '0' + 1;
-  } else {
-    index = *name - 'A' + 11;
-  }
-  name++;
-  if (*name != '_') {
-    return nullptr;
-  }
-
-  if (index >= saves_.size()) {
-    return nullptr;
-  }
-
-  last_save_name_ = false;
-  AppendCurrent(saves_[index]);
-  return name + 1;
-}
-
-const char* Demangler::ParseT(const char* name) {
-  if (template_saves_.empty()) {
-    return nullptr;
-  }
-
-  if (*name == '_') {
-    last_save_name_ = false;
-    AppendCurrent(template_saves_[0]);
-    return name + 1;
-  }
-
-  // Need to get the total number.
-  char* end;
-  unsigned long int index = strtoul(name, &end, 10) + 1;
-  if (name == end || *end != '_') {
-    return nullptr;
-  }
-
-  if (index >= template_saves_.size()) {
-    return nullptr;
-  }
-
-  last_save_name_ = false;
-  AppendCurrent(template_saves_[index]);
-  return end + 1;
-}
-
-const char* Demangler::ParseFunctionName(const char* name) {
-  if (*name == 'E') {
-    if (parse_funcs_.empty()) {
-      return nullptr;
-    }
-    parse_func_ = parse_funcs_.back();
-    parse_funcs_.pop_back();
-
-    // Remove the last saved part so that the full function name is not saved.
-    // But only if the last save was not something like a substitution.
-    if (!saves_.empty() && last_save_name_) {
-      saves_.pop_back();
-    }
-
-    function_name_ += cur_state_.str;
-    while (!cur_state_.suffixes.empty()) {
-      function_suffix_ += cur_state_.suffixes.back();
-      cur_state_.suffixes.pop_back();
-    }
-    cur_state_.Clear();
-
-    return name + 1;
-  }
-
-  if (*name == 'I') {
-    state_stack_.push(cur_state_);
-    cur_state_.Clear();
-
-    parse_funcs_.push_back(parse_func_);
-    parse_func_ = &Demangler::ParseFunctionNameTemplate;
-    return name + 1;
-  }
-
-  return ParseComplexString(name);
-}
-
-const char* Demangler::ParseFunctionNameTemplate(const char* name) {
-  if (*name == 'E' && name[1] == 'E') {
-    // Only consider this a template with saves if it is right before
-    // the end of the name.
-    template_found_ = true;
-    template_saves_ = cur_state_.args;
-  }
-  return ParseTemplateArgumentsComplex(name);
-}
-
-const char* Demangler::ParseComplexArgument(const char* name) {
-  if (*name == 'E') {
-    if (parse_funcs_.empty()) {
-      return nullptr;
-    }
-    parse_func_ = parse_funcs_.back();
-    parse_funcs_.pop_back();
-
-    AppendArgument(cur_state_.str);
-    cur_state_.str.clear();
-
-    return name + 1;
-  }
-
-  return ParseComplexString(name);
-}
-
-void Demangler::FinalizeTemplate() {
-  std::string arg_str(GetArgumentsString());
-  cur_state_ = state_stack_.top();
-  state_stack_.pop();
-  cur_state_.str += '<' + arg_str + '>';
-}
-
-const char* Demangler::ParseComplexString(const char* name) {
-  if (*name == 'S') {
-    name++;
-    if (*name == 't') {
-      AppendCurrent("std");
-      return name + 1;
-    }
-    return ParseS(name);
-  }
-  if (*name == 'L') {
-    name++;
-    if (!std::isdigit(*name)) {
-      return nullptr;
-    }
-  }
-  if (std::isdigit(*name)) {
-    std::string str;
-    name = GetStringFromLength(name, &str);
-    if (name == nullptr) {
-      return name;
-    }
-    AppendCurrent(str);
-    Save(cur_state_.str, true);
-    cur_state_.last_save = std::move(str);
-    return name;
-  }
-  if (*name == 'D') {
-    name++;
-    if (saves_.empty() || (*name != '0' && *name != '1' && *name != '2'
-        && *name != '5')) {
-      return nullptr;
-    }
-    last_save_name_ = false;
-    AppendCurrent("~" + cur_state_.last_save);
-    return name + 1;
-  }
-  if (*name == 'C') {
-    name++;
-    if (saves_.empty() || (*name != '1' && *name != '2' && *name != '3'
-        && *name != '5')) {
-      return nullptr;
-    }
-    last_save_name_ = false;
-    AppendCurrent(cur_state_.last_save);
-    return name + 1;
-  }
-  if (*name == 'K') {
-    cur_state_.suffixes.push_back(" const");
-    return name + 1;
-  }
-  if (*name == 'V') {
-    cur_state_.suffixes.push_back(" volatile");
-    return name + 1;
-  }
-  if (*name == 'I') {
-    // Save the current argument state.
-    state_stack_.push(cur_state_);
-    cur_state_.Clear();
-
-    parse_funcs_.push_back(parse_func_);
-    parse_func_ = &Demangler::ParseTemplateArgumentsComplex;
-    return name + 1;
-  }
-  name = AppendOperatorString(name);
-  if (name != nullptr) {
-    Save(cur_state_.str, true);
-  }
-  return name;
-}
-
-void Demangler::AppendArgument(const std::string& str) {
-  std::string arg(str);
-  while (!cur_state_.suffixes.empty()) {
-    arg += cur_state_.suffixes.back();
-    cur_state_.suffixes.pop_back();
-    Save(arg, false);
-  }
-  cur_state_.args.push_back(arg);
-}
-
-const char* Demangler::ParseFunctionArgument(const char* name) {
-  if (*name == 'E') {
-    // The first argument is the function modifier.
-    // The second argument is the function type.
-    // The third argument is the return type of the function.
-    // The rest of the arguments are the function arguments.
-    size_t num_args = cur_state_.args.size();
-    if (num_args < 4) {
-      return nullptr;
-    }
-    std::string function_modifier = cur_state_.args[0];
-    std::string function_type = cur_state_.args[1];
-
-    std::string str = cur_state_.args[2] + ' ';
-    if (!cur_state_.args[1].empty()) {
-      str += '(' + cur_state_.args[1] + ')';
-    }
-
-    if (num_args == 4 && cur_state_.args[3] == "void") {
-      str += "()";
-    } else {
-      str += '(' + cur_state_.args[3];
-      for (size_t i = 4; i < num_args; i++) {
-        str += ", " + cur_state_.args[i];
-      }
-      str += ')';
-    }
-    str += cur_state_.args[0];
-
-    cur_state_ = state_stack_.top();
-    state_stack_.pop();
-    cur_state_.args.emplace_back(std::move(str));
-
-    parse_func_ = parse_funcs_.back();
-    parse_funcs_.pop_back();
-    return name + 1;
-  }
-  return ParseArguments(name);
-}
-
-const char* Demangler::ParseArguments(const char* name) {
-  switch (*name) {
-  case 'P':
-    cur_state_.suffixes.push_back("*");
-    return name + 1;
-
-  case 'R':
-    // This should always be okay because the string is guaranteed to have
-    // at least two characters before this. A mangled string always starts
-    // with _Z.
-    if (name[-1] != 'R') {
-      // Multiple 'R's in a row only add a single &.
-      cur_state_.suffixes.push_back("&");
-    }
-    return name + 1;
-
-  case 'O':
-    cur_state_.suffixes.push_back("&&");
-    return name + 1;
-
-  case 'K':
-  case 'V': {
-    const char* suffix;
-    if (*name == 'K') {
-      suffix = " const";
-    } else {
-      suffix = " volatile";
-    }
-    if (!cur_state_.suffixes.empty() && (name[-1] == 'K' || name[-1] == 'V')) {
-      // Special case, const/volatile apply as a single entity.
-      size_t index = cur_state_.suffixes.size();
-      cur_state_.suffixes[index-1].insert(0, suffix);
-    } else {
-      cur_state_.suffixes.push_back(suffix);
-    }
-    return name + 1;
-  }
-
-  case 'F': {
-    std::string function_modifier;
-    std::string function_type;
-    if (!cur_state_.suffixes.empty()) {
-      // If the first element starts with a ' ', then this modifies the
-      // function itself.
-      if (cur_state_.suffixes.back()[0] == ' ') {
-        function_modifier = cur_state_.suffixes.back();
-        cur_state_.suffixes.pop_back();
-      }
-      while (!cur_state_.suffixes.empty()) {
-        function_type += cur_state_.suffixes.back();
-        cur_state_.suffixes.pop_back();
-      }
-    }
-
-    state_stack_.push(cur_state_);
-
-    cur_state_.Clear();
-
-    // The function parameter has this format:
-    //   First argument is the function modifier.
-    //   Second argument is the function type.
-    //   Third argument will be the return function type but has not
-    //     been parsed yet.
-    //   Any other parameters are the arguments to the function. There
-    //     must be at least one or this isn't valid.
-    cur_state_.args.push_back(function_modifier);
-    cur_state_.args.push_back(function_type);
-
-    parse_funcs_.push_back(parse_func_);
-    parse_func_ = &Demangler::ParseFunctionArgument;
-    return name + 1;
-  }
-
-  case 'N':
-    parse_funcs_.push_back(parse_func_);
-    parse_func_ = &Demangler::ParseComplexArgument;
-    return name + 1;
-
-  case 'S':
-    name++;
-    if (*name == 't') {
-      cur_state_.str = "std::";
-      return name + 1;
-    }
-    name = ParseS(name);
-    if (name == nullptr) {
-      return nullptr;
-    }
-    AppendArgument(cur_state_.str);
-    cur_state_.str.clear();
-    return name;
-
-  case 'D':
-    name++;
-    if (*name >= 'a' && *name <= 'z') {
-      const char* arg = Demangler::kDTypes[*name - 'a'];
-      if (arg == nullptr) {
-        return nullptr;
-      }
-      AppendArgument(arg);
-      return name + 1;
-    }
-    return nullptr;
-
-  case 'I':
-    // Save the current argument state.
-    state_stack_.push(cur_state_);
-    cur_state_.Clear();
-
-    parse_funcs_.push_back(parse_func_);
-    parse_func_ = &Demangler::ParseTemplateArguments;
-    return name + 1;
-
-  case 'v':
-    AppendArgument("void");
-    return name + 1;
-
-  default:
-    if (*name >= 'a' && *name <= 'z') {
-      const char* arg = Demangler::kTypes[*name - 'a'];
-      if (arg == nullptr) {
-        return nullptr;
-      }
-      AppendArgument(arg);
-      return name + 1;
-    } else if (std::isdigit(*name)) {
-      std::string arg = cur_state_.str;
-      name = GetStringFromLength(name, &arg);
-      if (name == nullptr) {
-        return nullptr;
-      }
-      Save(arg, true);
-      if (*name == 'I') {
-        // There is one case where this argument is not complete, and that's
-        // where this is a template argument.
-        cur_state_.str = arg;
-      } else {
-        AppendArgument(arg);
-        cur_state_.str.clear();
-      }
-      return name;
-    } else if (strcmp(name, ".cfi") == 0) {
-      function_suffix_ += " [clone .cfi]";
-      return name + 4;
-    }
-  }
-  return nullptr;
-}
-
-const char* Demangler::ParseTemplateLiteral(const char* name) {
-  if (*name == 'E') {
-    parse_func_ = parse_funcs_.back();
-    parse_funcs_.pop_back();
-    return name + 1;
-  }
-  // Only understand boolean values with 0 or 1.
-  if (*name == 'b') {
-    name++;
-    if (*name == '0') {
-      AppendArgument("false");
-      cur_state_.str.clear();
-    } else if (*name == '1') {
-      AppendArgument("true");
-      cur_state_.str.clear();
-    } else {
-      return nullptr;
-    }
-    return name + 1;
-  }
-  return nullptr;
-}
-
-const char* Demangler::ParseTemplateArgumentsComplex(const char* name) {
-  if (*name == 'E') {
-    if (parse_funcs_.empty()) {
-      return nullptr;
-    }
-    parse_func_ = parse_funcs_.back();
-    parse_funcs_.pop_back();
-
-    FinalizeTemplate();
-    Save(cur_state_.str, false);
-    return name + 1;
-  } else if (*name == 'L') {
-    // Literal value for a template.
-    parse_funcs_.push_back(parse_func_);
-    parse_func_ = &Demangler::ParseTemplateLiteral;
-    return name + 1;
-  }
-
-  return ParseArguments(name);
-}
-
-const char* Demangler::ParseTemplateArguments(const char* name) {
-  if (*name == 'E') {
-    if (parse_funcs_.empty()) {
-      return nullptr;
-    }
-    parse_func_ = parse_funcs_.back();
-    parse_funcs_.pop_back();
-    FinalizeTemplate();
-    AppendArgument(cur_state_.str);
-    cur_state_.str.clear();
-    return name + 1;
-  } else if (*name == 'L') {
-    // Literal value for a template.
-    parse_funcs_.push_back(parse_func_);
-    parse_func_ = &Demangler::ParseTemplateLiteral;
-    return name + 1;
-  }
-
-  return ParseArguments(name);
-}
-
-const char* Demangler::ParseFunctionTemplateArguments(const char* name) {
-  if (*name == 'E') {
-    parse_func_ = parse_funcs_.back();
-    parse_funcs_.pop_back();
-
-    function_name_ += '<' + GetArgumentsString() + '>';
-    template_found_ = true;
-    template_saves_ = cur_state_.args;
-    cur_state_.Clear();
-    return name + 1;
-  }
-  return ParseTemplateArgumentsComplex(name);
-}
-
-const char* Demangler::FindFunctionName(const char* name) {
-  if (*name == 'T') {
-    // non-virtual thunk, verify that it matches one of these patterns:
-    //   Thn[0-9]+_
-    //   Th[0-9]+_
-    //   Thn_
-    //   Th_
-    name++;
-    if (*name != 'h') {
-      return nullptr;
-    }
-    name++;
-    if (*name == 'n') {
-      name++;
-    }
-    while (std::isdigit(*name)) {
-      name++;
-    }
-    if (*name != '_') {
-      return nullptr;
-    }
-    function_name_ = "non-virtual thunk to ";
-    return name + 1;
-  }
-
-  if (*name == 'N') {
-    parse_funcs_.push_back(&Demangler::ParseArgumentsAtTopLevel);
-    parse_func_ = &Demangler::ParseFunctionName;
-    return name + 1;
-  }
-
-  if (*name == 'S') {
-    name++;
-    if (*name == 't') {
-      function_name_ = "std::";
-      name++;
-    } else {
-      return nullptr;
-    }
-  }
-
-  if (std::isdigit(*name)) {
-    name = GetStringFromLength(name, &function_name_);
-  } else if (*name == 'L' && std::isdigit(name[1])) {
-    name = GetStringFromLength(name + 1, &function_name_);
-  } else {
-    name = AppendOperatorString(name);
-    function_name_ = cur_state_.str;
-  }
-  cur_state_.Clear();
-
-  // Check for a template argument, which will still be part of the function
-  // name.
-  if (name != nullptr && *name == 'I') {
-    parse_funcs_.push_back(&Demangler::ParseArgumentsAtTopLevel);
-    parse_func_ = &Demangler::ParseFunctionTemplateArguments;
-    return name + 1;
-  }
-  parse_func_ = &Demangler::ParseArgumentsAtTopLevel;
-  return name;
-}
-
-const char* Demangler::ParseArgumentsAtTopLevel(const char* name) {
-  // At the top level is the only place where T is allowed.
-  if (*name == 'T') {
-    name++;
-    name = ParseT(name);
-    if (name == nullptr) {
-      return nullptr;
-    }
-    AppendArgument(cur_state_.str);
-    cur_state_.str.clear();
-    return name;
-  }
-
-  return Demangler::ParseArguments(name);
-}
-
-std::string Demangler::Parse(const char* name, size_t max_length) {
-  if (name[0] == '\0' || name[0] != '_' || name[1] == '\0' || name[1] != 'Z') {
-    // Name is not mangled.
-    return name;
-  }
-
-  Clear();
-
-  parse_func_ = &Demangler::FindFunctionName;
-  parse_funcs_.push_back(&Demangler::Fail);
-  const char* cur_name = name + 2;
-  while (cur_name != nullptr && *cur_name != '\0'
-      && static_cast<size_t>(cur_name - name) < max_length) {
-    cur_name = (this->*parse_func_)(cur_name);
-  }
-  if (cur_name == nullptr || *cur_name != '\0' || function_name_.empty() ||
-      !cur_state_.suffixes.empty()) {
-    return name;
-  }
-
-  std::string return_type;
-  if (template_found_) {
-    // Only a single argument with a template is not allowed.
-    if (cur_state_.args.size() == 1) {
-      return name;
-    }
-
-    // If there are at least two arguments, this template has a return type.
-    if (cur_state_.args.size() > 1) {
-      // The first argument will be the return value.
-      return_type = cur_state_.args[0] + ' ';
-      cur_state_.args.erase(cur_state_.args.begin());
-    }
-  }
-
-  std::string arg_str;
-  if (cur_state_.args.size() == 1 && cur_state_.args[0] == "void") {
-    // If the only argument is void, then don't print any args.
-    arg_str = "()";
-  } else {
-    arg_str = GetArgumentsString();
-    if (!arg_str.empty()) {
-      arg_str = '(' + arg_str + ')';
-    }
-  }
-  return return_type + function_name_ + arg_str + function_suffix_;
-}
-
-std::string demangle(const char* name) {
-  Demangler demangler;
-  return demangler.Parse(name);
-}
diff --git a/demangle/Demangler.h b/demangle/Demangler.h
deleted file mode 100644
index 3b7d44e..0000000
--- a/demangle/Demangler.h
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- * Copyright (C) 2017 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.
- */
-
-#ifndef __LIB_DEMANGLE_DEMANGLER_H
-#define __LIB_DEMANGLE_DEMANGLER_H
-
-#include <assert.h>
-
-#include <stack>
-#include <string>
-#include <vector>
-
-class Demangler {
- public:
-  Demangler() = default;
-
-  // NOTE: The max_length is not guaranteed to be the absolute max length
-  // of a string that will be rejected. Under certain circumstances the
-  // length check will not occur until after the second letter of a pair
-  // is checked.
-  std::string Parse(const char* name, size_t max_length = kMaxDefaultLength);
-
-  void AppendCurrent(const std::string& str);
-  void AppendCurrent(const char* str);
-  void AppendArgument(const std::string& str);
-  std::string GetArgumentsString();
-  void FinalizeTemplate();
-  const char* ParseS(const char* name);
-  const char* ParseT(const char* name);
-  const char* AppendOperatorString(const char* name);
-  void Save(const std::string& str, bool is_name);
-
- private:
-  void Clear() {
-    parse_funcs_.clear();
-    function_name_.clear();
-    function_suffix_.clear();
-    first_save_.clear();
-    cur_state_.Clear();
-    saves_.clear();
-    template_saves_.clear();
-    while (!state_stack_.empty()) {
-      state_stack_.pop();
-    }
-    last_save_name_ = false;
-    template_found_ = false;
-  }
-
-  using parse_func_type = const char* (Demangler::*)(const char*);
-  parse_func_type parse_func_;
-  std::vector<parse_func_type> parse_funcs_;
-  std::vector<std::string> saves_;
-  std::vector<std::string> template_saves_;
-  bool last_save_name_;
-  bool template_found_;
-
-  std::string function_name_;
-  std::string function_suffix_;
-
-  struct StateData {
-    void Clear() {
-      str.clear();
-      args.clear();
-      prefix.clear();
-      suffixes.clear();
-      last_save.clear();
-    }
-
-    std::string str;
-    std::vector<std::string> args;
-    std::string prefix;
-    std::vector<std::string> suffixes;
-    std::string last_save;
-  };
-  std::stack<StateData> state_stack_;
-  std::string first_save_;
-  StateData cur_state_;
-
-  static const char* GetStringFromLength(const char* name, std::string* str);
-
-  // Parsing functions.
-  const char* ParseComplexString(const char* name);
-  const char* ParseComplexArgument(const char* name);
-  const char* ParseArgumentsAtTopLevel(const char* name);
-  const char* ParseArguments(const char* name);
-  const char* ParseTemplateArguments(const char* name);
-  const char* ParseTemplateArgumentsComplex(const char* name);
-  const char* ParseTemplateLiteral(const char* name);
-  const char* ParseFunctionArgument(const char* name);
-  const char* ParseFunctionName(const char* name);
-  const char* ParseFunctionNameTemplate(const char* name);
-  const char* ParseFunctionTemplateArguments(const char* name);
-  const char* FindFunctionName(const char* name);
-  const char* Fail(const char*) { return nullptr; }
-
-  // The default maximum string length string to process.
-  static constexpr size_t kMaxDefaultLength = 2048;
-
-  static constexpr const char* kTypes[] = {
-    "signed char",        // a
-    "bool",               // b
-    "char",               // c
-    "double",             // d
-    "long double",        // e
-    "float",              // f
-    "__float128",         // g
-    "unsigned char",      // h
-    "int",                // i
-    "unsigned int",       // j
-    nullptr,              // k
-    "long",               // l
-    "unsigned long",      // m
-    "__int128",           // n
-    "unsigned __int128",  // o
-    nullptr,              // p
-    nullptr,              // q
-    nullptr,              // r
-    "short",              // s
-    "unsigned short",     // t
-    nullptr,              // u
-    "void",               // v
-    "wchar_t",            // w
-    "long long",          // x
-    "unsigned long long", // y
-    "...",                // z
-  };
-
-  static constexpr const char* kDTypes[] = {
-    "auto",               // a
-    nullptr,              // b
-    nullptr,              // c
-    "decimal64",          // d
-    "decimal128",         // e
-    "decimal32",          // f
-    nullptr,              // g
-    "half",               // h
-    "char32_t",           // i
-    nullptr,              // j
-    nullptr,              // k
-    nullptr,              // l
-    nullptr,              // m
-    "decltype(nullptr)",  // n
-    nullptr,              // o
-    nullptr,              // p
-    nullptr,              // q
-    nullptr,              // r
-    "char16_t",           // s
-    nullptr,              // t
-    nullptr,              // u
-    nullptr,              // v
-    nullptr,              // w
-    nullptr,              // x
-    nullptr,              // y
-    nullptr,              // z
-  };
-
-  static constexpr const char* kSTypes[] = {
-    "std::allocator",     // a
-    "std::basic_string",  // b
-    nullptr,              // c
-    "std::iostream",      // d
-    nullptr,              // e
-    nullptr,              // f
-    nullptr,              // g
-    nullptr,              // h
-    "std::istream",       // i
-    nullptr,              // j
-    nullptr,              // k
-    nullptr,              // l
-    nullptr,              // m
-    nullptr,              // n
-    "std::ostream",       // o
-    nullptr,              // p
-    nullptr,              // q
-    nullptr,              // r
-    "std::string",        // s
-    nullptr,              // t
-    nullptr,              // u
-    nullptr,              // v
-    nullptr,              // w
-    nullptr,              // x
-    nullptr,              // y
-    nullptr,              // z
-  };
-};
-
-#endif  // __LIB_DEMANGLE_DEMANGLER_H
diff --git a/demangle/OWNERS b/demangle/OWNERS
deleted file mode 100644
index 6f7e4a3..0000000
--- a/demangle/OWNERS
+++ /dev/null
@@ -1 +0,0 @@
-cferris@google.com
diff --git a/demangle/demangle.cpp b/demangle/demangle.cpp
deleted file mode 100644
index 66e5e58..0000000
--- a/demangle/demangle.cpp
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright (C) 2017 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 <getopt.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <cctype>
-#include <string>
-
-#include <demangle.h>
-
-extern "C" char* __cxa_demangle(const char*, char*, size_t*, int*);
-
-static void Usage(const char* prog_name) {
-  printf("usage: %s [-c] [NAME_TO_DEMANGLE...]\n", prog_name);
-  printf("\n");
-  printf("Demangles C++ mangled names if supplied on the command-line, or found\n");
-  printf("reading from stdin otherwise.\n");
-  printf("\n");
-  printf("-c\tCompare against __cxa_demangle\n");
-  printf("\n");
-}
-
-static std::string DemangleWithCxa(const char* name) {
-  const char* cxa_demangle = __cxa_demangle(name, nullptr, nullptr, nullptr);
-  if (cxa_demangle == nullptr) {
-    return name;
-  }
-
-  // The format of our demangler is slightly different from the cxa demangler
-  // so modify the cxa demangler output. Specifically, for templates, remove
-  // the spaces between '>' and '>'.
-  std::string demangled_str;
-  for (size_t i = 0; i < strlen(cxa_demangle); i++) {
-    if (i > 2 && cxa_demangle[i] == '>' && std::isspace(cxa_demangle[i - 1]) &&
-        cxa_demangle[i - 2] == '>') {
-      demangled_str.resize(demangled_str.size() - 1);
-    }
-    demangled_str += cxa_demangle[i];
-  }
-  return demangled_str;
-}
-
-static void Compare(const char* name, const std::string& demangled_name) {
-  std::string cxa_demangled_name(DemangleWithCxa(name));
-  if (cxa_demangled_name != demangled_name) {
-    printf("\nMismatch!\n");
-    printf("\tmangled name: %s\n", name);
-    printf("\tour demangle: %s\n", demangled_name.c_str());
-    printf("\tcxa demangle: %s\n", cxa_demangled_name.c_str());
-    exit(1);
-  }
-}
-
-static int Filter(bool compare) {
-  char* line = nullptr;
-  size_t line_length = 0;
-
-  while ((getline(&line, &line_length, stdin)) != -1) {
-    char* p = line;
-    char* name;
-    while ((name = strstr(p, "_Z")) != nullptr) {
-      // Output anything before the identifier.
-      *name = 0;
-      printf("%s", p);
-      *name = '_';
-
-      // Extract the identifier.
-      p = name;
-      while (*p && (std::isalnum(*p) || *p == '_' || *p == '.' || *p == '$')) ++p;
-
-      // Demangle and output.
-      std::string identifier(name, p);
-      std::string demangled_name = demangle(identifier.c_str());
-      printf("%s", demangled_name.c_str());
-
-      if (compare) Compare(identifier.c_str(), demangled_name);
-    }
-    // Output anything after the last identifier.
-    printf("%s", p);
-  }
-
-  free(line);
-  return 0;
-}
-
-int main(int argc, char** argv) {
-#ifdef __BIONIC__
-  const char* prog_name = getprogname();
-#else
-  const char* prog_name = argv[0];
-#endif
-
-  bool compare = false;
-  int opt_char;
-  while ((opt_char = getopt(argc, argv, "c")) != -1) {
-    if (opt_char == 'c') {
-      compare = true;
-    } else {
-      Usage(prog_name);
-      return 1;
-    }
-  }
-
-  // With no arguments, act as a filter.
-  if (optind == argc) return Filter(compare);
-
-  // Otherwise demangle each argument.
-  while (optind < argc) {
-    const char* name = argv[optind++];
-    std::string demangled_name = demangle(name);
-    printf("%s\n", demangled_name.c_str());
-
-    if (compare) Compare(name, demangled_name);
-  }
-  return 0;
-}
diff --git a/demangle/demangle_fuzzer.cpp b/demangle/demangle_fuzzer.cpp
deleted file mode 100644
index 83fafc2..0000000
--- a/demangle/demangle_fuzzer.cpp
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2017 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 <stddef.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include <string>
-
-#include "Demangler.h"
-
-extern "C" void LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
-  std::vector<char> data_str(size + 1);
-  memcpy(data_str.data(), data, size);
-  data_str[size] = '\0';
-
-  Demangler demangler;
-  std::string demangled_name = demangler.Parse(data_str.data());
-  if (size != 0 && data_str[0] != '\0' && demangled_name.empty()) {
-    abort();
-  }
-}
diff --git a/demangle/include/demangle.h b/demangle/include/demangle.h
deleted file mode 100644
index 01f1b80..0000000
--- a/demangle/include/demangle.h
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2017 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.
- */
-
-#ifndef __LIB_DEMANGLE_H_
-#define __LIB_DEMANGLE_H_
-
-#include <string>
-
-// If the name cannot be demangled, the original name will be returned as
-// a std::string. If the name can be demangled, then the demangled name
-// will be returned as a std::string.
-std::string demangle(const char* name);
-
-#endif  // __LIB_DEMANGLE_H_
diff --git a/fs_mgr/libsnapshot/Android.bp b/fs_mgr/libsnapshot/Android.bp
new file mode 100644
index 0000000..3a08049
--- /dev/null
+++ b/fs_mgr/libsnapshot/Android.bp
@@ -0,0 +1,36 @@
+//
+// Copyright (C) 2018 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.
+//
+
+cc_library {
+    name: "libsnapshot",
+    recovery_available: true,
+    defaults: ["fs_mgr_defaults"],
+    cppflags: [
+        "-D_FILE_OFFSET_BITS=64",
+    ],
+    srcs: [
+        "snapshot.cpp",
+    ],
+    shared_libs: [
+        "libbase",
+        "liblog",
+    ],
+    static_libs: [
+        "libdm",
+        "libext2_uuid",
+    ],
+    export_include_dirs: ["include"],
+}
diff --git a/fs_mgr/libsnapshot/OWNERS b/fs_mgr/libsnapshot/OWNERS
new file mode 100644
index 0000000..0cfa7e4
--- /dev/null
+++ b/fs_mgr/libsnapshot/OWNERS
@@ -0,0 +1,2 @@
+dvander@google.com
+elsk@google.com
diff --git a/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h b/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h
new file mode 100644
index 0000000..5cfd7fa
--- /dev/null
+++ b/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h
@@ -0,0 +1,88 @@
+// 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 <chrono>
+#include <memory>
+#include <string>
+
+namespace android {
+namespace snapshot {
+
+enum class UpdateStatus {
+    // No update or merge is in progress.
+    None,
+
+    // An update is pending, but has not been successfully booted yet.
+    Unverified,
+
+    // The kernel is merging in the background.
+    Merging,
+
+    // Merging is complete, and needs to be acknowledged.
+    MergeCompleted
+};
+
+class SnapshotManager final {
+  public:
+    // Return a new SnapshotManager instance, or null on error.
+    static std::unique_ptr<SnapshotManager> New();
+
+    // Create a new snapshot device with the given name, base device, and COW device
+    // size. The new device path will be returned in |dev_path|. If timeout_ms is
+    // greater than zero, this function will wait the given amount of time for
+    // |dev_path| to become available, and fail otherwise. If timeout_ms is 0, then
+    // no wait will occur and |dev_path| may not yet exist on return.
+    bool CreateSnapshot(const std::string& name, const std::string& base_device, uint64_t cow_size,
+                        std::string* dev_path, const std::chrono::milliseconds& timeout_ms);
+
+    // Map a snapshot device that was previously created with CreateSnapshot.
+    // If a merge was previously initiated, the device-mapper table will have a
+    // snapshot-merge target instead of a snapshot target. The timeout parameter
+    // is the same as in CreateSnapshotDevice.
+    bool MapSnapshotDevice(const std::string& name, const std::string& base_device,
+                           const std::chrono::milliseconds& timeout_ms, std::string* dev_path);
+
+    // Unmap a snapshot device previously mapped with MapSnapshotDevice().
+    bool UnmapSnapshotDevice(const std::string& name);
+
+    // Remove the backing copy-on-write image for the named snapshot. If the
+    // device is still mapped, this will attempt an Unmap, and fail if the
+    // unmap fails.
+    bool DeleteSnapshot(const std::string& name);
+
+    // Initiate a merge on all snapshot devices. This should only be used after an
+    // update has been marked successful after booting.
+    bool InitiateMerge();
+
+    // Wait for the current merge to finish, then perform cleanup when it
+    // completes. It is necessary to call this after InitiateMerge(), or when
+    // a merge is detected for the first time after boot.
+    bool WaitForMerge();
+
+    // Find the status of the current update, if any.
+    //
+    // |progress| depends on the returned status:
+    //   None: 0
+    //   Unverified: 0
+    //   Merging: Value in the range [0, 100)
+    //   MergeCompleted: 100
+    UpdateStatus GetUpdateStatus(double* progress);
+};
+
+}  // namespace snapshot
+}  // namespace android
diff --git a/fs_mgr/libsnapshot/snapshot.cpp b/fs_mgr/libsnapshot/snapshot.cpp
new file mode 100644
index 0000000..3e80239
--- /dev/null
+++ b/fs_mgr/libsnapshot/snapshot.cpp
@@ -0,0 +1,72 @@
+// 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 <libsnapshot/snapshot.h>
+
+namespace android {
+namespace snapshot {
+
+std::unique_ptr<SnapshotManager> SnapshotManager::New() {
+    return std::make_unique<SnapshotManager>();
+}
+
+bool SnapshotManager::CreateSnapshot(const std::string& name, const std::string& base_device,
+                                     uint64_t cow_size, std::string* dev_path,
+                                     const std::chrono::milliseconds& timeout_ms) {
+    // (1) Create COW device using libgsi_image.
+    // (2) Create snapshot device using libdm + DmTargetSnapshot.
+    // (3) Record partition in /metadata/ota.
+    (void)name;
+    (void)base_device;
+    (void)cow_size;
+    (void)dev_path;
+    (void)timeout_ms;
+    return false;
+}
+
+bool SnapshotManager::MapSnapshotDevice(const std::string& name, const std::string& base_device,
+                                        const std::chrono::milliseconds& timeout_ms,
+                                        std::string* dev_path) {
+    (void)name;
+    (void)base_device;
+    (void)dev_path;
+    (void)timeout_ms;
+    return false;
+}
+
+bool SnapshotManager::UnmapSnapshotDevice(const std::string& name) {
+    (void)name;
+    return false;
+}
+
+bool SnapshotManager::DeleteSnapshot(const std::string& name) {
+    (void)name;
+    return false;
+}
+
+bool SnapshotManager::InitiateMerge() {
+    return false;
+}
+
+bool SnapshotManager::WaitForMerge() {
+    return false;
+}
+
+UpdateStatus SnapshotManager::GetUpdateStatus(double* progress) {
+    *progress = 0.0f;
+    return UpdateStatus::None;
+}
+
+}  // namespace snapshot
+}  // namespace android
diff --git a/init/reboot.cpp b/init/reboot.cpp
index cb54d34..b0b5b54 100644
--- a/init/reboot.cpp
+++ b/init/reboot.cpp
@@ -670,11 +670,18 @@
                                << err;
                 }
             } else if (reboot_target == "recovery") {
-                const std::vector<std::string> options = {};
-                std::string err;
-                if (!write_bootloader_message(options, &err)) {
-                    LOG(ERROR) << "Failed to set bootloader message: " << err;
-                    return false;
+                bootloader_message boot = {};
+                if (std::string err; !read_bootloader_message(&boot, &err)) {
+                    LOG(ERROR) << "Failed to read bootloader message: " << err;
+                }
+                // Update the boot command field if it's empty, and preserve
+                // the other arguments in the bootloader message.
+                if (boot.command[0] == '\0') {
+                    strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
+                    if (std::string err; !write_bootloader_message(boot, &err)) {
+                        LOG(ERROR) << "Failed to set bootloader message: " << err;
+                        return false;
+                    }
                 }
             } else if (reboot_target == "sideload" || reboot_target == "sideload-auto-reboot" ||
                        reboot_target == "fastboot") {
diff --git a/libbacktrace/Android.bp b/libbacktrace/Android.bp
index 9ece847..565f2c3 100644
--- a/libbacktrace/Android.bp
+++ b/libbacktrace/Android.bp
@@ -97,7 +97,6 @@
             cflags: ["-DNO_LIBDEXFILE_SUPPORT"],
         },
     },
-    whole_static_libs: ["libdemangle"],
 }
 
 cc_test_library {
diff --git a/libbacktrace/Backtrace.cpp b/libbacktrace/Backtrace.cpp
index 71980d7..3e050ab 100644
--- a/libbacktrace/Backtrace.cpp
+++ b/libbacktrace/Backtrace.cpp
@@ -28,13 +28,13 @@
 #include <backtrace/Backtrace.h>
 #include <backtrace/BacktraceMap.h>
 
-#include <demangle.h>
-
 #include "BacktraceLog.h"
 #include "UnwindStack.h"
 
 using android::base::StringPrintf;
 
+extern "C" char* __cxa_demangle(const char*, char*, size_t*, int*);
+
 //-------------------------------------------------------------------------
 // Backtrace functions.
 //-------------------------------------------------------------------------
@@ -63,7 +63,14 @@
   if (map->start == 0 || (map->flags & PROT_DEVICE_MAP)) {
     return "";
   }
-  return demangle(GetFunctionNameRaw(pc, offset).c_str());
+  std::string name(GetFunctionNameRaw(pc, offset));
+  char* demangled_name = __cxa_demangle(name.c_str(), nullptr, nullptr, nullptr);
+  if (demangled_name != nullptr) {
+    name = demangled_name;
+    free(demangled_name);
+    return name;
+  }
+  return name;
 }
 
 bool Backtrace::VerifyReadWordArgs(uint64_t ptr, word_t* out_value) {
diff --git a/libbacktrace/UnwindStack.cpp b/libbacktrace/UnwindStack.cpp
index a128623..624711f 100644
--- a/libbacktrace/UnwindStack.cpp
+++ b/libbacktrace/UnwindStack.cpp
@@ -24,7 +24,6 @@
 #include <string>
 
 #include <backtrace/Backtrace.h>
-#include <demangle.h>
 #include <unwindstack/Elf.h>
 #include <unwindstack/MapInfo.h>
 #include <unwindstack/Maps.h>
@@ -41,6 +40,8 @@
 #include "UnwindStack.h"
 #include "UnwindStackMap.h"
 
+extern "C" char* __cxa_demangle(const char*, char*, size_t*, int*);
+
 bool Backtrace::Unwind(unwindstack::Regs* regs, BacktraceMap* back_map,
                        std::vector<backtrace_frame_data_t>* frames, size_t num_ignore_frames,
                        std::vector<std::string>* skip_names, BacktraceUnwindError* error) {
@@ -115,7 +116,13 @@
     back_frame->pc = frame->pc;
     back_frame->sp = frame->sp;
 
-    back_frame->func_name = demangle(frame->function_name.c_str());
+    char* demangled_name = __cxa_demangle(frame->function_name.c_str(), nullptr, nullptr, nullptr);
+    if (demangled_name != nullptr) {
+      back_frame->func_name = demangled_name;
+      free(demangled_name);
+    } else {
+      back_frame->func_name = frame->function_name;
+    }
     back_frame->func_offset = frame->function_offset;
 
     back_frame->map.name = frame->map_name;
diff --git a/libmeminfo/Android.bp b/libmeminfo/Android.bp
index 8eb41b9..8dcc77b 100644
--- a/libmeminfo/Android.bp
+++ b/libmeminfo/Android.bp
@@ -26,6 +26,12 @@
         "liblog",
         "libprocinfo",
     ],
+    target: {
+        darwin: {
+            enabled: false,
+        },
+
+    },
 }
 
 cc_library {
diff --git a/libmeminfo/tools/Android.bp b/libmeminfo/tools/Android.bp
index a592a25..3968c09 100644
--- a/libmeminfo/tools/Android.bp
+++ b/libmeminfo/tools/Android.bp
@@ -67,6 +67,12 @@
         "libbase",
         "libmeminfo",
     ],
+
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
 }
 
 cc_binary {
diff --git a/libnativeloader/Android.bp b/libnativeloader/Android.bp
index debc43f..b860db9 100644
--- a/libnativeloader/Android.bp
+++ b/libnativeloader/Android.bp
@@ -70,3 +70,27 @@
     host_supported: true,
     export_include_dirs: ["include"],
 }
+
+cc_test {
+    name: "libnativeloader_test",
+    srcs: [
+        "native_loader_test.cpp",
+        "native_loader.cpp",
+        "library_namespaces.cpp",
+        "native_loader_namespace.cpp",
+        "public_libraries.cpp",
+    ],
+    cflags: ["-DANDROID"],
+    static_libs: [
+        "libbase",
+        "liblog",
+        "libnativehelper",
+        "libgmock",
+    ],
+    header_libs: [
+        "libnativebridge-headers",
+        "libnativeloader-headers",
+    ],
+    system_shared_libs: ["libc", "libm"],
+    test_suites: ["device-tests"],
+}
diff --git a/libnativeloader/TEST_MAPPING b/libnativeloader/TEST_MAPPING
new file mode 100644
index 0000000..7becb77
--- /dev/null
+++ b/libnativeloader/TEST_MAPPING
@@ -0,0 +1,12 @@
+{
+  "presubmit": [
+    {
+      "name": "libnativeloader_test"
+    }
+  ],
+  "imports": [
+    {
+      "path": "cts/tests/tests/jni"
+    }
+  ]
+}
diff --git a/libnativeloader/library_namespaces.h b/libnativeloader/library_namespaces.h
index fd46cdc..6e9a190 100644
--- a/libnativeloader/library_namespaces.h
+++ b/libnativeloader/library_namespaces.h
@@ -42,7 +42,10 @@
   LibraryNamespaces& operator=(const LibraryNamespaces&) = delete;
 
   void Initialize();
-  void Reset() { namespaces_.clear(); }
+  void Reset() {
+    namespaces_.clear();
+    initialized_ = false;
+  }
   NativeLoaderNamespace* Create(JNIEnv* env, uint32_t target_sdk_version, jobject class_loader,
                                 bool is_shared, jstring dex_path, jstring java_library_path,
                                 jstring java_permitted_path, std::string* error_msg);
diff --git a/libnativeloader/native_loader_test.cpp b/libnativeloader/native_loader_test.cpp
new file mode 100644
index 0000000..614188b
--- /dev/null
+++ b/libnativeloader/native_loader_test.cpp
@@ -0,0 +1,566 @@
+/*
+ * 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 <dlfcn.h>
+#include <memory>
+#include <unordered_map>
+
+#include <android-base/strings.h>
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+#include <jni.h>
+
+#include "native_loader_namespace.h"
+#include "nativeloader/dlext_namespaces.h"
+#include "nativeloader/native_loader.h"
+#include "public_libraries.h"
+
+using namespace ::testing;
+
+namespace android {
+namespace nativeloader {
+
+// gmock interface that represents interested platform APIs on libdl and libnativebridge
+class Platform {
+ public:
+  virtual ~Platform() {}
+
+  // libdl APIs
+  virtual void* dlopen(const char* filename, int flags) = 0;
+  virtual int dlclose(void* handle) = 0;
+  virtual char* dlerror(void) = 0;
+
+  // These mock_* are the APIs semantically the same across libdl and libnativebridge.
+  // Instead of having two set of mock APIs for the two, define only one set with an additional
+  // argument 'bool bridged' to identify the context (i.e., called for libdl or libnativebridge).
+  typedef char* mock_namespace_handle;
+  virtual bool mock_init_anonymous_namespace(bool bridged, const char* sonames,
+                                             const char* search_paths) = 0;
+  virtual mock_namespace_handle mock_create_namespace(
+      bool bridged, const char* name, const char* ld_library_path, const char* default_library_path,
+      uint64_t type, const char* permitted_when_isolated_path, mock_namespace_handle parent) = 0;
+  virtual bool mock_link_namespaces(bool bridged, mock_namespace_handle from,
+                                    mock_namespace_handle to, const char* sonames) = 0;
+  virtual mock_namespace_handle mock_get_exported_namespace(bool bridged, const char* name) = 0;
+  virtual void* mock_dlopen_ext(bool bridged, const char* filename, int flags,
+                                mock_namespace_handle ns) = 0;
+
+  // libnativebridge APIs for which libdl has no corresponding APIs
+  virtual bool NativeBridgeInitialized() = 0;
+  virtual const char* NativeBridgeGetError() = 0;
+  virtual bool NativeBridgeIsPathSupported(const char*) = 0;
+  virtual bool NativeBridgeIsSupported(const char*) = 0;
+
+  // To mock "ClassLoader Object.getParent()"
+  virtual const char* JniObject_getParent(const char*) = 0;
+};
+
+// The mock does not actually create a namespace object. But simply casts the pointer to the
+// string for the namespace name as the handle to the namespace object.
+#define TO_ANDROID_NAMESPACE(str) \
+  reinterpret_cast<struct android_namespace_t*>(const_cast<char*>(str))
+
+#define TO_BRIDGED_NAMESPACE(str) \
+  reinterpret_cast<struct native_bridge_namespace_t*>(const_cast<char*>(str))
+
+#define TO_MOCK_NAMESPACE(ns) reinterpret_cast<Platform::mock_namespace_handle>(ns)
+
+// These represents built-in namespaces created by the linker according to ld.config.txt
+static std::unordered_map<std::string, Platform::mock_namespace_handle> namespaces = {
+    {"platform", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("platform"))},
+    {"default", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("default"))},
+    {"runtime", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("runtime"))},
+    {"sphal", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("sphal"))},
+    {"vndk", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("vndk"))},
+};
+
+// The actual gmock object
+class MockPlatform : public Platform {
+ public:
+  MockPlatform(bool is_bridged) : is_bridged_(is_bridged) {
+    ON_CALL(*this, NativeBridgeIsSupported(_)).WillByDefault(Return(is_bridged_));
+    ON_CALL(*this, NativeBridgeIsPathSupported(_)).WillByDefault(Return(is_bridged_));
+    ON_CALL(*this, mock_get_exported_namespace(_, _))
+        .WillByDefault(Invoke([](bool, const char* name) -> mock_namespace_handle {
+          if (namespaces.find(name) != namespaces.end()) {
+            return namespaces[name];
+          }
+          return nullptr;
+        }));
+  }
+
+  // Mocking libdl APIs
+  MOCK_METHOD2(dlopen, void*(const char*, int));
+  MOCK_METHOD1(dlclose, int(void*));
+  MOCK_METHOD0(dlerror, char*());
+
+  // Mocking the common APIs
+  MOCK_METHOD3(mock_init_anonymous_namespace, bool(bool, const char*, const char*));
+  MOCK_METHOD7(mock_create_namespace,
+               mock_namespace_handle(bool, const char*, const char*, const char*, uint64_t,
+                                     const char*, mock_namespace_handle));
+  MOCK_METHOD4(mock_link_namespaces,
+               bool(bool, mock_namespace_handle, mock_namespace_handle, const char*));
+  MOCK_METHOD2(mock_get_exported_namespace, mock_namespace_handle(bool, const char*));
+  MOCK_METHOD4(mock_dlopen_ext, void*(bool, const char*, int, mock_namespace_handle));
+
+  // Mocking libnativebridge APIs
+  MOCK_METHOD0(NativeBridgeInitialized, bool());
+  MOCK_METHOD0(NativeBridgeGetError, const char*());
+  MOCK_METHOD1(NativeBridgeIsPathSupported, bool(const char*));
+  MOCK_METHOD1(NativeBridgeIsSupported, bool(const char*));
+
+  // Mocking "ClassLoader Object.getParent()"
+  MOCK_METHOD1(JniObject_getParent, const char*(const char*));
+
+ private:
+  bool is_bridged_;
+};
+
+static std::unique_ptr<MockPlatform> mock;
+
+// Provide C wrappers for the mock object.
+extern "C" {
+void* dlopen(const char* file, int flag) {
+  return mock->dlopen(file, flag);
+}
+
+int dlclose(void* handle) {
+  return mock->dlclose(handle);
+}
+
+char* dlerror(void) {
+  return mock->dlerror();
+}
+
+bool android_init_anonymous_namespace(const char* sonames, const char* search_path) {
+  return mock->mock_init_anonymous_namespace(false, sonames, search_path);
+}
+
+struct android_namespace_t* android_create_namespace(const char* name, const char* ld_library_path,
+                                                     const char* default_library_path,
+                                                     uint64_t type,
+                                                     const char* permitted_when_isolated_path,
+                                                     struct android_namespace_t* parent) {
+  return TO_ANDROID_NAMESPACE(
+      mock->mock_create_namespace(false, name, ld_library_path, default_library_path, type,
+                                  permitted_when_isolated_path, TO_MOCK_NAMESPACE(parent)));
+}
+
+bool android_link_namespaces(struct android_namespace_t* from, struct android_namespace_t* to,
+                             const char* sonames) {
+  return mock->mock_link_namespaces(false, TO_MOCK_NAMESPACE(from), TO_MOCK_NAMESPACE(to), sonames);
+}
+
+struct android_namespace_t* android_get_exported_namespace(const char* name) {
+  return TO_ANDROID_NAMESPACE(mock->mock_get_exported_namespace(false, name));
+}
+
+void* android_dlopen_ext(const char* filename, int flags, const android_dlextinfo* info) {
+  return mock->mock_dlopen_ext(false, filename, flags, TO_MOCK_NAMESPACE(info->library_namespace));
+}
+
+// libnativebridge APIs
+bool NativeBridgeIsSupported(const char* libpath) {
+  return mock->NativeBridgeIsSupported(libpath);
+}
+
+struct native_bridge_namespace_t* NativeBridgeGetExportedNamespace(const char* name) {
+  return TO_BRIDGED_NAMESPACE(mock->mock_get_exported_namespace(true, name));
+}
+
+struct native_bridge_namespace_t* NativeBridgeCreateNamespace(
+    const char* name, const char* ld_library_path, const char* default_library_path, uint64_t type,
+    const char* permitted_when_isolated_path, struct native_bridge_namespace_t* parent) {
+  return TO_BRIDGED_NAMESPACE(
+      mock->mock_create_namespace(true, name, ld_library_path, default_library_path, type,
+                                  permitted_when_isolated_path, TO_MOCK_NAMESPACE(parent)));
+}
+
+bool NativeBridgeLinkNamespaces(struct native_bridge_namespace_t* from,
+                                struct native_bridge_namespace_t* to, const char* sonames) {
+  return mock->mock_link_namespaces(true, TO_MOCK_NAMESPACE(from), TO_MOCK_NAMESPACE(to), sonames);
+}
+
+void* NativeBridgeLoadLibraryExt(const char* libpath, int flag,
+                                 struct native_bridge_namespace_t* ns) {
+  return mock->mock_dlopen_ext(true, libpath, flag, TO_MOCK_NAMESPACE(ns));
+}
+
+bool NativeBridgeInitialized() {
+  return mock->NativeBridgeInitialized();
+}
+
+bool NativeBridgeInitAnonymousNamespace(const char* public_ns_sonames,
+                                        const char* anon_ns_library_path) {
+  return mock->mock_init_anonymous_namespace(true, public_ns_sonames, anon_ns_library_path);
+}
+
+const char* NativeBridgeGetError() {
+  return mock->NativeBridgeGetError();
+}
+
+bool NativeBridgeIsPathSupported(const char* path) {
+  return mock->NativeBridgeIsPathSupported(path);
+}
+
+}  // extern "C"
+
+// A very simple JNI mock.
+// jstring is a pointer to utf8 char array. We don't need utf16 char here.
+// jobject, jclass, and jmethodID are also a pointer to utf8 char array
+// Only a few JNI methods that are actually used in libnativeloader are mocked.
+JNINativeInterface* CreateJNINativeInterface() {
+  JNINativeInterface* inf = new JNINativeInterface();
+  memset(inf, 0, sizeof(JNINativeInterface));
+
+  inf->GetStringUTFChars = [](JNIEnv*, jstring s, jboolean*) -> const char* {
+    return reinterpret_cast<const char*>(s);
+  };
+
+  inf->ReleaseStringUTFChars = [](JNIEnv*, jstring, const char*) -> void { return; };
+
+  inf->NewStringUTF = [](JNIEnv*, const char* bytes) -> jstring {
+    return reinterpret_cast<jstring>(const_cast<char*>(bytes));
+  };
+
+  inf->FindClass = [](JNIEnv*, const char* name) -> jclass {
+    return reinterpret_cast<jclass>(const_cast<char*>(name));
+  };
+
+  inf->CallObjectMethodV = [](JNIEnv*, jobject obj, jmethodID mid, va_list) -> jobject {
+    if (strcmp("getParent", reinterpret_cast<const char*>(mid)) == 0) {
+      // JniObject_getParent can be a valid jobject or nullptr if there is
+      // no parent classloader.
+      const char* ret = mock->JniObject_getParent(reinterpret_cast<const char*>(obj));
+      return reinterpret_cast<jobject>(const_cast<char*>(ret));
+    }
+    return nullptr;
+  };
+
+  inf->GetMethodID = [](JNIEnv*, jclass, const char* name, const char*) -> jmethodID {
+    return reinterpret_cast<jmethodID>(const_cast<char*>(name));
+  };
+
+  inf->NewWeakGlobalRef = [](JNIEnv*, jobject obj) -> jobject { return obj; };
+
+  inf->IsSameObject = [](JNIEnv*, jobject a, jobject b) -> jboolean {
+    return strcmp(reinterpret_cast<const char*>(a), reinterpret_cast<const char*>(b)) == 0;
+  };
+
+  return inf;
+}
+
+static void* const any_nonnull = reinterpret_cast<void*>(0x12345678);
+
+// Custom matcher for comparing namespace handles
+MATCHER_P(NsEq, other, "") {
+  *result_listener << "comparing " << reinterpret_cast<const char*>(arg) << " and " << other;
+  return strcmp(reinterpret_cast<const char*>(arg), reinterpret_cast<const char*>(other)) == 0;
+}
+
+/////////////////////////////////////////////////////////////////
+
+// Test fixture
+class NativeLoaderTest : public ::testing::TestWithParam<bool> {
+ protected:
+  bool IsBridged() { return GetParam(); }
+
+  void SetUp() override {
+    mock = std::make_unique<NiceMock<MockPlatform>>(IsBridged());
+
+    env = std::make_unique<JNIEnv>();
+    env->functions = CreateJNINativeInterface();
+  }
+
+  void SetExpectations() {
+    std::vector<std::string> default_public_libs =
+        android::base::Split(default_public_libraries(), ":");
+    for (auto l : default_public_libs) {
+      EXPECT_CALL(*mock, dlopen(StrEq(l.c_str()), RTLD_NOW | RTLD_NODELETE))
+          .WillOnce(Return(any_nonnull));
+    }
+  }
+
+  void RunTest() { InitializeNativeLoader(); }
+
+  void TearDown() override {
+    ResetNativeLoader();
+    delete env->functions;
+    mock.reset();
+  }
+
+  std::unique_ptr<JNIEnv> env;
+};
+
+/////////////////////////////////////////////////////////////////
+
+TEST_P(NativeLoaderTest, InitializeLoadsDefaultPublicLibraries) {
+  SetExpectations();
+  RunTest();
+}
+
+INSTANTIATE_TEST_SUITE_P(NativeLoaderTests, NativeLoaderTest, testing::Bool());
+
+/////////////////////////////////////////////////////////////////
+
+class NativeLoaderTest_Create : public NativeLoaderTest {
+ protected:
+  // Test inputs (initialized to the default values). Overriding these
+  // must be done before calling SetExpectations() and RunTest().
+  uint32_t target_sdk_version = 29;
+  std::string class_loader = "my_classloader";
+  bool is_shared = false;
+  std::string dex_path = "/data/app/foo/classes.dex";
+  std::string library_path = "/data/app/foo/lib/arm";
+  std::string permitted_path = "/data/app/foo/lib";
+
+  // expected output (.. for the default test inputs)
+  std::string expected_namespace_name = "classloader-namespace";
+  uint64_t expected_namespace_flags = ANDROID_NAMESPACE_TYPE_ISOLATED;
+  std::string expected_library_path = library_path;
+  std::string expected_permitted_path = std::string("/data:/mnt/expand:") + permitted_path;
+  std::string expected_parent_namespace = "platform";
+  bool expected_link_with_platform_ns = true;
+  bool expected_link_with_runtime_ns = true;
+  bool expected_link_with_sphal_ns = !vendor_public_libraries().empty();
+  bool expected_link_with_vndk_ns = false;
+  bool expected_link_with_default_ns = false;
+  std::string expected_shared_libs_to_platform_ns = default_public_libraries();
+  std::string expected_shared_libs_to_runtime_ns = runtime_public_libraries();
+  std::string expected_shared_libs_to_sphal_ns = vendor_public_libraries();
+  std::string expected_shared_libs_to_vndk_ns = vndksp_libraries();
+  std::string expected_shared_libs_to_default_ns = default_public_libraries();
+
+  void SetExpectations() {
+    NativeLoaderTest::SetExpectations();
+
+    ON_CALL(*mock, JniObject_getParent(StrEq(class_loader))).WillByDefault(Return(nullptr));
+
+    EXPECT_CALL(*mock, NativeBridgeIsPathSupported(_)).Times(AnyNumber());
+    EXPECT_CALL(*mock, NativeBridgeInitialized()).Times(AnyNumber());
+
+    if (IsBridged()) {
+      EXPECT_CALL(*mock,
+                  mock_init_anonymous_namespace(false, StrEq(default_public_libraries()), nullptr))
+          .WillOnce(Return(true));
+
+      EXPECT_CALL(*mock, NativeBridgeInitialized()).WillOnce(Return(true));
+    }
+
+    EXPECT_CALL(*mock, mock_init_anonymous_namespace(
+                           Eq(IsBridged()), StrEq(default_public_libraries()), StrEq(library_path)))
+        .WillOnce(Return(true));
+    EXPECT_CALL(*mock, mock_create_namespace(
+                           Eq(IsBridged()), StrEq(expected_namespace_name), nullptr,
+                           StrEq(expected_library_path), expected_namespace_flags,
+                           StrEq(expected_permitted_path), NsEq(expected_parent_namespace.c_str())))
+        .WillOnce(Return(TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE(dex_path.c_str()))));
+    if (expected_link_with_platform_ns) {
+      EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("platform"),
+                                              StrEq(expected_shared_libs_to_platform_ns)))
+          .WillOnce(Return(true));
+    }
+    if (expected_link_with_runtime_ns) {
+      EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("runtime"),
+                                              StrEq(expected_shared_libs_to_runtime_ns)))
+          .WillOnce(Return(true));
+    }
+    if (expected_link_with_sphal_ns) {
+      EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("sphal"),
+                                              StrEq(expected_shared_libs_to_sphal_ns)))
+          .WillOnce(Return(true));
+    }
+    if (expected_link_with_vndk_ns) {
+      EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("vndk"),
+                                              StrEq(expected_shared_libs_to_vndk_ns)))
+          .WillOnce(Return(true));
+    }
+    if (expected_link_with_default_ns) {
+      EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("default"),
+                                              StrEq(expected_shared_libs_to_default_ns)))
+          .WillOnce(Return(true));
+    }
+  }
+
+  void RunTest() {
+    NativeLoaderTest::RunTest();
+
+    jstring err = CreateClassLoaderNamespace(
+        env(), target_sdk_version, env()->NewStringUTF(class_loader.c_str()), is_shared,
+        env()->NewStringUTF(dex_path.c_str()), env()->NewStringUTF(library_path.c_str()),
+        env()->NewStringUTF(permitted_path.c_str()));
+
+    // no error
+    EXPECT_EQ(err, nullptr);
+
+    if (!IsBridged()) {
+      struct android_namespace_t* ns =
+          FindNamespaceByClassLoader(env(), env()->NewStringUTF(class_loader.c_str()));
+
+      // The created namespace is for this apk
+      EXPECT_EQ(dex_path.c_str(), reinterpret_cast<const char*>(ns));
+    } else {
+      struct NativeLoaderNamespace* ns =
+          FindNativeLoaderNamespaceByClassLoader(env(), env()->NewStringUTF(class_loader.c_str()));
+
+      // The created namespace is for the this apk
+      EXPECT_STREQ(dex_path.c_str(),
+                   reinterpret_cast<const char*>(ns->ToRawNativeBridgeNamespace()));
+    }
+  }
+
+  JNIEnv* env() { return NativeLoaderTest::env.get(); }
+};
+
+TEST_P(NativeLoaderTest_Create, DownloadedApp) {
+  SetExpectations();
+  RunTest();
+}
+
+TEST_P(NativeLoaderTest_Create, BundledSystemApp) {
+  dex_path = "/system/app/foo/foo.apk";
+  is_shared = true;
+
+  expected_namespace_flags = ANDROID_NAMESPACE_TYPE_ISOLATED | ANDROID_NAMESPACE_TYPE_SHARED;
+  SetExpectations();
+  RunTest();
+}
+
+TEST_P(NativeLoaderTest_Create, BundledVendorApp) {
+  dex_path = "/vendor/app/foo/foo.apk";
+  is_shared = true;
+
+  expected_namespace_flags = ANDROID_NAMESPACE_TYPE_ISOLATED | ANDROID_NAMESPACE_TYPE_SHARED;
+  SetExpectations();
+  RunTest();
+}
+
+TEST_P(NativeLoaderTest_Create, UnbundledVendorApp) {
+  dex_path = "/vendor/app/foo/foo.apk";
+  is_shared = false;
+
+  expected_namespace_name = "vendor-classloader-namespace";
+  expected_library_path = expected_library_path + ":/vendor/lib";
+  expected_permitted_path = expected_permitted_path + ":/vendor/lib";
+  expected_shared_libs_to_platform_ns =
+      expected_shared_libs_to_platform_ns + ":" + llndk_libraries();
+  expected_link_with_vndk_ns = true;
+  SetExpectations();
+  RunTest();
+}
+
+TEST_P(NativeLoaderTest_Create, BundledProductApp_pre30) {
+  dex_path = "/product/app/foo/foo.apk";
+  is_shared = true;
+
+  expected_namespace_flags = ANDROID_NAMESPACE_TYPE_ISOLATED | ANDROID_NAMESPACE_TYPE_SHARED;
+  SetExpectations();
+  RunTest();
+}
+
+TEST_P(NativeLoaderTest_Create, BundledProductApp_post30) {
+  dex_path = "/product/app/foo/foo.apk";
+  is_shared = true;
+  target_sdk_version = 30;
+
+  expected_namespace_flags = ANDROID_NAMESPACE_TYPE_ISOLATED | ANDROID_NAMESPACE_TYPE_SHARED;
+  SetExpectations();
+  RunTest();
+}
+
+TEST_P(NativeLoaderTest_Create, UnbundledProductApp_pre30) {
+  dex_path = "/product/app/foo/foo.apk";
+  is_shared = false;
+  SetExpectations();
+  RunTest();
+}
+
+TEST_P(NativeLoaderTest_Create, UnbundledProductApp_post30) {
+  dex_path = "/product/app/foo/foo.apk";
+  is_shared = false;
+  target_sdk_version = 30;
+
+  expected_namespace_name = "vendor-classloader-namespace";
+  expected_library_path = expected_library_path + ":/product/lib:/system/product/lib";
+  expected_permitted_path = expected_permitted_path + ":/product/lib:/system/product/lib";
+  expected_shared_libs_to_platform_ns =
+      expected_shared_libs_to_platform_ns + ":" + llndk_libraries();
+  expected_link_with_vndk_ns = true;
+  SetExpectations();
+  RunTest();
+}
+
+TEST_P(NativeLoaderTest_Create, TwoApks) {
+  SetExpectations();
+  const uint32_t second_app_target_sdk_version = 29;
+  const std::string second_app_class_loader = "second_app_classloader";
+  const bool second_app_is_shared = false;
+  const std::string second_app_dex_path = "/data/app/bar/classes.dex";
+  const std::string second_app_library_path = "/data/app/bar/lib/arm";
+  const std::string second_app_permitted_path = "/data/app/bar/lib";
+  const std::string expected_second_app_permitted_path =
+      std::string("/data:/mnt/expand:") + second_app_permitted_path;
+  const std::string expected_second_app_parent_namespace = "classloader-namespace";
+
+  // The scenario is that second app is loaded by the first app.
+  // So the first app's classloader (`classloader`) is parent of the second
+  // app's classloader.
+  ON_CALL(*mock, JniObject_getParent(StrEq(second_app_class_loader)))
+      .WillByDefault(Return(class_loader.c_str()));
+
+  // namespace for the second app is created. Its parent is set to the namespace
+  // of the first app.
+  EXPECT_CALL(*mock, mock_create_namespace(Eq(IsBridged()), StrEq(expected_namespace_name), nullptr,
+                                           StrEq(second_app_library_path), expected_namespace_flags,
+                                           StrEq(expected_second_app_permitted_path),
+                                           NsEq(dex_path.c_str())))
+      .WillOnce(Return(TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE(second_app_dex_path.c_str()))));
+  EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), NsEq(second_app_dex_path.c_str()), _, _))
+      .WillRepeatedly(Return(true));
+
+  RunTest();
+  jstring err = CreateClassLoaderNamespace(
+      env(), second_app_target_sdk_version, env()->NewStringUTF(second_app_class_loader.c_str()),
+      second_app_is_shared, env()->NewStringUTF(second_app_dex_path.c_str()),
+      env()->NewStringUTF(second_app_library_path.c_str()),
+      env()->NewStringUTF(second_app_permitted_path.c_str()));
+
+  // success
+  EXPECT_EQ(err, nullptr);
+
+  if (!IsBridged()) {
+    struct android_namespace_t* ns =
+        FindNamespaceByClassLoader(env(), env()->NewStringUTF(second_app_class_loader.c_str()));
+
+    // The created namespace is for the second apk
+    EXPECT_EQ(second_app_dex_path.c_str(), reinterpret_cast<const char*>(ns));
+  } else {
+    struct NativeLoaderNamespace* ns = FindNativeLoaderNamespaceByClassLoader(
+        env(), env()->NewStringUTF(second_app_class_loader.c_str()));
+
+    // The created namespace is for the second apk
+    EXPECT_STREQ(second_app_dex_path.c_str(),
+                 reinterpret_cast<const char*>(ns->ToRawNativeBridgeNamespace()));
+  }
+}
+
+INSTANTIATE_TEST_SUITE_P(NativeLoaderTests_Create, NativeLoaderTest_Create, testing::Bool());
+
+// TODO(b/130388701#comment22) add a test for anonymous namespace
+
+}  // namespace nativeloader
+}  // namespace android
diff --git a/libunwindstack/Android.bp b/libunwindstack/Android.bp
index 46fd69e..73237e6 100644
--- a/libunwindstack/Android.bp
+++ b/libunwindstack/Android.bp
@@ -158,6 +158,7 @@
 cc_test {
     name: "libunwindstack_test",
     defaults: ["libunwindstack_flags"],
+    isolated: true,
 
     srcs: [
         "tests/ArmExidxDecodeTest.cpp",
@@ -180,6 +181,7 @@
         "tests/ElfInterfaceTest.cpp",
         "tests/ElfTest.cpp",
         "tests/ElfTestUtils.cpp",
+        "tests/IsolatedSettings.cpp",
         "tests/JitDebugTest.cpp",
         "tests/LocalUnwinderTest.cpp",
         "tests/LogFake.cpp",
diff --git a/libunwindstack/tests/IsolatedSettings.cpp b/libunwindstack/tests/IsolatedSettings.cpp
new file mode 100644
index 0000000..dbd8bd6
--- /dev/null
+++ b/libunwindstack/tests/IsolatedSettings.cpp
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2016 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 <stdint.h>
+#include <stdio.h>
+
+extern "C" bool GetInitialArgs(const char*** args, size_t* num_args) {
+  static const char* initial_args[2] = {"--slow_threshold_ms=90000",
+                                        "--deadline_threshold_ms=120000"};
+  *args = initial_args;
+  *num_args = 2;
+  return true;
+}
diff --git a/libunwindstack/tests/MapInfoCreateMemoryTest.cpp b/libunwindstack/tests/MapInfoCreateMemoryTest.cpp
index 5b4ca7c..6c1cfa2 100644
--- a/libunwindstack/tests/MapInfoCreateMemoryTest.cpp
+++ b/libunwindstack/tests/MapInfoCreateMemoryTest.cpp
@@ -58,7 +58,7 @@
     ASSERT_TRUE(android::base::WriteFully(fd, buffer.data(), buffer.size()));
   }
 
-  static void SetUpTestSuite() {
+  void SetUp() override {
     std::vector<uint8_t> buffer(12288, 0);
     memcpy(buffer.data(), ELFMAG, SELFMAG);
     buffer[EI_CLASS] = ELFCLASS32;
@@ -72,9 +72,7 @@
 
     InitElf<Elf32_Ehdr, Elf32_Shdr>(elf32_at_map_.fd, 0x1000, 0x2000, ELFCLASS32);
     InitElf<Elf64_Ehdr, Elf64_Shdr>(elf64_at_map_.fd, 0x2000, 0x3000, ELFCLASS64);
-  }
 
-  void SetUp() override {
     memory_ = new MemoryFake;
     process_memory_.reset(memory_);
   }
@@ -82,17 +80,13 @@
   MemoryFake* memory_;
   std::shared_ptr<Memory> process_memory_;
 
-  static TemporaryFile elf_;
+  TemporaryFile elf_;
 
-  static TemporaryFile elf_at_1000_;
+  TemporaryFile elf_at_1000_;
 
-  static TemporaryFile elf32_at_map_;
-  static TemporaryFile elf64_at_map_;
+  TemporaryFile elf32_at_map_;
+  TemporaryFile elf64_at_map_;
 };
-TemporaryFile MapInfoCreateMemoryTest::elf_;
-TemporaryFile MapInfoCreateMemoryTest::elf_at_1000_;
-TemporaryFile MapInfoCreateMemoryTest::elf32_at_map_;
-TemporaryFile MapInfoCreateMemoryTest::elf64_at_map_;
 
 TEST_F(MapInfoCreateMemoryTest, end_le_start) {
   MapInfo info(nullptr, 0x100, 0x100, 0, 0, elf_.path);
diff --git a/libziparchive/Android.bp b/libziparchive/Android.bp
index 3843252..0253f2f 100644
--- a/libziparchive/Android.bp
+++ b/libziparchive/Android.bp
@@ -76,6 +76,10 @@
         "liblog",
     ],
 
+    // for FRIEND_TEST
+    static_libs: ["libgtest_prod"],
+    export_static_lib_headers: ["libgtest_prod"],
+
     export_include_dirs: ["include"],
 }
 
diff --git a/libziparchive/include/ziparchive/zip_writer.h b/libziparchive/include/ziparchive/zip_writer.h
index a2a0dbf..d68683d 100644
--- a/libziparchive/include/ziparchive/zip_writer.h
+++ b/libziparchive/include/ziparchive/zip_writer.h
@@ -19,6 +19,7 @@
 #include <cstdio>
 #include <ctime>
 
+#include <gtest/gtest_prod.h>
 #include <memory>
 #include <string>
 #include <string_view>
@@ -165,6 +166,7 @@
   int32_t StoreBytes(FileEntry* file, const void* data, uint32_t len);
   int32_t CompressBytes(FileEntry* file, const void* data, uint32_t len);
   int32_t FlushCompressedBytes(FileEntry* file);
+  bool ShouldUseDataDescriptor() const;
 
   enum class State {
     kWritingZip,
@@ -182,4 +184,6 @@
 
   std::unique_ptr<z_stream, void (*)(z_stream*)> z_stream_;
   std::vector<uint8_t> buffer_;
+
+  FRIEND_TEST(zipwriter, WriteToUnseekableFile);
 };
diff --git a/libziparchive/zip_writer.cc b/libziparchive/zip_writer.cc
index 198154b..67279a6 100644
--- a/libziparchive/zip_writer.cc
+++ b/libziparchive/zip_writer.cc
@@ -455,6 +455,11 @@
   return kNoError;
 }
 
+bool ZipWriter::ShouldUseDataDescriptor() const {
+  // Only use a trailing "data descriptor" if the output isn't seekable.
+  return !seekable_;
+}
+
 int32_t ZipWriter::FinishEntry() {
   if (state_ != State::kWritingEntry) {
     return kInvalidState;
@@ -467,7 +472,7 @@
     }
   }
 
-  if ((current_file_entry_.compression_method & kCompressDeflated) || !seekable_) {
+  if (ShouldUseDataDescriptor()) {
     // Some versions of ZIP don't allow STORED data to have a trailing DataDescriptor.
     // If this file is not seekable, or if the data is compressed, write a DataDescriptor.
     const uint32_t sig = DataDescriptor::kOptSignature;
@@ -515,7 +520,7 @@
   for (FileEntry& file : files_) {
     CentralDirectoryRecord cdr = {};
     cdr.record_signature = CentralDirectoryRecord::kSignature;
-    if ((file.compression_method & kCompressDeflated) || !seekable_) {
+    if (ShouldUseDataDescriptor()) {
       cdr.gpb_flags |= kGPBDDFlagMask;
     }
     cdr.compression_method = file.compression_method;
diff --git a/libziparchive/zip_writer_test.cc b/libziparchive/zip_writer_test.cc
index c3da23c..d324d4b 100644
--- a/libziparchive/zip_writer_test.cc
+++ b/libziparchive/zip_writer_test.cc
@@ -243,6 +243,7 @@
   ZipEntry data;
   ASSERT_EQ(0, FindEntry(handle, "file.txt", &data));
   EXPECT_EQ(kCompressDeflated, data.method);
+  EXPECT_EQ(0u, data.has_data_descriptor);
   ASSERT_EQ(4u, data.uncompressed_length);
   ASSERT_TRUE(AssertFileEntryContentsEq("helo", handle, &data));
 
@@ -351,6 +352,29 @@
   CloseArchive(handle);
 }
 
+TEST_F(zipwriter, WriteToUnseekableFile) {
+  const char* expected = "hello";
+  ZipWriter writer(file_);
+  writer.seekable_ = false;
+
+  ASSERT_EQ(0, writer.StartEntry("file.txt", 0));
+  ASSERT_EQ(0, writer.WriteBytes(expected, strlen(expected)));
+  ASSERT_EQ(0, writer.FinishEntry());
+  ASSERT_EQ(0, writer.Finish());
+  ASSERT_GE(0, lseek(fd_, 0, SEEK_SET));
+
+  ZipArchiveHandle handle;
+  ASSERT_EQ(0, OpenArchiveFd(fd_, "temp", &handle, false));
+  ZipEntry data;
+  ASSERT_EQ(0, FindEntry(handle, "file.txt", &data));
+  EXPECT_EQ(kCompressStored, data.method);
+  EXPECT_EQ(1u, data.has_data_descriptor);
+  EXPECT_EQ(strlen(expected), data.compressed_length);
+  ASSERT_EQ(strlen(expected), data.uncompressed_length);
+  ASSERT_TRUE(AssertFileEntryContentsEq(expected, handle, &data));
+  CloseArchive(handle);
+}
+
 TEST_F(zipwriter, TruncateFileAfterBackup) {
   ZipWriter writer(file_);
 
diff --git a/rootdir/init.rc b/rootdir/init.rc
index b438124..d22e9a7 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -414,6 +414,7 @@
     mkdir /metadata/vold
     chmod 0700 /metadata/vold
     mkdir /metadata/password_slots 0771 root system
+    mkdir /metadata/ota 0700 root system
 
     mkdir /metadata/apex 0700 root system
     mkdir /metadata/apex/sessions 0700 root system
diff --git a/rootdir/update_and_install_ld_config.mk b/rootdir/update_and_install_ld_config.mk
index 30537e7..dbe60e5 100644
--- a/rootdir/update_and_install_ld_config.mk
+++ b/rootdir/update_and_install_ld_config.mk
@@ -93,7 +93,7 @@
 # $(2): output file with the filtered list of lib names
 $(LOCAL_BUILT_MODULE): private-filter-out-private-libs = \
   paste -sd ":" $(1) > $(2) && \
-  cat $(PRIVATE_VNDK_PRIVATE_LIBRARIES_FILE) | xargs -n 1 -I privatelib bash -c "sed -i.bak 's/privatelib//' $(2)" && \
+  while read -r privatelib; do sed -i.bak "s/$$privatelib//" $(2) ; done < $(PRIVATE_VNDK_PRIVATE_LIBRARIES_FILE) && \
   sed -i.bak -e 's/::\+/:/g ; s/^:\+// ; s/:\+$$//' $(2) && \
   rm -f $(2).bak
 
@@ -154,8 +154,9 @@
 endif
 
 	$(hide) echo -n > $(PRIVATE_INTERMEDIATES_DIR)/private_llndk && \
-	cat $(PRIVATE_VNDK_PRIVATE_LIBRARIES_FILE) | \
-	xargs -n 1 -I privatelib bash -c "(grep privatelib $(PRIVATE_LLNDK_LIBRARIES_FILE) || true) >> $(PRIVATE_INTERMEDIATES_DIR)/private_llndk" && \
+	while read -r privatelib; \
+	do (grep $$privatelib $(PRIVATE_LLNDK_LIBRARIES_FILE) || true) >> $(PRIVATE_INTERMEDIATES_DIR)/private_llndk ; \
+	done < $(PRIVATE_VNDK_PRIVATE_LIBRARIES_FILE) && \
 	paste -sd ":" $(PRIVATE_INTERMEDIATES_DIR)/private_llndk | \
 	sed -i.bak -e "s?%PRIVATE_LLNDK_LIBRARIES%?$$(cat -)?g" $@