Merge "Provide Recent Disk Perf via IStoraged"
diff --git a/adb/Android.mk b/adb/Android.mk
index d76d175..0eeafb6 100644
--- a/adb/Android.mk
+++ b/adb/Android.mk
@@ -237,7 +237,7 @@
 LOCAL_LDLIBS_linux := -lrt -ldl -lpthread
 LOCAL_LDLIBS_darwin := -framework CoreFoundation -framework IOKit -lobjc
 LOCAL_LDLIBS_windows := -lws2_32 -luserenv
-LOCAL_STATIC_LIBRARIES_windows := AdbWinApi
+LOCAL_SHARED_LIBRARIES_windows := AdbWinApi
 
 LOCAL_MULTILIB := first
 
@@ -254,8 +254,8 @@
 # Use wmain instead of main
 LOCAL_LDFLAGS_windows := -municode
 LOCAL_LDLIBS_windows := -lws2_32 -lgdi32
-LOCAL_STATIC_LIBRARIES_windows := AdbWinApi
-LOCAL_REQUIRED_MODULES_windows := AdbWinApi AdbWinUsbApi
+LOCAL_SHARED_LIBRARIES_windows := AdbWinApi
+LOCAL_REQUIRED_MODULES_windows := AdbWinUsbApi
 
 LOCAL_SRC_FILES := \
     adb_client.cpp \
diff --git a/adb/adb.cpp b/adb/adb.cpp
index 6b30be8..0e38897 100644
--- a/adb/adb.cpp
+++ b/adb/adb.cpp
@@ -240,7 +240,10 @@
     D("Calling send_connect");
     apacket* cp = get_apacket();
     cp->msg.command = A_CNXN;
-    cp->msg.arg0 = t->get_protocol_version();
+    // Send the max supported version, but because the transport is
+    // initialized to A_VERSION_MIN, this will be compatible with every
+    // device.
+    cp->msg.arg0 = A_VERSION;
     cp->msg.arg1 = t->get_max_payload();
 
     std::string connection_str = get_connection_string();
diff --git a/adb/adb.h b/adb/adb.h
index 3651413..21e5d4b 100644
--- a/adb/adb.h
+++ b/adb/adb.h
@@ -44,7 +44,12 @@
 #define A_AUTH 0x48545541
 
 // ADB protocol version.
-#define A_VERSION 0x01000000
+// Version revision:
+// 0x01000000: original
+// 0x01000001: skip checksum (Dec 2017)
+#define A_VERSION_MIN 0x01000000
+#define A_VERSION_SKIP_CHECKSUM 0x01000001
+#define A_VERSION 0x01000001
 
 // Used for help/version information.
 #define ADB_VERSION_MAJOR 1
@@ -53,7 +58,7 @@
 std::string adb_version();
 
 // Increment this when we want to force users to start a new adb server.
-#define ADB_SERVER_VERSION 39
+#define ADB_SERVER_VERSION 40
 
 using TransportId = uint64_t;
 class atransport;
diff --git a/adb/client/usb_libusb.cpp b/adb/client/usb_libusb.cpp
index a5e6f23..18f585d 100644
--- a/adb/client/usb_libusb.cpp
+++ b/adb/client/usb_libusb.cpp
@@ -22,6 +22,7 @@
 
 #include <atomic>
 #include <chrono>
+#include <condition_variable>
 #include <memory>
 #include <mutex>
 #include <string>
diff --git a/adb/socket_spec.cpp b/adb/socket_spec.cpp
index 14eb16b..eb4df97 100644
--- a/adb/socket_spec.cpp
+++ b/adb/socket_spec.cpp
@@ -118,7 +118,7 @@
 bool is_socket_spec(const std::string& spec) {
     for (const auto& it : kLocalSocketTypes) {
         std::string prefix = it.first + ":";
-        if (StartsWith(spec, prefix.c_str())) {
+        if (StartsWith(spec, prefix)) {
             return true;
         }
     }
@@ -128,7 +128,7 @@
 bool is_local_socket_spec(const std::string& spec) {
     for (const auto& it : kLocalSocketTypes) {
         std::string prefix = it.first + ":";
-        if (StartsWith(spec, prefix.c_str())) {
+        if (StartsWith(spec, prefix)) {
             return true;
         }
     }
@@ -170,7 +170,7 @@
 
     for (const auto& it : kLocalSocketTypes) {
         std::string prefix = it.first + ":";
-        if (StartsWith(spec, prefix.c_str())) {
+        if (StartsWith(spec, prefix)) {
             if (!it.second.available) {
                 *error = StringPrintf("socket type %s is unavailable on this platform",
                                       it.first.c_str());
@@ -213,7 +213,7 @@
 
     for (const auto& it : kLocalSocketTypes) {
         std::string prefix = it.first + ":";
-        if (StartsWith(spec, prefix.c_str())) {
+        if (StartsWith(spec, prefix)) {
             if (!it.second.available) {
                 *error = StringPrintf("attempted to listen on unavailable socket type: '%s'",
                                       spec.c_str());
diff --git a/adb/transport.cpp b/adb/transport.cpp
index 089a1ec..f221785 100644
--- a/adb/transport.cpp
+++ b/adb/transport.cpp
@@ -163,7 +163,12 @@
 
 void send_packet(apacket* p, atransport* t) {
     p->msg.magic = p->msg.command ^ 0xffffffff;
-    p->msg.data_check = calculate_apacket_checksum(p);
+    // compute a checksum for connection/auth packets for compatibility reasons
+    if (t->get_protocol_version() >= A_VERSION_SKIP_CHECKSUM) {
+        p->msg.data_check = 0;
+    } else {
+        p->msg.data_check = calculate_apacket_checksum(p);
+    }
 
     print_packet("send", p);
 
@@ -947,10 +952,18 @@
 }
 
 std::string list_transports(bool long_listing) {
-    std::string result;
-
     std::lock_guard<std::recursive_mutex> lock(transport_lock);
-    for (const auto& t : transport_list) {
+
+    auto sorted_transport_list = transport_list;
+    sorted_transport_list.sort([](atransport*& x, atransport*& y) {
+        if (x->type != y->type) {
+            return x->type < y->type;
+        }
+        return strcmp(x->serial, y->serial) < 0;
+    });
+
+    std::string result;
+    for (const auto& t : sorted_transport_list) {
         append_transport(t, &result, long_listing);
     }
     return result;
@@ -1089,10 +1102,6 @@
     return true;
 }
 
-bool check_data(apacket* p) {
-    return calculate_apacket_checksum(p) == p->msg.data_check;
-}
-
 #if ADB_HOST
 std::shared_ptr<RSA> atransport::NextKey() {
     if (keys_.empty()) keys_ = adb_auth_get_private_keys();
diff --git a/adb/transport.h b/adb/transport.h
index 8c101fd..86cd992 100644
--- a/adb/transport.h
+++ b/adb/transport.h
@@ -66,7 +66,9 @@
     atransport(ConnectionState state = kCsOffline)
         : id(NextTransportId()), connection_state_(state) {
         transport_fde = {};
-        protocol_version = A_VERSION;
+        // Initialize protocol to min version for compatibility with older versions.
+        // Version will be updated post-connect.
+        protocol_version = A_VERSION_MIN;
         max_payload = MAX_PAYLOAD;
     }
     virtual ~atransport() {}
@@ -223,7 +225,6 @@
 void unregister_usb_transport(usb_handle* usb);
 
 bool check_header(apacket* p, atransport* t);
-bool check_data(apacket* p);
 
 void close_usb_devices();
 void close_usb_devices(std::function<bool(const atransport*)> predicate);
diff --git a/adb/transport_local.cpp b/adb/transport_local.cpp
index 9cd378c..d6c84da 100644
--- a/adb/transport_local.cpp
+++ b/adb/transport_local.cpp
@@ -77,11 +77,6 @@
         return -1;
     }
 
-    if (!check_data(p)) {
-        D("bad data: terminated (data)");
-        return -1;
-    }
-
     return 0;
 }
 
diff --git a/adb/transport_usb.cpp b/adb/transport_usb.cpp
index c3ac344..3474820 100644
--- a/adb/transport_usb.cpp
+++ b/adb/transport_usb.cpp
@@ -109,10 +109,6 @@
             goto err_msg;
         }
     }
-    if (!check_data(p)) {
-        D("remote usb: check_data failed, skip it");
-        goto err_msg;
-    }
     return 0;
 
 err_msg:
@@ -143,11 +139,6 @@
         }
     }
 
-    if (!check_data(p)) {
-        LOG(ERROR) << "remote usb: check_data failed";
-        return -1;
-    }
-
     return 0;
 }
 #endif
diff --git a/base/Android.bp b/base/Android.bp
index ad0edf4..01800af 100644
--- a/base/Android.bp
+++ b/base/Android.bp
@@ -116,6 +116,7 @@
         "stringprintf_test.cpp",
         "strings_test.cpp",
         "test_main.cpp",
+        "test_utils_test.cpp",
     ],
     target: {
         android: {
diff --git a/base/include/android-base/logging.h b/base/include/android-base/logging.h
index f93c696..afff2c9 100644
--- a/base/include/android-base/logging.h
+++ b/base/include/android-base/logging.h
@@ -42,6 +42,10 @@
 // By default, output goes to logcat on Android and stderr on the host.
 // A process can use `SetLogger` to decide where all logging goes.
 // Implementations are provided for logcat, stderr, and dmesg.
+//
+// By default, the process' name is used as the log tag.
+// Code can choose a specific log tag by defining LOG_TAG
+// before including this header.
 
 // This header also provides assertions:
 //
@@ -63,6 +67,16 @@
 
 #include "android-base/macros.h"
 
+// Note: DO NOT USE DIRECTLY. Use LOG_TAG instead.
+#ifdef _LOG_TAG_INTERNAL
+#error "_LOG_TAG_INTERNAL must not be defined"
+#endif
+#ifdef LOG_TAG
+#define _LOG_TAG_INTERNAL LOG_TAG
+#else
+#define _LOG_TAG_INTERNAL nullptr
+#endif
+
 namespace android {
 namespace base {
 
@@ -201,10 +215,10 @@
 
 // Get an ostream that can be used for logging at the given severity and to the
 // given destination. The same notes as for LOG_STREAM apply.
-#define LOG_STREAM_TO(dest, severity)                                   \
-  ::android::base::LogMessage(__FILE__, __LINE__,                       \
-                              ::android::base::dest,                    \
-                              SEVERITY_LAMBDA(severity), -1).stream()
+#define LOG_STREAM_TO(dest, severity)                                           \
+  ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::dest,        \
+                              SEVERITY_LAMBDA(severity), _LOG_TAG_INTERNAL, -1) \
+      .stream()
 
 // Logs a message to logcat on Android otherwise to stderr. If the severity is
 // FATAL it also causes an abort. For example:
@@ -231,10 +245,10 @@
 #define PLOG(severity) PLOG_TO(DEFAULT, severity)
 
 // Behaves like PLOG, but logs to the specified log ID.
-#define PLOG_TO(dest, severity)                                              \
-  LOGGING_PREAMBLE(severity) &&                                              \
-      ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::dest, \
-                                  SEVERITY_LAMBDA(severity), errno)          \
+#define PLOG_TO(dest, severity)                                                        \
+  LOGGING_PREAMBLE(severity) &&                                                        \
+      ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::dest,           \
+                                  SEVERITY_LAMBDA(severity), _LOG_TAG_INTERNAL, errno) \
           .stream()
 
 // Marker that code is yet to be implemented.
@@ -247,23 +261,26 @@
 //
 //     CHECK(false == true) results in a log message of
 //       "Check failed: false == true".
-#define CHECK(x)                                                                \
-  LIKELY((x)) || ABORT_AFTER_LOG_FATAL_EXPR(false) ||                           \
-      ::android::base::LogMessage(                                              \
-          __FILE__, __LINE__, ::android::base::DEFAULT, ::android::base::FATAL, \
-          -1).stream()                                                          \
+#define CHECK(x)                                                                 \
+  LIKELY((x)) || ABORT_AFTER_LOG_FATAL_EXPR(false) ||                            \
+      ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT,  \
+                                  ::android::base::FATAL, _LOG_TAG_INTERNAL, -1) \
+              .stream()                                                          \
           << "Check failed: " #x << " "
 
+// clang-format off
 // Helper for CHECK_xx(x,y) macros.
-#define CHECK_OP(LHS, RHS, OP)                                              \
-  for (auto _values = ::android::base::MakeEagerEvaluator(LHS, RHS);        \
-       UNLIKELY(!(_values.lhs OP _values.rhs));                             \
-       /* empty */)                                                         \
-  ABORT_AFTER_LOG_FATAL                                                     \
-  ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT, \
-                              ::android::base::FATAL, -1).stream()          \
-      << "Check failed: " << #LHS << " " << #OP << " " << #RHS              \
-      << " (" #LHS "=" << _values.lhs << ", " #RHS "=" << _values.rhs << ") "
+#define CHECK_OP(LHS, RHS, OP)                                                                 \
+  for (auto _values = ::android::base::MakeEagerEvaluator(LHS, RHS);                           \
+       UNLIKELY(!(_values.lhs OP _values.rhs));                                                \
+       /* empty */)                                                                            \
+  ABORT_AFTER_LOG_FATAL                                                                        \
+  ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT,                    \
+                              ::android::base::FATAL, _LOG_TAG_INTERNAL, -1)                   \
+          .stream()                                                                            \
+      << "Check failed: " << #LHS << " " << #OP << " " << #RHS << " (" #LHS "=" << _values.lhs \
+      << ", " #RHS "=" << _values.rhs << ") "
+// clang-format on
 
 // Check whether a condition holds between x and y, LOG(FATAL) if not. The value
 // of the expressions x and y is evaluated once. Extra logging can be appended
@@ -278,14 +295,17 @@
 #define CHECK_GE(x, y) CHECK_OP(x, y, >= )
 #define CHECK_GT(x, y) CHECK_OP(x, y, > )
 
+// clang-format off
 // Helper for CHECK_STRxx(s1,s2) macros.
 #define CHECK_STROP(s1, s2, sense)                                             \
   while (UNLIKELY((strcmp(s1, s2) == 0) != (sense)))                           \
     ABORT_AFTER_LOG_FATAL                                                      \
     ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT,  \
-                                ::android::base::FATAL, -1).stream()           \
+                                ::android::base::FATAL, _LOG_TAG_INTERNAL, -1) \
+        .stream()                                                              \
         << "Check failed: " << "\"" << (s1) << "\""                            \
         << ((sense) ? " == " : " != ") << "\"" << (s2) << "\""
+// clang-format on
 
 // Check for string (const char*) equality between s1 and s2, LOG(FATAL) if not.
 #define CHECK_STREQ(s1, s2) CHECK_STROP(s1, s2, true)
@@ -400,8 +420,8 @@
 // of a CHECK. The destructor will abort if the severity is FATAL.
 class LogMessage {
  public:
-  LogMessage(const char* file, unsigned int line, LogId id,
-             LogSeverity severity, int error);
+  LogMessage(const char* file, unsigned int line, LogId id, LogSeverity severity, const char* tag,
+             int error);
 
   ~LogMessage();
 
@@ -410,12 +430,17 @@
   std::ostream& stream();
 
   // The routine that performs the actual logging.
-  static void LogLine(const char* file, unsigned int line, LogId id,
-                      LogSeverity severity, const char* msg);
+  static void LogLine(const char* file, unsigned int line, LogId id, LogSeverity severity,
+                      const char* tag, const char* msg);
 
  private:
   const std::unique_ptr<LogMessageData> data_;
 
+  // TODO(b/35361699): remove these symbols once all prebuilds stop using it.
+  LogMessage(const char* file, unsigned int line, LogId id, LogSeverity severity, int error);
+  static void LogLine(const char* file, unsigned int line, LogId id, LogSeverity severity,
+                      const char* msg);
+
   DISALLOW_COPY_AND_ASSIGN(LogMessage);
 };
 
diff --git a/base/include/android-base/stringprintf.h b/base/include/android-base/stringprintf.h
index cf666ab..1fd6297 100644
--- a/base/include/android-base/stringprintf.h
+++ b/base/include/android-base/stringprintf.h
@@ -28,27 +28,27 @@
 // if the mingw version of vsnprintf is used, use `gnu_printf' which allows z
 // in %zd and PRIu64 (and related) to be recognized by the compile-time
 // checking.
-#define FORMAT_ARCHETYPE __printf__
+#define ANDROID_BASE_FORMAT_ARCHETYPE __printf__
 #ifdef __USE_MINGW_ANSI_STDIO
 #if __USE_MINGW_ANSI_STDIO
-#undef FORMAT_ARCHETYPE
-#define FORMAT_ARCHETYPE gnu_printf
+#undef ANDROID_BASE_FORMAT_ARCHETYPE
+#define ANDROID_BASE_FORMAT_ARCHETYPE gnu_printf
 #endif
 #endif
 
 // Returns a string corresponding to printf-like formatting of the arguments.
 std::string StringPrintf(const char* fmt, ...)
-    __attribute__((__format__(FORMAT_ARCHETYPE, 1, 2)));
+    __attribute__((__format__(ANDROID_BASE_FORMAT_ARCHETYPE, 1, 2)));
 
 // Appends a printf-like formatting of the arguments to 'dst'.
 void StringAppendF(std::string* dst, const char* fmt, ...)
-    __attribute__((__format__(FORMAT_ARCHETYPE, 2, 3)));
+    __attribute__((__format__(ANDROID_BASE_FORMAT_ARCHETYPE, 2, 3)));
 
 // Appends a printf-like formatting of the arguments to 'dst'.
 void StringAppendV(std::string* dst, const char* format, va_list ap)
-    __attribute__((__format__(FORMAT_ARCHETYPE, 2, 0)));
+    __attribute__((__format__(ANDROID_BASE_FORMAT_ARCHETYPE, 2, 0)));
 
-#undef FORMAT_ARCHETYPE
+#undef ANDROID_BASE_FORMAT_ARCHETYPE
 
 }  // namespace base
 }  // namespace android
diff --git a/base/include/android-base/strings.h b/base/include/android-base/strings.h
index f5f5c11..c11acb1 100644
--- a/base/include/android-base/strings.h
+++ b/base/include/android-base/strings.h
@@ -57,12 +57,18 @@
 extern template std::string Join(const std::vector<const char*>&, const std::string&);
 
 // Tests whether 's' starts with 'prefix'.
+// TODO: string_view
 bool StartsWith(const std::string& s, const char* prefix);
 bool StartsWithIgnoreCase(const std::string& s, const char* prefix);
+bool StartsWith(const std::string& s, const std::string& prefix);
+bool StartsWithIgnoreCase(const std::string& s, const std::string& prefix);
 
 // Tests whether 's' ends with 'suffix'.
+// TODO: string_view
 bool EndsWith(const std::string& s, const char* suffix);
 bool EndsWithIgnoreCase(const std::string& s, const char* suffix);
+bool EndsWith(const std::string& s, const std::string& prefix);
+bool EndsWithIgnoreCase(const std::string& s, const std::string& prefix);
 
 // Tests whether 'lhs' equals 'rhs', ignoring case.
 bool EqualsIgnoreCase(const std::string& lhs, const std::string& rhs);
diff --git a/base/include/android-base/test_utils.h b/base/include/android-base/test_utils.h
index 4cfa06b..2edafe3 100644
--- a/base/include/android-base/test_utils.h
+++ b/base/include/android-base/test_utils.h
@@ -17,6 +17,7 @@
 #ifndef ANDROID_BASE_TEST_UTILS_H
 #define ANDROID_BASE_TEST_UTILS_H
 
+#include <regex>
 #include <string>
 
 #include <android-base/macros.h>
@@ -70,4 +71,32 @@
   DISALLOW_COPY_AND_ASSIGN(CapturedStderr);
 };
 
+#define ASSERT_MATCH(str, pattern)                                             \
+  do {                                                                         \
+    if (!std::regex_search((str), std::regex((pattern)))) {                    \
+      FAIL() << "regex mismatch: expected " << (pattern) << " in:\n" << (str); \
+    }                                                                          \
+  } while (0)
+
+#define ASSERT_NOT_MATCH(str, pattern)                                                     \
+  do {                                                                                     \
+    if (std::regex_search((str), std::regex((pattern)))) {                                 \
+      FAIL() << "regex mismatch: expected to not find " << (pattern) << " in:\n" << (str); \
+    }                                                                                      \
+  } while (0)
+
+#define EXPECT_MATCH(str, pattern)                                                    \
+  do {                                                                                \
+    if (!std::regex_search((str), std::regex((pattern)))) {                           \
+      ADD_FAILURE() << "regex mismatch: expected " << (pattern) << " in:\n" << (str); \
+    }                                                                                 \
+  } while (0)
+
+#define EXPECT_NOT_MATCH(str, pattern)                                                            \
+  do {                                                                                            \
+    if (std::regex_search((str), std::regex((pattern)))) {                                        \
+      ADD_FAILURE() << "regex mismatch: expected to not find " << (pattern) << " in:\n" << (str); \
+    }                                                                                             \
+  } while (0)
+
 #endif  // ANDROID_BASE_TEST_UTILS_H
diff --git a/base/include/android-base/thread_annotations.h b/base/include/android-base/thread_annotations.h
index fbb5923..1307f0e 100644
--- a/base/include/android-base/thread_annotations.h
+++ b/base/include/android-base/thread_annotations.h
@@ -38,6 +38,12 @@
 #define PT_GUARDED_BY(x) \
       THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded_by(x))
 
+#define EXCLUSIVE_LOCKS_REQUIRED(...) \
+      THREAD_ANNOTATION_ATTRIBUTE__(exclusive_locks_required(__VA_ARGS__))
+
+#define SHARED_LOCKS_REQUIRED(...) \
+      THREAD_ANNOTATION_ATTRIBUTE__(shared_locks_required(__VA_ARGS__))
+
 #define ACQUIRED_BEFORE(...) \
       THREAD_ANNOTATION_ATTRIBUTE__(acquired_before(__VA_ARGS__))
 
diff --git a/base/logging.cpp b/base/logging.cpp
index 75078e5..0f2012a 100644
--- a/base/logging.cpp
+++ b/base/logging.cpp
@@ -187,8 +187,8 @@
 }
 #endif
 
-void StderrLogger(LogId, LogSeverity severity, const char*, const char* file,
-                  unsigned int line, const char* message) {
+void StderrLogger(LogId, LogSeverity severity, const char* tag, const char* file, unsigned int line,
+                  const char* message) {
   struct tm now;
   time_t t = time(nullptr);
 
@@ -205,8 +205,8 @@
   static_assert(arraysize(log_characters) - 1 == FATAL + 1,
                 "Mismatch in size of log_characters and values in LogSeverity");
   char severity_char = log_characters[severity];
-  fprintf(stderr, "%s %c %s %5d %5d %s:%u] %s\n", ProgramInvocationName().c_str(),
-          severity_char, timestamp, getpid(), GetThreadId(), file, line, message);
+  fprintf(stderr, "%s %c %s %5d %5d %s:%u] %s\n", tag ? tag : "nullptr", severity_char, timestamp,
+          getpid(), GetThreadId(), file, line, message);
 }
 
 void DefaultAborter(const char* abort_message) {
@@ -344,14 +344,14 @@
 // checks/logging in a function.
 class LogMessageData {
  public:
-  LogMessageData(const char* file, unsigned int line, LogId id,
-                 LogSeverity severity, int error)
+  LogMessageData(const char* file, unsigned int line, LogId id, LogSeverity severity,
+                 const char* tag, int error)
       : file_(GetFileBasename(file)),
         line_number_(line),
         id_(id),
         severity_(severity),
-        error_(error) {
-  }
+        tag_(tag),
+        error_(error) {}
 
   const char* GetFile() const {
     return file_;
@@ -365,6 +365,8 @@
     return severity_;
   }
 
+  const char* GetTag() const { return tag_; }
+
   LogId GetId() const {
     return id_;
   }
@@ -387,15 +389,19 @@
   const unsigned int line_number_;
   const LogId id_;
   const LogSeverity severity_;
+  const char* const tag_;
   const int error_;
 
   DISALLOW_COPY_AND_ASSIGN(LogMessageData);
 };
 
-LogMessage::LogMessage(const char* file, unsigned int line, LogId id,
-                       LogSeverity severity, int error)
-    : data_(new LogMessageData(file, line, id, severity, error)) {
-}
+LogMessage::LogMessage(const char* file, unsigned int line, LogId id, LogSeverity severity,
+                       const char* tag, int error)
+    : data_(new LogMessageData(file, line, id, severity, tag, error)) {}
+
+LogMessage::LogMessage(const char* file, unsigned int line, LogId id, LogSeverity severity,
+                       int error)
+    : LogMessage(file, line, id, severity, nullptr, error) {}
 
 LogMessage::~LogMessage() {
   // Check severity again. This is duplicate work wrt/ LOG macros, but not LOG_STREAM.
@@ -413,16 +419,16 @@
     // Do the actual logging with the lock held.
     std::lock_guard<std::mutex> lock(LoggingLock());
     if (msg.find('\n') == std::string::npos) {
-      LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
-              data_->GetSeverity(), msg.c_str());
+      LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(), data_->GetSeverity(),
+              data_->GetTag(), msg.c_str());
     } else {
       msg += '\n';
       size_t i = 0;
       while (i < msg.size()) {
         size_t nl = msg.find('\n', i);
         msg[nl] = '\0';
-        LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
-                data_->GetSeverity(), &msg[i]);
+        LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(), data_->GetSeverity(),
+                data_->GetTag(), &msg[i]);
         // Undo the zero-termination so we can give the complete message to the aborter.
         msg[nl] = '\n';
         i = nl + 1;
@@ -440,12 +446,17 @@
   return data_->GetBuffer();
 }
 
-void LogMessage::LogLine(const char* file, unsigned int line, LogId id,
-                         LogSeverity severity, const char* message) {
-  const char* tag = ProgramInvocationName().c_str();
+void LogMessage::LogLine(const char* file, unsigned int line, LogId id, LogSeverity severity,
+                         const char* tag, const char* message) {
+  if (tag == nullptr) tag = ProgramInvocationName().c_str();
   Logger()(id, severity, tag, file, line, message);
 }
 
+void LogMessage::LogLine(const char* file, unsigned int line, LogId id, LogSeverity severity,
+                         const char* message) {
+  LogLine(file, line, id, severity, nullptr, message);
+}
+
 LogSeverity GetMinimumLogSeverity() {
     return gMinimumLogSeverity;
 }
diff --git a/base/strings.cpp b/base/strings.cpp
index bfdaf12..a8bb2a9 100644
--- a/base/strings.cpp
+++ b/base/strings.cpp
@@ -91,12 +91,20 @@
   return strncmp(s.c_str(), prefix, strlen(prefix)) == 0;
 }
 
+bool StartsWith(const std::string& s, const std::string& prefix) {
+  return strncmp(s.c_str(), prefix.c_str(), prefix.size()) == 0;
+}
+
 bool StartsWithIgnoreCase(const std::string& s, const char* prefix) {
   return strncasecmp(s.c_str(), prefix, strlen(prefix)) == 0;
 }
 
-static bool EndsWith(const std::string& s, const char* suffix, bool case_sensitive) {
-  size_t suffix_length = strlen(suffix);
+bool StartsWithIgnoreCase(const std::string& s, const std::string& prefix) {
+  return strncasecmp(s.c_str(), prefix.c_str(), prefix.size()) == 0;
+}
+
+static bool EndsWith(const std::string& s, const char* suffix, size_t suffix_length,
+                     bool case_sensitive) {
   size_t string_length = s.size();
   if (suffix_length > string_length) {
     return false;
@@ -106,11 +114,19 @@
 }
 
 bool EndsWith(const std::string& s, const char* suffix) {
-  return EndsWith(s, suffix, true);
+  return EndsWith(s, suffix, strlen(suffix), true);
+}
+
+bool EndsWith(const std::string& s, const std::string& suffix) {
+  return EndsWith(s, suffix.c_str(), suffix.size(), true);
 }
 
 bool EndsWithIgnoreCase(const std::string& s, const char* suffix) {
-  return EndsWith(s, suffix, false);
+  return EndsWith(s, suffix, strlen(suffix), false);
+}
+
+bool EndsWithIgnoreCase(const std::string& s, const std::string& suffix) {
+  return EndsWith(s, suffix.c_str(), suffix.size(), false);
 }
 
 bool EqualsIgnoreCase(const std::string& lhs, const std::string& rhs) {
diff --git a/base/strings_test.cpp b/base/strings_test.cpp
index 121197c..b8639ea 100644
--- a/base/strings_test.cpp
+++ b/base/strings_test.cpp
@@ -253,6 +253,26 @@
   ASSERT_FALSE(android::base::EndsWithIgnoreCase("foobar", "FOO"));
 }
 
+TEST(strings, StartsWith_std_string) {
+  ASSERT_TRUE(android::base::StartsWith("hello", std::string{"hell"}));
+  ASSERT_FALSE(android::base::StartsWith("goodbye", std::string{"hell"}));
+}
+
+TEST(strings, StartsWithIgnoreCase_std_string) {
+  ASSERT_TRUE(android::base::StartsWithIgnoreCase("HeLlO", std::string{"hell"}));
+  ASSERT_FALSE(android::base::StartsWithIgnoreCase("GoOdByE", std::string{"hell"}));
+}
+
+TEST(strings, EndsWith_std_string) {
+  ASSERT_TRUE(android::base::EndsWith("hello", std::string{"lo"}));
+  ASSERT_FALSE(android::base::EndsWith("goodbye", std::string{"lo"}));
+}
+
+TEST(strings, EndsWithIgnoreCase_std_string) {
+  ASSERT_TRUE(android::base::EndsWithIgnoreCase("HeLlO", std::string{"lo"}));
+  ASSERT_FALSE(android::base::EndsWithIgnoreCase("GoOdByE", std::string{"lo"}));
+}
+
 TEST(strings, EqualsIgnoreCase) {
   ASSERT_TRUE(android::base::EqualsIgnoreCase("foo", "FOO"));
   ASSERT_TRUE(android::base::EqualsIgnoreCase("FOO", "foo"));
diff --git a/base/test_utils_test.cpp b/base/test_utils_test.cpp
new file mode 100644
index 0000000..597271a
--- /dev/null
+++ b/base/test_utils_test.cpp
@@ -0,0 +1,46 @@
+/*
+ * 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 "android-base/test_utils.h"
+
+#include <gtest/gtest-spi.h>
+#include <gtest/gtest.h>
+
+namespace android {
+namespace base {
+
+TEST(TestUtilsTest, AssertMatch) {
+  ASSERT_MATCH("foobar", R"(fo+baz?r)");
+  EXPECT_FATAL_FAILURE(ASSERT_MATCH("foobar", R"(foobaz)"), "regex mismatch");
+}
+
+TEST(TestUtilsTest, AssertNotMatch) {
+  ASSERT_NOT_MATCH("foobar", R"(foobaz)");
+  EXPECT_FATAL_FAILURE(ASSERT_NOT_MATCH("foobar", R"(foobar)"), "regex mismatch");
+}
+
+TEST(TestUtilsTest, ExpectMatch) {
+  EXPECT_MATCH("foobar", R"(fo+baz?r)");
+  EXPECT_NONFATAL_FAILURE(EXPECT_MATCH("foobar", R"(foobaz)"), "regex mismatch");
+}
+
+TEST(TestUtilsTest, ExpectNotMatch) {
+  EXPECT_NOT_MATCH("foobar", R"(foobaz)");
+  EXPECT_NONFATAL_FAILURE(EXPECT_NOT_MATCH("foobar", R"(foobar)"), "regex mismatch");
+}
+
+}  // namespace base
+}  // namespace android
diff --git a/bootstat/bootstat.cpp b/bootstat/bootstat.cpp
index 8db9121..ae0a401 100644
--- a/bootstat/bootstat.cpp
+++ b/bootstat/bootstat.cpp
@@ -246,6 +246,41 @@
     {"watchdog_sdi_apps_reset", 106},
     {"smpl", 107},
     {"oem_modem_failed_to_powerup", 108},
+    {"reboot_normal", 109},
+    {"oem_lpass_cfg", 110},
+    {"oem_xpu_ns_error", 111},
+    {"power_key_press", 112},
+    {"hardware_reset", 113},
+    {"reboot_by_powerkey", 114},
+    {"reboot_verity", 115},
+    {"oem_rpm_undef_error", 116},
+    {"oem_crash_on_the_lk", 117},
+    {"oem_rpm_reset", 118},
+    {"oem_lpass_cfg", 119},
+    {"oem_xpu_ns_error", 120},
+    {"factory_cable", 121},
+    {"oem_ar6320_failed_to_powerup", 122},
+    {"watchdog_rpm_bite", 123},
+    {"power_on_cable", 124},
+    {"reboot_unknown", 125},
+    {"wireless_charger", 126},
+    {"0x776655ff", 127},
+    {"oem_thermal_bite_reset", 128},
+    {"charger", 129},
+    {"pon1", 130},
+    {"unknown", 131},
+    {"reboot_rtc", 132},
+    {"cold_boot", 133},
+    {"hard_rst", 134},
+    {"power-on", 135},
+    {"oem_adsp_resetting_the_soc", 136},
+    {"kpdpwr", 137},
+    {"oem_modem_timeout_waiting", 138},
+    {"usb_chg", 139},
+    {"warm_reset_0x02", 140},
+    {"warm_reset_0x80", 141},
+    {"pon_reason_0xb0", 142},
+    {"reboot_download", 143},
 };
 
 // Converts a string value representing the reason the system booted to an
@@ -289,8 +324,7 @@
   for (auto& s : knownReasons) {
     if (s == "cold") break;
     // Prefix defined as terminated by a nul or comma (,).
-    if (android::base::StartsWith(r, s.c_str()) &&
-        ((r.length() == s.length()) || (r[s.length()] == ','))) {
+    if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
       return true;
     }
   }
@@ -302,8 +336,7 @@
   for (auto& s : knownReasons) {
     if (s == "recovery") break;
     // Prefix defined as terminated by a nul or comma (,).
-    if (android::base::StartsWith(r, s.c_str()) &&
-        ((r.length() == s.length()) || (r[s.length()] == ','))) {
+    if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
       return true;
     }
   }
@@ -314,8 +347,7 @@
 bool isKnownRebootReason(const std::string& r) {
   for (auto& s : knownReasons) {
     // Prefix defined as terminated by a nul or comma (,).
-    if (android::base::StartsWith(r, s.c_str()) &&
-        ((r.length() == s.length()) || (r[s.length()] == ','))) {
+    if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
       return true;
     }
   }
diff --git a/debuggerd/Android.bp b/debuggerd/Android.bp
index 17a9f3a..7fec47d 100644
--- a/debuggerd/Android.bp
+++ b/debuggerd/Android.bp
@@ -4,9 +4,12 @@
         "-Wall",
         "-Wextra",
         "-Werror",
+        "-Wno-unused-argument",
+        "-Wno-unused-function",
         "-Wno-nullability-completeness",
         "-Os",
     ],
+    cpp_std: "gnu++17",
 
     local_include_dirs: ["include"],
 }
@@ -73,6 +76,7 @@
 
     whole_static_libs: [
         "libasync_safe",
+        "libcutils",
         "libdebuggerd",
     ],
 
@@ -148,27 +152,6 @@
         "libdebuggerd/utility.cpp",
     ],
 
-    target: {
-        android_arm: {
-            srcs: ["libdebuggerd/arm/machine.cpp"],
-        },
-        android_arm64: {
-            srcs: ["libdebuggerd/arm64/machine.cpp"],
-        },
-        android_mips: {
-            srcs: ["libdebuggerd/mips/machine.cpp"],
-        },
-        android_mips64: {
-            srcs: ["libdebuggerd/mips64/machine.cpp"],
-        },
-        android_x86: {
-            srcs: ["libdebuggerd/x86/machine.cpp"],
-        },
-        android_x86_64: {
-            srcs: ["libdebuggerd/x86_64/machine.cpp"],
-        },
-    },
-
     local_include_dirs: ["libdebuggerd/include"],
     export_include_dirs: ["libdebuggerd/include"],
 
@@ -193,7 +176,6 @@
         "libdebuggerd/test/elf_fake.cpp",
         "libdebuggerd/test/log_fake.cpp",
         "libdebuggerd/test/open_files_list_test.cpp",
-        "libdebuggerd/test/ptrace_fake.cpp",
         "libdebuggerd/test/tombstone_test.cpp",
     ],
 
@@ -218,6 +200,7 @@
 
     static_libs: [
         "libdebuggerd",
+        "libunwindstack",
     ],
 
     local_include_dirs: [
@@ -235,6 +218,16 @@
     },
 }
 
+cc_benchmark {
+    name: "debuggerd_benchmark",
+    defaults: ["debuggerd_defaults"],
+    srcs: ["debuggerd_benchmark.cpp"],
+    shared_libs: [
+        "libbase",
+        "libdebuggerd_client",
+    ],
+}
+
 cc_binary {
     name: "crash_dump",
     srcs: [
@@ -264,6 +257,7 @@
         "libbase",
         "liblog",
         "libprocinfo",
+        "libunwindstack",
     ],
 }
 
diff --git a/debuggerd/crash_dump.cpp b/debuggerd/crash_dump.cpp
index 827420e..a1f0211 100644
--- a/debuggerd/crash_dump.cpp
+++ b/debuggerd/crash_dump.cpp
@@ -18,11 +18,11 @@
 #include <dirent.h>
 #include <fcntl.h>
 #include <stdlib.h>
-#include <sys/capability.h>
 #include <sys/prctl.h>
 #include <sys/ptrace.h>
 #include <sys/types.h>
 #include <sys/un.h>
+#include <sys/wait.h>
 #include <syscall.h>
 #include <unistd.h>
 
@@ -47,6 +47,8 @@
 #define ATRACE_TAG ATRACE_TAG_BIONIC
 #include <utils/Trace.h>
 
+#include <unwindstack/Regs.h>
+
 #include "libdebuggerd/backtrace.h"
 #include "libdebuggerd/tombstone.h"
 #include "libdebuggerd/utility.h"
@@ -58,21 +60,9 @@
 #include "util.h"
 
 using android::base::unique_fd;
-using android::base::ReadFileToString;
 using android::base::StringPrintf;
-using android::base::Trim;
 
-static std::string get_process_name(pid_t pid) {
-  std::string result = "<unknown>";
-  ReadFileToString(StringPrintf("/proc/%d/cmdline", pid), &result);
-  return result;
-}
-
-static std::string get_thread_name(pid_t tid) {
-  std::string result = "<unknown>";
-  ReadFileToString(StringPrintf("/proc/%d/comm", tid), &result);
-  return Trim(result);
-}
+using unwindstack::Regs;
 
 static bool pid_contains_tid(int pid_proc_fd, pid_t tid) {
   struct stat st;
@@ -90,8 +80,8 @@
 }
 
 // Attach to a thread, and verify that it's still a member of the given process
-static bool ptrace_seize_thread(int pid_proc_fd, pid_t tid, std::string* error) {
-  if (ptrace(PTRACE_SEIZE, tid, 0, 0) != 0) {
+static bool ptrace_seize_thread(int pid_proc_fd, pid_t tid, std::string* error, int flags = 0) {
+  if (ptrace(PTRACE_SEIZE, tid, 0, flags) != 0) {
     if (errno == EPERM) {
       pid_t tracer = get_tracer(tid);
       if (tracer != -1) {
@@ -108,18 +98,43 @@
   // Make sure that the task we attached to is actually part of the pid we're dumping.
   if (!pid_contains_tid(pid_proc_fd, tid)) {
     if (ptrace(PTRACE_DETACH, tid, 0, 0) != 0) {
-      PLOG(FATAL) << "failed to detach from thread " << tid;
+      PLOG(WARNING) << "failed to detach from thread " << tid;
     }
     *error = StringPrintf("thread %d is not in process", tid);
     return false;
   }
 
-  // Put the task into ptrace-stop state.
-  if (ptrace(PTRACE_INTERRUPT, tid, 0, 0) != 0) {
-    PLOG(FATAL) << "failed to interrupt thread " << tid;
+  return true;
+}
+
+static bool wait_for_stop(pid_t tid, int* received_signal) {
+  while (true) {
+    int status;
+    pid_t result = waitpid(tid, &status, __WALL);
+    if (result != tid) {
+      PLOG(ERROR) << "waitpid failed on " << tid << " while detaching";
+      return false;
+    }
+
+    if (WIFSTOPPED(status)) {
+      if (status >> 16 == PTRACE_EVENT_STOP) {
+        *received_signal = 0;
+      } else {
+        *received_signal = WSTOPSIG(status);
+      }
+      return true;
+    }
+  }
+}
+
+// Interrupt a process and wait for it to be interrupted.
+static bool ptrace_interrupt(pid_t tid, int* received_signal) {
+  if (ptrace(PTRACE_INTERRUPT, tid, 0, 0) == 0) {
+    return wait_for_stop(tid, received_signal);
   }
 
-  return true;
+  PLOG(ERROR) << "failed to interrupt " << tid << " to detach";
+  return false;
 }
 
 static bool activity_manager_notify(pid_t pid, int signal, const std::string& amfd_data) {
@@ -169,70 +184,39 @@
   return true;
 }
 
-static void signal_handler(int) {
-  // We can't log easily, because the heap might be corrupt.
-  // Just die and let the surrounding log context explain things.
-  _exit(1);
-}
+// Globals used by the abort handler.
+static pid_t g_target_thread = -1;
+static bool g_tombstoned_connected = false;
+static unique_fd g_tombstoned_socket;
+static unique_fd g_output_fd;
 
-static void abort_handler(pid_t target, const bool tombstoned_connected,
-                          unique_fd& tombstoned_socket, unique_fd& output_fd,
-                          const char* abort_msg) {
-  // If we abort before we get an output fd, contact tombstoned to let any
-  // potential listeners know that we failed.
-  if (!tombstoned_connected) {
-    if (!tombstoned_connect(target, &tombstoned_socket, &output_fd, kDebuggerdAnyIntercept)) {
-      // We failed to connect, not much we can do.
-      LOG(ERROR) << "failed to connected to tombstoned to report failure";
-      _exit(1);
-    }
-  }
-
-  dprintf(output_fd.get(), "crash_dump failed to dump process");
-  if (target != 1) {
-    dprintf(output_fd.get(), " %d: %s\n", target, abort_msg);
-  } else {
-    dprintf(output_fd.get(), ": %s\n", abort_msg);
-  }
-
-  _exit(1);
-}
-
-static void drop_capabilities() {
-  ATRACE_CALL();
-  __user_cap_header_struct capheader;
-  memset(&capheader, 0, sizeof(capheader));
-  capheader.version = _LINUX_CAPABILITY_VERSION_3;
-  capheader.pid = 0;
-
-  __user_cap_data_struct capdata[2];
-  memset(&capdata, 0, sizeof(capdata));
-
-  if (capset(&capheader, &capdata[0]) == -1) {
-    PLOG(FATAL) << "failed to drop capabilities";
-  }
-
-  if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0) {
-    PLOG(FATAL) << "failed to set PR_SET_NO_NEW_PRIVS";
-  }
-}
-
-int main(int argc, char** argv) {
-  atrace_begin(ATRACE_TAG, "before reparent");
-
-  pid_t target = getppid();
-  bool tombstoned_connected = false;
-  unique_fd tombstoned_socket;
-  unique_fd output_fd;
-
+static void Initialize(char** argv) {
   android::base::InitLogging(argv);
-  android::base::SetAborter([&](const char* abort_msg) {
-    abort_handler(target, tombstoned_connected, tombstoned_socket, output_fd, abort_msg);
+  android::base::SetAborter([](const char* abort_msg) {
+    // If we abort before we get an output fd, contact tombstoned to let any
+    // potential listeners know that we failed.
+    if (!g_tombstoned_connected) {
+      if (!tombstoned_connect(g_target_thread, &g_tombstoned_socket, &g_output_fd,
+                              kDebuggerdAnyIntercept)) {
+        // We failed to connect, not much we can do.
+        LOG(ERROR) << "failed to connected to tombstoned to report failure";
+        _exit(1);
+      }
+    }
+
+    dprintf(g_output_fd.get(), "crash_dump failed to dump process");
+    if (g_target_thread != 1) {
+      dprintf(g_output_fd.get(), " %d: %s\n", g_target_thread, abort_msg);
+    } else {
+      dprintf(g_output_fd.get(), ": %s\n", abort_msg);
+    }
+
+    _exit(1);
   });
 
   // Don't try to dump ourselves.
   struct sigaction action = {};
-  action.sa_handler = signal_handler;
+  action.sa_handler = SIG_DFL;
   debuggerd_register_handlers(&action);
 
   sigset_t mask;
@@ -240,216 +224,328 @@
   if (sigprocmask(SIG_SETMASK, &mask, nullptr) != 0) {
     PLOG(FATAL) << "failed to set signal mask";
   }
+}
 
+static void ParseArgs(int argc, char** argv, pid_t* pseudothread_tid, DebuggerdDumpType* dump_type) {
   if (argc != 4) {
-    LOG(FATAL) << "Wrong number of args: " << argc << " (expected 4)";
+    LOG(FATAL) << "wrong number of args: " << argc << " (expected 4)";
   }
 
-  pid_t main_tid;
-  pid_t pseudothread_tid;
-  int dump_type;
-
-  if (!android::base::ParseInt(argv[1], &main_tid, 1, std::numeric_limits<pid_t>::max())) {
-    LOG(FATAL) << "invalid main tid: " << argv[1];
+  if (!android::base::ParseInt(argv[1], &g_target_thread, 1, std::numeric_limits<pid_t>::max())) {
+    LOG(FATAL) << "invalid target tid: " << argv[1];
   }
 
-  if (!android::base::ParseInt(argv[2], &pseudothread_tid, 1, std::numeric_limits<pid_t>::max())) {
+  if (!android::base::ParseInt(argv[2], pseudothread_tid, 1, std::numeric_limits<pid_t>::max())) {
     LOG(FATAL) << "invalid pseudothread tid: " << argv[2];
   }
 
-  if (!android::base::ParseInt(argv[3], &dump_type, 0, 1)) {
+  int dump_type_int;
+  if (!android::base::ParseInt(argv[3], &dump_type_int, 0, 1)) {
     LOG(FATAL) << "invalid requested dump type: " << argv[3];
   }
+  *dump_type = static_cast<DebuggerdDumpType>(dump_type_int);
+}
 
-  if (target == 1) {
-    LOG(FATAL) << "target died before we could attach (received main tid = " << main_tid << ")";
+static void ReadCrashInfo(unique_fd& fd, siginfo_t* siginfo,
+                          std::unique_ptr<unwindstack::Regs>* regs, uintptr_t* abort_address) {
+  std::aligned_storage<sizeof(CrashInfo) + 1, alignof(CrashInfo)>::type buf;
+  ssize_t rc = TEMP_FAILURE_RETRY(read(fd.get(), &buf, sizeof(buf)));
+  if (rc == -1) {
+    PLOG(FATAL) << "failed to read target ucontext";
+  } else if (rc != sizeof(CrashInfo)) {
+    LOG(FATAL) << "read " << rc << " bytes when reading target crash information, expected "
+               << sizeof(CrashInfo);
   }
 
-  android::procinfo::ProcessInfo target_info;
-  if (!android::procinfo::GetProcessInfo(main_tid, &target_info)) {
-    LOG(FATAL) << "failed to fetch process info for target " << main_tid;
+  CrashInfo* crash_info = reinterpret_cast<CrashInfo*>(&buf);
+  if (crash_info->version != 1) {
+    LOG(FATAL) << "version mismatch, expected 1, received " << crash_info->version;
   }
 
-  if (main_tid != target_info.tid || target != target_info.pid) {
-    LOG(FATAL) << "target info mismatch, expected pid " << target << ", tid " << main_tid
-               << ", received pid " << target_info.pid << ", tid " << target_info.tid;
+  *siginfo = crash_info->siginfo;
+  regs->reset(Regs::CreateFromUcontext(Regs::CurrentArch(), &crash_info->ucontext));
+  *abort_address = crash_info->abort_msg_address;
+}
+
+// Wait for a process to clone and return the child's pid.
+// Note: this leaves the parent in PTRACE_EVENT_STOP.
+static pid_t wait_for_clone(pid_t pid, bool resume_child) {
+  int status;
+  pid_t result = TEMP_FAILURE_RETRY(waitpid(pid, &status, __WALL));
+  if (result == -1) {
+    PLOG(FATAL) << "failed to waitpid";
   }
 
-  // Open /proc/`getppid()` in the original process, and pass it down to the forked child.
-  std::string target_proc_path = "/proc/" + std::to_string(target);
+  if (WIFEXITED(status)) {
+    LOG(FATAL) << "traced process exited with status " << WEXITSTATUS(status);
+  } else if (WIFSIGNALED(status)) {
+    LOG(FATAL) << "traced process exited with signal " << WTERMSIG(status);
+  } else if (!WIFSTOPPED(status)) {
+    LOG(FATAL) << "process didn't stop? (status = " << status << ")";
+  }
+
+  if (status >> 8 != (SIGTRAP | (PTRACE_EVENT_CLONE << 8))) {
+    LOG(FATAL) << "process didn't stop due to PTRACE_O_TRACECLONE (status = " << status << ")";
+  }
+
+  pid_t child;
+  if (ptrace(PTRACE_GETEVENTMSG, pid, 0, &child) != 0) {
+    PLOG(FATAL) << "failed to get child pid via PTRACE_GETEVENTMSG";
+  }
+
+  int stop_signal;
+  if (!wait_for_stop(child, &stop_signal)) {
+    PLOG(FATAL) << "failed to waitpid on child";
+  }
+
+  CHECK_EQ(0, stop_signal);
+
+  if (resume_child) {
+    if (ptrace(PTRACE_CONT, child, 0, 0) != 0) {
+      PLOG(FATAL) << "failed to resume child (pid = " << child << ")";
+    }
+  }
+
+  return child;
+}
+
+static pid_t wait_for_vm_process(pid_t pseudothread_tid) {
+  // The pseudothread will double-fork, we want its grandchild.
+  pid_t intermediate = wait_for_clone(pseudothread_tid, true);
+  pid_t vm_pid = wait_for_clone(intermediate, false);
+  if (ptrace(PTRACE_DETACH, intermediate, 0, 0) != 0) {
+    PLOG(FATAL) << "failed to detach from intermediate vm process";
+  }
+
+  return vm_pid;
+}
+
+int main(int argc, char** argv) {
+  atrace_begin(ATRACE_TAG, "before reparent");
+  pid_t target_process = getppid();
+
+  // Open /proc/`getppid()` before we daemonize.
+  std::string target_proc_path = "/proc/" + std::to_string(target_process);
   int target_proc_fd = open(target_proc_path.c_str(), O_DIRECTORY | O_RDONLY);
   if (target_proc_fd == -1) {
     PLOG(FATAL) << "failed to open " << target_proc_path;
   }
 
-  // Make sure our parent didn't die.
-  if (getppid() != target) {
-    PLOG(FATAL) << "parent died";
+  // Make sure getppid() hasn't changed.
+  if (getppid() != target_process) {
+    LOG(FATAL) << "parent died";
   }
-
   atrace_end(ATRACE_TAG);
 
   // Reparent ourselves to init, so that the signal handler can waitpid on the
   // original process to avoid leaving a zombie for non-fatal dumps.
+  // Move the input/output pipes off of stdout/stderr, out of paranoia.
+  unique_fd output_pipe(dup(STDOUT_FILENO));
+  unique_fd input_pipe(dup(STDIN_FILENO));
+
+  unique_fd fork_exit_read, fork_exit_write;
+  if (!Pipe(&fork_exit_read, &fork_exit_write)) {
+    PLOG(FATAL) << "failed to create pipe";
+  }
+
   pid_t forkpid = fork();
   if (forkpid == -1) {
     PLOG(FATAL) << "fork failed";
-  } else if (forkpid != 0) {
-    exit(0);
+  } else if (forkpid == 0) {
+    fork_exit_read.reset();
+  } else {
+    // We need the pseudothread to live until we get around to verifying the vm pid against it.
+    // The last thing it does is block on a waitpid on us, so wait until our child tells us to die.
+    fork_exit_write.reset();
+    char buf;
+    TEMP_FAILURE_RETRY(read(fork_exit_read.get(), &buf, sizeof(buf)));
+    _exit(0);
   }
 
   ATRACE_NAME("after reparent");
+  pid_t pseudothread_tid;
+  DebuggerdDumpType dump_type;
+  uintptr_t abort_address = 0;
+
+  Initialize(argv);
+  ParseArgs(argc, argv, &pseudothread_tid, &dump_type);
 
   // Die if we take too long.
   //
   // Note: processes with many threads and minidebug-info can take a bit to
   //       unwind, do not make this too small. b/62828735
-  alarm(5);
+  alarm(30);
 
-  std::string attach_error;
-
-  std::map<pid_t, std::string> threads;
-
-  {
-    ATRACE_NAME("ptrace");
-    // Seize the main thread.
-    if (!ptrace_seize_thread(target_proc_fd, main_tid, &attach_error)) {
-      LOG(FATAL) << attach_error;
-    }
-
-    // Seize the siblings.
-    {
-      std::set<pid_t> siblings;
-      if (!android::procinfo::GetProcessTids(target, &siblings)) {
-        PLOG(FATAL) << "failed to get process siblings";
-      }
-
-      // but not the already attached main thread.
-      siblings.erase(main_tid);
-      // or the handler pseudothread.
-      siblings.erase(pseudothread_tid);
-
-      for (pid_t sibling_tid : siblings) {
-        if (!ptrace_seize_thread(target_proc_fd, sibling_tid, &attach_error)) {
-          LOG(WARNING) << attach_error;
-        } else {
-          threads.emplace(sibling_tid, get_thread_name(sibling_tid));
-        }
-      }
-    }
-  }
-
-  // Collect the backtrace map, open files, and process/thread names, while we still have caps.
-  std::unique_ptr<BacktraceMap> backtrace_map;
-  {
-    ATRACE_NAME("backtrace map");
-    backtrace_map.reset(BacktraceMap::Create(main_tid));
-    if (!backtrace_map) {
-      LOG(FATAL) << "failed to create backtrace map";
-    }
-  }
+  // Get the process name (aka cmdline).
+  std::string process_name = get_process_name(g_target_thread);
 
   // Collect the list of open files.
   OpenFilesList open_files;
   {
     ATRACE_NAME("open files");
-    populate_open_files_list(target, &open_files);
+    populate_open_files_list(g_target_thread, &open_files);
   }
 
-  std::string process_name = get_process_name(main_tid);
-  threads.emplace(main_tid, get_thread_name(main_tid));
+  // In order to reduce the duration that we pause the process for, we ptrace
+  // the threads, fetch their registers and associated information, and then
+  // fork a separate process as a snapshot of the process's address space.
+  std::set<pid_t> threads;
+  if (!android::procinfo::GetProcessTids(g_target_thread, &threads)) {
+    PLOG(FATAL) << "failed to get process threads";
+  }
 
-  // Drop our capabilities now that we've attached to the threads we care about.
+  std::map<pid_t, ThreadInfo> thread_info;
+  siginfo_t siginfo;
+  std::string error;
+
+  {
+    ATRACE_NAME("ptrace");
+    for (pid_t thread : threads) {
+      // Trace the pseudothread separately, so we can use different options.
+      if (thread == pseudothread_tid) {
+        continue;
+      }
+
+      if (!ptrace_seize_thread(target_proc_fd, thread, &error)) {
+        bool fatal = thread == g_target_thread;
+        LOG(fatal ? FATAL : WARNING) << error;
+      }
+
+      ThreadInfo info;
+      info.pid = target_process;
+      info.tid = thread;
+      info.process_name = process_name;
+      info.thread_name = get_thread_name(thread);
+
+      if (!ptrace_interrupt(thread, &info.signo)) {
+        PLOG(WARNING) << "failed to ptrace interrupt thread " << thread;
+        ptrace(PTRACE_DETACH, thread, 0, 0);
+        continue;
+      }
+
+      if (thread == g_target_thread) {
+        // Read the thread's registers along with the rest of the crash info out of the pipe.
+        ReadCrashInfo(input_pipe, &siginfo, &info.registers, &abort_address);
+        info.siginfo = &siginfo;
+        info.signo = info.siginfo->si_signo;
+      } else {
+        info.registers.reset(Regs::RemoteGet(thread));
+        if (!info.registers) {
+          PLOG(WARNING) << "failed to fetch registers for thread " << thread;
+          ptrace(PTRACE_DETACH, thread, 0, 0);
+          continue;
+        }
+      }
+
+      thread_info[thread] = std::move(info);
+    }
+  }
+
+  // Trace the pseudothread with PTRACE_O_TRACECLONE and tell it to fork.
+  if (!ptrace_seize_thread(target_proc_fd, pseudothread_tid, &error, PTRACE_O_TRACECLONE)) {
+    LOG(FATAL) << "failed to seize pseudothread: " << error;
+  }
+
+  if (TEMP_FAILURE_RETRY(write(output_pipe.get(), "\1", 1)) != 1) {
+    PLOG(FATAL) << "failed to write to pseudothread";
+  }
+
+  pid_t vm_pid = wait_for_vm_process(pseudothread_tid);
+  if (ptrace(PTRACE_DETACH, pseudothread_tid, 0, 0) != 0) {
+    PLOG(FATAL) << "failed to detach from pseudothread";
+  }
+
+  // The pseudothread can die now.
+  fork_exit_write.reset();
+
+  // Defer the message until later, for readability.
+  bool wait_for_gdb = android::base::GetBoolProperty("debug.debuggerd.wait_for_gdb", false);
+  if (siginfo.si_signo == DEBUGGER_SIGNAL) {
+    wait_for_gdb = false;
+  }
+
+  // Detach from all of our attached threads before resuming.
+  for (const auto& [tid, thread] : thread_info) {
+    int resume_signal = thread.signo == DEBUGGER_SIGNAL ? 0 : thread.signo;
+    if (wait_for_gdb) {
+      resume_signal = 0;
+      if (tgkill(target_process, tid, SIGSTOP) != 0) {
+        PLOG(WARNING) << "failed to send SIGSTOP to " << tid;
+      }
+    }
+
+    LOG(DEBUG) << "detaching from thread " << tid;
+    if (ptrace(PTRACE_DETACH, tid, 0, resume_signal) != 0) {
+      PLOG(ERROR) << "failed to detach from thread " << tid;
+    }
+  }
+
+  // Drop our capabilities now that we've fetched all of the information we need.
   drop_capabilities();
 
   {
     ATRACE_NAME("tombstoned_connect");
-    const DebuggerdDumpType dump_type_enum = static_cast<DebuggerdDumpType>(dump_type);
-    LOG(INFO) << "obtaining output fd from tombstoned, type: " << dump_type_enum;
-    tombstoned_connected = tombstoned_connect(target, &tombstoned_socket, &output_fd, dump_type_enum);
+    LOG(INFO) << "obtaining output fd from tombstoned, type: " << dump_type;
+    g_tombstoned_connected =
+        tombstoned_connect(g_target_thread, &g_tombstoned_socket, &g_output_fd, dump_type);
   }
 
-  // Write a '\1' to stdout to tell the crashing process to resume.
-  // It also restores the value of PR_SET_DUMPABLE at this point.
-  if (TEMP_FAILURE_RETRY(write(STDOUT_FILENO, "\1", 1)) == -1) {
-    PLOG(ERROR) << "failed to communicate to target process";
-  }
-
-  if (tombstoned_connected) {
-    if (TEMP_FAILURE_RETRY(dup2(output_fd.get(), STDOUT_FILENO)) == -1) {
-      PLOG(ERROR) << "failed to dup2 output fd (" << output_fd.get() << ") to STDOUT_FILENO";
+  if (g_tombstoned_connected) {
+    if (TEMP_FAILURE_RETRY(dup2(g_output_fd.get(), STDOUT_FILENO)) == -1) {
+      PLOG(ERROR) << "failed to dup2 output fd (" << g_output_fd.get() << ") to STDOUT_FILENO";
     }
   } else {
     unique_fd devnull(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
     TEMP_FAILURE_RETRY(dup2(devnull.get(), STDOUT_FILENO));
-    output_fd = std::move(devnull);
+    g_output_fd = std::move(devnull);
   }
 
-  LOG(INFO) << "performing dump of process " << target << " (target tid = " << main_tid << ")";
-
-  // At this point, the thread that made the request has been attached and is
-  // in ptrace-stopped state. After resumption, the triggering signal that has
-  // been queued will be delivered.
-  if (ptrace(PTRACE_CONT, main_tid, 0, 0) != 0) {
-    PLOG(ERROR) << "PTRACE_CONT(" << main_tid << ") failed";
-    exit(1);
-  }
-
-  siginfo_t siginfo = {};
-  {
-    ATRACE_NAME("wait_for_signal");
-    if (!wait_for_signal(main_tid, &siginfo)) {
-      printf("failed to wait for signal in tid %d: %s\n", main_tid, strerror(errno));
-      exit(1);
-    }
-  }
+  LOG(INFO) << "performing dump of process " << target_process << " (target tid = " << g_target_thread
+            << ")";
 
   int signo = siginfo.si_signo;
   bool fatal_signal = signo != DEBUGGER_SIGNAL;
   bool backtrace = false;
-  uintptr_t abort_address = 0;
 
-  // si_value can represent three things:
+  // si_value is special when used with DEBUGGER_SIGNAL.
   //   0: dump tombstone
   //   1: dump backtrace
-  //   everything else: abort message address (implies dump tombstone)
-  if (siginfo.si_value.sival_int == 1) {
-    backtrace = true;
-  } else if (siginfo.si_value.sival_ptr != nullptr) {
-    abort_address = reinterpret_cast<uintptr_t>(siginfo.si_value.sival_ptr);
+  if (!fatal_signal) {
+    int si_val = siginfo.si_value.sival_int;
+    if (si_val == 0) {
+      backtrace = false;
+    } else if (si_val == 1) {
+      backtrace = true;
+    } else {
+      LOG(WARNING) << "unknown si_value value " << si_val;
+    }
   }
 
   // TODO: Use seccomp to lock ourselves down.
+  std::unique_ptr<BacktraceMap> map(BacktraceMap::Create(vm_pid, false));
+  if (!map) {
+    LOG(FATAL) << "failed to create backtrace map";
+  }
+
+  std::shared_ptr<unwindstack::Memory> process_memory = map->GetProcessMemory();
+  if (!process_memory) {
+    LOG(FATAL) << "failed to get unwindstack::Memory handle";
+  }
 
   std::string amfd_data;
   if (backtrace) {
     ATRACE_NAME("dump_backtrace");
-    dump_backtrace(output_fd.get(), backtrace_map.get(), target, main_tid, process_name, threads, 0);
+    dump_backtrace(std::move(g_output_fd), map.get(), thread_info, g_target_thread);
   } else {
     ATRACE_NAME("engrave_tombstone");
-    engrave_tombstone(output_fd.get(), backtrace_map.get(), &open_files, target, main_tid,
-                      process_name, threads, abort_address, fatal_signal ? &amfd_data : nullptr);
+    engrave_tombstone(std::move(g_output_fd), map.get(), process_memory.get(), thread_info,
+                      g_target_thread, abort_address, &open_files, &amfd_data);
   }
 
-  // We don't actually need to PTRACE_DETACH, as long as our tracees aren't in
-  // group-stop state, which is true as long as no stopping signals are sent.
-
-  bool wait_for_gdb = android::base::GetBoolProperty("debug.debuggerd.wait_for_gdb", false);
-  if (!fatal_signal || siginfo.si_code == SI_USER) {
-    // Don't wait_for_gdb when the process didn't actually crash.
-    wait_for_gdb = false;
-  }
-
-  // If the process crashed or we need to send it SIGSTOP for wait_for_gdb,
-  // get it in a state where it can receive signals, and then send the relevant
-  // signal.
-  if (wait_for_gdb || fatal_signal) {
-    if (ptrace(PTRACE_INTERRUPT, main_tid, 0, 0) != 0) {
-      PLOG(ERROR) << "failed to use PTRACE_INTERRUPT on " << main_tid;
-    }
-
-    if (tgkill(target, main_tid, wait_for_gdb ? SIGSTOP : signo) != 0) {
-      PLOG(ERROR) << "failed to resend signal " << signo << " to " << main_tid;
+  if (fatal_signal) {
+    // Don't try to notify ActivityManager if it just crashed, or we might hang until timeout.
+    if (thread_info[target_process].thread_name != "system_server") {
+      activity_manager_notify(target_process, signo, amfd_data);
     }
   }
 
@@ -463,19 +559,12 @@
         "*     gdbclient.py -p %d\n"
         "*\n"
         "***********************************************************",
-        target, target);
-  }
-
-  if (fatal_signal) {
-    // Don't try to notify ActivityManager if it just crashed, or we might hang until timeout.
-    if (target_info.name != "system_server" || target_info.uid != AID_SYSTEM) {
-      activity_manager_notify(target, signo, amfd_data);
-    }
+        target_process, target_process);
   }
 
   // Close stdout before we notify tombstoned of completion.
   close(STDOUT_FILENO);
-  if (tombstoned_connected && !tombstoned_notify_completion(tombstoned_socket.get())) {
+  if (g_tombstoned_connected && !tombstoned_notify_completion(g_tombstoned_socket.get())) {
     LOG(ERROR) << "failed to notify tombstoned of completion";
   }
 
diff --git a/debuggerd/crasher/crasher.cpp b/debuggerd/crasher/crasher.cpp
index e9a3ebd..4b32b9d 100644
--- a/debuggerd/crasher/crasher.cpp
+++ b/debuggerd/crasher/crasher.cpp
@@ -289,7 +289,7 @@
         munmap(map, sizeof(int));
         map[0] = '8';
     } else if (!strcasecmp(arg, "seccomp")) {
-        set_seccomp_filter();
+        set_system_seccomp_filter();
         syscall(99999);
 #if defined(__arm__)
     } else if (!strcasecmp(arg, "kuser_helper_version")) {
diff --git a/debuggerd/debuggerd_benchmark.cpp b/debuggerd/debuggerd_benchmark.cpp
new file mode 100644
index 0000000..37ee214
--- /dev/null
+++ b/debuggerd/debuggerd_benchmark.cpp
@@ -0,0 +1,128 @@
+/*
+ * Copyright 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 <err.h>
+#include <errno.h>
+#include <sched.h>
+#include <string.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include <chrono>
+#include <thread>
+
+#include <benchmark/benchmark.h>
+#include <debuggerd/client.h>
+
+using namespace std::chrono_literals;
+
+static_assert(std::chrono::high_resolution_clock::is_steady);
+
+enum class ThreadState { Starting, Started, Stopping };
+
+static void SetScheduler() {
+  struct sched_param param {
+    .sched_priority = 1,
+  };
+
+  if (sched_setscheduler(getpid(), SCHED_FIFO, &param) != 0) {
+    fprintf(stderr, "failed to set scheduler to SCHED_FIFO: %s", strerror(errno));
+  }
+}
+
+static std::chrono::duration<double> GetMaximumPause(std::atomic<ThreadState>& state) {
+  std::chrono::duration<double> max_diff(0);
+
+  const auto begin = std::chrono::high_resolution_clock::now();
+  auto last = begin;
+  state.store(ThreadState::Started);
+  while (state.load() != ThreadState::Stopping) {
+    auto now = std::chrono::high_resolution_clock::now();
+
+    auto diff = now - last;
+    if (diff > max_diff) {
+      max_diff = diff;
+    }
+
+    last = now;
+  }
+
+  return max_diff;
+}
+
+static void PerformDump() {
+  pid_t target = getpid();
+  pid_t forkpid = fork();
+  if (forkpid == -1) {
+    err(1, "fork failed");
+  } else if (forkpid != 0) {
+    int status;
+    pid_t pid = waitpid(forkpid, &status, 0);
+    if (pid == -1) {
+      err(1, "waitpid failed");
+    } else if (!WIFEXITED(status)) {
+      err(1, "child didn't exit");
+    } else if (WEXITSTATUS(status) != 0) {
+      errx(1, "child exited with non-zero status %d", WEXITSTATUS(status));
+    }
+  } else {
+    android::base::unique_fd output_fd(open("/dev/null", O_WRONLY | O_CLOEXEC));
+    if (output_fd == -1) {
+      err(1, "failed to open /dev/null");
+    }
+
+    if (!debuggerd_trigger_dump(target, kDebuggerdNativeBacktrace, 1000, std::move(output_fd))) {
+      errx(1, "failed to trigger dump");
+    }
+
+    _exit(0);
+  }
+}
+
+template <typename Fn>
+static void BM_maximum_pause_impl(benchmark::State& state, const Fn& function) {
+  SetScheduler();
+
+  for (auto _ : state) {
+    std::chrono::duration<double> max_pause;
+    std::atomic<ThreadState> thread_state(ThreadState::Starting);
+    auto thread = std::thread([&]() { max_pause = GetMaximumPause(thread_state); });
+
+    while (thread_state != ThreadState::Started) {
+      std::this_thread::sleep_for(1ms);
+    }
+
+    function();
+
+    thread_state = ThreadState::Stopping;
+    thread.join();
+
+    state.SetIterationTime(max_pause.count());
+  }
+}
+
+static void BM_maximum_pause_noop(benchmark::State& state) {
+  BM_maximum_pause_impl(state, []() {});
+}
+
+static void BM_maximum_pause_debuggerd(benchmark::State& state) {
+  BM_maximum_pause_impl(state, []() { PerformDump(); });
+}
+
+BENCHMARK(BM_maximum_pause_noop)->Iterations(128)->UseManualTime();
+BENCHMARK(BM_maximum_pause_debuggerd)->Iterations(128)->UseManualTime();
+
+BENCHMARK_MAIN();
diff --git a/debuggerd/debuggerd_test.cpp b/debuggerd/debuggerd_test.cpp
index 8d0c98b..939f4d2 100644
--- a/debuggerd/debuggerd_test.cpp
+++ b/debuggerd/debuggerd_test.cpp
@@ -36,6 +36,7 @@
 #include <android-base/parseint.h>
 #include <android-base/properties.h>
 #include <android-base/strings.h>
+#include <android-base/test_utils.h>
 #include <android-base/unique_fd.h>
 #include <cutils/sockets.h>
 #include <gtest/gtest.h>
@@ -75,22 +76,6 @@
     return value;                                                  \
   }()
 
-#define ASSERT_MATCH(str, pattern)                                              \
-  do {                                                                          \
-    std::regex r((pattern));                                                    \
-    if (!std::regex_search((str), r)) {                                         \
-      FAIL() << "regex mismatch: expected " << (pattern) << " in: \n" << (str); \
-    }                                                                           \
-  } while (0)
-
-#define ASSERT_NOT_MATCH(str, pattern)                                                      \
-  do {                                                                                      \
-    std::regex r((pattern));                                                                \
-    if (std::regex_search((str), r)) {                                                      \
-      FAIL() << "regex mismatch: expected to not find " << (pattern) << " in: \n" << (str); \
-    }                                                                                       \
-  } while (0)
-
 #define ASSERT_BACKTRACE_FRAME(result, frame_name)                        \
   ASSERT_MATCH(result, R"(#\d\d pc [0-9a-f]+\s+ /system/lib)" ARCH_SUFFIX \
                        R"(/libc.so \()" frame_name R"(\+)")
@@ -245,6 +230,8 @@
   int status;
   pid_t pid = TIMEOUT(5, waitpid(crasher_pid, &status, 0));
   if (pid != crasher_pid) {
+    printf("failed to wait for crasher (pid %d)\n", crasher_pid);
+    sleep(100);
     FAIL() << "failed to wait for crasher: " << strerror(errno);
   }
 
@@ -341,13 +328,12 @@
   int intercept_result;
   unique_fd output_fd;
   StartProcess([]() {
-    abort();
+    while (true) {
+      sleep(1);
+    }
   });
   StartIntercept(&output_fd);
-
-  // Wait for a bit, or we might end up killing the process before the signal
-  // handler even gets a chance to be registered.
-  std::this_thread::sleep_for(100ms);
+  FinishCrasher();
   ASSERT_EQ(0, kill(crasher_pid, SIGSEGV));
 
   AssertDeath(SIGSEGV);
@@ -439,19 +425,6 @@
   AssertDeath(SIGABRT);
 }
 
-// wait_for_gdb shouldn't trigger on manually sent signals.
-TEST_F(CrasherTest, wait_for_gdb_signal) {
-  if (!android::base::SetProperty(kWaitForGdbKey, "1")) {
-    FAIL() << "failed to enable wait_for_gdb";
-  }
-
-  StartProcess([]() {
-    abort();
-  });
-  ASSERT_EQ(0, kill(crasher_pid, SIGSEGV)) << strerror(errno);
-  AssertDeath(SIGSEGV);
-}
-
 TEST_F(CrasherTest, backtrace) {
   std::string result;
   int intercept_result;
@@ -596,15 +569,13 @@
   int intercept_result;
   unique_fd output_fd;
   StartProcess([]() {
-    while (true) {
-    }
+    raise(SIGABRT);
   });
 
   StartIntercept(&output_fd);
-  FinishCrasher();
 
   ASSERT_EQ(0, ptrace(PTRACE_SEIZE, crasher_pid, 0, 0));
-  ASSERT_EQ(0, kill(crasher_pid, SIGABRT));
+  FinishCrasher();
 
   int status;
   ASSERT_EQ(crasher_pid, waitpid(crasher_pid, &status, 0));
@@ -622,6 +593,10 @@
   regex += R"( \(.+debuggerd_test)";
   ASSERT_MATCH(result, regex.c_str());
 
+  ASSERT_EQ(crasher_pid, waitpid(crasher_pid, &status, 0));
+  ASSERT_TRUE(WIFSTOPPED(status));
+  ASSERT_EQ(SIGABRT, WSTOPSIG(status));
+
   ASSERT_EQ(0, ptrace(PTRACE_DETACH, crasher_pid, 0, SIGABRT));
   AssertDeath(SIGABRT);
 }
diff --git a/debuggerd/handler/debuggerd_fallback.cpp b/debuggerd/handler/debuggerd_fallback.cpp
index 06d4a9b..5fddddc 100644
--- a/debuggerd/handler/debuggerd_fallback.cpp
+++ b/debuggerd/handler/debuggerd_fallback.cpp
@@ -36,10 +36,14 @@
 #include <unistd.h>
 
 #include <atomic>
+#include <memory>
 
 #include <android-base/file.h>
 #include <android-base/unique_fd.h>
 #include <async_safe/log.h>
+#include <backtrace/BacktraceMap.h>
+#include <unwindstack/Memory.h>
+#include <unwindstack/Regs.h>
 
 #include "debuggerd/handler.h"
 #include "tombstoned/tombstoned.h"
@@ -49,6 +53,7 @@
 #include "libdebuggerd/tombstone.h"
 
 using android::base::unique_fd;
+using unwindstack::Regs;
 
 extern "C" void __linker_enable_fallback_allocator();
 extern "C" void __linker_disable_fallback_allocator();
@@ -61,7 +66,19 @@
 // exhaustion.
 static void debuggerd_fallback_trace(int output_fd, ucontext_t* ucontext) {
   __linker_enable_fallback_allocator();
-  dump_backtrace_ucontext(output_fd, ucontext);
+  {
+    std::unique_ptr<Regs> regs;
+
+    ThreadInfo thread;
+    thread.pid = getpid();
+    thread.tid = gettid();
+    thread.thread_name = get_thread_name(gettid());
+    thread.registers.reset(Regs::CreateFromUcontext(Regs::CurrentArch(), ucontext));
+
+    // TODO: Create this once and store it in a global?
+    std::unique_ptr<BacktraceMap> map(BacktraceMap::Create(getpid()));
+    dump_backtrace_thread(output_fd, map.get(), thread);
+  }
   __linker_disable_fallback_allocator();
 }
 
@@ -162,41 +179,41 @@
 
   // Send a signal to all of our siblings, asking them to dump their stack.
   iterate_siblings(
-    [](pid_t tid, int output_fd) {
-      // Use a pipe, to be able to detect situations where the thread gracefully exits before
-      // receiving our signal.
-      unique_fd pipe_read, pipe_write;
-      if (!Pipe(&pipe_read, &pipe_write)) {
-        async_safe_format_log(ANDROID_LOG_ERROR, "libc", "failed to create pipe: %s",
-                              strerror(errno));
-        return false;
-      }
+      [](pid_t tid, int output_fd) {
+        // Use a pipe, to be able to detect situations where the thread gracefully exits before
+        // receiving our signal.
+        unique_fd pipe_read, pipe_write;
+        if (!Pipe(&pipe_read, &pipe_write)) {
+          async_safe_format_log(ANDROID_LOG_ERROR, "libc", "failed to create pipe: %s",
+                                strerror(errno));
+          return false;
+        }
 
-      trace_output_fd.store(pipe_write.get());
+        trace_output_fd.store(pipe_write.get());
 
-      siginfo_t siginfo = {};
-      siginfo.si_code = SI_QUEUE;
-      siginfo.si_value.sival_int = ~0;
-      siginfo.si_pid = getpid();
-      siginfo.si_uid = getuid();
+        siginfo_t siginfo = {};
+        siginfo.si_code = SI_QUEUE;
+        siginfo.si_value.sival_int = ~0;
+        siginfo.si_pid = getpid();
+        siginfo.si_uid = getuid();
 
-      if (syscall(__NR_rt_tgsigqueueinfo, getpid(), tid, DEBUGGER_SIGNAL, &siginfo) != 0) {
-        async_safe_format_log(ANDROID_LOG_ERROR, "libc", "failed to send trace signal to %d: %s",
-                              tid, strerror(errno));
-        return false;
-      }
+        if (syscall(__NR_rt_tgsigqueueinfo, getpid(), tid, DEBUGGER_SIGNAL, &siginfo) != 0) {
+          async_safe_format_log(ANDROID_LOG_ERROR, "libc", "failed to send trace signal to %d: %s",
+                                tid, strerror(errno));
+          return false;
+        }
 
-      bool success = forward_output(pipe_read.get(), output_fd);
-      if (success) {
-        // The signaled thread has closed trace_output_fd already.
-        (void)pipe_write.release();
-      } else {
-        trace_output_fd.store(-1);
-      }
+        bool success = forward_output(pipe_read.get(), output_fd);
+        if (success) {
+          // The signaled thread has closed trace_output_fd already.
+          (void)pipe_write.release();
+        } else {
+          trace_output_fd.store(-1);
+        }
 
-      return true;
-    },
-    output_fd.get());
+        return true;
+      },
+      output_fd.get());
 
   dump_backtrace_footer(output_fd.get());
   tombstoned_notify_completion(tombstone_socket.get());
@@ -206,7 +223,8 @@
 }
 
 static void crash_handler(siginfo_t* info, ucontext_t* ucontext, void* abort_message) {
-  // Only allow one thread to handle a crash.
+  // Only allow one thread to handle a crash at a time (this can happen multiple times without
+  // exit, since tombstones can be requested without a real crash happening.)
   static pthread_mutex_t crash_mutex = PTHREAD_MUTEX_INITIALIZER;
   int ret = pthread_mutex_lock(&crash_mutex);
   if (ret != 0) {
@@ -221,11 +239,13 @@
   if (tombstoned_connected) {
     tombstoned_notify_completion(tombstone_socket.get());
   }
+
+  pthread_mutex_unlock(&crash_mutex);
 }
 
 extern "C" void debuggerd_fallback_handler(siginfo_t* info, ucontext_t* ucontext,
                                            void* abort_message) {
-  if (info->si_signo == DEBUGGER_SIGNAL) {
+  if (info->si_signo == DEBUGGER_SIGNAL && info->si_value.sival_int != 0) {
     return trace_handler(info, ucontext);
   } else {
     return crash_handler(info, ucontext, abort_message);
diff --git a/debuggerd/handler/debuggerd_handler.cpp b/debuggerd/handler/debuggerd_handler.cpp
index bd202ff..05e6efa 100644
--- a/debuggerd/handler/debuggerd_handler.cpp
+++ b/debuggerd/handler/debuggerd_handler.cpp
@@ -44,15 +44,21 @@
 #include <sys/prctl.h>
 #include <sys/socket.h>
 #include <sys/syscall.h>
+#include <sys/uio.h>
 #include <sys/un.h>
 #include <sys/wait.h>
 #include <unistd.h>
 
 #include <android-base/unique_fd.h>
 #include <async_safe/log.h>
+#include <cutils/properties.h>
+
+#include <libdebuggerd/utility.h>
 
 #include "dump_type.h"
+#include "protocol.h"
 
+using android::base::Pipe;
 using android::base::unique_fd;
 
 // see man(2) prctl, specifically the section about PR_GET_NAME
@@ -114,7 +120,7 @@
   va_list args;
   va_start(args, fmt);
 
-  char buf[4096];
+  char buf[256];
   async_safe_format_buffer_va_list(buf, sizeof(buf), fmt, args);
   fatal("%s: %s", buf, strerror(err));
 }
@@ -147,7 +153,7 @@
  * mutex is being held, so we don't want to use any libc functions that
  * could allocate memory or hold a lock.
  */
-static void log_signal_summary(int signum, const siginfo_t* info) {
+static void log_signal_summary(const siginfo_t* info) {
   char thread_name[MAX_TASK_NAME_LEN + 1];  // one more for termination
   if (prctl(PR_GET_NAME, reinterpret_cast<unsigned long>(thread_name), 0, 0, 0) != 0) {
     strcpy(thread_name, "<name unknown>");
@@ -157,57 +163,19 @@
     thread_name[MAX_TASK_NAME_LEN] = 0;
   }
 
-  if (signum == DEBUGGER_SIGNAL) {
+  if (info->si_signo == DEBUGGER_SIGNAL) {
     async_safe_format_log(ANDROID_LOG_INFO, "libc", "Requested dump for tid %d (%s)", __gettid(),
                           thread_name);
     return;
   }
 
-  const char* signal_name = "???";
-  bool has_address = false;
-  switch (signum) {
-    case SIGABRT:
-      signal_name = "SIGABRT";
-      break;
-    case SIGBUS:
-      signal_name = "SIGBUS";
-      has_address = true;
-      break;
-    case SIGFPE:
-      signal_name = "SIGFPE";
-      has_address = true;
-      break;
-    case SIGILL:
-      signal_name = "SIGILL";
-      has_address = true;
-      break;
-    case SIGSEGV:
-      signal_name = "SIGSEGV";
-      has_address = true;
-      break;
-#if defined(SIGSTKFLT)
-    case SIGSTKFLT:
-      signal_name = "SIGSTKFLT";
-      break;
-#endif
-    case SIGSYS:
-      signal_name = "SIGSYS";
-      break;
-    case SIGTRAP:
-      signal_name = "SIGTRAP";
-      break;
-  }
+  const char* signal_name = get_signame(info->si_signo);
+  bool has_address = signal_has_si_addr(info->si_signo, info->si_code);
 
-  // "info" will be null if the siginfo_t information was not available.
-  // Many signals don't have an address or a code.
-  char code_desc[32];  // ", code -6"
-  char addr_desc[32];  // ", fault addr 0x1234"
-  addr_desc[0] = code_desc[0] = 0;
-  if (info != nullptr) {
-    async_safe_format_buffer(code_desc, sizeof(code_desc), ", code %d", info->si_code);
-    if (has_address) {
-      async_safe_format_buffer(addr_desc, sizeof(addr_desc), ", fault addr %p", info->si_addr);
-    }
+  // Many signals don't have an address.
+  char addr_desc[32] = "";  // ", fault addr 0x1234"
+  if (has_address) {
+    async_safe_format_buffer(addr_desc, sizeof(addr_desc), ", fault addr %p", info->si_addr);
   }
 
   char main_thread_name[MAX_TASK_NAME_LEN + 1];
@@ -216,8 +184,9 @@
   }
 
   async_safe_format_log(
-      ANDROID_LOG_FATAL, "libc", "Fatal signal %d (%s)%s%s in tid %d (%s), pid %d (%s)", signum,
-      signal_name, code_desc, addr_desc, __gettid(), thread_name, __getpid(), main_thread_name);
+      ANDROID_LOG_FATAL, "libc", "Fatal signal %d (%s), code %d (%s)%s in tid %d (%s), pid %d (%s)",
+      info->si_signo, signal_name, info->si_code, get_sigcode(info->si_signo, info->si_code),
+      addr_desc, __gettid(), thread_name, __getpid(), main_thread_name);
 }
 
 /*
@@ -268,12 +237,44 @@
   }
 }
 
+static pid_t __fork() {
+  return clone(nullptr, nullptr, 0, nullptr);
+}
+
+// Double-clone, with CLONE_FILES to share the file descriptor table for kcmp validation.
+// Returns 0 in the orphaned child, the pid of the orphan in the original process, or -1 on failure.
+static void create_vm_process() {
+  pid_t first = clone(nullptr, nullptr, CLONE_FILES, nullptr);
+  if (first == -1) {
+    fatal_errno("failed to clone vm process");
+  } else if (first == 0) {
+    drop_capabilities();
+
+    if (clone(nullptr, nullptr, CLONE_FILES, nullptr) == -1) {
+      _exit(errno);
+    }
+
+    // Exit immediately on both sides of the fork.
+    // crash_dump is ptracing us, so it'll get to do whatever it wants in between.
+    _exit(0);
+  }
+
+  int status;
+  if (TEMP_FAILURE_RETRY(waitpid(first, &status, __WCLONE)) != first) {
+    fatal_errno("failed to waitpid in double fork");
+  } else if (!WIFEXITED(status)) {
+    fatal("intermediate process didn't exit cleanly in double fork (status = %d)", status);
+  } else if (WEXITSTATUS(status)) {
+    fatal("second clone failed: %s", strerror(WEXITSTATUS(status)));
+  }
+}
+
 struct debugger_thread_info {
-  bool crash_dump_started;
   pid_t crashing_tid;
   pid_t pseudothread_tid;
-  int signal_number;
-  siginfo_t* info;
+  siginfo_t* siginfo;
+  void* ucontext;
+  uintptr_t abort_msg;
 };
 
 // Logging and contacting debuggerd requires free file descriptors, which we might not have.
@@ -284,7 +285,8 @@
 static void* pseudothread_stack;
 
 static DebuggerdDumpType get_dump_type(const debugger_thread_info* thread_info) {
-  if (thread_info->signal_number == DEBUGGER_SIGNAL && thread_info->info->si_value.sival_int) {
+  if (thread_info->siginfo->si_signo == DEBUGGER_SIGNAL &&
+      thread_info->siginfo->si_value.sival_int) {
     return kDebuggerdNativeBacktrace;
   }
 
@@ -299,25 +301,58 @@
   }
 
   int devnull = TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR));
+  if (devnull == -1) {
+    fatal_errno("failed to open /dev/null");
+  } else if (devnull != 0) {
+    fatal_errno("expected /dev/null fd to be 0, actually %d", devnull);
+  }
 
   // devnull will be 0.
-  TEMP_FAILURE_RETRY(dup2(devnull, STDOUT_FILENO));
-  TEMP_FAILURE_RETRY(dup2(devnull, STDERR_FILENO));
+  TEMP_FAILURE_RETRY(dup2(devnull, 1));
+  TEMP_FAILURE_RETRY(dup2(devnull, 2));
 
-  unique_fd pipe_read, pipe_write;
-  if (!android::base::Pipe(&pipe_read, &pipe_write)) {
+  unique_fd input_read, input_write;
+  unique_fd output_read, output_write;
+  if (!Pipe(&input_read, &input_write) != 0 || !Pipe(&output_read, &output_write)) {
     fatal_errno("failed to create pipe");
   }
 
+  // ucontext_t is absurdly large on AArch64, so piece it together manually with writev.
+  uint32_t version = 1;
+  constexpr size_t expected =
+      sizeof(version) + sizeof(siginfo_t) + sizeof(ucontext_t) + sizeof(uintptr_t);
+
+  errno = 0;
+  if (fcntl(output_write.get(), F_SETPIPE_SZ, expected) < static_cast<int>(expected)) {
+    fatal_errno("failed to set pipe bufer size");
+  }
+
+  struct iovec iovs[4] = {
+      {.iov_base = &version, .iov_len = sizeof(version)},
+      {.iov_base = thread_info->siginfo, .iov_len = sizeof(siginfo_t)},
+      {.iov_base = thread_info->ucontext, .iov_len = sizeof(ucontext_t)},
+      {.iov_base = &thread_info->abort_msg, .iov_len = sizeof(uintptr_t)},
+  };
+
+  ssize_t rc = TEMP_FAILURE_RETRY(writev(output_write.get(), iovs, 4));
+  if (rc == -1) {
+    fatal_errno("failed to write crash info");
+  } else if (rc != expected) {
+    fatal("failed to write crash info, wrote %zd bytes, expected %zd", rc, expected);
+  }
+
   // Don't use fork(2) to avoid calling pthread_atfork handlers.
-  int forkpid = clone(nullptr, nullptr, 0, nullptr);
-  if (forkpid == -1) {
+  pid_t crash_dump_pid = __fork();
+  if (crash_dump_pid == -1) {
     async_safe_format_log(ANDROID_LOG_FATAL, "libc",
                           "failed to fork in debuggerd signal handler: %s", strerror(errno));
-  } else if (forkpid == 0) {
-    TEMP_FAILURE_RETRY(dup2(pipe_write.get(), STDOUT_FILENO));
-    pipe_write.reset();
-    pipe_read.reset();
+  } else if (crash_dump_pid == 0) {
+    TEMP_FAILURE_RETRY(dup2(input_write.get(), STDOUT_FILENO));
+    TEMP_FAILURE_RETRY(dup2(output_read.get(), STDIN_FILENO));
+    input_read.reset();
+    input_write.reset();
+    output_read.reset();
+    output_write.reset();
 
     raise_caps();
 
@@ -332,45 +367,54 @@
 
     execle(CRASH_DUMP_PATH, CRASH_DUMP_NAME, main_tid, pseudothread_tid, debuggerd_dump_type,
            nullptr, nullptr);
-
     fatal_errno("exec failed");
-  } else {
-    pipe_write.reset();
-    char buf[4];
-    ssize_t rc = TEMP_FAILURE_RETRY(read(pipe_read.get(), &buf, sizeof(buf)));
-    if (rc == -1) {
-      async_safe_format_log(ANDROID_LOG_FATAL, "libc", "read of IPC pipe failed: %s",
-                            strerror(errno));
-    } else if (rc == 0) {
-      async_safe_format_log(ANDROID_LOG_FATAL, "libc", "crash_dump helper failed to exec");
-    } else if (rc != 1) {
-      async_safe_format_log(ANDROID_LOG_FATAL, "libc",
-                            "read of IPC pipe returned unexpected value: %zd", rc);
-    } else {
-      if (buf[0] != '\1') {
-        async_safe_format_log(ANDROID_LOG_FATAL, "libc", "crash_dump helper reported failure");
-      } else {
-        thread_info->crash_dump_started = true;
-      }
-    }
-    pipe_read.reset();
-
-    // Don't leave a zombie child.
-    int status;
-    if (TEMP_FAILURE_RETRY(waitpid(forkpid, &status, 0)) == -1) {
-      async_safe_format_log(ANDROID_LOG_FATAL, "libc", "failed to wait for crash_dump helper: %s",
-                            strerror(errno));
-    } else if (WIFSTOPPED(status) || WIFSIGNALED(status)) {
-      async_safe_format_log(ANDROID_LOG_FATAL, "libc", "crash_dump helper crashed or stopped");
-      thread_info->crash_dump_started = false;
-    }
   }
 
-  syscall(__NR_exit, 0);
+  input_write.reset();
+  output_read.reset();
+
+  // crash_dump will ptrace and pause all of our threads, and then write to the pipe to tell
+  // us to fork off a process to read memory from.
+  char buf[4];
+  rc = TEMP_FAILURE_RETRY(read(input_read.get(), &buf, sizeof(buf)));
+  if (rc == -1) {
+    async_safe_format_log(ANDROID_LOG_FATAL, "libc", "read of IPC pipe failed: %s", strerror(errno));
+    return 1;
+  } else if (rc == 0) {
+    async_safe_format_log(ANDROID_LOG_FATAL, "libc", "crash_dump helper failed to exec");
+    return 1;
+  } else if (rc != 1) {
+    async_safe_format_log(ANDROID_LOG_FATAL, "libc",
+                          "read of IPC pipe returned unexpected value: %zd", rc);
+    return 1;
+  } else if (buf[0] != '\1') {
+    async_safe_format_log(ANDROID_LOG_FATAL, "libc", "crash_dump helper reported failure");
+    return 1;
+  }
+
+  // crash_dump is ptracing us, fork off a copy of our address space for it to use.
+  create_vm_process();
+
+  // Don't leave a zombie child.
+  int status;
+  if (TEMP_FAILURE_RETRY(waitpid(crash_dump_pid, &status, 0)) == -1) {
+    async_safe_format_log(ANDROID_LOG_FATAL, "libc", "failed to wait for crash_dump helper: %s",
+                          strerror(errno));
+  } else if (WIFSTOPPED(status) || WIFSIGNALED(status)) {
+    async_safe_format_log(ANDROID_LOG_FATAL, "libc", "crash_dump helper crashed or stopped");
+  }
+
+  if (thread_info->siginfo->si_signo != DEBUGGER_SIGNAL) {
+    // For crashes, we don't need to minimize pause latency.
+    // Wait for the dump to complete before having the process exit, to avoid being murdered by
+    // ActivityManager or init.
+    TEMP_FAILURE_RETRY(read(input_read, &buf, sizeof(buf)));
+  }
+
   return 0;
 }
 
-static void resend_signal(siginfo_t* info, bool crash_dump_started) {
+static void resend_signal(siginfo_t* info) {
   // Signals can either be fatal or nonfatal.
   // For fatal signals, crash_dump will send us the signal we crashed with
   // before resuming us, so that processes using waitpid on us will see that we
@@ -379,16 +423,6 @@
   // to deregister our signal handler for that signal before continuing.
   if (info->si_signo != DEBUGGER_SIGNAL) {
     signal(info->si_signo, SIG_DFL);
-  }
-
-  // We need to return from our signal handler so that crash_dump can see the
-  // signal via ptrace and dump the thread that crashed. However, returning
-  // does not guarantee that the signal will be thrown again, even for SIGSEGV
-  // and friends, since the signal could have been sent manually. We blocked
-  // all signals when registering the handler, so resending the signal (using
-  // rt_tgsigqueueinfo(2) to preserve SA_SIGINFO) will cause it to be delivered
-  // when our signal handler returns.
-  if (crash_dump_started || info->si_signo != DEBUGGER_SIGNAL) {
     int rc = syscall(SYS_rt_tgsigqueueinfo, __getpid(), __gettid(), info->si_signo, info);
     if (rc != 0) {
       fatal_errno("failed to resend signal during crash");
@@ -425,7 +459,7 @@
   }
 
   void* abort_message = nullptr;
-  if (g_callbacks.get_abort_message) {
+  if (signal_number != DEBUGGER_SIGNAL && g_callbacks.get_abort_message) {
     abort_message = g_callbacks.get_abort_message();
   }
 
@@ -439,7 +473,7 @@
     // you can only set NO_NEW_PRIVS to 1, and the effect should be at worst a single missing
     // ANR trace.
     debuggerd_fallback_handler(info, static_cast<ucontext_t*>(context), abort_message);
-    resend_signal(info, false);
+    resend_signal(info);
     return;
   }
 
@@ -450,20 +484,14 @@
     return;
   }
 
-  log_signal_summary(signal_number, info);
-
-  // If this was a fatal crash, populate si_value with the abort message address if possible.
-  // Note that applications can set an abort message without aborting.
-  if (abort_message && signal_number != DEBUGGER_SIGNAL) {
-    info->si_value.sival_ptr = abort_message;
-  }
+  log_signal_summary(info);
 
   debugger_thread_info thread_info = {
-    .crash_dump_started = false,
-    .pseudothread_tid = -1,
-    .crashing_tid = __gettid(),
-    .signal_number = signal_number,
-    .info = info
+      .pseudothread_tid = -1,
+      .crashing_tid = __gettid(),
+      .siginfo = info,
+      .ucontext = context,
+      .abort_msg = reinterpret_cast<uintptr_t>(abort_message),
   };
 
   // Set PR_SET_DUMPABLE to 1, so that crash_dump can ptrace us.
@@ -472,7 +500,19 @@
     fatal_errno("failed to set dumpable");
   }
 
-  // Essentially pthread_create without CLONE_FILES (see debuggerd_dispatch_pseudothread).
+  // On kernels with yama_ptrace enabled, also allow any process to attach.
+  bool restore_orig_ptracer = true;
+  if (prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY) != 0) {
+    if (errno == EINVAL) {
+      // This kernel does not support PR_SET_PTRACER_ANY, or Yama is not enabled.
+      restore_orig_ptracer = false;
+    } else {
+      fatal_errno("failed to set traceable");
+    }
+  }
+
+  // Essentially pthread_create without CLONE_FILES, so we still work during file descriptor
+  // exhaustion.
   pid_t child_pid =
     clone(debuggerd_dispatch_pseudothread, pseudothread_stack,
           CLONE_THREAD | CLONE_SIGHAND | CLONE_VM | CLONE_CHILD_SETTID | CLONE_CHILD_CLEARTID,
@@ -484,7 +524,7 @@
   // Wait for the child to start...
   futex_wait(&thread_info.pseudothread_tid, -1);
 
-  // and then wait for it to finish.
+  // and then wait for it to terminate.
   futex_wait(&thread_info.pseudothread_tid, child_pid);
 
   // Restore PR_SET_DUMPABLE to its original value.
@@ -492,21 +532,18 @@
     fatal_errno("failed to restore dumpable");
   }
 
-  // Signals can either be fatal or nonfatal.
-  // For fatal signals, crash_dump will PTRACE_CONT us with the signal we
-  // crashed with, so that processes using waitpid on us will see that we
-  // exited with the correct exit status (e.g. so that sh will report
-  // "Segmentation fault" instead of "Killed"). For this to work, we need
-  // to deregister our signal handler for that signal before continuing.
-  if (signal_number != DEBUGGER_SIGNAL) {
-    signal(signal_number, SIG_DFL);
+  // Restore PR_SET_PTRACER to its original value.
+  if (restore_orig_ptracer && prctl(PR_SET_PTRACER, 0) != 0) {
+    fatal_errno("failed to restore traceable");
   }
 
-  resend_signal(info, thread_info.crash_dump_started);
   if (info->si_signo == DEBUGGER_SIGNAL) {
     // If the signal is fatal, don't unlock the mutex to prevent other crashing threads from
     // starting to dump right before our death.
     pthread_mutex_unlock(&crash_mutex);
+  } else {
+    // Resend the signal, so that either gdb or the parent's waitpid sees it.
+    resend_signal(info);
   }
 }
 
diff --git a/debuggerd/libdebuggerd/arm/machine.cpp b/debuggerd/libdebuggerd/arm/machine.cpp
deleted file mode 100644
index bfb5ea4..0000000
--- a/debuggerd/libdebuggerd/arm/machine.cpp
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- *
- * Copyright 2006, 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.
- */
-
-#define LOG_TAG "DEBUG"
-
-#include "libdebuggerd/machine.h"
-
-#include <errno.h>
-#include <stdint.h>
-#include <string.h>
-#include <sys/ptrace.h>
-
-#include <backtrace/Backtrace.h>
-#include <log/log.h>
-
-#include "libdebuggerd/utility.h"
-
-void dump_memory_and_code(log_t* log, Backtrace* backtrace) {
-  pt_regs regs;
-  if (ptrace(PTRACE_GETREGS, backtrace->Tid(), 0, &regs)) {
-    ALOGE("cannot get registers: %s\n", strerror(errno));
-    return;
-  }
-
-  static const char reg_names[] = "r0r1r2r3r4r5r6r7r8r9slfpipsp";
-
-  for (int reg = 0; reg < 14; reg++) {
-    dump_memory(log, backtrace, regs.uregs[reg], "memory near %.2s:", &reg_names[reg * 2]);
-  }
-
-  dump_memory(log, backtrace, static_cast<uintptr_t>(regs.ARM_pc), "code around pc:");
-
-  if (regs.ARM_pc != regs.ARM_lr) {
-    dump_memory(log, backtrace, static_cast<uintptr_t>(regs.ARM_lr), "code around lr:");
-  }
-}
-
-#define DUMP_GP_REGISTERS(log, reg_prefix)                                             \
-  _LOG(log, logtype::REGISTERS, "    r0 %08x  r1 %08x  r2 %08x  r3 %08x\n",            \
-       static_cast<uint32_t>(reg_prefix##r0), static_cast<uint32_t>(reg_prefix##r1),   \
-       static_cast<uint32_t>(reg_prefix##r2), static_cast<uint32_t>(reg_prefix##r3));  \
-  _LOG(log, logtype::REGISTERS, "    r4 %08x  r5 %08x  r6 %08x  r7 %08x\n",            \
-       static_cast<uint32_t>(reg_prefix##r4), static_cast<uint32_t>(reg_prefix##r5),   \
-       static_cast<uint32_t>(reg_prefix##r6), static_cast<uint32_t>(reg_prefix##r7));  \
-  _LOG(log, logtype::REGISTERS, "    r8 %08x  r9 %08x  sl %08x  fp %08x\n",            \
-       static_cast<uint32_t>(reg_prefix##r8), static_cast<uint32_t>(reg_prefix##r9),   \
-       static_cast<uint32_t>(reg_prefix##r10), static_cast<uint32_t>(reg_prefix##fp)); \
-  _LOG(log, logtype::REGISTERS, "    ip %08x  sp %08x  lr %08x  pc %08x  cpsr %08x\n", \
-       static_cast<uint32_t>(reg_prefix##ip), static_cast<uint32_t>(reg_prefix##sp),   \
-       static_cast<uint32_t>(reg_prefix##lr), static_cast<uint32_t>(reg_prefix##pc),   \
-       static_cast<uint32_t>(reg_prefix##cpsr))
-
-void dump_registers(log_t* log, pid_t tid) {
-  pt_regs r;
-  if (ptrace(PTRACE_GETREGS, tid, 0, &r)) {
-    ALOGE("cannot get registers: %s\n", strerror(errno));
-    return;
-  }
-
-  DUMP_GP_REGISTERS(log, r.ARM_);
-
-  user_vfp vfp_regs;
-  if (ptrace(PTRACE_GETVFPREGS, tid, 0, &vfp_regs)) {
-    ALOGE("cannot get FP registers: %s\n", strerror(errno));
-    return;
-  }
-
-  for (size_t i = 0; i < 32; i += 2) {
-    _LOG(log, logtype::FP_REGISTERS, "    d%-2d %016llx  d%-2d %016llx\n",
-         i, vfp_regs.fpregs[i], i+1, vfp_regs.fpregs[i+1]);
-  }
-  _LOG(log, logtype::FP_REGISTERS, "    scr %08lx\n", vfp_regs.fpscr);
-}
-
-void dump_registers(log_t* log, const ucontext_t* uc) {
-  DUMP_GP_REGISTERS(log, uc->uc_mcontext.arm_);
-}
diff --git a/debuggerd/libdebuggerd/arm64/machine.cpp b/debuggerd/libdebuggerd/arm64/machine.cpp
deleted file mode 100644
index ad1c951..0000000
--- a/debuggerd/libdebuggerd/arm64/machine.cpp
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- *
- * Copyright 2014, The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "DEBUG"
-
-#include "libdebuggerd/machine.h"
-
-#include <elf.h>
-#include <errno.h>
-#include <stdint.h>
-#include <string.h>
-#include <sys/ptrace.h>
-#include <sys/uio.h>
-
-#include <backtrace/Backtrace.h>
-#include <log/log.h>
-
-#include "libdebuggerd/utility.h"
-
-void dump_memory_and_code(log_t* log, Backtrace* backtrace) {
-  struct user_pt_regs regs;
-  struct iovec io;
-  io.iov_base = &regs;
-  io.iov_len = sizeof(regs);
-
-  if (ptrace(PTRACE_GETREGSET, backtrace->Tid(), reinterpret_cast<void*>(NT_PRSTATUS), &io) == -1) {
-    ALOGE("ptrace failed to get registers: %s", strerror(errno));
-    return;
-  }
-
-  for (int reg = 0; reg < 31; reg++) {
-    dump_memory(log, backtrace, regs.regs[reg], "memory near x%d:", reg);
-  }
-
-  dump_memory(log, backtrace, static_cast<uintptr_t>(regs.pc), "code around pc:");
-
-  if (regs.pc != regs.sp) {
-    dump_memory(log, backtrace, static_cast<uintptr_t>(regs.sp), "code around sp:");
-  }
-}
-
-#define DUMP_GP_REGISTERS(log)                                                                   \
-  for (int i = 0; i < 28; i += 4) {                                                              \
-    const char* fmt = "    x%-2d  %016llx  x%-2d  %016llx  x%-2d  %016llx  x%-2d  %016llx\n";    \
-    _LOG(log, logtype::REGISTERS, fmt, i, r.regs[i], i + 1, r.regs[i + 1], i + 2, r.regs[i + 2], \
-         i + 3, r.regs[i + 3]);                                                                  \
-  }                                                                                              \
-  _LOG(log, logtype::REGISTERS, "    x28  %016llx  x29  %016llx  x30  %016llx\n", r.regs[28],    \
-       r.regs[29], r.regs[30]);                                                                  \
-  _LOG(log, logtype::REGISTERS, "    sp   %016llx  pc   %016llx  pstate %016llx\n", r.sp, r.pc,  \
-       r.pstate)
-
-void dump_registers(log_t* log, pid_t tid) {
-  struct user_pt_regs r;
-  struct iovec io;
-  io.iov_base = &r;
-  io.iov_len = sizeof(r);
-
-  if (ptrace(PTRACE_GETREGSET, tid, (void*) NT_PRSTATUS, (void*) &io) == -1) {
-    ALOGE("ptrace error: %s\n", strerror(errno));
-    return;
-  }
-
-  DUMP_GP_REGISTERS(log);
-
-  struct user_fpsimd_state f;
-  io.iov_base = &f;
-  io.iov_len = sizeof(f);
-
-  if (ptrace(PTRACE_GETREGSET, tid, (void*) NT_PRFPREG, (void*) &io) == -1) {
-    ALOGE("ptrace error: %s\n", strerror(errno));
-    return;
-  }
-
-  for (int i = 0; i < 32; i += 2) {
-    _LOG(log, logtype::FP_REGISTERS,
-         "    v%-2d  %016" PRIx64 "%016" PRIx64 "  v%-2d  %016" PRIx64 "%016" PRIx64 "\n",
-         i,
-         static_cast<uint64_t>(f.vregs[i] >> 64),
-         static_cast<uint64_t>(f.vregs[i]),
-         i+1,
-         static_cast<uint64_t>(f.vregs[i+1] >> 64),
-         static_cast<uint64_t>(f.vregs[i+1]));
-  }
-  _LOG(log, logtype::FP_REGISTERS, "    fpsr %08x  fpcr %08x\n", f.fpsr, f.fpcr);
-}
-
-void dump_registers(log_t* log, const ucontext_t* ucontext) {
-  const mcontext_t& r = ucontext->uc_mcontext;
-  DUMP_GP_REGISTERS(log);
-}
diff --git a/debuggerd/libdebuggerd/backtrace.cpp b/debuggerd/libdebuggerd/backtrace.cpp
index f616e1b..f0a01f4 100644
--- a/debuggerd/libdebuggerd/backtrace.cpp
+++ b/debuggerd/libdebuggerd/backtrace.cpp
@@ -30,12 +30,15 @@
 #include <time.h>
 #include <unistd.h>
 
+#include <map>
 #include <memory>
 #include <string>
 
+#include <android-base/unique_fd.h>
 #include <backtrace/Backtrace.h>
 #include <log/log.h>
 
+#include "libdebuggerd/types.h"
 #include "libdebuggerd/utility.h"
 
 static void dump_process_header(log_t* log, pid_t pid, const char* process_name) {
@@ -56,62 +59,46 @@
   _LOG(log, logtype::BACKTRACE, "\n----- end %d -----\n", pid);
 }
 
-static void log_thread_name(log_t* log, pid_t tid, const char* thread_name) {
-  _LOG(log, logtype::BACKTRACE, "\n\"%s\" sysTid=%d\n", thread_name, tid);
-}
-
-static void dump_thread(log_t* log, BacktraceMap* map, pid_t pid, pid_t tid,
-                        const std::string& thread_name) {
-  log_thread_name(log, tid, thread_name.c_str());
-
-  std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, tid, map));
-  if (backtrace->Unwind(0)) {
-    dump_backtrace_to_log(backtrace.get(), log, "  ");
-  } else {
-    ALOGE("Unwind failed: tid = %d: %s", tid,
-          backtrace->GetErrorString(backtrace->GetError()).c_str());
-  }
-}
-
-void dump_backtrace(int fd, BacktraceMap* map, pid_t pid, pid_t tid, const std::string& process_name,
-                    const std::map<pid_t, std::string>& threads, std::string* amfd_data) {
-  log_t log;
-  log.tfd = fd;
-  log.amfd_data = amfd_data;
-
-  dump_process_header(&log, pid, process_name.c_str());
-  dump_thread(&log, map, pid, tid, threads.find(tid)->second.c_str());
-
-  for (const auto& it : threads) {
-    pid_t thread_tid = it.first;
-    const std::string& thread_name = it.second;
-    if (thread_tid != tid) {
-      dump_thread(&log, map, pid, thread_tid, thread_name.c_str());
-    }
-  }
-
-  dump_process_footer(&log, pid);
-}
-
-void dump_backtrace_ucontext(int output_fd, ucontext_t* ucontext) {
-  pid_t pid = getpid();
-  pid_t tid = gettid();
-
+void dump_backtrace_thread(int output_fd, BacktraceMap* map, const ThreadInfo& thread) {
   log_t log;
   log.tfd = output_fd;
   log.amfd_data = nullptr;
 
-  char thread_name[16];
-  read_with_default("/proc/self/comm", thread_name, sizeof(thread_name), "<unknown>");
-  log_thread_name(&log, tid, thread_name);
+  _LOG(&log, logtype::BACKTRACE, "\n\"%s\" sysTid=%d\n", thread.thread_name.c_str(), thread.tid);
 
-  std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, tid));
-  if (backtrace->Unwind(0, ucontext)) {
-    dump_backtrace_to_log(backtrace.get(), &log, "  ");
-  } else {
-    ALOGE("Unwind failed: tid = %d: %s", tid,
-          backtrace->GetErrorString(backtrace->GetError()).c_str());
+  std::vector<backtrace_frame_data_t> frames;
+  if (!Backtrace::Unwind(thread.registers.get(), map, &frames, 0, nullptr)) {
+    _LOG(&log, logtype::THREAD, "Unwind failed: tid = %d", thread.tid);
+    return;
   }
+
+  for (auto& frame : frames) {
+    _LOG(&log, logtype::BACKTRACE, "  %s\n", Backtrace::FormatFrameData(&frame).c_str());
+  }
+}
+
+void dump_backtrace(android::base::unique_fd output_fd, BacktraceMap* map,
+                    const std::map<pid_t, ThreadInfo>& thread_info, pid_t target_thread) {
+  log_t log;
+  log.tfd = output_fd.get();
+  log.amfd_data = nullptr;
+
+  auto target = thread_info.find(target_thread);
+  if (target == thread_info.end()) {
+    ALOGE("failed to find target thread in thread info");
+    return;
+  }
+
+  dump_process_header(&log, target->second.pid, target->second.process_name.c_str());
+
+  dump_backtrace_thread(output_fd.get(), map, target->second);
+  for (const auto& [tid, info] : thread_info) {
+    if (tid != target_thread) {
+      dump_backtrace_thread(output_fd.get(), map, info);
+    }
+  }
+
+  dump_process_footer(&log, target->second.pid);
 }
 
 void dump_backtrace_header(int output_fd) {
@@ -131,9 +118,3 @@
 
   dump_process_footer(&log, getpid());
 }
-
-void dump_backtrace_to_log(Backtrace* backtrace, log_t* log, const char* prefix) {
-  for (size_t i = 0; i < backtrace->NumFrames(); i++) {
-    _LOG(log, logtype::BACKTRACE, "%s%s\n", prefix, backtrace->FormatFrameData(i).c_str());
-  }
-}
diff --git a/debuggerd/libdebuggerd/elf_utils.cpp b/debuggerd/libdebuggerd/elf_utils.cpp
index a35102f..d7afc0b 100644
--- a/debuggerd/libdebuggerd/elf_utils.cpp
+++ b/debuggerd/libdebuggerd/elf_utils.cpp
@@ -26,28 +26,28 @@
 #include <string>
 
 #include <android-base/stringprintf.h>
-#include <backtrace/Backtrace.h>
 #include <log/log.h>
+#include <unwindstack/Memory.h>
 
 #define NOTE_ALIGN(size)  (((size) + 3) & ~3)
 
 template <typename HdrType, typename PhdrType, typename NhdrType>
-static bool get_build_id(
-    Backtrace* backtrace, uintptr_t base_addr, uint8_t* e_ident, std::string* build_id) {
+static bool get_build_id(unwindstack::Memory* memory, uintptr_t base_addr, uint8_t* e_ident,
+                         std::string* build_id) {
   HdrType hdr;
 
   memcpy(&hdr.e_ident[0], e_ident, EI_NIDENT);
 
   // First read the rest of the header.
-  if (backtrace->Read(base_addr + EI_NIDENT, reinterpret_cast<uint8_t*>(&hdr) + EI_NIDENT,
-                      sizeof(HdrType) - EI_NIDENT) != sizeof(HdrType) - EI_NIDENT) {
+  if (memory->Read(base_addr + EI_NIDENT, reinterpret_cast<uint8_t*>(&hdr) + EI_NIDENT,
+                   sizeof(HdrType) - EI_NIDENT) != sizeof(HdrType) - EI_NIDENT) {
     return false;
   }
 
   for (size_t i = 0; i < hdr.e_phnum; i++) {
     PhdrType phdr;
-    if (backtrace->Read(base_addr + hdr.e_phoff + i * hdr.e_phentsize,
-                        reinterpret_cast<uint8_t*>(&phdr), sizeof(phdr)) != sizeof(phdr)) {
+    if (memory->Read(base_addr + hdr.e_phoff + i * hdr.e_phentsize,
+                     reinterpret_cast<uint8_t*>(&phdr), sizeof(phdr)) != sizeof(phdr)) {
       return false;
     }
     // Looking for the .note.gnu.build-id note.
@@ -56,7 +56,7 @@
       uintptr_t addr = base_addr + phdr.p_offset;
       while (hdr_size >= sizeof(NhdrType)) {
         NhdrType nhdr;
-        if (backtrace->Read(addr, reinterpret_cast<uint8_t*>(&nhdr), sizeof(nhdr)) != sizeof(nhdr)) {
+        if (memory->Read(addr, reinterpret_cast<uint8_t*>(&nhdr), sizeof(nhdr)) != sizeof(nhdr)) {
           return false;
         }
         addr += sizeof(nhdr);
@@ -69,7 +69,7 @@
                   nhdr.n_descsz);
             return false;
           }
-          if (backtrace->Read(addr, build_id_data, nhdr.n_descsz) != nhdr.n_descsz) {
+          if (memory->Read(addr, build_id_data, nhdr.n_descsz) != nhdr.n_descsz) {
             return false;
           }
 
@@ -95,10 +95,10 @@
   return false;
 }
 
-bool elf_get_build_id(Backtrace* backtrace, uintptr_t addr, std::string* build_id) {
+bool elf_get_build_id(unwindstack::Memory* memory, uintptr_t addr, std::string* build_id) {
   // Read and verify the elf magic number first.
   uint8_t e_ident[EI_NIDENT];
-  if (backtrace->Read(addr, e_ident, SELFMAG) != SELFMAG) {
+  if (memory->Read(addr, e_ident, SELFMAG) != SELFMAG) {
     return false;
   }
 
@@ -107,14 +107,14 @@
   }
 
   // Read the rest of EI_NIDENT.
-  if (backtrace->Read(addr + SELFMAG, e_ident + SELFMAG, EI_NIDENT - SELFMAG) != EI_NIDENT - SELFMAG) {
+  if (memory->Read(addr + SELFMAG, e_ident + SELFMAG, EI_NIDENT - SELFMAG) != EI_NIDENT - SELFMAG) {
     return false;
   }
 
   if (e_ident[EI_CLASS] == ELFCLASS32) {
-    return get_build_id<Elf32_Ehdr, Elf32_Phdr, Elf32_Nhdr>(backtrace, addr, e_ident, build_id);
+    return get_build_id<Elf32_Ehdr, Elf32_Phdr, Elf32_Nhdr>(memory, addr, e_ident, build_id);
   } else if (e_ident[EI_CLASS] == ELFCLASS64) {
-    return get_build_id<Elf64_Ehdr, Elf64_Phdr, Elf64_Nhdr>(backtrace, addr, e_ident, build_id);
+    return get_build_id<Elf64_Ehdr, Elf64_Phdr, Elf64_Nhdr>(memory, addr, e_ident, build_id);
   }
 
   return false;
diff --git a/debuggerd/libdebuggerd/include/libdebuggerd/backtrace.h b/debuggerd/libdebuggerd/include/libdebuggerd/backtrace.h
index fe738f1..119e59b 100644
--- a/debuggerd/libdebuggerd/include/libdebuggerd/backtrace.h
+++ b/debuggerd/libdebuggerd/include/libdebuggerd/backtrace.h
@@ -23,21 +23,20 @@
 #include <map>
 #include <string>
 
+#include <android-base/unique_fd.h>
+
+#include "types.h"
 #include "utility.h"
 
-class Backtrace;
 class BacktraceMap;
 
 // Dumps a backtrace using a format similar to what Dalvik uses so that the result
 // can be intermixed in a bug report.
-void dump_backtrace(int fd, BacktraceMap* map, pid_t pid, pid_t tid, const std::string& process_name,
-                    const std::map<pid_t, std::string>& threads, std::string* amfd_data);
+void dump_backtrace(android::base::unique_fd output_fd, BacktraceMap* map,
+                    const std::map<pid_t, ThreadInfo>& thread_info, pid_t target_thread);
 
-/* Dumps the backtrace in the backtrace data structure to the log. */
-void dump_backtrace_to_log(Backtrace* backtrace, log_t* log, const char* prefix);
-
-void dump_backtrace_ucontext(int output_fd, ucontext_t* ucontext);
 void dump_backtrace_header(int output_fd);
+void dump_backtrace_thread(int output_fd, BacktraceMap* map, const ThreadInfo& thread);
 void dump_backtrace_footer(int output_fd);
 
 #endif // _DEBUGGERD_BACKTRACE_H
diff --git a/debuggerd/libdebuggerd/include/libdebuggerd/elf_utils.h b/debuggerd/libdebuggerd/include/libdebuggerd/elf_utils.h
index 11d0a43..5d0d924 100644
--- a/debuggerd/libdebuggerd/include/libdebuggerd/elf_utils.h
+++ b/debuggerd/libdebuggerd/include/libdebuggerd/elf_utils.h
@@ -20,8 +20,10 @@
 #include <stdint.h>
 #include <string>
 
-class Backtrace;
+namespace unwindstack {
+class Memory;
+}
 
-bool elf_get_build_id(Backtrace*, uintptr_t, std::string*);
+bool elf_get_build_id(unwindstack::Memory*, uintptr_t, std::string*);
 
 #endif // _DEBUGGERD_ELF_UTILS_H
diff --git a/debuggerd/libdebuggerd/include/libdebuggerd/machine.h b/debuggerd/libdebuggerd/include/libdebuggerd/machine.h
deleted file mode 100644
index 5e56682..0000000
--- a/debuggerd/libdebuggerd/include/libdebuggerd/machine.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (C) 2011 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 _DEBUGGERD_MACHINE_H
-#define _DEBUGGERD_MACHINE_H
-
-#include <sys/types.h>
-
-#include <backtrace/Backtrace.h>
-
-#include "utility.h"
-
-void dump_memory_and_code(log_t* log, Backtrace* backtrace);
-void dump_registers(log_t* log, pid_t tid);
-void dump_registers(log_t* log, const ucontext_t* uc);
-
-#endif // _DEBUGGERD_MACHINE_H
diff --git a/debuggerd/libdebuggerd/include/libdebuggerd/open_files_list.h b/debuggerd/libdebuggerd/include/libdebuggerd/open_files_list.h
index b37228d..4727ca4 100644
--- a/debuggerd/libdebuggerd/include/libdebuggerd/open_files_list.h
+++ b/debuggerd/libdebuggerd/include/libdebuggerd/open_files_list.h
@@ -31,6 +31,6 @@
 void populate_open_files_list(pid_t pid, OpenFilesList* list);
 
 /* Dumps the open files list to the log. */
-void dump_open_files_list_to_log(const OpenFilesList& files, log_t* log, const char* prefix);
+void dump_open_files_list(log_t* log, const OpenFilesList& files, const char* prefix);
 
 #endif // _DEBUGGERD_OPEN_FILES_LIST_H
diff --git a/debuggerd/libdebuggerd/include/libdebuggerd/tombstone.h b/debuggerd/libdebuggerd/include/libdebuggerd/tombstone.h
index 79743b6..198c48b 100644
--- a/debuggerd/libdebuggerd/include/libdebuggerd/tombstone.h
+++ b/debuggerd/libdebuggerd/include/libdebuggerd/tombstone.h
@@ -24,7 +24,10 @@
 #include <map>
 #include <string>
 
+#include <android-base/unique_fd.h>
+
 #include "open_files_list.h"
+#include "types.h"
 
 class BacktraceMap;
 
@@ -43,11 +46,10 @@
 void engrave_tombstone_ucontext(int tombstone_fd, uintptr_t abort_msg_address, siginfo_t* siginfo,
                                 ucontext_t* ucontext);
 
-// Compatibility shim.
-__attribute__((__unused__))
-static void engrave_tombstone_ucontext(int tombstone_fd, pid_t, pid_t, uintptr_t abort_msg_address,
-                                       siginfo_t* siginfo, ucontext_t* ucontext) {
-  engrave_tombstone_ucontext(tombstone_fd, abort_msg_address, siginfo, ucontext);
-}
+void engrave_tombstone(android::base::unique_fd output_fd, BacktraceMap* map,
+                       unwindstack::Memory* process_memory,
+                       const std::map<pid_t, ThreadInfo>& thread_info, pid_t target_thread,
+                       uintptr_t abort_msg_address, OpenFilesList* open_files,
+                       std::string* amfd_data);
 
-#endif // _DEBUGGERD_TOMBSTONE_H
+#endif  // _DEBUGGERD_TOMBSTONE_H
diff --git a/debuggerd/libdebuggerd/test/ptrace_fake.h b/debuggerd/libdebuggerd/include/libdebuggerd/types.h
similarity index 62%
copy from debuggerd/libdebuggerd/test/ptrace_fake.h
copy to debuggerd/libdebuggerd/include/libdebuggerd/types.h
index fdbb663..70583af 100644
--- a/debuggerd/libdebuggerd/test/ptrace_fake.h
+++ b/debuggerd/libdebuggerd/include/libdebuggerd/types.h
@@ -1,5 +1,7 @@
+#pragma once
+
 /*
- * Copyright (C) 2015 The Android Open Source Project
+ * Copyright (C) 2012 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.
@@ -14,11 +16,19 @@
  * limitations under the License.
  */
 
-#ifndef _DEBUGGERD_TEST_PTRACE_FAKE_H
-#define _DEBUGGERD_TEST_PTRACE_FAKE_H
+#include <memory>
+#include <string>
 
-#include <signal.h>
+#include <unwindstack/Regs.h>
 
-void ptrace_set_fake_getsiginfo(const siginfo_t&);
+struct ThreadInfo {
+  std::unique_ptr<unwindstack::Regs> registers;
+  pid_t tid;
+  std::string thread_name;
 
-#endif // _DEBUGGERD_TEST_PTRACE_FAKE_H
+  pid_t pid;
+  std::string process_name;
+
+  int signo = 0;
+  siginfo_t* siginfo = nullptr;
+};
diff --git a/debuggerd/libdebuggerd/include/libdebuggerd/utility.h b/debuggerd/libdebuggerd/include/libdebuggerd/utility.h
index f481b78..c5abfe2 100644
--- a/debuggerd/libdebuggerd/include/libdebuggerd/utility.h
+++ b/debuggerd/libdebuggerd/include/libdebuggerd/utility.h
@@ -27,21 +27,24 @@
 #include <android-base/macros.h>
 #include <backtrace/Backtrace.h>
 
-struct log_t{
-    // Tombstone file descriptor.
-    int tfd;
-    // Data to be sent to the Activity Manager.
-    std::string* amfd_data;
-    // The tid of the thread that crashed.
-    pid_t crashed_tid;
-    // The tid of the thread we are currently working with.
-    pid_t current_tid;
-    // logd daemon crash, can block asking for logcat data, allow suppression.
-    bool should_retrieve_logcat;
+struct log_t {
+  // Tombstone file descriptor.
+  int tfd;
+  // Data to be sent to the Activity Manager.
+  std::string* amfd_data;
+  // The tid of the thread that crashed.
+  pid_t crashed_tid;
+  // The tid of the thread we are currently working with.
+  pid_t current_tid;
+  // logd daemon crash, can block asking for logcat data, allow suppression.
+  bool should_retrieve_logcat;
 
-    log_t()
-        : tfd(-1), amfd_data(nullptr), crashed_tid(-1), current_tid(-1),
-          should_retrieve_logcat(true) {}
+  log_t()
+      : tfd(-1),
+        amfd_data(nullptr),
+        crashed_tid(-1),
+        current_tid(-1),
+        should_retrieve_logcat(true) {}
 };
 
 // List of types of logs to simplify the logging decision in _LOG
@@ -59,13 +62,20 @@
 };
 
 // Log information onto the tombstone.
-void _LOG(log_t* log, logtype ltype, const char *fmt, ...)
-        __attribute__ ((format(printf, 3, 4)));
+void _LOG(log_t* log, logtype ltype, const char* fmt, ...) __attribute__((format(printf, 3, 4)));
 
-bool wait_for_signal(pid_t tid, siginfo_t* siginfo);
+namespace unwindstack {
+class Memory;
+}
 
-void dump_memory(log_t* log, Backtrace* backtrace, uintptr_t addr, const char* fmt, ...);
+void dump_memory(log_t* log, unwindstack::Memory* backtrace, uintptr_t addr, const char* fmt, ...);
 
 void read_with_default(const char* path, char* buf, size_t len, const char* default_value);
 
+void drop_capabilities();
+
+bool signal_has_si_addr(int si_signo, int si_code);
+const char* get_signame(int sig);
+const char* get_sigcode(int signo, int code);
+
 #endif // _DEBUGGERD_UTILITY_H
diff --git a/debuggerd/libdebuggerd/mips/machine.cpp b/debuggerd/libdebuggerd/mips/machine.cpp
deleted file mode 100644
index 1fc690b..0000000
--- a/debuggerd/libdebuggerd/mips/machine.cpp
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright 2012, 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.
- */
-
-#define LOG_TAG "DEBUG"
-
-#include "libdebuggerd/machine.h"
-
-#include <errno.h>
-#include <inttypes.h>
-#include <stdint.h>
-#include <string.h>
-#include <sys/ptrace.h>
-
-#include <backtrace/Backtrace.h>
-#include <log/log.h>
-
-#include "libdebuggerd/utility.h"
-
-#define R(x) (static_cast<uintptr_t>(x))
-
-// If configured to do so, dump memory around *all* registers
-// for the crashing thread.
-void dump_memory_and_code(log_t* log, Backtrace* backtrace) {
-  pt_regs r;
-  if (ptrace(PTRACE_GETREGS, backtrace->Tid(), 0, &r)) {
-    ALOGE("cannot get registers: %s\n", strerror(errno));
-    return;
-  }
-
-  static const char reg_names[] = "$0atv0v1a0a1a2a3t0t1t2t3t4t5t6t7s0s1s2s3s4s5s6s7t8t9k0k1gpsps8ra";
-
-  for (int reg = 0; reg < 32; reg++) {
-    // skip uninteresting registers
-    if (reg == 0 // $0
-        || reg == 26 // $k0
-        || reg == 27 // $k1
-        || reg == 31 // $ra (done below)
-       )
-      continue;
-
-    dump_memory(log, backtrace, R(r.regs[reg]), "memory near %.2s:", &reg_names[reg * 2]);
-  }
-
-  uintptr_t pc = R(r.cp0_epc);
-  uintptr_t ra = R(r.regs[31]);
-  dump_memory(log, backtrace, pc, "code around pc:");
-  if (pc != ra) {
-    dump_memory(log, backtrace, ra, "code around ra:");
-  }
-}
-
-void dump_registers(log_t* log, pid_t tid) {
-  pt_regs r;
-  if(ptrace(PTRACE_GETREGS, tid, 0, &r)) {
-    ALOGE("cannot get registers: %s\n", strerror(errno));
-    return;
-  }
-
-  _LOG(log, logtype::REGISTERS, " zr %08" PRIxPTR "  at %08" PRIxPTR
-       "  v0 %08" PRIxPTR "  v1 %08" PRIxPTR "\n",
-       R(r.regs[0]), R(r.regs[1]), R(r.regs[2]), R(r.regs[3]));
-  _LOG(log, logtype::REGISTERS, " a0 %08" PRIxPTR "  a1 %08" PRIxPTR
-       "  a2 %08" PRIxPTR "  a3 %08" PRIxPTR "\n",
-       R(r.regs[4]), R(r.regs[5]), R(r.regs[6]), R(r.regs[7]));
-  _LOG(log, logtype::REGISTERS, " t0 %08" PRIxPTR "  t1 %08" PRIxPTR
-       "  t2 %08" PRIxPTR "  t3 %08" PRIxPTR "\n",
-       R(r.regs[8]), R(r.regs[9]), R(r.regs[10]), R(r.regs[11]));
-  _LOG(log, logtype::REGISTERS, " t4 %08" PRIxPTR "  t5 %08" PRIxPTR
-       "  t6 %08" PRIxPTR "  t7 %08" PRIxPTR "\n",
-       R(r.regs[12]), R(r.regs[13]), R(r.regs[14]), R(r.regs[15]));
-  _LOG(log, logtype::REGISTERS, " s0 %08" PRIxPTR "  s1 %08" PRIxPTR
-       "  s2 %08" PRIxPTR "  s3 %08" PRIxPTR "\n",
-       R(r.regs[16]), R(r.regs[17]), R(r.regs[18]), R(r.regs[19]));
-  _LOG(log, logtype::REGISTERS, " s4 %08" PRIxPTR "  s5 %08" PRIxPTR
-       "  s6 %08" PRIxPTR "  s7 %08" PRIxPTR "\n",
-       R(r.regs[20]), R(r.regs[21]), R(r.regs[22]), R(r.regs[23]));
-  _LOG(log, logtype::REGISTERS, " t8 %08" PRIxPTR "  t9 %08" PRIxPTR
-       "  k0 %08" PRIxPTR "  k1 %08" PRIxPTR "\n",
-       R(r.regs[24]), R(r.regs[25]), R(r.regs[26]), R(r.regs[27]));
-  _LOG(log, logtype::REGISTERS, " gp %08" PRIxPTR "  sp %08" PRIxPTR
-       "  s8 %08" PRIxPTR "  ra %08" PRIxPTR "\n",
-       R(r.regs[28]), R(r.regs[29]), R(r.regs[30]), R(r.regs[31]));
-  _LOG(log, logtype::REGISTERS, " hi %08" PRIxPTR "  lo %08" PRIxPTR
-       " bva %08" PRIxPTR " epc %08" PRIxPTR "\n",
-       R(r.hi), R(r.lo), R(r.cp0_badvaddr), R(r.cp0_epc));
-}
diff --git a/debuggerd/libdebuggerd/mips64/machine.cpp b/debuggerd/libdebuggerd/mips64/machine.cpp
deleted file mode 100644
index 955e507..0000000
--- a/debuggerd/libdebuggerd/mips64/machine.cpp
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright 2014, The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "DEBUG"
-
-#include "libdebuggerd/machine.h"
-
-#include <errno.h>
-#include <inttypes.h>
-#include <stdint.h>
-#include <string.h>
-#include <sys/ptrace.h>
-
-#include <backtrace/Backtrace.h>
-#include <log/log.h>
-
-#include "libdebuggerd/utility.h"
-
-#define R(x) (static_cast<uintptr_t>(x))
-
-// If configured to do so, dump memory around *all* registers
-// for the crashing thread.
-void dump_memory_and_code(log_t* log, Backtrace* backtrace) {
-  pt_regs r;
-  if (ptrace(PTRACE_GETREGS, backtrace->Tid(), 0, &r)) {
-    ALOGE("cannot get registers: %s\n", strerror(errno));
-    return;
-  }
-
-  static const char reg_names[] = "$0atv0v1a0a1a2a3a4a5a6a7t0t1t2t3s0s1s2s3s4s5s6s7t8t9k0k1gpsps8ra";
-
-  for (int reg = 0; reg < 32; reg++) {
-    // skip uninteresting registers
-    if (reg == 0 // $0
-        || reg == 26 // $k0
-        || reg == 27 // $k1
-        || reg == 31 // $ra (done below)
-       )
-      continue;
-
-    dump_memory(log, backtrace, R(r.regs[reg]), "memory near %.2s:", &reg_names[reg * 2]);
-  }
-
-  uintptr_t pc = R(r.cp0_epc);
-  uintptr_t ra = R(r.regs[31]);
-  dump_memory(log, backtrace, pc, "code around pc:");
-  if (pc != ra) {
-    dump_memory(log, backtrace, ra, "code around ra:");
-  }
-}
-
-void dump_registers(log_t* log, pid_t tid) {
-  pt_regs r;
-  if(ptrace(PTRACE_GETREGS, tid, 0, &r)) {
-    ALOGE("cannot get registers: %s\n", strerror(errno));
-    return;
-  }
-
-  _LOG(log, logtype::REGISTERS, " zr %016" PRIxPTR "  at %016" PRIxPTR
-       "  v0 %016" PRIxPTR "  v1 %016" PRIxPTR "\n",
-       R(r.regs[0]), R(r.regs[1]), R(r.regs[2]), R(r.regs[3]));
-  _LOG(log, logtype::REGISTERS, " a0 %016" PRIxPTR "  a1 %016" PRIxPTR
-       "  a2 %016" PRIxPTR "  a3 %016" PRIxPTR "\n",
-       R(r.regs[4]), R(r.regs[5]), R(r.regs[6]), R(r.regs[7]));
-  _LOG(log, logtype::REGISTERS, " a4 %016" PRIxPTR "  a5 %016" PRIxPTR
-       "  a6 %016" PRIxPTR "  a7 %016" PRIxPTR "\n",
-       R(r.regs[8]), R(r.regs[9]), R(r.regs[10]), R(r.regs[11]));
-  _LOG(log, logtype::REGISTERS, " t0 %016" PRIxPTR "  t1 %016" PRIxPTR
-       "  t2 %016" PRIxPTR "  t3 %016" PRIxPTR "\n",
-       R(r.regs[12]), R(r.regs[13]), R(r.regs[14]), R(r.regs[15]));
-  _LOG(log, logtype::REGISTERS, " s0 %016" PRIxPTR "  s1 %016" PRIxPTR
-       "  s2 %016" PRIxPTR "  s3 %016" PRIxPTR "\n",
-       R(r.regs[16]), R(r.regs[17]), R(r.regs[18]), R(r.regs[19]));
-  _LOG(log, logtype::REGISTERS, " s4 %016" PRIxPTR "  s5 %016" PRIxPTR
-       "  s6 %016" PRIxPTR "  s7 %016" PRIxPTR "\n",
-       R(r.regs[20]), R(r.regs[21]), R(r.regs[22]), R(r.regs[23]));
-  _LOG(log, logtype::REGISTERS, " t8 %016" PRIxPTR "  t9 %016" PRIxPTR
-       "  k0 %016" PRIxPTR "  k1 %016" PRIxPTR "\n",
-       R(r.regs[24]), R(r.regs[25]), R(r.regs[26]), R(r.regs[27]));
-  _LOG(log, logtype::REGISTERS, " gp %016" PRIxPTR "  sp %016" PRIxPTR
-       "  s8 %016" PRIxPTR "  ra %016" PRIxPTR "\n",
-       R(r.regs[28]), R(r.regs[29]), R(r.regs[30]), R(r.regs[31]));
-  _LOG(log, logtype::REGISTERS, " hi %016" PRIxPTR "  lo %016" PRIxPTR
-       " bva %016" PRIxPTR " epc %016" PRIxPTR "\n",
-       R(r.hi), R(r.lo), R(r.cp0_badvaddr), R(r.cp0_epc));
-}
diff --git a/debuggerd/libdebuggerd/open_files_list.cpp b/debuggerd/libdebuggerd/open_files_list.cpp
index e199db8..b12703e 100644
--- a/debuggerd/libdebuggerd/open_files_list.cpp
+++ b/debuggerd/libdebuggerd/open_files_list.cpp
@@ -61,7 +61,7 @@
   }
 }
 
-void dump_open_files_list_to_log(const OpenFilesList& files, log_t* log, const char* prefix) {
+void dump_open_files_list(log_t* log, const OpenFilesList& files, const char* prefix) {
   for (auto& file : files) {
     _LOG(log, logtype::OPEN_FILES, "%sfd %i: %s\n", prefix, file.first, file.second.c_str());
   }
diff --git a/debuggerd/libdebuggerd/test/BacktraceMock.h b/debuggerd/libdebuggerd/test/BacktraceMock.h
index 6104f7e..e7dbed7 100644
--- a/debuggerd/libdebuggerd/test/BacktraceMock.h
+++ b/debuggerd/libdebuggerd/test/BacktraceMock.h
@@ -17,15 +17,6 @@
 #ifndef _DEBUGGERD_TEST_BACKTRACE_MOCK_H
 #define _DEBUGGERD_TEST_BACKTRACE_MOCK_H
 
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/ucontext.h>
-
-#include <string>
-#include <vector>
-
-#include <backtrace/Backtrace.h>
 #include <backtrace/BacktraceMap.h>
 
 class BacktraceMapMock : public BacktraceMap {
@@ -38,69 +29,4 @@
   }
 };
 
-
-class BacktraceMock : public Backtrace {
- public:
-  explicit BacktraceMock(BacktraceMapMock* map) : Backtrace(0, 0, map) {
-    if (map_ == nullptr) {
-      abort();
-    }
-  }
-  virtual ~BacktraceMock() {}
-
-  virtual bool Unwind(size_t, ucontext_t*) { return false; }
-  virtual bool ReadWord(uintptr_t, word_t*) { return false;}
-
-  virtual std::string GetFunctionNameRaw(uintptr_t, uintptr_t*) { return ""; }
-
-  virtual size_t Read(uintptr_t addr, uint8_t* buffer, size_t bytes) {
-    size_t offset = 0;
-    if (last_read_addr_ > 0) {
-      offset = addr - last_read_addr_;
-    }
-    size_t bytes_available = buffer_.size() - offset;
-
-    if (do_partial_read_) {
-      // Do a partial read.
-      if (bytes > bytes_partial_read_) {
-        bytes = bytes_partial_read_;
-      }
-      bytes_partial_read_ -= bytes;
-      // Only support a single partial read.
-      do_partial_read_ = false;
-    } else if (bytes > bytes_available) {
-      bytes = bytes_available;
-    }
-
-    if (bytes > 0) {
-      memcpy(buffer, buffer_.data() + offset, bytes);
-    }
-
-    last_read_addr_ = addr;
-    return bytes;
-  }
-
-  void SetReadData(uint8_t* buffer, size_t bytes) {
-    buffer_.resize(bytes);
-    memcpy(buffer_.data(), buffer, bytes);
-    bytes_partial_read_ = 0;
-    do_partial_read_ = false;
-    last_read_addr_ = 0;
-  }
-
-  void SetPartialReadAmount(size_t bytes) {
-    if (bytes > buffer_.size()) {
-      abort();
-    }
-    bytes_partial_read_ = bytes;
-    do_partial_read_ = true;
-  }
-
- private:
-  std::vector<uint8_t> buffer_;
-  size_t bytes_partial_read_ = 0;
-  uintptr_t last_read_addr_ = 0;
-  bool do_partial_read_ = false;
-};
-
 #endif //  _DEBUGGERD_TEST_BACKTRACE_MOCK_H
diff --git a/debuggerd/libdebuggerd/test/dump_memory_test.cpp b/debuggerd/libdebuggerd/test/dump_memory_test.cpp
index 0fad2cf..7c8a0ea 100644
--- a/debuggerd/libdebuggerd/test/dump_memory_test.cpp
+++ b/debuggerd/libdebuggerd/test/dump_memory_test.cpp
@@ -19,12 +19,12 @@
 #include <memory>
 #include <string>
 
-#include <gtest/gtest.h>
 #include <android-base/file.h>
+#include <gtest/gtest.h>
+#include <unwindstack/Memory.h>
 
 #include "libdebuggerd/utility.h"
 
-#include "BacktraceMock.h"
 #include "log_fake.h"
 
 const char g_expected_full_dump[] =
@@ -103,11 +103,59 @@
 "    123456d0 -------- -------- -------- --------  ................\n";
 #endif
 
+class MemoryMock : public unwindstack::Memory {
+ public:
+  virtual ~MemoryMock() = default;
+
+  virtual size_t Read(uint64_t addr, void* buffer, size_t bytes) override {
+    size_t offset = 0;
+    if (last_read_addr_ > 0) {
+      offset = addr - last_read_addr_;
+    }
+    size_t bytes_available = buffer_.size() - offset;
+
+    if (partial_read_) {
+      bytes = std::min(bytes, bytes_partial_read_);
+      bytes_partial_read_ -= bytes;
+      partial_read_ = bytes_partial_read_;
+    } else if (bytes > bytes_available) {
+      bytes = bytes_available;
+    }
+
+    if (bytes > 0) {
+      memcpy(buffer, buffer_.data() + offset, bytes);
+    }
+
+    last_read_addr_ = addr;
+    return bytes;
+  }
+
+  void SetReadData(uint8_t* buffer, size_t bytes) {
+    buffer_.resize(bytes);
+    memcpy(buffer_.data(), buffer, bytes);
+    bytes_partial_read_ = 0;
+    last_read_addr_ = 0;
+  }
+
+  void SetPartialReadAmount(size_t bytes) {
+    if (bytes > buffer_.size()) {
+      abort();
+    }
+    partial_read_ = true;
+    bytes_partial_read_ = bytes;
+  }
+
+ private:
+  std::vector<uint8_t> buffer_;
+  bool partial_read_ = false;
+  size_t bytes_partial_read_ = 0;
+  uintptr_t last_read_addr_ = 0;
+};
+
 class DumpMemoryTest : public ::testing::Test {
  protected:
   virtual void SetUp() {
-    map_mock_.reset(new BacktraceMapMock());
-    backtrace_mock_.reset(new BacktraceMock(map_mock_.get()));
+    memory_mock_ = std::make_unique<MemoryMock>();
 
     char tmp_file[256];
     const char data_template[] = "/data/local/tmp/debuggerd_memory_testXXXXXX";
@@ -138,10 +186,10 @@
     if (log_.tfd >= 0) {
       close(log_.tfd);
     }
+    memory_mock_.reset();
   }
 
-  std::unique_ptr<BacktraceMapMock> map_mock_;
-  std::unique_ptr<BacktraceMock> backtrace_mock_;
+  std::unique_ptr<MemoryMock> memory_mock_;
 
   log_t log_;
 };
@@ -151,9 +199,9 @@
   for (size_t i = 0; i < sizeof(buffer); i++) {
     buffer[i] = i;
   }
-  backtrace_mock_->SetReadData(buffer, sizeof(buffer));
+  memory_mock_->SetReadData(buffer, sizeof(buffer));
 
-  dump_memory(&log_, backtrace_mock_.get(), 0x12345678, "memory near %.2s:", "r1");
+  dump_memory(&log_, memory_mock_.get(), 0x12345678, "memory near %.2s:", "r1");
 
   std::string tombstone_contents;
   ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
@@ -170,10 +218,10 @@
   for (size_t i = 0; i < sizeof(buffer); i++) {
     buffer[i] = i;
   }
-  backtrace_mock_->SetReadData(buffer, sizeof(buffer));
-  backtrace_mock_->SetPartialReadAmount(96);
+  memory_mock_->SetReadData(buffer, sizeof(buffer));
+  memory_mock_->SetPartialReadAmount(96);
 
-  dump_memory(&log_, backtrace_mock_.get(), 0x12345679, "memory near %.2s:", "r1");
+  dump_memory(&log_, memory_mock_.get(), 0x12345679, "memory near %.2s:", "r1");
 
   std::string tombstone_contents;
   ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
@@ -190,9 +238,9 @@
   for (size_t i = 0; i < sizeof(buffer); i++) {
     buffer[i] = i;
   }
-  backtrace_mock_->SetReadData(buffer, sizeof(buffer));
+  memory_mock_->SetReadData(buffer, sizeof(buffer));
 
-  dump_memory(&log_, backtrace_mock_.get(), 0x12345679, "memory near %.2s:", "r1");
+  dump_memory(&log_, memory_mock_.get(), 0x12345679, "memory near %.2s:", "r1");
 
   std::string tombstone_contents;
   ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
@@ -205,7 +253,7 @@
 }
 
 TEST_F(DumpMemoryTest, memory_unreadable) {
-  dump_memory(&log_, backtrace_mock_.get(), 0xa2345678, "memory near pc:");
+  dump_memory(&log_, memory_mock_.get(), 0xa2345678, "memory near pc:");
 
   std::string tombstone_contents;
   ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
@@ -259,9 +307,9 @@
   for (size_t i = 0; i < sizeof(buffer); i++) {
     buffer[i] = i;
   }
-  backtrace_mock_->SetReadData(buffer, sizeof(buffer));
+  memory_mock_->SetReadData(buffer, sizeof(buffer));
 
-  dump_memory(&log_, backtrace_mock_.get(), 0x12345600, "memory near pc:");
+  dump_memory(&log_, memory_mock_.get(), 0x12345600, "memory near pc:");
 
   std::string tombstone_contents;
   ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
@@ -278,10 +326,10 @@
   for (size_t i = 0; i < sizeof(buffer); i++) {
     buffer[i] = i;
   }
-  backtrace_mock_->SetReadData(buffer, sizeof(buffer));
-  backtrace_mock_->SetPartialReadAmount(102);
+  memory_mock_->SetReadData(buffer, sizeof(buffer));
+  memory_mock_->SetPartialReadAmount(102);
 
-  dump_memory(&log_, backtrace_mock_.get(), 0x12345600, "memory near pc:");
+  dump_memory(&log_, memory_mock_.get(), 0x12345600, "memory near pc:");
 
   std::string tombstone_contents;
   ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
@@ -303,10 +351,10 @@
   for (size_t i = 0; i < sizeof(buffer); i++) {
     buffer[i] = i;
   }
-  backtrace_mock_->SetReadData(buffer, sizeof(buffer));
-  backtrace_mock_->SetPartialReadAmount(45);
+  memory_mock_->SetReadData(buffer, sizeof(buffer));
+  memory_mock_->SetPartialReadAmount(45);
 
-  dump_memory(&log_, backtrace_mock_.get(), 0x12345600, "memory near pc:");
+  dump_memory(&log_, memory_mock_.get(), 0x12345600, "memory near pc:");
 
   std::string tombstone_contents;
   ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
@@ -330,9 +378,9 @@
 TEST_F(DumpMemoryTest, address_low_fence) {
   uint8_t buffer[256];
   memset(buffer, 0, sizeof(buffer));
-  backtrace_mock_->SetReadData(buffer, sizeof(buffer));
+  memory_mock_->SetReadData(buffer, sizeof(buffer));
 
-  dump_memory(&log_, backtrace_mock_.get(), 0x1000, "memory near %.2s:", "r1");
+  dump_memory(&log_, memory_mock_.get(), 0x1000, "memory near %.2s:", "r1");
 
   std::string tombstone_contents;
   ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
@@ -384,9 +432,9 @@
 TEST_F(DumpMemoryTest, memory_address_too_low) {
   uint8_t buffer[256];
   memset(buffer, 0, sizeof(buffer));
-  backtrace_mock_->SetReadData(buffer, sizeof(buffer));
+  memory_mock_->SetReadData(buffer, sizeof(buffer));
 
-  dump_memory(&log_, backtrace_mock_.get(), 0, "memory near %.2s:", "r1");
+  dump_memory(&log_, memory_mock_.get(), 0, "memory near %.2s:", "r1");
 
   std::string tombstone_contents;
   ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
@@ -401,16 +449,16 @@
 TEST_F(DumpMemoryTest, memory_address_too_high) {
   uint8_t buffer[256];
   memset(buffer, 0, sizeof(buffer));
-  backtrace_mock_->SetReadData(buffer, sizeof(buffer));
+  memory_mock_->SetReadData(buffer, sizeof(buffer));
 
 #if defined(__LP64__)
-  dump_memory(&log_, backtrace_mock_.get(), 0x4000000000000000UL, "memory near %.2s:", "r1");
-  dump_memory(&log_, backtrace_mock_.get(), 0x4000000000000000UL - 32, "memory near %.2s:", "r1");
-  dump_memory(&log_, backtrace_mock_.get(), 0x4000000000000000UL - 216, "memory near %.2s:", "r1");
+  dump_memory(&log_, memory_mock_.get(), 0x4000000000000000UL, "memory near %.2s:", "r1");
+  dump_memory(&log_, memory_mock_.get(), 0x4000000000000000UL - 32, "memory near %.2s:", "r1");
+  dump_memory(&log_, memory_mock_.get(), 0x4000000000000000UL - 216, "memory near %.2s:", "r1");
 #else
-  dump_memory(&log_, backtrace_mock_.get(), 0xffff0000, "memory near %.2s:", "r1");
-  dump_memory(&log_, backtrace_mock_.get(), 0xffff0000 - 32, "memory near %.2s:", "r1");
-  dump_memory(&log_, backtrace_mock_.get(), 0xffff0000 - 220, "memory near %.2s:", "r1");
+  dump_memory(&log_, memory_mock_.get(), 0xffff0000, "memory near %.2s:", "r1");
+  dump_memory(&log_, memory_mock_.get(), 0xffff0000 - 32, "memory near %.2s:", "r1");
+  dump_memory(&log_, memory_mock_.get(), 0xffff0000 - 220, "memory near %.2s:", "r1");
 #endif
 
   std::string tombstone_contents;
@@ -426,12 +474,12 @@
 TEST_F(DumpMemoryTest, memory_address_would_overflow) {
   uint8_t buffer[256];
   memset(buffer, 0, sizeof(buffer));
-  backtrace_mock_->SetReadData(buffer, sizeof(buffer));
+  memory_mock_->SetReadData(buffer, sizeof(buffer));
 
 #if defined(__LP64__)
-  dump_memory(&log_, backtrace_mock_.get(), 0xfffffffffffffff0, "memory near %.2s:", "r1");
+  dump_memory(&log_, memory_mock_.get(), 0xfffffffffffffff0, "memory near %.2s:", "r1");
 #else
-  dump_memory(&log_, backtrace_mock_.get(), 0xfffffff0, "memory near %.2s:", "r1");
+  dump_memory(&log_, memory_mock_.get(), 0xfffffff0, "memory near %.2s:", "r1");
 #endif
 
   std::string tombstone_contents;
@@ -449,12 +497,12 @@
   for (size_t i = 0; i < sizeof(buffer); i++) {
     buffer[i] = i;
   }
-  backtrace_mock_->SetReadData(buffer, sizeof(buffer));
+  memory_mock_->SetReadData(buffer, sizeof(buffer));
 
 #if defined(__LP64__)
-  dump_memory(&log_, backtrace_mock_.get(), 0x4000000000000000UL - 224, "memory near %.2s:", "r4");
+  dump_memory(&log_, memory_mock_.get(), 0x4000000000000000UL - 224, "memory near %.2s:", "r4");
 #else
-  dump_memory(&log_, backtrace_mock_.get(), 0xffff0000 - 224, "memory near %.2s:", "r4");
+  dump_memory(&log_, memory_mock_.get(), 0xffff0000 - 224, "memory near %.2s:", "r4");
 #endif
 
   std::string tombstone_contents;
@@ -509,12 +557,12 @@
   for (size_t i = 0; i < sizeof(buffer); i++) {
     buffer[i] = i;
   }
-  backtrace_mock_->SetReadData(buffer, sizeof(buffer));
-  backtrace_mock_->SetPartialReadAmount(0);
+  memory_mock_->SetReadData(buffer, sizeof(buffer));
+  memory_mock_->SetPartialReadAmount(0);
 
   size_t page_size = sysconf(_SC_PAGE_SIZE);
   uintptr_t addr = 0x10000020 + page_size - 120;
-  dump_memory(&log_, backtrace_mock_.get(), addr, "memory near %.2s:", "r4");
+  dump_memory(&log_, memory_mock_.get(), addr, "memory near %.2s:", "r4");
 
   std::string tombstone_contents;
   ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
@@ -568,12 +616,12 @@
   for (size_t i = 0; i < sizeof(buffer); i++) {
     buffer[i] = i;
   }
-  backtrace_mock_->SetReadData(buffer, sizeof(buffer));
-  backtrace_mock_->SetPartialReadAmount(0);
+  memory_mock_->SetReadData(buffer, sizeof(buffer));
+  memory_mock_->SetPartialReadAmount(0);
 
   size_t page_size = sysconf(_SC_PAGE_SIZE);
   uintptr_t addr = 0x10000020 + page_size - 192;
-  dump_memory(&log_, backtrace_mock_.get(), addr, "memory near %.2s:", "r4");
+  dump_memory(&log_, memory_mock_.get(), addr, "memory near %.2s:", "r4");
 
   std::string tombstone_contents;
   ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
@@ -627,11 +675,11 @@
   for (size_t i = 0; i < sizeof(buffer); i++) {
     buffer[i] = i;
   }
-  backtrace_mock_->SetReadData(buffer, sizeof(buffer));
-  backtrace_mock_->SetPartialReadAmount(0);
+  memory_mock_->SetReadData(buffer, sizeof(buffer));
+  memory_mock_->SetPartialReadAmount(0);
 
   uintptr_t addr = 0x10000020;
-  dump_memory(&log_, backtrace_mock_.get(), addr, "memory near %.2s:", "r4");
+  dump_memory(&log_, memory_mock_.get(), addr, "memory near %.2s:", "r4");
 
   std::string tombstone_contents;
   ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
@@ -685,13 +733,13 @@
   for (size_t i = 0; i < sizeof(buffer); i++) {
     buffer[i] = i;
   }
-  backtrace_mock_->SetReadData(buffer, sizeof(buffer));
-  backtrace_mock_->SetPartialReadAmount(0);
+  memory_mock_->SetReadData(buffer, sizeof(buffer));
+  memory_mock_->SetPartialReadAmount(0);
 
   size_t page_size = sysconf(_SC_PAGE_SIZE);
   uintptr_t addr = 0x10000020 + page_size - 256;
 
-  dump_memory(&log_, backtrace_mock_.get(), addr, "memory near %.2s:", "r4");
+  dump_memory(&log_, memory_mock_.get(), addr, "memory near %.2s:", "r4");
 
   std::string tombstone_contents;
   ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
diff --git a/debuggerd/libdebuggerd/test/elf_fake.cpp b/debuggerd/libdebuggerd/test/elf_fake.cpp
index f8cbca7..9b8281a 100644
--- a/debuggerd/libdebuggerd/test/elf_fake.cpp
+++ b/debuggerd/libdebuggerd/test/elf_fake.cpp
@@ -20,7 +20,9 @@
 
 #include <string>
 
-class Backtrace;
+namespace unwindstack {
+class Memory;
+}
 
 std::string g_build_id;
 
@@ -28,7 +30,7 @@
   g_build_id = build_id;
 }
 
-bool elf_get_build_id(Backtrace*, uintptr_t, std::string* build_id) {
+bool elf_get_build_id(unwindstack::Memory*, uintptr_t, std::string* build_id) {
   if (g_build_id != "") {
     *build_id = g_build_id;
     return true;
diff --git a/debuggerd/libdebuggerd/test/ptrace_fake.cpp b/debuggerd/libdebuggerd/test/ptrace_fake.cpp
deleted file mode 100644
index 0d4080e..0000000
--- a/debuggerd/libdebuggerd/test/ptrace_fake.cpp
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2015 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 "ptrace_fake.h"
-
-#include <errno.h>
-#include <signal.h>
-#include <stdarg.h>
-#include <sys/ptrace.h>
-
-#include <string>
-
-siginfo_t g_fake_si = {.si_signo = 0};
-
-void ptrace_set_fake_getsiginfo(const siginfo_t& si) {
-  g_fake_si = si;
-}
-
-#if !defined(__BIONIC__)
-extern "C" long ptrace_fake(enum __ptrace_request request, ...) {
-#else
-extern "C" long ptrace_fake(int request, ...) {
-#endif
-  if (request == PTRACE_GETSIGINFO) {
-    if (g_fake_si.si_signo == 0) {
-      errno = EFAULT;
-      return -1;
-    }
-
-    va_list ap;
-    va_start(ap, request);
-    va_arg(ap, int);
-    va_arg(ap, int);
-    siginfo_t* si = va_arg(ap, siginfo*);
-    va_end(ap);
-    *si = g_fake_si;
-    return 0;
-  }
-  return -1;
-}
diff --git a/debuggerd/libdebuggerd/test/tombstone_test.cpp b/debuggerd/libdebuggerd/test/tombstone_test.cpp
index 59a43b7..1e3a10f 100644
--- a/debuggerd/libdebuggerd/test/tombstone_test.cpp
+++ b/debuggerd/libdebuggerd/test/tombstone_test.cpp
@@ -29,11 +29,6 @@
 #include "elf_fake.h"
 #include "host_signal_fixup.h"
 #include "log_fake.h"
-#include "ptrace_fake.h"
-
-// In order to test this code, we need to include the tombstone.cpp code.
-// Including it, also allows us to override the ptrace function.
-#define ptrace ptrace_fake
 
 #include "tombstone.cpp"
 
@@ -50,7 +45,6 @@
  protected:
   virtual void SetUp() {
     map_mock_.reset(new BacktraceMapMock());
-    backtrace_mock_.reset(new BacktraceMock(map_mock_.get()));
 
     char tmp_file[256];
     const char data_template[] = "/data/local/tmp/debuggerd_memory_testXXXXXX";
@@ -77,11 +71,6 @@
 
     resetLogs();
     elf_set_fake_build_id("");
-    siginfo_t si;
-    memset(&si, 0, sizeof(si));
-    si.si_signo = SIGABRT;
-    si.si_code = SI_KERNEL;
-    ptrace_set_fake_getsiginfo(si);
   }
 
   virtual void TearDown() {
@@ -91,7 +80,6 @@
   }
 
   std::unique_ptr<BacktraceMapMock> map_mock_;
-  std::unique_ptr<BacktraceMock> backtrace_mock_;
 
   log_t log_;
   std::string amfd_data_;
@@ -108,7 +96,7 @@
 #endif
   map_mock_->AddMap(map);
 
-  dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
+  dump_all_maps(&log_, map_mock_.get(), nullptr, 0);
 
   std::string tombstone_contents;
   ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
@@ -143,7 +131,7 @@
   map_mock_->AddMap(map);
 
   elf_set_fake_build_id("abcdef1234567890abcdef1234567890");
-  dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
+  dump_all_maps(&log_, map_mock_.get(), nullptr, 0);
 
   std::string tombstone_contents;
   ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
@@ -182,7 +170,7 @@
   map_mock_->AddMap(map);
 
   elf_set_fake_build_id("abcdef1234567890abcdef1234567890");
-  dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
+  dump_all_maps(&log_, map_mock_.get(), nullptr, 0);
 
   std::string tombstone_contents;
   ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
@@ -240,7 +228,7 @@
   map.name = "/system/lib/fake.so";
   map_mock_->AddMap(map);
 
-  dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
+  dump_all_maps(&log_, map_mock_.get(), nullptr, 0);
 
   std::string tombstone_contents;
   ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
@@ -294,13 +282,7 @@
   map.name = "/system/lib/fake.so";
   map_mock_->AddMap(map);
 
-  siginfo_t si;
-  memset(&si, 0, sizeof(si));
-  si.si_signo = SIGBUS;
-  si.si_code = SI_KERNEL;
-  si.si_addr = reinterpret_cast<void*>(0x1000);
-  ptrace_set_fake_getsiginfo(si);
-  dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
+  dump_all_maps(&log_, map_mock_.get(), nullptr, 0x1000);
 
   std::string tombstone_contents;
   ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
@@ -352,13 +334,7 @@
   map.name = "/system/lib/fake.so";
   map_mock_->AddMap(map);
 
-  siginfo_t si;
-  memset(&si, 0, sizeof(si));
-  si.si_signo = SIGBUS;
-  si.si_code = SI_KERNEL;
-  si.si_addr = reinterpret_cast<void*>(0xa533000);
-  ptrace_set_fake_getsiginfo(si);
-  dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
+  dump_all_maps(&log_, map_mock_.get(), nullptr, 0xa533000);
 
   std::string tombstone_contents;
   ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
@@ -410,13 +386,7 @@
   map.name = "/system/lib/fake.so";
   map_mock_->AddMap(map);
 
-  siginfo_t si;
-  memset(&si, 0, sizeof(si));
-  si.si_signo = SIGBUS;
-  si.si_code = SI_KERNEL;
-  si.si_addr = reinterpret_cast<void*>(0xa534040);
-  ptrace_set_fake_getsiginfo(si);
-  dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
+  dump_all_maps(&log_, map_mock_.get(), nullptr, 0xa534040);
 
   std::string tombstone_contents;
   ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
@@ -466,17 +436,12 @@
   map.name = "/system/lib/fake.so";
   map_mock_->AddMap(map);
 
-  siginfo_t si;
-  memset(&si, 0, sizeof(si));
-  si.si_signo = SIGBUS;
-  si.si_code = SI_KERNEL;
 #if defined(__LP64__)
-  si.si_addr = reinterpret_cast<void*>(0x12345a534040UL);
+  uintptr_t addr = 0x12345a534040UL;
 #else
-  si.si_addr = reinterpret_cast<void*>(0xf534040UL);
+  uintptr_t addr = 0xf534040UL;
 #endif
-  ptrace_set_fake_getsiginfo(si);
-  dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
+  dump_all_maps(&log_, map_mock_.get(), nullptr, addr);
 
   std::string tombstone_contents;
   ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
@@ -503,124 +468,6 @@
   ASSERT_STREQ("", getFakeLogPrint().c_str());
 }
 
-TEST_F(TombstoneTest, multiple_maps_getsiginfo_fail) {
-  backtrace_map_t map;
-
-  map.start = 0xa434000;
-  map.end = 0xa435000;
-  map.offset = 0x1000;
-  map.load_bias = 0xd000;
-  map.flags = PROT_WRITE;
-  map_mock_->AddMap(map);
-
-  siginfo_t si;
-  memset(&si, 0, sizeof(si));
-  ptrace_set_fake_getsiginfo(si);
-  dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
-
-  std::string tombstone_contents;
-  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
-  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &tombstone_contents));
-  const char* expected_dump =
-      "\nmemory map (1 entry):\n"
-#if defined(__LP64__)
-      "    00000000'0a434000-00000000'0a434fff -w-      1000      1000  (load bias 0xd000)\n";
-#else
-      "    0a434000-0a434fff -w-      1000      1000  (load bias 0xd000)\n";
-#endif
-  ASSERT_STREQ(expected_dump, tombstone_contents.c_str());
-
-  ASSERT_STREQ("", amfd_data_.c_str());
-
-  // Verify that the log buf is empty, and no error messages.
-  ASSERT_STREQ("", getFakeLogBuf().c_str());
-  ASSERT_STREQ("6 DEBUG Cannot get siginfo for 100: Bad address\n\n", getFakeLogPrint().c_str());
-}
-
-TEST_F(TombstoneTest, multiple_maps_check_signal_has_si_addr) {
-  backtrace_map_t map;
-
-  map.start = 0xa434000;
-  map.end = 0xa435000;
-  map.flags = PROT_WRITE;
-  map_mock_->AddMap(map);
-
-  for (int i = 1; i < 255; i++) {
-    ASSERT_TRUE(ftruncate(log_.tfd, 0) == 0);
-    ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
-
-    siginfo_t si;
-    memset(&si, 0, sizeof(si));
-    si.si_signo = i;
-    si.si_code = SI_KERNEL;
-    si.si_addr = reinterpret_cast<void*>(0x1000);
-    ptrace_set_fake_getsiginfo(si);
-    dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
-
-    std::string tombstone_contents;
-    ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
-    ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &tombstone_contents));
-    bool has_addr = false;
-    switch (si.si_signo) {
-    case SIGBUS:
-    case SIGFPE:
-    case SIGILL:
-    case SIGSEGV:
-    case SIGTRAP:
-      has_addr = true;
-      break;
-    }
-
-    const char* expected_addr_dump = \
-"\nmemory map (1 entry):\n"
-#if defined(__LP64__)
-"--->Fault address falls at 00000000'00001000 before any mapped regions\n"
-"    00000000'0a434000-00000000'0a434fff -w-         0      1000\n";
-#else
-"--->Fault address falls at 00001000 before any mapped regions\n"
-"    0a434000-0a434fff -w-         0      1000\n";
-#endif
-    const char* expected_dump = \
-"\nmemory map (1 entry):\n"
-#if defined(__LP64__)
-"    00000000'0a434000-00000000'0a434fff -w-         0      1000\n";
-#else
-"    0a434000-0a434fff -w-         0      1000\n";
-#endif
-    if (has_addr) {
-      ASSERT_STREQ(expected_addr_dump, tombstone_contents.c_str())
-        << "Signal " << si.si_signo << " expected to include an address.";
-    } else {
-      ASSERT_STREQ(expected_dump, tombstone_contents.c_str())
-        << "Signal " << si.si_signo << " is not expected to include an address.";
-    }
-
-    ASSERT_STREQ("", amfd_data_.c_str());
-
-    // Verify that the log buf is empty, and no error messages.
-    ASSERT_STREQ("", getFakeLogBuf().c_str());
-    ASSERT_STREQ("", getFakeLogPrint().c_str());
-  }
-}
-
-TEST_F(TombstoneTest, dump_signal_info_error) {
-  siginfo_t si;
-  memset(&si, 0, sizeof(si));
-  ptrace_set_fake_getsiginfo(si);
-
-  dump_signal_info(&log_, 123);
-
-  std::string tombstone_contents;
-  ASSERT_TRUE(lseek(log_.tfd, 0, SEEK_SET) == 0);
-  ASSERT_TRUE(android::base::ReadFdToString(log_.tfd, &tombstone_contents));
-  ASSERT_STREQ("", tombstone_contents.c_str());
-
-  ASSERT_STREQ("", getFakeLogBuf().c_str());
-  ASSERT_STREQ("6 DEBUG cannot get siginfo: Bad address\n\n", getFakeLogPrint().c_str());
-
-  ASSERT_STREQ("", amfd_data_.c_str());
-}
-
 TEST_F(TombstoneTest, dump_log_file_error) {
   log_.should_retrieve_logcat = true;
   dump_log_file(&log_, 123, "/fake/filename", 10);
diff --git a/debuggerd/libdebuggerd/tombstone.cpp b/debuggerd/libdebuggerd/tombstone.cpp
index a0ba81b..89a125b 100644
--- a/debuggerd/libdebuggerd/tombstone.cpp
+++ b/debuggerd/libdebuggerd/tombstone.cpp
@@ -35,8 +35,10 @@
 #include <string>
 
 #include <android-base/file.h>
+#include <android-base/logging.h>
 #include <android-base/properties.h>
 #include <android-base/stringprintf.h>
+#include <android-base/strings.h>
 #include <android-base/unique_fd.h>
 #include <android/log.h>
 #include <backtrace/Backtrace.h>
@@ -44,169 +46,27 @@
 #include <log/log.h>
 #include <log/logprint.h>
 #include <private/android_filesystem_config.h>
+#include <unwindstack/Memory.h>
+#include <unwindstack/Regs.h>
 
 // Needed to get DEBUGGER_SIGNAL.
 #include "debuggerd/handler.h"
 
 #include "libdebuggerd/backtrace.h"
 #include "libdebuggerd/elf_utils.h"
-#include "libdebuggerd/machine.h"
 #include "libdebuggerd/open_files_list.h"
+#include "libdebuggerd/utility.h"
 
 using android::base::GetBoolProperty;
 using android::base::GetProperty;
 using android::base::StringPrintf;
+using android::base::unique_fd;
+
+using unwindstack::Memory;
+using unwindstack::Regs;
 
 #define STACK_WORDS 16
 
-static bool signal_has_si_addr(int si_signo, int si_code) {
-  // Manually sent signals won't have si_addr.
-  if (si_code == SI_USER || si_code == SI_QUEUE || si_code == SI_TKILL) {
-    return false;
-  }
-
-  switch (si_signo) {
-    case SIGBUS:
-    case SIGFPE:
-    case SIGILL:
-    case SIGSEGV:
-    case SIGTRAP:
-      return true;
-    default:
-      return false;
-  }
-}
-
-static const char* get_signame(int sig) {
-  switch (sig) {
-    case SIGABRT: return "SIGABRT";
-    case SIGBUS: return "SIGBUS";
-    case SIGFPE: return "SIGFPE";
-    case SIGILL: return "SIGILL";
-    case SIGSEGV: return "SIGSEGV";
-#if defined(SIGSTKFLT)
-    case SIGSTKFLT: return "SIGSTKFLT";
-#endif
-    case SIGSTOP: return "SIGSTOP";
-    case SIGSYS: return "SIGSYS";
-    case SIGTRAP: return "SIGTRAP";
-    case DEBUGGER_SIGNAL: return "<debuggerd signal>";
-    default: return "?";
-  }
-}
-
-static const char* get_sigcode(int signo, int code) {
-  // Try the signal-specific codes...
-  switch (signo) {
-    case SIGILL:
-      switch (code) {
-        case ILL_ILLOPC: return "ILL_ILLOPC";
-        case ILL_ILLOPN: return "ILL_ILLOPN";
-        case ILL_ILLADR: return "ILL_ILLADR";
-        case ILL_ILLTRP: return "ILL_ILLTRP";
-        case ILL_PRVOPC: return "ILL_PRVOPC";
-        case ILL_PRVREG: return "ILL_PRVREG";
-        case ILL_COPROC: return "ILL_COPROC";
-        case ILL_BADSTK: return "ILL_BADSTK";
-      }
-      static_assert(NSIGILL == ILL_BADSTK, "missing ILL_* si_code");
-      break;
-    case SIGBUS:
-      switch (code) {
-        case BUS_ADRALN: return "BUS_ADRALN";
-        case BUS_ADRERR: return "BUS_ADRERR";
-        case BUS_OBJERR: return "BUS_OBJERR";
-        case BUS_MCEERR_AR: return "BUS_MCEERR_AR";
-        case BUS_MCEERR_AO: return "BUS_MCEERR_AO";
-      }
-      static_assert(NSIGBUS == BUS_MCEERR_AO, "missing BUS_* si_code");
-      break;
-    case SIGFPE:
-      switch (code) {
-        case FPE_INTDIV: return "FPE_INTDIV";
-        case FPE_INTOVF: return "FPE_INTOVF";
-        case FPE_FLTDIV: return "FPE_FLTDIV";
-        case FPE_FLTOVF: return "FPE_FLTOVF";
-        case FPE_FLTUND: return "FPE_FLTUND";
-        case FPE_FLTRES: return "FPE_FLTRES";
-        case FPE_FLTINV: return "FPE_FLTINV";
-        case FPE_FLTSUB: return "FPE_FLTSUB";
-      }
-      static_assert(NSIGFPE == FPE_FLTSUB, "missing FPE_* si_code");
-      break;
-    case SIGSEGV:
-      switch (code) {
-        case SEGV_MAPERR: return "SEGV_MAPERR";
-        case SEGV_ACCERR: return "SEGV_ACCERR";
-#if defined(SEGV_BNDERR)
-        case SEGV_BNDERR: return "SEGV_BNDERR";
-#endif
-#if defined(SEGV_PKUERR)
-        case SEGV_PKUERR: return "SEGV_PKUERR";
-#endif
-      }
-#if defined(SEGV_PKUERR)
-      static_assert(NSIGSEGV == SEGV_PKUERR, "missing SEGV_* si_code");
-#elif defined(SEGV_BNDERR)
-      static_assert(NSIGSEGV == SEGV_BNDERR, "missing SEGV_* si_code");
-#else
-      static_assert(NSIGSEGV == SEGV_ACCERR, "missing SEGV_* si_code");
-#endif
-      break;
-#if defined(SYS_SECCOMP) // Our glibc is too old, and we build this for the host too.
-    case SIGSYS:
-      switch (code) {
-        case SYS_SECCOMP: return "SYS_SECCOMP";
-      }
-      static_assert(NSIGSYS == SYS_SECCOMP, "missing SYS_* si_code");
-      break;
-#endif
-    case SIGTRAP:
-      switch (code) {
-        case TRAP_BRKPT: return "TRAP_BRKPT";
-        case TRAP_TRACE: return "TRAP_TRACE";
-        case TRAP_BRANCH: return "TRAP_BRANCH";
-        case TRAP_HWBKPT: return "TRAP_HWBKPT";
-      }
-      if ((code & 0xff) == SIGTRAP) {
-        switch ((code >> 8) & 0xff) {
-          case PTRACE_EVENT_FORK:
-            return "PTRACE_EVENT_FORK";
-          case PTRACE_EVENT_VFORK:
-            return "PTRACE_EVENT_VFORK";
-          case PTRACE_EVENT_CLONE:
-            return "PTRACE_EVENT_CLONE";
-          case PTRACE_EVENT_EXEC:
-            return "PTRACE_EVENT_EXEC";
-          case PTRACE_EVENT_VFORK_DONE:
-            return "PTRACE_EVENT_VFORK_DONE";
-          case PTRACE_EVENT_EXIT:
-            return "PTRACE_EVENT_EXIT";
-          case PTRACE_EVENT_SECCOMP:
-            return "PTRACE_EVENT_SECCOMP";
-          case PTRACE_EVENT_STOP:
-            return "PTRACE_EVENT_STOP";
-        }
-      }
-      static_assert(NSIGTRAP == TRAP_HWBKPT, "missing TRAP_* si_code");
-      break;
-  }
-  // Then the other codes...
-  switch (code) {
-    case SI_USER: return "SI_USER";
-    case SI_KERNEL: return "SI_KERNEL";
-    case SI_QUEUE: return "SI_QUEUE";
-    case SI_TIMER: return "SI_TIMER";
-    case SI_MESGQ: return "SI_MESGQ";
-    case SI_ASYNCIO: return "SI_ASYNCIO";
-    case SI_SIGIO: return "SI_SIGIO";
-    case SI_TKILL: return "SI_TKILL";
-    case SI_DETHREAD: return "SI_DETHREAD";
-  }
-  // Then give up...
-  return "?";
-}
-
 static void dump_header_info(log_t* log) {
   auto fingerprint = GetProperty("ro.build.fingerprint", "unknown");
   auto revision = GetProperty("ro.revision", "unknown");
@@ -216,73 +76,64 @@
   _LOG(log, logtype::HEADER, "ABI: '%s'\n", ABI_STRING);
 }
 
-static void dump_probable_cause(log_t* log, const siginfo_t& si) {
+static void dump_probable_cause(log_t* log, const siginfo_t* si) {
   std::string cause;
-  if (si.si_signo == SIGSEGV && si.si_code == SEGV_MAPERR) {
-    if (si.si_addr < reinterpret_cast<void*>(4096)) {
+  if (si->si_signo == SIGSEGV && si->si_code == SEGV_MAPERR) {
+    if (si->si_addr < reinterpret_cast<void*>(4096)) {
       cause = StringPrintf("null pointer dereference");
-    } else if (si.si_addr == reinterpret_cast<void*>(0xffff0ffc)) {
+    } else if (si->si_addr == reinterpret_cast<void*>(0xffff0ffc)) {
       cause = "call to kuser_helper_version";
-    } else if (si.si_addr == reinterpret_cast<void*>(0xffff0fe0)) {
+    } else if (si->si_addr == reinterpret_cast<void*>(0xffff0fe0)) {
       cause = "call to kuser_get_tls";
-    } else if (si.si_addr == reinterpret_cast<void*>(0xffff0fc0)) {
+    } else if (si->si_addr == reinterpret_cast<void*>(0xffff0fc0)) {
       cause = "call to kuser_cmpxchg";
-    } else if (si.si_addr == reinterpret_cast<void*>(0xffff0fa0)) {
+    } else if (si->si_addr == reinterpret_cast<void*>(0xffff0fa0)) {
       cause = "call to kuser_memory_barrier";
-    } else if (si.si_addr == reinterpret_cast<void*>(0xffff0f60)) {
+    } else if (si->si_addr == reinterpret_cast<void*>(0xffff0f60)) {
       cause = "call to kuser_cmpxchg64";
     }
-  } else if (si.si_signo == SIGSYS && si.si_code == SYS_SECCOMP) {
-    cause = StringPrintf("seccomp prevented call to disallowed %s system call %d",
-                         ABI_STRING, si.si_syscall);
+  } else if (si->si_signo == SIGSYS && si->si_code == SYS_SECCOMP) {
+    cause = StringPrintf("seccomp prevented call to disallowed %s system call %d", ABI_STRING,
+                         si->si_syscall);
   }
 
   if (!cause.empty()) _LOG(log, logtype::HEADER, "Cause: %s\n", cause.c_str());
 }
 
-static void dump_signal_info(log_t* log, const siginfo_t* siginfo) {
-  const siginfo_t& si = *siginfo;
+static void dump_signal_info(log_t* log, const siginfo_t* si) {
   char addr_desc[32]; // ", fault addr 0x1234"
-  if (signal_has_si_addr(si.si_signo, si.si_code)) {
-    snprintf(addr_desc, sizeof(addr_desc), "%p", si.si_addr);
+  if (signal_has_si_addr(si->si_signo, si->si_code)) {
+    snprintf(addr_desc, sizeof(addr_desc), "%p", si->si_addr);
   } else {
     snprintf(addr_desc, sizeof(addr_desc), "--------");
   }
 
-  _LOG(log, logtype::HEADER, "signal %d (%s), code %d (%s), fault addr %s\n", si.si_signo,
-       get_signame(si.si_signo), si.si_code, get_sigcode(si.si_signo, si.si_code), addr_desc);
+  _LOG(log, logtype::HEADER, "signal %d (%s), code %d (%s), fault addr %s\n", si->si_signo,
+       get_signame(si->si_signo), si->si_code, get_sigcode(si->si_signo, si->si_code), addr_desc);
 
   dump_probable_cause(log, si);
 }
 
-static void dump_signal_info(log_t* log, pid_t tid) {
-  siginfo_t si;
-  memset(&si, 0, sizeof(si));
-  if (ptrace(PTRACE_GETSIGINFO, tid, 0, &si) == -1) {
-    ALOGE("cannot get siginfo: %s\n", strerror(errno));
-    return;
-  }
-
-  dump_signal_info(log, &si);
-}
-
-static void dump_thread_info(log_t* log, pid_t pid, pid_t tid, const char* process_name,
-                             const char* thread_name) {
+static void dump_thread_info(log_t* log, const ThreadInfo& thread_info) {
   // Blacklist logd, logd.reader, logd.writer, logd.auditd, logd.control ...
   // TODO: Why is this controlled by thread name?
-  if (strcmp(thread_name, "logd") == 0 || strncmp(thread_name, "logd.", 4) == 0) {
+  if (thread_info.thread_name == "logd" ||
+      android::base::StartsWith(thread_info.thread_name, "logd.")) {
     log->should_retrieve_logcat = false;
   }
 
-  _LOG(log, logtype::HEADER, "pid: %d, tid: %d, name: %s  >>> %s <<<\n", pid, tid, thread_name,
-       process_name);
+  _LOG(log, logtype::HEADER, "pid: %d, tid: %d, name: %s  >>> %s <<<\n", thread_info.pid,
+       thread_info.tid, thread_info.thread_name.c_str(), thread_info.process_name.c_str());
 }
 
-static void dump_stack_segment(
-    Backtrace* backtrace, log_t* log, uintptr_t* sp, size_t words, int label) {
+static void dump_stack_segment(log_t* log, BacktraceMap* backtrace_map, Memory* process_memory,
+                               uintptr_t* sp, size_t words, int label) {
   // Read the data all at once.
   word_t stack_data[words];
-  size_t bytes_read = backtrace->Read(*sp, reinterpret_cast<uint8_t*>(&stack_data[0]), sizeof(word_t) * words);
+
+  // TODO: Do we need to word align this for crashes caused by a misaligned sp?
+  //       The process_vm_readv implementation of Memory should handle this appropriately?
+  size_t bytes_read = process_memory->Read(*sp, stack_data, sizeof(word_t) * words);
   words = bytes_read / sizeof(word_t);
   std::string line;
   for (size_t i = 0; i < words; i++) {
@@ -296,11 +147,11 @@
     line += StringPrintf("%" PRIPTR "  %" PRIPTR, *sp, stack_data[i]);
 
     backtrace_map_t map;
-    backtrace->FillInMap(stack_data[i], &map);
+    backtrace_map->FillIn(stack_data[i], &map);
     if (BacktraceMap::IsValid(map) && !map.name.empty()) {
       line += "  " + map.name;
       uintptr_t offset = 0;
-      std::string func_name(backtrace->GetFunctionName(stack_data[i], &offset, &map));
+      std::string func_name = backtrace_map->GetFunctionName(stack_data[i], &offset);
       if (!func_name.empty()) {
         line += " (" + func_name;
         if (offset) {
@@ -315,36 +166,38 @@
   }
 }
 
-static void dump_stack(Backtrace* backtrace, log_t* log) {
+static void dump_stack(log_t* log, BacktraceMap* backtrace_map, Memory* process_memory,
+                       std::vector<backtrace_frame_data_t>& frames) {
   size_t first = 0, last;
-  for (size_t i = 0; i < backtrace->NumFrames(); i++) {
-    const backtrace_frame_data_t* frame = backtrace->GetFrame(i);
-    if (frame->sp) {
+  for (size_t i = 0; i < frames.size(); i++) {
+    const backtrace_frame_data_t& frame = frames[i];
+    if (frame.sp) {
       if (!first) {
         first = i+1;
       }
       last = i;
     }
   }
+
   if (!first) {
     return;
   }
   first--;
 
   // Dump a few words before the first frame.
-  word_t sp = backtrace->GetFrame(first)->sp - STACK_WORDS * sizeof(word_t);
-  dump_stack_segment(backtrace, log, &sp, STACK_WORDS, -1);
+  word_t sp = frames[first].sp - STACK_WORDS * sizeof(word_t);
+  dump_stack_segment(log, backtrace_map, process_memory, &sp, STACK_WORDS, -1);
 
   // Dump a few words from all successive frames.
   // Only log the first 3 frames, put the rest in the tombstone.
   for (size_t i = first; i <= last; i++) {
-    const backtrace_frame_data_t* frame = backtrace->GetFrame(i);
+    const backtrace_frame_data_t* frame = &frames[i];
     if (sp != frame->sp) {
       _LOG(log, logtype::STACK, "         ........  ........\n");
       sp = frame->sp;
     }
     if (i == last) {
-      dump_stack_segment(backtrace, log, &sp, STACK_WORDS, i);
+      dump_stack_segment(log, backtrace_map, process_memory, &sp, STACK_WORDS, i);
       if (sp < frame->sp + frame->stack_size) {
         _LOG(log, logtype::STACK, "         ........  ........\n");
       }
@@ -355,7 +208,7 @@
       } else if (words > STACK_WORDS) {
         words = STACK_WORDS;
       }
-      dump_stack_segment(backtrace, log, &sp, words, i);
+      dump_stack_segment(log, backtrace_map, process_memory, &sp, words, i);
     }
   }
 }
@@ -372,44 +225,34 @@
   return addr_str;
 }
 
-static void dump_abort_message(Backtrace* backtrace, log_t* log, uintptr_t address) {
+static void dump_abort_message(log_t* log, Memory* process_memory, uintptr_t address) {
   if (address == 0) {
     return;
   }
 
-  address += sizeof(size_t);  // Skip the buffer length.
+  size_t length;
+  if (!process_memory->ReadFully(address, &length, sizeof(length))) {
+    _LOG(log, logtype::HEADER, "Failed to read abort message header: %s\n", strerror(errno));
+    return;
+  }
 
   char msg[512];
-  memset(msg, 0, sizeof(msg));
-  char* p = &msg[0];
-  while (p < &msg[sizeof(msg)]) {
-    word_t data;
-    size_t len = sizeof(word_t);
-    if (!backtrace->ReadWord(address, &data)) {
-      break;
-    }
-    address += sizeof(word_t);
-
-    while (len > 0 && (*p++ = (data >> (sizeof(word_t) - len) * 8) & 0xff) != 0) {
-      len--;
-    }
+  if (length >= sizeof(msg)) {
+    _LOG(log, logtype::HEADER, "Abort message too long: claimed length = %zd\n", length);
+    return;
   }
-  msg[sizeof(msg) - 1] = '\0';
 
+  if (!process_memory->ReadFully(address + sizeof(length), msg, length)) {
+    _LOG(log, logtype::HEADER, "Failed to read abort message: %s\n", strerror(errno));
+    return;
+  }
+
+  msg[length] = '\0';
   _LOG(log, logtype::HEADER, "Abort message: '%s'\n", msg);
 }
 
-static void dump_all_maps(Backtrace* backtrace, BacktraceMap* map, log_t* log, pid_t tid) {
-  bool print_fault_address_marker = false;
-  uintptr_t addr = 0;
-  siginfo_t si;
-  memset(&si, 0, sizeof(si));
-  if (ptrace(PTRACE_GETSIGINFO, tid, 0, &si) != -1) {
-    print_fault_address_marker = signal_has_si_addr(si.si_signo, si.si_code);
-    addr = reinterpret_cast<uintptr_t>(si.si_addr);
-  } else {
-    ALOGE("Cannot get siginfo for %d: %s\n", tid, strerror(errno));
-  }
+static void dump_all_maps(log_t* log, BacktraceMap* map, Memory* process_memory, uintptr_t addr) {
+  bool print_fault_address_marker = addr;
 
   ScopedBacktraceMapIteratorLock lock(map);
   _LOG(log, logtype::MAPS,
@@ -464,7 +307,7 @@
       space_needed = false;
       line += "  " + entry->name;
       std::string build_id;
-      if ((entry->flags & PROT_READ) && elf_get_build_id(backtrace, entry->start, &build_id)) {
+      if ((entry->flags & PROT_READ) && elf_get_build_id(process_memory, entry->start, &build_id)) {
         line += " (BuildId: " + build_id + ")";
       }
     }
@@ -482,50 +325,117 @@
   }
 }
 
-static void dump_backtrace_and_stack(Backtrace* backtrace, log_t* log) {
-  if (backtrace->NumFrames()) {
-    _LOG(log, logtype::BACKTRACE, "\nbacktrace:\n");
-    dump_backtrace_to_log(backtrace, log, "    ");
-
-    _LOG(log, logtype::STACK, "\nstack:\n");
-    dump_stack(backtrace, log);
+void dump_backtrace(log_t* log, std::vector<backtrace_frame_data_t>& frames, const char* prefix) {
+  for (auto& frame : frames) {
+    _LOG(log, logtype::BACKTRACE, "%s%s\n", prefix, Backtrace::FormatFrameData(&frame).c_str());
   }
 }
 
-// Weak noop implementation, real implementations are in <arch>/machine.cpp.
-__attribute__((weak)) void dump_registers(log_t* log, const ucontext_t*) {
-  _LOG(log, logtype::REGISTERS, "    register dumping unimplemented on this architecture");
+static void print_register_row(log_t* log,
+                               const std::vector<std::pair<std::string, uint64_t>>& registers) {
+  std::string output;
+  for (auto& [name, value] : registers) {
+    output += android::base::StringPrintf("  %-3s %0*" PRIxPTR, name.c_str(),
+                                          static_cast<int>(2 * sizeof(void*)),
+                                          static_cast<uintptr_t>(value));
+  }
+
+  _LOG(log, logtype::REGISTERS, "  %s\n", output.c_str());
 }
 
-static void dump_thread(log_t* log, pid_t pid, pid_t tid, const std::string& process_name,
-                        const std::string& thread_name, BacktraceMap* map,
-                        uintptr_t abort_msg_address, bool primary_thread) {
-  log->current_tid = tid;
+void dump_registers(log_t* log, Regs* regs) {
+  // Split lr/sp/pc into their own special row.
+  static constexpr size_t column_count = 4;
+  std::vector<std::pair<std::string, uint64_t>> current_row;
+  std::vector<std::pair<std::string, uint64_t>> special_row;
+
+#if defined(__arm__) || defined(__aarch64__)
+  static constexpr const char* special_registers[] = {"ip", "lr", "sp", "pc"};
+#elif defined(__i386__)
+  static constexpr const char* special_registers[] = {"ebp", "esp", "eip"};
+#elif defined(__x86_64__)
+  static constexpr const char* special_registers[] = {"rbp", "rsp", "rip"};
+#else
+  static constexpr const char* special_registers[] = {};
+#endif
+
+  regs->IterateRegisters([log, &current_row, &special_row](const char* name, uint64_t value) {
+    auto row = &current_row;
+    for (const char* special_name : special_registers) {
+      if (strcmp(special_name, name) == 0) {
+        row = &special_row;
+        break;
+      }
+    }
+
+    row->emplace_back(name, value);
+    if (current_row.size() == column_count) {
+      print_register_row(log, current_row);
+      current_row.clear();
+    }
+  });
+
+  if (!current_row.empty()) {
+    print_register_row(log, current_row);
+  }
+
+  print_register_row(log, special_row);
+}
+
+void dump_memory_and_code(log_t* log, Memory* memory, Regs* regs) {
+  regs->IterateRegisters([log, memory](const char* name, uint64_t value) {
+    dump_memory(log, memory, value, "memory near %s:", name);
+  });
+}
+
+static bool dump_thread(log_t* log, BacktraceMap* map, Memory* process_memory,
+                        const ThreadInfo& thread_info, uintptr_t abort_msg_address,
+                        bool primary_thread) {
+  UNUSED(process_memory);
+  log->current_tid = thread_info.tid;
   if (!primary_thread) {
     _LOG(log, logtype::THREAD, "--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---\n");
   }
-  dump_thread_info(log, pid, tid, process_name.c_str(), thread_name.c_str());
-  dump_signal_info(log, tid);
+  dump_thread_info(log, thread_info);
 
-  std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, tid, map));
-  if (primary_thread) {
-    dump_abort_message(backtrace.get(), log, abort_msg_address);
-  }
-  dump_registers(log, tid);
-  if (backtrace->Unwind(0)) {
-    dump_backtrace_and_stack(backtrace.get(), log);
-  } else {
-    ALOGE("Unwind failed: pid = %d, tid = %d", pid, tid);
+  if (thread_info.siginfo) {
+    dump_signal_info(log, thread_info.siginfo);
   }
 
   if (primary_thread) {
-    dump_memory_and_code(log, backtrace.get());
+    dump_abort_message(log, process_memory, abort_msg_address);
+  }
+
+  dump_registers(log, thread_info.registers.get());
+
+  std::vector<backtrace_frame_data_t> frames;
+  if (!Backtrace::Unwind(thread_info.registers.get(), map, &frames, 0, nullptr)) {
+    _LOG(log, logtype::THREAD, "Failed to unwind");
+    return false;
+  }
+
+  if (!frames.empty()) {
+    _LOG(log, logtype::BACKTRACE, "\nbacktrace:\n");
+    dump_backtrace(log, frames, "    ");
+
+    _LOG(log, logtype::STACK, "\nstack:\n");
+    dump_stack(log, map, process_memory, frames);
+  }
+
+  if (primary_thread) {
+    dump_memory_and_code(log, process_memory, thread_info.registers.get());
     if (map) {
-      dump_all_maps(backtrace.get(), map, log, tid);
+      uintptr_t addr = 0;
+      siginfo_t* si = thread_info.siginfo;
+      if (signal_has_si_addr(si->si_signo, si->si_code)) {
+        addr = reinterpret_cast<uintptr_t>(si->si_addr);
+      }
+      dump_all_maps(log, map, process_memory, addr);
     }
   }
 
   log->current_tid = log->crashed_tid;
+  return true;
 }
 
 // Reads the contents of the specified log device, filters out the entries
@@ -534,8 +444,7 @@
 // If "tail" is non-zero, log the last "tail" number of lines.
 static EventTagMap* g_eventTagMap = NULL;
 
-static void dump_log_file(
-    log_t* log, pid_t pid, const char* filename, unsigned int tail) {
+static void dump_log_file(log_t* log, pid_t pid, const char* filename, unsigned int tail) {
   bool first = true;
   struct logger_list* logger_list;
 
@@ -654,56 +563,15 @@
 // Dumps the logs generated by the specified pid to the tombstone, from both
 // "system" and "main" log devices.  Ideally we'd interleave the output.
 static void dump_logs(log_t* log, pid_t pid, unsigned int tail) {
+  if (pid == getpid()) {
+    // Cowardly refuse to dump logs while we're running in-process.
+    return;
+  }
+
   dump_log_file(log, pid, "system", tail);
   dump_log_file(log, pid, "main", tail);
 }
 
-// Dumps all information about the specified pid to the tombstone.
-static void dump_crash(log_t* log, BacktraceMap* map, const OpenFilesList* open_files, pid_t pid,
-                       pid_t tid, const std::string& process_name,
-                       const std::map<pid_t, std::string>& threads, uintptr_t abort_msg_address) {
-  // don't copy log messages to tombstone unless this is a dev device
-  bool want_logs = GetBoolProperty("ro.debuggable", false);
-
-  _LOG(log, logtype::HEADER,
-       "*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***\n");
-  dump_header_info(log);
-  dump_thread(log, pid, tid, process_name, threads.find(tid)->second, map, abort_msg_address, true);
-  if (want_logs) {
-    dump_logs(log, pid, 5);
-  }
-
-  for (const auto& it : threads) {
-    pid_t thread_tid = it.first;
-    const std::string& thread_name = it.second;
-
-    if (thread_tid != tid) {
-      dump_thread(log, pid, thread_tid, process_name, thread_name, map, 0, false);
-    }
-  }
-
-  if (open_files) {
-    _LOG(log, logtype::OPEN_FILES, "\nopen files:\n");
-    dump_open_files_list_to_log(*open_files, log, "    ");
-  }
-
-  if (want_logs) {
-    dump_logs(log, pid, 0);
-  }
-}
-
-void engrave_tombstone(int tombstone_fd, BacktraceMap* map, const OpenFilesList* open_files,
-                       pid_t pid, pid_t tid, const std::string& process_name,
-                       const std::map<pid_t, std::string>& threads, uintptr_t abort_msg_address,
-                       std::string* amfd_data) {
-  log_t log;
-  log.current_tid = tid;
-  log.crashed_tid = tid;
-  log.tfd = tombstone_fd;
-  log.amfd_data = amfd_data;
-  dump_crash(&log, map, open_files, pid, tid, process_name, threads, abort_msg_address);
-}
-
 void engrave_tombstone_ucontext(int tombstone_fd, uintptr_t abort_msg_address, siginfo_t* siginfo,
                                 ucontext_t* ucontext) {
   pid_t pid = getpid();
@@ -721,31 +589,69 @@
   read_with_default("/proc/self/comm", thread_name, sizeof(thread_name), "<unknown>");
   read_with_default("/proc/self/cmdline", process_name, sizeof(process_name), "<unknown>");
 
-  _LOG(&log, logtype::HEADER, "*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***\n");
-  dump_header_info(&log);
-  dump_thread_info(&log, pid, tid, thread_name, process_name);
-  dump_signal_info(&log, siginfo);
+  std::unique_ptr<Regs> regs(Regs::CreateFromUcontext(Regs::CurrentArch(), ucontext));
 
-  std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, tid));
-  dump_abort_message(backtrace.get(), &log, abort_msg_address);
-  dump_registers(&log, ucontext);
+  std::map<pid_t, ThreadInfo> threads;
+  threads[gettid()] = ThreadInfo{
+      .registers = std::move(regs),
+      .tid = tid,
+      .thread_name = thread_name,
+      .pid = pid,
+      .process_name = process_name,
+      .siginfo = siginfo,
+  };
 
-  if (backtrace->Unwind(0, ucontext)) {
-    dump_backtrace_and_stack(backtrace.get(), &log);
-  } else {
-    ALOGE("Unwind failed: pid = %d, tid = %d", pid, tid);
+  std::unique_ptr<BacktraceMap> backtrace_map(BacktraceMap::Create(getpid(), false));
+  if (!backtrace_map) {
+    ALOGE("failed to create backtrace map");
+    _exit(1);
   }
 
-  // TODO: Make this match the format of dump_all_maps above.
-  _LOG(&log, logtype::MAPS, "memory map:\n");
-  android::base::unique_fd maps_fd(open("/proc/self/maps", O_RDONLY | O_CLOEXEC));
-  if (maps_fd == -1) {
-    _LOG(&log, logtype::MAPS, "    failed to open /proc/self/maps: %s", strerror(errno));
-  } else {
-    char buf[256];
-    ssize_t rc;
-    while ((rc = TEMP_FAILURE_RETRY(read(maps_fd.get(), buf, sizeof(buf)))) > 0) {
-      android::base::WriteFully(tombstone_fd, buf, rc);
+  std::shared_ptr<Memory> process_memory = backtrace_map->GetProcessMemory();
+  engrave_tombstone(unique_fd(dup(tombstone_fd)), backtrace_map.get(), process_memory.get(),
+                    threads, tid, abort_msg_address, nullptr, nullptr);
+}
+
+void engrave_tombstone(unique_fd output_fd, BacktraceMap* map, Memory* process_memory,
+                       const std::map<pid_t, ThreadInfo>& threads, pid_t target_thread,
+                       uintptr_t abort_msg_address, OpenFilesList* open_files,
+                       std::string* amfd_data) {
+  // don't copy log messages to tombstone unless this is a dev device
+  bool want_logs = android::base::GetBoolProperty("ro.debuggable", false);
+
+  log_t log;
+  log.current_tid = target_thread;
+  log.crashed_tid = target_thread;
+  log.tfd = output_fd.get();
+  log.amfd_data = amfd_data;
+
+  _LOG(&log, logtype::HEADER, "*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***\n");
+  dump_header_info(&log);
+
+  auto it = threads.find(target_thread);
+  if (it == threads.end()) {
+    LOG(FATAL) << "failed to find target thread";
+  }
+  dump_thread(&log, map, process_memory, it->second, abort_msg_address, true);
+
+  if (want_logs) {
+    dump_logs(&log, it->second.pid, 50);
+  }
+
+  for (auto& [tid, thread_info] : threads) {
+    if (tid == target_thread) {
+      continue;
     }
+
+    dump_thread(&log, map, process_memory, thread_info, 0, false);
+  }
+
+  if (open_files) {
+    _LOG(&log, logtype::OPEN_FILES, "\nopen files:\n");
+    dump_open_files_list(&log, *open_files, "    ");
+  }
+
+  if (want_logs) {
+    dump_logs(&log, it->second.pid, 0);
   }
 }
diff --git a/debuggerd/libdebuggerd/utility.cpp b/debuggerd/libdebuggerd/utility.cpp
index 1b74652..247d806 100644
--- a/debuggerd/libdebuggerd/utility.cpp
+++ b/debuggerd/libdebuggerd/utility.cpp
@@ -21,6 +21,8 @@
 #include <errno.h>
 #include <signal.h>
 #include <string.h>
+#include <sys/capability.h>
+#include <sys/prctl.h>
 #include <sys/ptrace.h>
 #include <sys/uio.h>
 #include <sys/wait.h>
@@ -34,7 +36,9 @@
 #include <android-base/strings.h>
 #include <android-base/unique_fd.h>
 #include <backtrace/Backtrace.h>
+#include <debuggerd/handler.h>
 #include <log/log.h>
+#include <unwindstack/Memory.h>
 
 using android::base::unique_fd;
 
@@ -117,34 +121,10 @@
   }
 }
 
-bool wait_for_signal(pid_t tid, siginfo_t* siginfo) {
-  while (true) {
-    int status;
-    pid_t n = TEMP_FAILURE_RETRY(waitpid(tid, &status, __WALL));
-    if (n == -1) {
-      ALOGE("waitpid failed: tid %d, %s", tid, strerror(errno));
-      return false;
-    } else if (n == tid) {
-      if (WIFSTOPPED(status)) {
-        if (ptrace(PTRACE_GETSIGINFO, tid, nullptr, siginfo) != 0) {
-          ALOGE("PTRACE_GETSIGINFO failed: %s", strerror(errno));
-          return false;
-        }
-        return true;
-      } else {
-        ALOGE("unexpected waitpid response: n=%d, status=%08x\n", n, status);
-        // This is the only circumstance under which we can allow a detach
-        // to fail with ESRCH, which indicates the tid has exited.
-        return false;
-      }
-    }
-  }
-}
-
 #define MEMORY_BYTES_TO_DUMP 256
 #define MEMORY_BYTES_PER_LINE 16
 
-void dump_memory(log_t* log, Backtrace* backtrace, uintptr_t addr, const char* fmt, ...) {
+void dump_memory(log_t* log, unwindstack::Memory* memory, uintptr_t addr, const char* fmt, ...) {
   std::string log_msg;
   va_list ap;
   va_start(ap, fmt);
@@ -172,7 +152,7 @@
   // Dump 256 bytes
   uintptr_t data[MEMORY_BYTES_TO_DUMP/sizeof(uintptr_t)];
   memset(data, 0, MEMORY_BYTES_TO_DUMP);
-  size_t bytes = backtrace->Read(addr, reinterpret_cast<uint8_t*>(data), sizeof(data));
+  size_t bytes = memory->Read(addr, reinterpret_cast<uint8_t*>(data), sizeof(data));
   if (bytes % sizeof(uintptr_t) != 0) {
     // This should never happen, but just in case.
     ALOGE("Bytes read %zu, is not a multiple of %zu", bytes, sizeof(uintptr_t));
@@ -199,8 +179,8 @@
     // into a readable map. Only requires one extra read because a map has
     // to contain at least one page, and the total number of bytes to dump
     // is smaller than a page.
-    size_t bytes2 = backtrace->Read(addr + start + bytes, reinterpret_cast<uint8_t*>(data) + bytes,
-                                    sizeof(data) - bytes - start);
+    size_t bytes2 = memory->Read(addr + start + bytes, reinterpret_cast<uint8_t*>(data) + bytes,
+                                 sizeof(data) - bytes - start);
     bytes += bytes2;
     if (bytes2 > 0 && bytes % sizeof(uintptr_t) != 0) {
       // This should never happen, but we'll try and continue any way.
@@ -264,3 +244,169 @@
   }
   strcpy(buf, default_value);
 }
+
+void drop_capabilities() {
+  __user_cap_header_struct capheader;
+  memset(&capheader, 0, sizeof(capheader));
+  capheader.version = _LINUX_CAPABILITY_VERSION_3;
+  capheader.pid = 0;
+
+  __user_cap_data_struct capdata[2];
+  memset(&capdata, 0, sizeof(capdata));
+
+  if (capset(&capheader, &capdata[0]) == -1) {
+    PLOG(FATAL) << "failed to drop capabilities";
+  }
+
+  if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0) {
+    PLOG(FATAL) << "failed to set PR_SET_NO_NEW_PRIVS";
+  }
+}
+
+bool signal_has_si_addr(int si_signo, int si_code) {
+  // Manually sent signals won't have si_addr.
+  if (si_code == SI_USER || si_code == SI_QUEUE || si_code == SI_TKILL) {
+    return false;
+  }
+
+  switch (si_signo) {
+    case SIGBUS:
+    case SIGFPE:
+    case SIGILL:
+    case SIGSEGV:
+    case SIGTRAP:
+      return true;
+    default:
+      return false;
+  }
+}
+
+const char* get_signame(int sig) {
+  switch (sig) {
+    case SIGABRT: return "SIGABRT";
+    case SIGBUS: return "SIGBUS";
+    case SIGFPE: return "SIGFPE";
+    case SIGILL: return "SIGILL";
+    case SIGSEGV: return "SIGSEGV";
+#if defined(SIGSTKFLT)
+    case SIGSTKFLT: return "SIGSTKFLT";
+#endif
+    case SIGSTOP: return "SIGSTOP";
+    case SIGSYS: return "SIGSYS";
+    case SIGTRAP: return "SIGTRAP";
+    case DEBUGGER_SIGNAL: return "<debuggerd signal>";
+    default: return "?";
+  }
+}
+
+const char* get_sigcode(int signo, int code) {
+  // Try the signal-specific codes...
+  switch (signo) {
+    case SIGILL:
+      switch (code) {
+        case ILL_ILLOPC: return "ILL_ILLOPC";
+        case ILL_ILLOPN: return "ILL_ILLOPN";
+        case ILL_ILLADR: return "ILL_ILLADR";
+        case ILL_ILLTRP: return "ILL_ILLTRP";
+        case ILL_PRVOPC: return "ILL_PRVOPC";
+        case ILL_PRVREG: return "ILL_PRVREG";
+        case ILL_COPROC: return "ILL_COPROC";
+        case ILL_BADSTK: return "ILL_BADSTK";
+      }
+      static_assert(NSIGILL == ILL_BADSTK, "missing ILL_* si_code");
+      break;
+    case SIGBUS:
+      switch (code) {
+        case BUS_ADRALN: return "BUS_ADRALN";
+        case BUS_ADRERR: return "BUS_ADRERR";
+        case BUS_OBJERR: return "BUS_OBJERR";
+        case BUS_MCEERR_AR: return "BUS_MCEERR_AR";
+        case BUS_MCEERR_AO: return "BUS_MCEERR_AO";
+      }
+      static_assert(NSIGBUS == BUS_MCEERR_AO, "missing BUS_* si_code");
+      break;
+    case SIGFPE:
+      switch (code) {
+        case FPE_INTDIV: return "FPE_INTDIV";
+        case FPE_INTOVF: return "FPE_INTOVF";
+        case FPE_FLTDIV: return "FPE_FLTDIV";
+        case FPE_FLTOVF: return "FPE_FLTOVF";
+        case FPE_FLTUND: return "FPE_FLTUND";
+        case FPE_FLTRES: return "FPE_FLTRES";
+        case FPE_FLTINV: return "FPE_FLTINV";
+        case FPE_FLTSUB: return "FPE_FLTSUB";
+      }
+      static_assert(NSIGFPE == FPE_FLTSUB, "missing FPE_* si_code");
+      break;
+    case SIGSEGV:
+      switch (code) {
+        case SEGV_MAPERR: return "SEGV_MAPERR";
+        case SEGV_ACCERR: return "SEGV_ACCERR";
+#if defined(SEGV_BNDERR)
+        case SEGV_BNDERR: return "SEGV_BNDERR";
+#endif
+#if defined(SEGV_PKUERR)
+        case SEGV_PKUERR: return "SEGV_PKUERR";
+#endif
+      }
+#if defined(SEGV_PKUERR)
+      static_assert(NSIGSEGV == SEGV_PKUERR, "missing SEGV_* si_code");
+#elif defined(SEGV_BNDERR)
+      static_assert(NSIGSEGV == SEGV_BNDERR, "missing SEGV_* si_code");
+#else
+      static_assert(NSIGSEGV == SEGV_ACCERR, "missing SEGV_* si_code");
+#endif
+      break;
+#if defined(SYS_SECCOMP) // Our glibc is too old, and we build this for the host too.
+    case SIGSYS:
+      switch (code) {
+        case SYS_SECCOMP: return "SYS_SECCOMP";
+      }
+      static_assert(NSIGSYS == SYS_SECCOMP, "missing SYS_* si_code");
+      break;
+#endif
+    case SIGTRAP:
+      switch (code) {
+        case TRAP_BRKPT: return "TRAP_BRKPT";
+        case TRAP_TRACE: return "TRAP_TRACE";
+        case TRAP_BRANCH: return "TRAP_BRANCH";
+        case TRAP_HWBKPT: return "TRAP_HWBKPT";
+      }
+      if ((code & 0xff) == SIGTRAP) {
+        switch ((code >> 8) & 0xff) {
+          case PTRACE_EVENT_FORK:
+            return "PTRACE_EVENT_FORK";
+          case PTRACE_EVENT_VFORK:
+            return "PTRACE_EVENT_VFORK";
+          case PTRACE_EVENT_CLONE:
+            return "PTRACE_EVENT_CLONE";
+          case PTRACE_EVENT_EXEC:
+            return "PTRACE_EVENT_EXEC";
+          case PTRACE_EVENT_VFORK_DONE:
+            return "PTRACE_EVENT_VFORK_DONE";
+          case PTRACE_EVENT_EXIT:
+            return "PTRACE_EVENT_EXIT";
+          case PTRACE_EVENT_SECCOMP:
+            return "PTRACE_EVENT_SECCOMP";
+          case PTRACE_EVENT_STOP:
+            return "PTRACE_EVENT_STOP";
+        }
+      }
+      static_assert(NSIGTRAP == TRAP_HWBKPT, "missing TRAP_* si_code");
+      break;
+  }
+  // Then the other codes...
+  switch (code) {
+    case SI_USER: return "SI_USER";
+    case SI_KERNEL: return "SI_KERNEL";
+    case SI_QUEUE: return "SI_QUEUE";
+    case SI_TIMER: return "SI_TIMER";
+    case SI_MESGQ: return "SI_MESGQ";
+    case SI_ASYNCIO: return "SI_ASYNCIO";
+    case SI_SIGIO: return "SI_SIGIO";
+    case SI_TKILL: return "SI_TKILL";
+    case SI_DETHREAD: return "SI_DETHREAD";
+  }
+  // Then give up...
+  return "?";
+}
diff --git a/debuggerd/libdebuggerd/x86/machine.cpp b/debuggerd/libdebuggerd/x86/machine.cpp
deleted file mode 100644
index 09a64cd..0000000
--- a/debuggerd/libdebuggerd/x86/machine.cpp
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright 2006, 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.
- */
-
-#define LOG_TAG "DEBUG"
-
-#include "libdebuggerd/machine.h"
-
-#include <errno.h>
-#include <stdint.h>
-#include <string.h>
-#include <sys/ptrace.h>
-
-#include <backtrace/Backtrace.h>
-#include <log/log.h>
-
-#include "libdebuggerd/utility.h"
-
-void dump_memory_and_code(log_t* log, Backtrace* backtrace) {
-  struct pt_regs r;
-  if (ptrace(PTRACE_GETREGS, backtrace->Tid(), 0, &r) == -1) {
-    ALOGE("cannot get registers: %s\n", strerror(errno));
-    return;
-  }
-
-  dump_memory(log, backtrace, static_cast<uintptr_t>(r.eax), "memory near eax:");
-  dump_memory(log, backtrace, static_cast<uintptr_t>(r.ebx), "memory near ebx:");
-  dump_memory(log, backtrace, static_cast<uintptr_t>(r.ecx), "memory near ecx:");
-  dump_memory(log, backtrace, static_cast<uintptr_t>(r.edx), "memory near edx:");
-  dump_memory(log, backtrace, static_cast<uintptr_t>(r.esi), "memory near esi:");
-  dump_memory(log, backtrace, static_cast<uintptr_t>(r.edi), "memory near edi:");
-
-  dump_memory(log, backtrace, static_cast<uintptr_t>(r.eip), "code around eip:");
-}
-
-void dump_registers(log_t* log, pid_t tid) {
-  struct pt_regs r;
-  if (ptrace(PTRACE_GETREGS, tid, 0, &r) == -1) {
-    ALOGE("cannot get registers: %s\n", strerror(errno));
-    return;
-  }
-
-  _LOG(log, logtype::REGISTERS, "    eax %08lx  ebx %08lx  ecx %08lx  edx %08lx\n",
-       r.eax, r.ebx, r.ecx, r.edx);
-  _LOG(log, logtype::REGISTERS, "    esi %08lx  edi %08lx\n",
-       r.esi, r.edi);
-  _LOG(log, logtype::REGISTERS, "    xcs %08x  xds %08x  xes %08x  xfs %08x  xss %08x\n",
-       r.xcs, r.xds, r.xes, r.xfs, r.xss);
-  _LOG(log, logtype::REGISTERS, "    eip %08lx  ebp %08lx  esp %08lx  flags %08lx\n",
-       r.eip, r.ebp, r.esp, r.eflags);
-}
diff --git a/debuggerd/libdebuggerd/x86_64/machine.cpp b/debuggerd/libdebuggerd/x86_64/machine.cpp
deleted file mode 100644
index de1c268..0000000
--- a/debuggerd/libdebuggerd/x86_64/machine.cpp
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
-** Copyright 2013, The Android Open Source Project
-**
-** Licensed under the Apache License, Version 2.0 (the "License");
-** you may not use this file except in compliance with the License.
-** You may obtain a copy of the License at
-**
-**     http://www.apache.org/licenses/LICENSE-2.0
-**
-** Unless required by applicable law or agreed to in writing, software
-** distributed under the License is distributed on an "AS IS" BASIS,
-** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-** See the License for the specific language governing permissions and
-** limitations under the License.
-*/
-
-#define LOG_TAG "DEBUG"
-
-#include "libdebuggerd/machine.h"
-
-#include <errno.h>
-#include <stdint.h>
-#include <string.h>
-#include <sys/ptrace.h>
-#include <sys/user.h>
-
-#include <backtrace/Backtrace.h>
-#include <log/log.h>
-
-#include "libdebuggerd/utility.h"
-
-void dump_memory_and_code(log_t* log, Backtrace* backtrace) {
-  struct user_regs_struct r;
-  if (ptrace(PTRACE_GETREGS, backtrace->Tid(), 0, &r) == -1) {
-    ALOGE("cannot get registers: %s\n", strerror(errno));
-    return;
-  }
-
-  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rax), "memory near rax:");
-  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rbx), "memory near rbx:");
-  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rcx), "memory near rcx:");
-  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rdx), "memory near rdx:");
-  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rsi), "memory near rsi:");
-  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rdi), "memory near rdi:");
-
-  dump_memory(log, backtrace, static_cast<uintptr_t>(r.rip), "code around rip:");
-}
-
-void dump_registers(log_t* log, pid_t tid) {
-  struct user_regs_struct r;
-  if (ptrace(PTRACE_GETREGS, tid, 0, &r) == -1) {
-    ALOGE("cannot get registers: %s\n", strerror(errno));
-    return;
-  }
-
-  _LOG(log, logtype::REGISTERS, "    rax %016lx  rbx %016lx  rcx %016lx  rdx %016lx\n",
-       r.rax, r.rbx, r.rcx, r.rdx);
-  _LOG(log, logtype::REGISTERS, "    rsi %016lx  rdi %016lx\n",
-       r.rsi, r.rdi);
-  _LOG(log, logtype::REGISTERS, "    r8  %016lx  r9  %016lx  r10 %016lx  r11 %016lx\n",
-       r.r8, r.r9, r.r10, r.r11);
-  _LOG(log, logtype::REGISTERS, "    r12 %016lx  r13 %016lx  r14 %016lx  r15 %016lx\n",
-       r.r12, r.r13, r.r14, r.r15);
-  _LOG(log, logtype::REGISTERS, "    cs  %016lx  ss  %016lx\n",
-       r.cs, r.ss);
-  _LOG(log, logtype::REGISTERS, "    rip %016lx  rbp %016lx  rsp %016lx  eflags %016lx\n",
-       r.rip, r.rbp, r.rsp, r.eflags);
-}
diff --git a/debuggerd/protocol.h b/debuggerd/protocol.h
index 7e1961e..6903b0e 100644
--- a/debuggerd/protocol.h
+++ b/debuggerd/protocol.h
@@ -16,7 +16,10 @@
 
 #pragma once
 
+#include <signal.h>
 #include <stdint.h>
+#include <sys/ucontext.h>
+#include <unistd.h>
 
 #include "dump_type.h"
 
@@ -76,3 +79,11 @@
   InterceptStatus status;
   char error_message[127];  // always null-terminated
 };
+
+// Sent from handler to crash_dump via pipe.
+struct __attribute__((__packed__)) CrashInfo {
+  uint32_t version;  // must be 1.
+  siginfo_t siginfo;
+  ucontext_t ucontext;
+  uintptr_t abort_msg_address;
+};
diff --git a/debuggerd/util.cpp b/debuggerd/util.cpp
index 0bb07ac..50c5efc 100644
--- a/debuggerd/util.cpp
+++ b/debuggerd/util.cpp
@@ -18,8 +18,12 @@
 
 #include <sys/socket.h>
 
+#include <string>
 #include <utility>
 
+#include <android-base/file.h>
+#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
 #include <android-base/unique_fd.h>
 #include <cutils/sockets.h>
 #include "protocol.h"
@@ -86,3 +90,15 @@
 
   return result;
 }
+
+std::string get_process_name(pid_t pid) {
+  std::string result = "<unknown>";
+  android::base::ReadFileToString(android::base::StringPrintf("/proc/%d/cmdline", pid), &result);
+  return result;
+}
+
+std::string get_thread_name(pid_t tid) {
+  std::string result = "<unknown>";
+  android::base::ReadFileToString(android::base::StringPrintf("/proc/%d/comm", tid), &result);
+  return android::base::Trim(result);
+}
diff --git a/debuggerd/util.h b/debuggerd/util.h
index 171e07a..8260b44 100644
--- a/debuggerd/util.h
+++ b/debuggerd/util.h
@@ -16,6 +16,8 @@
 
 #pragma once
 
+#include <string>
+
 #include <sys/cdefs.h>
 #include <sys/types.h>
 
@@ -42,3 +44,6 @@
 //   plus any errors returned by the underlying recvmsg.
 ssize_t recv_fd(int sockfd, void* _Nonnull data, size_t len,
                 android::base::unique_fd* _Nullable out_fd);
+
+std::string get_process_name(pid_t pid);
+std::string get_thread_name(pid_t tid);
diff --git a/fastboot/Android.mk b/fastboot/Android.mk
index 10ef356..dfcf090 100644
--- a/fastboot/Android.mk
+++ b/fastboot/Android.mk
@@ -50,8 +50,8 @@
 LOCAL_CFLAGS_darwin := -Wno-unused-parameter
 
 LOCAL_SRC_FILES_windows := usb_windows.cpp
-LOCAL_STATIC_LIBRARIES_windows := AdbWinApi
-LOCAL_REQUIRED_MODULES_windows := AdbWinApi AdbWinUsbApi
+LOCAL_SHARED_LIBRARIES_windows := AdbWinApi
+LOCAL_REQUIRED_MODULES_windows := AdbWinUsbApi
 LOCAL_LDLIBS_windows := -lws2_32
 LOCAL_C_INCLUDES_windows := development/host/windows/usb/api
 
diff --git a/fastboot/engine.cpp b/fastboot/engine.cpp
index 7e10cc9..271b792 100644
--- a/fastboot/engine.cpp
+++ b/fastboot/engine.cpp
@@ -114,7 +114,7 @@
 
     if (cmdsize >= sizeof(a->cmd)) {
         free(a);
-        die("Command length (%d) exceeds maximum size (%d)", cmdsize, sizeof(a->cmd));
+        die("Command length (%zu) exceeds maximum size (%zu)", cmdsize, sizeof(a->cmd));
     }
 
     if (action_last) {
diff --git a/fastboot/fastboot.h b/fastboot/fastboot.h
index e3c60ae..f4faa21 100644
--- a/fastboot/fastboot.h
+++ b/fastboot/fastboot.h
@@ -75,7 +75,22 @@
 /* util stuff */
 double now();
 char *mkmsg(const char *fmt, ...);
-__attribute__((__noreturn__)) void die(const char *fmt, ...);
+
+// These printf-like functions are implemented in terms of vsnprintf, so they
+// use the same attribute for compile-time format string checking. On Windows,
+// if the mingw version of vsnprintf is used, use `gnu_printf' which allows z
+// in %zd and PRIu64 (and related) to be recognized by the compile-time
+// checking.
+#define FASTBOOT_FORMAT_ARCHETYPE __printf__
+#ifdef __USE_MINGW_ANSI_STDIO
+#if __USE_MINGW_ANSI_STDIO
+#undef FASTBOOT_FORMAT_ARCHETYPE
+#define FASTBOOT_FORMAT_ARCHETYPE gnu_printf
+#endif
+#endif
+void die(const char* fmt, ...) __attribute__((__noreturn__))
+__attribute__((__format__(FASTBOOT_FORMAT_ARCHETYPE, 1, 2)));
+#undef FASTBOOT_FORMAT_ARCHETYPE
 
 /* Current product */
 extern char cur_product[FB_RESPONSE_SZ + 1];
diff --git a/fs_mgr/fs_mgr.cpp b/fs_mgr/fs_mgr.cpp
index 4b94f9c..a2b80ad 100644
--- a/fs_mgr/fs_mgr.cpp
+++ b/fs_mgr/fs_mgr.cpp
@@ -38,6 +38,7 @@
 #include <android-base/properties.h>
 #include <android-base/stringprintf.h>
 #include <android-base/unique_fd.h>
+#include <cutils/android_filesystem_config.h>
 #include <cutils/android_reboot.h>
 #include <cutils/partition_utils.h>
 #include <cutils/properties.h>
@@ -353,7 +354,7 @@
         reserved_blocks = max_reserved_blocks;
     }
 
-    if (ext4_r_blocks_count(sb) == reserved_blocks) {
+    if ((ext4_r_blocks_count(sb) == reserved_blocks) && (sb->s_def_resgid == AID_RESERVED_DISK)) {
         return;
     }
 
@@ -363,11 +364,12 @@
         return;
     }
 
-    char buf[32];
-    const char* argv[] = {TUNE2FS_BIN, "-r", buf, blk_device};
-
-    snprintf(buf, sizeof(buf), "%" PRIu64, reserved_blocks);
     LINFO << "Setting reserved block count on " << blk_device << " to " << reserved_blocks;
+
+    auto reserved_blocks_str = std::to_string(reserved_blocks);
+    auto reserved_gid_str = std::to_string(AID_RESERVED_DISK);
+    const char* argv[] = {
+        TUNE2FS_BIN, "-r", reserved_blocks_str.c_str(), "-g", reserved_gid_str.c_str(), blk_device};
     if (!run_tune2fs(argv, ARRAY_SIZE(argv))) {
         LERROR << "Failed to run " TUNE2FS_BIN " to set the number of reserved blocks on "
                << blk_device;
diff --git a/fs_mgr/fs_mgr_fstab.cpp b/fs_mgr/fs_mgr_fstab.cpp
index 34afed1..1c01d8c 100644
--- a/fs_mgr/fs_mgr_fstab.cpp
+++ b/fs_mgr/fs_mgr_fstab.cpp
@@ -638,6 +638,7 @@
  * frees up memory of the return value without touching a and b. */
 static struct fstab *in_place_merge(struct fstab *a, struct fstab *b)
 {
+    if (!a && !b) return nullptr;
     if (!a) return b;
     if (!b) return a;
 
@@ -654,12 +655,13 @@
     }
 
     for (int i = a->num_entries, j = 0; i < total_entries; i++, j++) {
-        // copy the pointer directly *without* malloc and memcpy
+        // Copy the structs by assignment.
         a->recs[i] = b->recs[j];
     }
 
-    // Frees up b, but don't free b->recs[X] to make sure they are
-    // accessible through a->recs[X].
+    // We can't call fs_mgr_free_fstab because a->recs still references the
+    // memory allocated by strdup.
+    free(b->recs);
     free(b->fstab_filename);
     free(b);
 
@@ -754,15 +756,17 @@
         default_fstab = get_fstab_path();
     }
 
-    if (default_fstab.empty()) {
-        LWARNING << __FUNCTION__ << "(): failed to find device default fstab";
+    struct fstab* fstab = nullptr;
+    if (!default_fstab.empty()) {
+        fstab = fs_mgr_read_fstab(default_fstab.c_str());
+    } else {
+        LINFO << __FUNCTION__ << "(): failed to find device default fstab";
     }
 
+    struct fstab* fstab_dt = fs_mgr_read_fstab_dt();
+
     // combines fstab entries passed in from device tree with
     // the ones found from default_fstab file
-    struct fstab *fstab_dt = fs_mgr_read_fstab_dt();
-    struct fstab *fstab = fs_mgr_read_fstab(default_fstab.c_str());
-
     return in_place_merge(fstab_dt, fstab);
 }
 
diff --git a/healthd/Android.bp b/healthd/Android.bp
index 3a71d03..df12ff0 100644
--- a/healthd/Android.bp
+++ b/healthd/Android.bp
@@ -39,6 +39,7 @@
     static_libs: [
         "android.hardware.health@2.0-impl",
         "android.hardware.health@1.0-convert",
+        "libhealthstoragedefault",
         "libbatterymonitor",
     ],
 
@@ -72,6 +73,7 @@
         "android.hardware.health@2.0-impl",
         "android.hardware.health@1.0-convert",
         "libbatterymonitor",
+        "libhealthstoragedefault",
     ],
 
     shared_libs: [
diff --git a/healthd/Android.mk b/healthd/Android.mk
index 7e58785..9127c60 100644
--- a/healthd/Android.mk
+++ b/healthd/Android.mk
@@ -50,6 +50,7 @@
     android.hardware.health@2.0 \
     android.hardware.health@2.0-impl \
     android.hardware.health@1.0 \
+    libhealthstoragedefault \
     libminui \
     libpng \
     libz \
@@ -98,6 +99,7 @@
     libhidltransport \
     libhidlbase \
     libhwbinder \
+    libhealthstoragedefault \
     libvndksupport \
     libhealthd_charger \
     libhealthd_draw \
diff --git a/healthd/BatteryMonitor.cpp b/healthd/BatteryMonitor.cpp
index 08b8b26..676ee41 100644
--- a/healthd/BatteryMonitor.cpp
+++ b/healthd/BatteryMonitor.cpp
@@ -42,6 +42,7 @@
 #define POWER_SUPPLY_SYSFS_PATH "/sys/class/" POWER_SUPPLY_SUBSYSTEM
 #define FAKE_BATTERY_CAPACITY 42
 #define FAKE_BATTERY_TEMPERATURE 424
+#define ALWAYS_PLUGGED_CAPACITY 100
 #define MILLION 1.0e6
 #define DEFAULT_VBUS_VOLTAGE 5000000
 
@@ -80,11 +81,8 @@
     props->batteryTechnology.clear();
 }
 
-BatteryMonitor::BatteryMonitor()
-    : mHealthdConfig(nullptr),
-      mBatteryDevicePresent(false),
-      mBatteryFixedCapacity(0),
-      mBatteryFixedTemperature(0) {
+BatteryMonitor::BatteryMonitor() : mHealthdConfig(nullptr), mBatteryDevicePresent(false),
+    mAlwaysPluggedDevice(false), mBatteryFixedCapacity(0), mBatteryFixedTemperature(0) {
     initBatteryProperties(&props);
 }
 
@@ -225,6 +223,15 @@
         mBatteryFixedTemperature :
         getIntField(mHealthdConfig->batteryTemperaturePath);
 
+    // For devices which do not have battery and are always plugged
+    // into power souce.
+    if (mAlwaysPluggedDevice) {
+        props.chargerAcOnline = true;
+        props.batteryPresent = true;
+        props.batteryStatus = BATTERY_STATUS_CHARGING;
+        props.batteryHealth = BATTERY_HEALTH_GOOD;
+    }
+
     std::string buf;
 
     if (readFromFile(mHealthdConfig->batteryStatusPath, &buf) > 0)
@@ -398,7 +405,11 @@
         break;
 
     case BATTERY_PROP_BATTERY_STATUS:
-        val->valueInt64 = getChargeStatus();
+        if (mAlwaysPluggedDevice) {
+            val->valueInt64 = BATTERY_STATUS_CHARGING;
+        } else {
+            val->valueInt64 = getChargeStatus();
+        }
         ret = NO_ERROR;
         break;
 
@@ -617,6 +628,9 @@
         KLOG_WARNING(LOG_TAG, "No battery devices found\n");
         hc->periodic_chores_interval_fast = -1;
         hc->periodic_chores_interval_slow = -1;
+        mBatteryFixedCapacity = ALWAYS_PLUGGED_CAPACITY;
+        mBatteryFixedTemperature = FAKE_BATTERY_TEMPERATURE;
+        mAlwaysPluggedDevice = true;
     } else {
         if (mHealthdConfig->batteryStatusPath.isEmpty())
             KLOG_WARNING(LOG_TAG, "BatteryStatusPath not found\n");
diff --git a/healthd/HealthServiceCommon.cpp b/healthd/HealthServiceCommon.cpp
index 266ca3a..e8fbcb0 100644
--- a/healthd/HealthServiceCommon.cpp
+++ b/healthd/HealthServiceCommon.cpp
@@ -28,6 +28,8 @@
 
 using android::hardware::IPCThreadState;
 using android::hardware::configureRpcThreadpool;
+using android::hardware::handleTransportPoll;
+using android::hardware::setupTransportPolling;
 using android::hardware::health::V1_0::HealthInfo;
 using android::hardware::health::V1_0::hal_conversion::convertToHealthInfo;
 using android::hardware::health::V2_0::IHealth;
@@ -35,21 +37,19 @@
 
 extern int healthd_main(void);
 
+static int gBinderFd = -1;
+
 static void binder_event(uint32_t /*epevents*/) {
-    IPCThreadState::self()->handlePolledCommands();
+    if (gBinderFd >= 0) handleTransportPoll(gBinderFd);
 }
 
 void healthd_mode_service_2_0_init(struct healthd_config* config) {
-    int binderFd;
-
     LOG(INFO) << LOG_TAG << " Hal is starting up...";
 
-    configureRpcThreadpool(1, false /* callerWillJoin */);
-    IPCThreadState::self()->disableBackgroundScheduling(true);
-    IPCThreadState::self()->setupPolling(&binderFd);
+    gBinderFd = setupTransportPolling();
 
-    if (binderFd >= 0) {
-        if (healthd_register_event(binderFd, binder_event))
+    if (gBinderFd >= 0) {
+        if (healthd_register_event(gBinderFd, binder_event))
             LOG(ERROR) << LOG_TAG << ": Register for binder events failed";
     }
 
diff --git a/healthd/include/healthd/BatteryMonitor.h b/healthd/include/healthd/BatteryMonitor.h
index 97435c7..f9067cc 100644
--- a/healthd/include/healthd/BatteryMonitor.h
+++ b/healthd/include/healthd/BatteryMonitor.h
@@ -47,6 +47,7 @@
     struct healthd_config *mHealthdConfig;
     Vector<String8> mChargerNames;
     bool mBatteryDevicePresent;
+    bool mAlwaysPluggedDevice;
     int mBatteryFixedCapacity;
     int mBatteryFixedTemperature;
     struct BatteryProperties props;
diff --git a/init/Android.bp b/init/Android.bp
index 0ec348c..0db7824 100644
--- a/init/Android.bp
+++ b/init/Android.bp
@@ -75,6 +75,7 @@
         "persistent_properties.cpp",
         "persistent_properties.proto",
         "property_service.cpp",
+        "property_type.cpp",
         "security.cpp",
         "selinux.cpp",
         "service.cpp",
@@ -95,6 +96,8 @@
         "libprocessgroup",
         "libfs_mgr",
         "libprotobuf-cpp-lite",
+        "libpropertyinfoserializer",
+        "libpropertyinfoparser",
     ],
     include_dirs: [
         "system/core/mkbootimg",
@@ -176,6 +179,7 @@
         "init_test.cpp",
         "persistent_properties_test.cpp",
         "property_service_test.cpp",
+        "property_type_test.cpp",
         "result_test.cpp",
         "rlimit_parser_test.cpp",
         "service_test.cpp",
@@ -193,6 +197,7 @@
         "libselinux",
         "libcrypto",
         "libprotobuf-cpp-lite",
+        "libpropertyinfoparser",
     ],
 }
 
diff --git a/init/Android.mk b/init/Android.mk
index 516f1b3..5239366 100644
--- a/init/Android.mk
+++ b/init/Android.mk
@@ -84,6 +84,8 @@
     libavb \
     libkeyutils \
     libprotobuf-cpp-lite \
+    libpropertyinfoserializer \
+    libpropertyinfoparser \
 
 LOCAL_REQUIRED_MODULES := \
     e2fsdroid \
diff --git a/init/action.cpp b/init/action.cpp
index 5fa6bec..ba03e66 100644
--- a/init/action.cpp
+++ b/init/action.cpp
@@ -21,6 +21,7 @@
 #include <android-base/properties.h>
 #include <android-base/strings.h>
 
+#include "stable_properties.h"
 #include "util.h"
 
 using android::base::Join;
@@ -50,12 +51,19 @@
     : func_(std::move(f)), execute_in_subcontext_(execute_in_subcontext), args_(args), line_(line) {}
 
 Result<Success> Command::InvokeFunc(Subcontext* subcontext) const {
-    if (execute_in_subcontext_ && subcontext) {
-        return subcontext->Execute(args_);
-    } else {
-        const std::string& context = subcontext ? subcontext->context() : kInitContext;
-        return RunBuiltinFunction(func_, args_, context);
+    if (subcontext) {
+        if (execute_in_subcontext_) {
+            return subcontext->Execute(args_);
+        }
+
+        auto expanded_args = subcontext->ExpandArgs(args_);
+        if (!expanded_args) {
+            return expanded_args.error();
+        }
+        return RunBuiltinFunction(func_, *expanded_args, subcontext->context());
     }
+
+    return RunBuiltinFunction(func_, args_, kInitContext);
 }
 
 std::string Command::BuildCommandString() const {
@@ -127,6 +135,25 @@
     }
 }
 
+static bool IsActionableProperty(Subcontext* subcontext, const std::string& prop_name) {
+    static bool enabled =
+        android::base::GetBoolProperty("ro.actionable_compatible_property.enabled", false);
+
+    if (subcontext == nullptr || !enabled) {
+        return true;
+    }
+
+    if (kExportedActionableProperties.count(prop_name) == 1) {
+        return true;
+    }
+    for (const auto& prefix : kPartnerPrefixes) {
+        if (android::base::StartsWith(prop_name, prefix)) {
+            return true;
+        }
+    }
+    return false;
+}
+
 Result<Success> Action::ParsePropertyTrigger(const std::string& trigger) {
     const static std::string prop_str("property:");
     std::string prop_name(trigger.substr(prop_str.length()));
@@ -138,6 +165,10 @@
     std::string prop_value(prop_name.substr(equal_pos + 1));
     prop_name.erase(equal_pos);
 
+    if (!IsActionableProperty(subcontext_, prop_name)) {
+        return Error() << "unexported property tigger found: " << prop_name;
+    }
+
     if (auto [it, inserted] = property_triggers_.emplace(prop_name, prop_value); !inserted) {
         return Error() << "multiple property triggers found for same property";
     }
@@ -358,7 +389,7 @@
     Subcontext* action_subcontext = nullptr;
     if (subcontexts_) {
         for (auto& subcontext : *subcontexts_) {
-            if (StartsWith(filename, subcontext.path_prefix().c_str())) {
+            if (StartsWith(filename, subcontext.path_prefix())) {
                 action_subcontext = &subcontext;
                 break;
             }
diff --git a/init/devices.cpp b/init/devices.cpp
index af6b50a..8d27f4f 100644
--- a/init/devices.cpp
+++ b/init/devices.cpp
@@ -127,7 +127,7 @@
 }
 
 bool Permissions::Match(const std::string& path) const {
-    if (prefix_) return StartsWith(path, name_.c_str());
+    if (prefix_) return StartsWith(path, name_);
     if (wildcard_) return fnmatch(name_.c_str(), path.c_str(), FNM_PATHNAME) == 0;
     return path == name_;
 }
@@ -300,9 +300,9 @@
         static const std::string devices_platform_prefix = "/devices/platform/";
         static const std::string devices_prefix = "/devices/";
 
-        if (StartsWith(device, devices_platform_prefix.c_str())) {
+        if (StartsWith(device, devices_platform_prefix)) {
             device = device.substr(devices_platform_prefix.length());
-        } else if (StartsWith(device, devices_prefix.c_str())) {
+        } else if (StartsWith(device, devices_prefix)) {
             device = device.substr(devices_prefix.length());
         }
 
diff --git a/init/parser.cpp b/init/parser.cpp
index 6ddb09f..4c69bac 100644
--- a/init/parser.cpp
+++ b/init/parser.cpp
@@ -76,7 +76,7 @@
                 // current section parsers.  This is meant for /sys/ and /dev/ line entries for
                 // uevent.
                 for (const auto& [prefix, callback] : line_callbacks_) {
-                    if (android::base::StartsWith(args[0], prefix.c_str())) {
+                    if (android::base::StartsWith(args[0], prefix)) {
                         end_section();
 
                         if (auto result = callback(std::move(args)); !result) {
diff --git a/init/property_service.cpp b/init/property_service.cpp
index 3cf3ab9..79f7f25 100644
--- a/init/property_service.cpp
+++ b/init/property_service.cpp
@@ -50,17 +50,28 @@
 #include <android-base/strings.h>
 #include <bootimg.h>
 #include <fs_mgr.h>
+#include <property_info_parser/property_info_parser.h>
+#include <property_info_serializer/property_info_serializer.h>
 #include <selinux/android.h>
 #include <selinux/label.h>
 #include <selinux/selinux.h>
 
 #include "init.h"
 #include "persistent_properties.h"
+#include "property_type.h"
 #include "util.h"
 
+using android::base::ReadFileToString;
+using android::base::Split;
 using android::base::StartsWith;
 using android::base::StringPrintf;
 using android::base::Timer;
+using android::base::Trim;
+using android::base::WriteStringToFile;
+using android::properties::BuildTrie;
+using android::properties::ParsePropertyInfoFile;
+using android::properties::PropertyInfoAreaFile;
+using android::properties::PropertyInfoEntry;
 
 #define RECOVERY_MOUNT_POINT "/recovery"
 
@@ -71,27 +82,24 @@
 
 static int property_set_fd = -1;
 
-static struct selabel_handle* sehandle_prop;
+static PropertyInfoAreaFile property_info_area;
+
+void CreateSerializedPropertyInfo();
 
 void property_init() {
+    mkdir("/dev/__properties__", S_IRWXU | S_IXGRP | S_IXOTH);
+    CreateSerializedPropertyInfo();
     if (__system_property_area_init()) {
         LOG(FATAL) << "Failed to initialize property area";
     }
+    if (!property_info_area.LoadDefaultPath()) {
+        LOG(FATAL) << "Failed to load serialized property info file";
+    }
 }
-
-static bool check_mac_perms(const std::string& name, char* sctx, struct ucred* cr) {
-
-    if (!sctx) {
-      return false;
-    }
-
-    if (!sehandle_prop) {
-      return false;
-    }
-
-    char* tctx = nullptr;
-    if (selabel_lookup(sehandle_prop, &tctx, name.c_str(), 1) != 0) {
-      return false;
+static bool CheckMacPerms(const std::string& name, const char* target_context,
+                          const char* source_context, struct ucred* cr) {
+    if (!target_context || !source_context) {
+        return false;
     }
 
     property_audit_data audit_data;
@@ -99,29 +107,12 @@
     audit_data.name = name.c_str();
     audit_data.cr = cr;
 
-    bool has_access = (selinux_check_access(sctx, tctx, "property_service", "set", &audit_data) == 0);
+    bool has_access = (selinux_check_access(source_context, target_context, "property_service",
+                                            "set", &audit_data) == 0);
 
-    freecon(tctx);
     return has_access;
 }
 
-static int check_control_mac_perms(const char *name, char *sctx, struct ucred *cr)
-{
-    /*
-     *  Create a name prefix out of ctl.<service name>
-     *  The new prefix allows the use of the existing
-     *  property service backend labeling while avoiding
-     *  mislabels based on true property prefixes.
-     */
-    char ctl_name[PROP_VALUE_MAX+4];
-    int ret = snprintf(ctl_name, sizeof(ctl_name), "ctl.%s", name);
-
-    if (ret < 0 || (size_t) ret >= sizeof(ctl_name))
-        return 0;
-
-    return check_mac_perms(ctl_name, sctx, cr);
-}
-
 bool is_legal_property_name(const std::string& name) {
     size_t namelen = name.size();
 
@@ -338,13 +329,15 @@
     ufds[0].events = POLLIN;
     ufds[0].revents = 0;
     while (*timeout_ms > 0) {
-      Timer timer;
-      int nr = poll(ufds, 1, *timeout_ms);
-      uint64_t millis = timer.duration().count();
-      *timeout_ms = (millis > *timeout_ms) ? 0 : *timeout_ms - millis;
+        auto start_time = std::chrono::steady_clock::now();
+        int nr = poll(ufds, 1, *timeout_ms);
+        auto now = std::chrono::steady_clock::now();
+        auto time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - start_time);
+        uint64_t millis = time_elapsed.count();
+        *timeout_ms = (millis > *timeout_ms) ? 0 : *timeout_ms - millis;
 
-      if (nr > 0) {
-        return true;
+        if (nr > 0) {
+            return true;
       }
 
       if (nr == 0) {
@@ -408,52 +401,70 @@
   struct ucred cr = socket.cred();
   char* source_ctx = nullptr;
   getpeercon(socket.socket(), &source_ctx);
+  std::string source_context = source_ctx;
+  freecon(source_ctx);
 
   if (StartsWith(name, "ctl.")) {
-    if (check_control_mac_perms(value.c_str(), source_ctx, &cr)) {
+      // ctl. properties have their name ctl.<action> and their value is the name of the service to
+      // apply that action to.  Permissions for these actions are based on the service, so we must
+      // create a fake name of ctl.<service> to check permissions.
+      auto control_string = "ctl." + value;
+      const char* target_context = nullptr;
+      const char* type = nullptr;
+      property_info_area->GetPropertyInfo(control_string.c_str(), &target_context, &type);
+      if (!CheckMacPerms(control_string, target_context, source_context.c_str(), &cr)) {
+          LOG(ERROR) << "sys_prop(" << cmd_name << "): Unable to " << (name.c_str() + 4)
+                     << " service ctl [" << value << "]"
+                     << " uid:" << cr.uid << " gid:" << cr.gid << " pid:" << cr.pid;
+          if (!legacy_protocol) {
+              socket.SendUint32(PROP_ERROR_HANDLE_CONTROL_MESSAGE);
+          }
+          return;
+      }
+
       handle_control_message(name.c_str() + 4, value.c_str());
       if (!legacy_protocol) {
-        socket.SendUint32(PROP_SUCCESS);
+          socket.SendUint32(PROP_SUCCESS);
       }
-    } else {
-      LOG(ERROR) << "sys_prop(" << cmd_name << "): Unable to " << (name.c_str() + 4)
-                 << " service ctl [" << value << "]"
-                 << " uid:" << cr.uid
-                 << " gid:" << cr.gid
-                 << " pid:" << cr.pid;
-      if (!legacy_protocol) {
-        socket.SendUint32(PROP_ERROR_HANDLE_CONTROL_MESSAGE);
-      }
-    }
   } else {
-    if (check_mac_perms(name, source_ctx, &cr)) {
+      const char* target_context = nullptr;
+      const char* type = nullptr;
+      property_info_area->GetPropertyInfo(name.c_str(), &target_context, &type);
+      if (!CheckMacPerms(name, target_context, source_context.c_str(), &cr)) {
+          LOG(ERROR) << "sys_prop(" << cmd_name << "): permission denied uid:" << cr.uid
+                     << " name:" << name;
+          if (!legacy_protocol) {
+              socket.SendUint32(PROP_ERROR_PERMISSION_DENIED);
+          }
+          return;
+      }
+      if (type == nullptr || !CheckType(type, value)) {
+          LOG(ERROR) << "sys_prop(" << cmd_name << "): type check failed, type: '"
+                     << (type ?: "(null)") << "' value: '" << value << "'";
+          if (!legacy_protocol) {
+              socket.SendUint32(PROP_ERROR_INVALID_VALUE);
+          }
+          return;
+      }
       // sys.powerctl is a special property that is used to make the device reboot.  We want to log
       // any process that sets this property to be able to accurately blame the cause of a shutdown.
       if (name == "sys.powerctl") {
-        std::string cmdline_path = StringPrintf("proc/%d/cmdline", cr.pid);
-        std::string process_cmdline;
-        std::string process_log_string;
-        if (android::base::ReadFileToString(cmdline_path, &process_cmdline)) {
-          // Since cmdline is null deliminated, .c_str() conveniently gives us just the process path.
-          process_log_string = StringPrintf(" (%s)", process_cmdline.c_str());
-        }
-        LOG(INFO) << "Received sys.powerctl='" << value << "' from pid: " << cr.pid
-                  << process_log_string;
+          std::string cmdline_path = StringPrintf("proc/%d/cmdline", cr.pid);
+          std::string process_cmdline;
+          std::string process_log_string;
+          if (ReadFileToString(cmdline_path, &process_cmdline)) {
+              // Since cmdline is null deliminated, .c_str() conveniently gives us just the process path.
+              process_log_string = StringPrintf(" (%s)", process_cmdline.c_str());
+          }
+          LOG(INFO) << "Received sys.powerctl='" << value << "' from pid: " << cr.pid
+                    << process_log_string;
       }
 
       uint32_t result = property_set(name, value);
       if (!legacy_protocol) {
-        socket.SendUint32(result);
+          socket.SendUint32(result);
       }
-    } else {
-      LOG(ERROR) << "sys_prop(" << cmd_name << "): permission denied uid:" << cr.uid << " name:" << name;
-      if (!legacy_protocol) {
-        socket.SendUint32(PROP_ERROR_PERMISSION_DENIED);
-      }
-    }
   }
-
-  freecon(source_ctx);
 }
 
 static void handle_property_set_fd() {
@@ -714,9 +725,59 @@
     return 0;
 }
 
-void start_property_service() {
-    sehandle_prop = selinux_android_prop_context_handle();
+bool LoadPropertyInfoFromFile(const std::string& filename,
+                              std::vector<PropertyInfoEntry>* property_infos) {
+    auto file_contents = std::string();
+    if (!ReadFileToString(filename, &file_contents)) {
+        PLOG(ERROR) << "Could not read properties from '" << filename << "'";
+        return false;
+    }
 
+    auto errors = std::vector<std::string>{};
+    ParsePropertyInfoFile(file_contents, property_infos, &errors);
+    // Individual parsing errors are reported but do not cause a failed boot, which is what
+    // returning false would do here.
+    for (const auto& error : errors) {
+        LOG(ERROR) << "Could not read line from '" << filename << "': " << error;
+    }
+
+    return true;
+}
+
+void CreateSerializedPropertyInfo() {
+    auto property_infos = std::vector<PropertyInfoEntry>();
+    if (access("/system/etc/selinux/plat_property_contexts", R_OK) != -1) {
+        if (!LoadPropertyInfoFromFile("/system/etc/selinux/plat_property_contexts",
+                                      &property_infos)) {
+            return;
+        }
+        // Don't check for failure here, so we always have a sane list of properties.
+        // E.g. In case of recovery, the vendor partition will not have mounted and we
+        // still need the system / platform properties to function.
+        LoadPropertyInfoFromFile("/vendor/etc/selinux/nonplat_property_contexts", &property_infos);
+    } else {
+        if (!LoadPropertyInfoFromFile("/plat_property_contexts", &property_infos)) {
+            return;
+        }
+        LoadPropertyInfoFromFile("/nonplat_property_contexts", &property_infos);
+    }
+
+    auto serialized_contexts = std::string();
+    auto error = std::string();
+    if (!BuildTrie(property_infos, "u:object_r:default_prop:s0", "string", &serialized_contexts,
+                   &error)) {
+        LOG(ERROR) << "Unable to serialize property contexts: " << error;
+        return;
+    }
+
+    constexpr static const char kPropertyInfosPath[] = "/dev/__properties__/property_info";
+    if (!WriteStringToFile(serialized_contexts, kPropertyInfosPath, 0444, 0, 0, false)) {
+        PLOG(ERROR) << "Unable to write serialized property infos to file";
+    }
+    selinux_android_restorecon(kPropertyInfosPath, 0);
+}
+
+void start_property_service() {
     selinux_callback cb;
     cb.func_audit = SelinuxAuditCallback;
     selinux_set_callback(SELINUX_CB_AUDIT, cb);
diff --git a/init/property_type.cpp b/init/property_type.cpp
new file mode 100644
index 0000000..249b12b
--- /dev/null
+++ b/init/property_type.cpp
@@ -0,0 +1,81 @@
+//
+// 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 "property_type.h"
+
+#include <android-base/parsedouble.h>
+#include <android-base/parseint.h>
+#include <android-base/strings.h>
+
+using android::base::ParseDouble;
+using android::base::ParseInt;
+using android::base::ParseUint;
+using android::base::Split;
+
+namespace android {
+namespace init {
+
+bool CheckType(const std::string& type_string, const std::string& value) {
+    auto type_strings = Split(type_string, " ");
+    if (type_strings.empty()) {
+        return false;
+    }
+    auto type = type_strings[0];
+
+    if (type == "string") {
+        return true;
+    }
+    if (type == "bool") {
+        return value == "true" || value == "false" || value == "1" || value == "0";
+    }
+    if (type == "int") {
+        int64_t parsed;
+        return ParseInt(value, &parsed);
+    }
+    if (type == "uint") {
+        uint64_t parsed;
+        if (value.empty() || value.front() == '-') {
+            return false;
+        }
+        return ParseUint(value, &parsed);
+    }
+    if (type == "double") {
+        double parsed;
+        return ParseDouble(value.c_str(), &parsed);
+    }
+    if (type == "size") {
+        auto it = value.begin();
+        while (it != value.end() && isdigit(*it)) {
+            it++;
+        }
+        if (it == value.begin() || it == value.end() || (*it != 'g' && *it != 'k' && *it != 'm')) {
+            return false;
+        }
+        it++;
+        return it == value.end();
+    }
+    if (type == "enum") {
+        for (auto it = std::next(type_strings.begin()); it != type_strings.end(); ++it) {
+            if (*it == value) {
+                return true;
+            }
+        }
+    }
+    return false;
+}
+
+}  // namespace init
+}  // namespace android
diff --git a/debuggerd/libdebuggerd/test/ptrace_fake.h b/init/property_type.h
similarity index 65%
copy from debuggerd/libdebuggerd/test/ptrace_fake.h
copy to init/property_type.h
index fdbb663..c889e16 100644
--- a/debuggerd/libdebuggerd/test/ptrace_fake.h
+++ b/init/property_type.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2015 The Android Open Source Project
+ * 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.
@@ -14,11 +14,17 @@
  * limitations under the License.
  */
 
-#ifndef _DEBUGGERD_TEST_PTRACE_FAKE_H
-#define _DEBUGGERD_TEST_PTRACE_FAKE_H
+#ifndef _INIT_PROPERTY_TYPE_H
+#define _INIT_PROPERTY_TYPE_H
 
-#include <signal.h>
+#include <string>
 
-void ptrace_set_fake_getsiginfo(const siginfo_t&);
+namespace android {
+namespace init {
 
-#endif // _DEBUGGERD_TEST_PTRACE_FAKE_H
+bool CheckType(const std::string& type_string, const std::string& value);
+
+}  // namespace init
+}  // namespace android
+
+#endif
diff --git a/init/property_type_test.cpp b/init/property_type_test.cpp
new file mode 100644
index 0000000..068bccc
--- /dev/null
+++ b/init/property_type_test.cpp
@@ -0,0 +1,95 @@
+/*
+ * 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 "property_type.h"
+
+#include <gtest/gtest.h>
+
+namespace android {
+namespace init {
+
+TEST(property_type, CheckType_string) {
+    EXPECT_TRUE(CheckType("string", ""));
+    EXPECT_TRUE(CheckType("string", "-234"));
+    EXPECT_TRUE(CheckType("string", "234"));
+    EXPECT_TRUE(CheckType("string", "true"));
+    EXPECT_TRUE(CheckType("string", "false"));
+    EXPECT_TRUE(CheckType("string", "45645634563456345634563456"));
+    EXPECT_TRUE(CheckType("string", "some other string"));
+}
+
+TEST(property_type, CheckType_int) {
+    EXPECT_FALSE(CheckType("int", ""));
+    EXPECT_FALSE(CheckType("int", "abc"));
+    EXPECT_FALSE(CheckType("int", "-abc"));
+    EXPECT_TRUE(CheckType("int", "0"));
+    EXPECT_TRUE(CheckType("int", std::to_string(std::numeric_limits<int64_t>::min())));
+    EXPECT_TRUE(CheckType("int", std::to_string(std::numeric_limits<int64_t>::max())));
+    EXPECT_TRUE(CheckType("int", "123"));
+    EXPECT_TRUE(CheckType("int", "-123"));
+}
+
+TEST(property_type, CheckType_uint) {
+    EXPECT_FALSE(CheckType("uint", ""));
+    EXPECT_FALSE(CheckType("uint", "abc"));
+    EXPECT_FALSE(CheckType("uint", "-abc"));
+    EXPECT_TRUE(CheckType("uint", "0"));
+    EXPECT_TRUE(CheckType("uint", std::to_string(std::numeric_limits<uint64_t>::max())));
+    EXPECT_TRUE(CheckType("uint", "123"));
+    EXPECT_FALSE(CheckType("uint", "-123"));
+}
+
+TEST(property_type, CheckType_double) {
+    EXPECT_FALSE(CheckType("double", ""));
+    EXPECT_FALSE(CheckType("double", "abc"));
+    EXPECT_FALSE(CheckType("double", "-abc"));
+    EXPECT_TRUE(CheckType("double", "0.0"));
+    EXPECT_TRUE(CheckType("double", std::to_string(std::numeric_limits<double>::min())));
+    EXPECT_TRUE(CheckType("double", std::to_string(std::numeric_limits<double>::max())));
+    EXPECT_TRUE(CheckType("double", "123.1"));
+    EXPECT_TRUE(CheckType("double", "-123.1"));
+}
+
+TEST(property_type, CheckType_size) {
+    EXPECT_FALSE(CheckType("size", ""));
+    EXPECT_FALSE(CheckType("size", "ab"));
+    EXPECT_FALSE(CheckType("size", "abcd"));
+    EXPECT_FALSE(CheckType("size", "0"));
+
+    EXPECT_TRUE(CheckType("size", "512g"));
+    EXPECT_TRUE(CheckType("size", "512k"));
+    EXPECT_TRUE(CheckType("size", "512m"));
+
+    EXPECT_FALSE(CheckType("size", "512gggg"));
+    EXPECT_FALSE(CheckType("size", "512mgk"));
+    EXPECT_FALSE(CheckType("size", "g"));
+    EXPECT_FALSE(CheckType("size", "m"));
+}
+
+TEST(property_type, CheckType_enum) {
+    EXPECT_FALSE(CheckType("enum abc", ""));
+    EXPECT_FALSE(CheckType("enum abc", "ab"));
+    EXPECT_FALSE(CheckType("enum abc", "abcd"));
+    EXPECT_FALSE(CheckType("enum 123 456 789", "0"));
+
+    EXPECT_TRUE(CheckType("enum abc", "abc"));
+    EXPECT_TRUE(CheckType("enum 123 456 789", "123"));
+    EXPECT_TRUE(CheckType("enum 123 456 789", "456"));
+    EXPECT_TRUE(CheckType("enum 123 456 789", "789"));
+}
+
+}  // namespace init
+}  // namespace android
diff --git a/init/service.cpp b/init/service.cpp
index 331b859..a4e33f7 100644
--- a/init/service.cpp
+++ b/init/service.cpp
@@ -1125,7 +1125,7 @@
     Subcontext* restart_action_subcontext = nullptr;
     if (subcontexts_) {
         for (auto& subcontext : *subcontexts_) {
-            if (StartsWith(filename, subcontext.path_prefix().c_str())) {
+            if (StartsWith(filename, subcontext.path_prefix())) {
                 restart_action_subcontext = &subcontext;
                 break;
             }
diff --git a/init/stable_properties.h b/init/stable_properties.h
new file mode 100644
index 0000000..8219838
--- /dev/null
+++ b/init/stable_properties.h
@@ -0,0 +1,46 @@
+/*
+ * 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.
+ */
+
+#ifndef _INIT_STABLE_PROPERTIES_H
+#define _INIT_STABLE_PROPERTIES_H
+
+#include <set>
+#include <string>
+
+namespace android {
+namespace init {
+
+static constexpr const char* kPartnerPrefixes[] = {
+    "init.svc.vendor.", "ro.vendor.", "persist.vendor.", "vendor.",
+    "init.svc.odm.",    "ro.odm.",    "persist.odm.",    "odm.",
+};
+
+static const std::set<std::string> kExportedActionableProperties = {
+    "init.svc.zygote",         "persist.bluetooth.btsnoopenable",
+    "persist.sys.crash_rcu",   "persist.sys.zram_enabled",
+    "ro.boot.revision",        "ro.bootmode",
+    "ro.build.type",           "sys.boot_completed",
+    "sys.retaildemo.enabled",  "sys.shutdown.requested",
+    "sys.usb.config",          "sys.usb.configfs",
+    "sys.usb.ffs.mtp.ready",   "sys.usb.ffs.ready",
+    "sys.user.0.ce_available", "sys.vdso",
+    "vts.native_server.on",
+};
+
+}  // namespace init
+}  // namespace android
+
+#endif
diff --git a/init/subcontext.cpp b/init/subcontext.cpp
index 068be6e..be754da 100644
--- a/init/subcontext.cpp
+++ b/init/subcontext.cpp
@@ -28,7 +28,6 @@
 
 #include "action.h"
 #include "selinux.h"
-#include "system/core/init/subcontext.pb.h"
 #include "util.h"
 
 using android::base::GetExecutablePath;
@@ -84,7 +83,9 @@
 
   private:
     void RunCommand(const SubcontextCommand::ExecuteCommand& execute_command,
-                    SubcontextReply::ResultMessage* result_message) const;
+                    SubcontextReply* reply) const;
+    void ExpandArgs(const SubcontextCommand::ExpandArgsCommand& expand_args_command,
+                    SubcontextReply* reply) const;
 
     const KeywordFunctionMap* function_map_;
     const std::string context_;
@@ -92,7 +93,7 @@
 };
 
 void SubcontextProcess::RunCommand(const SubcontextCommand::ExecuteCommand& execute_command,
-                                   SubcontextReply::ResultMessage* result_message) const {
+                                   SubcontextReply* reply) const {
     // Need to use ArraySplice instead of this code.
     auto args = std::vector<std::string>();
     for (const auto& string : execute_command.args()) {
@@ -108,11 +109,27 @@
     }
 
     if (result) {
-        result_message->set_success(true);
+        reply->set_success(true);
     } else {
-        result_message->set_success(false);
-        result_message->set_error_string(result.error_string());
-        result_message->set_error_errno(result.error_errno());
+        auto* failure = reply->mutable_failure();
+        failure->set_error_string(result.error_string());
+        failure->set_error_errno(result.error_errno());
+    }
+}
+
+void SubcontextProcess::ExpandArgs(const SubcontextCommand::ExpandArgsCommand& expand_args_command,
+                                   SubcontextReply* reply) const {
+    for (const auto& arg : expand_args_command.args()) {
+        auto expanded_prop = std::string{};
+        if (!expand_props(arg, &expanded_prop)) {
+            auto* failure = reply->mutable_failure();
+            failure->set_error_string("Failed to expand '" + arg + "'");
+            failure->set_error_errno(0);
+            return;
+        } else {
+            auto* expand_args_reply = reply->mutable_expand_args_reply();
+            expand_args_reply->add_expanded_args(expanded_prop);
+        }
     }
 }
 
@@ -142,7 +159,11 @@
         auto reply = SubcontextReply();
         switch (subcontext_command.command_case()) {
             case SubcontextCommand::kExecuteCommand: {
-                RunCommand(subcontext_command.execute_command(), reply.mutable_result());
+                RunCommand(subcontext_command.execute_command(), &reply);
+                break;
+            }
+            case SubcontextCommand::kExpandArgsCommand: {
+                ExpandArgs(subcontext_command.expand_args_command(), &reply);
                 break;
             }
             default:
@@ -219,12 +240,7 @@
     Fork();
 }
 
-Result<Success> Subcontext::Execute(const std::vector<std::string>& args) {
-    auto subcontext_command = SubcontextCommand();
-    std::copy(
-        args.begin(), args.end(),
-        RepeatedPtrFieldBackInserter(subcontext_command.mutable_execute_command()->mutable_args()));
-
+Result<SubcontextReply> Subcontext::TransmitMessage(const SubcontextCommand& subcontext_command) {
     if (auto result = SendMessage(socket_, subcontext_command); !result) {
         Restart();
         return ErrnoError() << "Failed to send message to subcontext";
@@ -236,25 +252,59 @@
         return Error() << "Failed to receive result from subcontext: " << subcontext_message.error();
     }
 
-    auto subcontext_reply = SubcontextReply();
+    auto subcontext_reply = SubcontextReply{};
     if (!subcontext_reply.ParseFromString(*subcontext_message)) {
         Restart();
         return Error() << "Unable to parse message from subcontext";
     }
-
-    switch (subcontext_reply.reply_case()) {
-        case SubcontextReply::kResult: {
-            auto result = subcontext_reply.result();
-            if (result.success()) {
-                return Success();
-            } else {
-                return ResultError(result.error_string(), result.error_errno());
-            }
-        }
-        default:
-            return Error() << "Unknown message type from subcontext: "
-                           << subcontext_reply.reply_case();
+    if (subcontext_reply.reply_case() == SubcontextReply::kFailure) {
+        auto& failure = subcontext_reply.failure();
+        return ResultError(failure.error_string(), failure.error_errno());
     }
+    return subcontext_reply;
+}
+
+Result<Success> Subcontext::Execute(const std::vector<std::string>& args) {
+    auto subcontext_command = SubcontextCommand();
+    std::copy(
+        args.begin(), args.end(),
+        RepeatedPtrFieldBackInserter(subcontext_command.mutable_execute_command()->mutable_args()));
+
+    auto subcontext_reply = TransmitMessage(subcontext_command);
+    if (!subcontext_reply) {
+        return subcontext_reply.error();
+    }
+
+    if (subcontext_reply->reply_case() != SubcontextReply::kSuccess) {
+        return Error() << "Unexpected message type from subcontext: "
+                       << subcontext_reply->reply_case();
+    }
+
+    return Success();
+}
+
+Result<std::vector<std::string>> Subcontext::ExpandArgs(const std::vector<std::string>& args) {
+    auto subcontext_command = SubcontextCommand{};
+    std::copy(args.begin(), args.end(),
+              RepeatedPtrFieldBackInserter(
+                  subcontext_command.mutable_expand_args_command()->mutable_args()));
+
+    auto subcontext_reply = TransmitMessage(subcontext_command);
+    if (!subcontext_reply) {
+        return subcontext_reply.error();
+    }
+
+    if (subcontext_reply->reply_case() != SubcontextReply::kExpandArgsReply) {
+        return Error() << "Unexpected message type from subcontext: "
+                       << subcontext_reply->reply_case();
+    }
+
+    auto& reply = subcontext_reply->expand_args_reply();
+    auto expanded_args = std::vector<std::string>{};
+    for (const auto& string : reply.expanded_args()) {
+        expanded_args.emplace_back(string);
+    }
+    return expanded_args;
 }
 
 static std::vector<Subcontext> subcontexts;
diff --git a/init/subcontext.h b/init/subcontext.h
index eadabee..262440d 100644
--- a/init/subcontext.h
+++ b/init/subcontext.h
@@ -25,6 +25,7 @@
 #include <android-base/unique_fd.h>
 
 #include "builtins.h"
+#include "system/core/init/subcontext.pb.h"
 
 namespace android {
 namespace init {
@@ -39,7 +40,8 @@
         Fork();
     }
 
-    Result<Success> Execute(const std::vector<std::string>& command);
+    Result<Success> Execute(const std::vector<std::string>& args);
+    Result<std::vector<std::string>> ExpandArgs(const std::vector<std::string>& args);
     void Restart();
 
     const std::string& path_prefix() const { return path_prefix_; }
@@ -48,6 +50,7 @@
 
   private:
     void Fork();
+    Result<SubcontextReply> TransmitMessage(const SubcontextCommand& subcontext_command);
 
     std::string path_prefix_;
     std::string context_;
diff --git a/init/subcontext.proto b/init/subcontext.proto
index 0d89734..e68115e 100644
--- a/init/subcontext.proto
+++ b/init/subcontext.proto
@@ -19,15 +19,23 @@
 
 message SubcontextCommand {
     message ExecuteCommand { repeated string args = 1; }
-    oneof command { ExecuteCommand execute_command = 1; }
+    message ExpandArgsCommand { repeated string args = 1; }
+    oneof command {
+        ExecuteCommand execute_command = 1;
+        ExpandArgsCommand expand_args_command = 2;
+    }
 }
 
 message SubcontextReply {
-    message ResultMessage {
-        optional bool success = 1;
-        optional string error_string = 2;
-        optional int32 error_errno = 3;
+    message Failure {
+        optional string error_string = 1;
+        optional int32 error_errno = 2;
     }
+    message ExpandArgsReply { repeated string expanded_args = 1; }
 
-    oneof reply { ResultMessage result = 1; }
+    oneof reply {
+        bool success = 1;
+        Failure failure = 2;
+        ExpandArgsReply expand_args_reply = 3;
+    }
 }
\ No newline at end of file
diff --git a/init/subcontext_test.cpp b/init/subcontext_test.cpp
index ca45266..230203a 100644
--- a/init/subcontext_test.cpp
+++ b/init/subcontext_test.cpp
@@ -143,6 +143,34 @@
     });
 }
 
+TEST(subcontext, ExpandArgs) {
+    RunTest([](auto& subcontext, auto& context_string) {
+        auto args = std::vector<std::string>{
+            "first",
+            "${ro.hardware}",
+            "$$third",
+        };
+        auto result = subcontext.ExpandArgs(args);
+        ASSERT_TRUE(result) << result.error();
+        ASSERT_EQ(3U, result->size());
+        EXPECT_EQ(args[0], result->at(0));
+        EXPECT_EQ(GetProperty("ro.hardware", ""), result->at(1));
+        EXPECT_EQ("$third", result->at(2));
+    });
+}
+
+TEST(subcontext, ExpandArgsFailure) {
+    RunTest([](auto& subcontext, auto& context_string) {
+        auto args = std::vector<std::string>{
+            "first",
+            "${",
+        };
+        auto result = subcontext.ExpandArgs(args);
+        ASSERT_FALSE(result);
+        EXPECT_EQ("Failed to expand '" + args[1] + "'", result.error_string());
+    });
+}
+
 TestFunctionMap BuildTestFunctionMap() {
     TestFunctionMap test_function_map;
     // For CheckDifferentPid
diff --git a/libbacktrace/Backtrace.cpp b/libbacktrace/Backtrace.cpp
index e18dbf3..5bb6edc 100644
--- a/libbacktrace/Backtrace.cpp
+++ b/libbacktrace/Backtrace.cpp
@@ -142,22 +142,33 @@
 }
 
 std::string Backtrace::GetErrorString(BacktraceUnwindError error) {
-  switch (error) {
-  case BACKTRACE_UNWIND_NO_ERROR:
-    return "No error";
-  case BACKTRACE_UNWIND_ERROR_SETUP_FAILED:
-    return "Setup failed";
-  case BACKTRACE_UNWIND_ERROR_MAP_MISSING:
-    return "No map found";
-  case BACKTRACE_UNWIND_ERROR_INTERNAL:
-    return "Internal libbacktrace error, please submit a bugreport";
-  case BACKTRACE_UNWIND_ERROR_THREAD_DOESNT_EXIST:
-    return "Thread doesn't exist";
-  case BACKTRACE_UNWIND_ERROR_THREAD_TIMEOUT:
-    return "Thread has not responded to signal in time";
-  case BACKTRACE_UNWIND_ERROR_UNSUPPORTED_OPERATION:
-    return "Attempt to use an unsupported feature";
-  case BACKTRACE_UNWIND_ERROR_NO_CONTEXT:
-    return "Attempt to do an offline unwind without a context";
+  switch (error.error_code) {
+    case BACKTRACE_UNWIND_NO_ERROR:
+      return "No error";
+    case BACKTRACE_UNWIND_ERROR_SETUP_FAILED:
+      return "Setup failed";
+    case BACKTRACE_UNWIND_ERROR_MAP_MISSING:
+      return "No map found";
+    case BACKTRACE_UNWIND_ERROR_INTERNAL:
+      return "Internal libbacktrace error, please submit a bugreport";
+    case BACKTRACE_UNWIND_ERROR_THREAD_DOESNT_EXIST:
+      return "Thread doesn't exist";
+    case BACKTRACE_UNWIND_ERROR_THREAD_TIMEOUT:
+      return "Thread has not responded to signal in time";
+    case BACKTRACE_UNWIND_ERROR_UNSUPPORTED_OPERATION:
+      return "Attempt to use an unsupported feature";
+    case BACKTRACE_UNWIND_ERROR_NO_CONTEXT:
+      return "Attempt to do an offline unwind without a context";
+    case BACKTRACE_UNWIND_ERROR_EXCEED_MAX_FRAMES_LIMIT:
+      return "Exceed MAX_BACKTRACE_FRAMES limit";
+    case BACKTRACE_UNWIND_ERROR_ACCESS_MEM_FAILED:
+      return android::base::StringPrintf("Failed to read memory at addr 0x%" PRIx64,
+                                         error.error_info.addr);
+    case BACKTRACE_UNWIND_ERROR_ACCESS_REG_FAILED:
+      return android::base::StringPrintf("Failed to read register %" PRIu64, error.error_info.regno);
+    case BACKTRACE_UNWIND_ERROR_FIND_PROC_INFO_FAILED:
+      return "Failed to find a function in debug sections";
+    case BACKTRACE_UNWIND_ERROR_EXECUTE_DWARF_INSTRUCTION_FAILED:
+      return "Failed to execute dwarf instructions in debug sections";
   }
 }
diff --git a/libbacktrace/BacktraceCurrent.cpp b/libbacktrace/BacktraceCurrent.cpp
index fb76b85..474d099 100644
--- a/libbacktrace/BacktraceCurrent.cpp
+++ b/libbacktrace/BacktraceCurrent.cpp
@@ -67,11 +67,11 @@
 bool BacktraceCurrent::Unwind(size_t num_ignore_frames, ucontext_t* ucontext) {
   if (GetMap() == nullptr) {
     // Without a map object, we can't do anything.
-    error_ = BACKTRACE_UNWIND_ERROR_MAP_MISSING;
+    error_.error_code = BACKTRACE_UNWIND_ERROR_MAP_MISSING;
     return false;
   }
 
-  error_ = BACKTRACE_UNWIND_NO_ERROR;
+  error_.error_code = BACKTRACE_UNWIND_NO_ERROR;
   if (ucontext) {
     return UnwindFromContext(num_ignore_frames, ucontext);
   }
@@ -163,7 +163,7 @@
     BACK_ASYNC_SAFE_LOGE("sigaction failed: %s", strerror(errno));
     ThreadEntry::Remove(entry);
     pthread_mutex_unlock(&g_sigaction_mutex);
-    error_ = BACKTRACE_UNWIND_ERROR_INTERNAL;
+    error_.error_code = BACKTRACE_UNWIND_ERROR_INTERNAL;
     return false;
   }
 
@@ -171,9 +171,9 @@
     // Do not emit an error message, this might be expected. Set the
     // error and let the caller decide.
     if (errno == ESRCH) {
-      error_ = BACKTRACE_UNWIND_ERROR_THREAD_DOESNT_EXIST;
+      error_.error_code = BACKTRACE_UNWIND_ERROR_THREAD_DOESNT_EXIST;
     } else {
-      error_ = BACKTRACE_UNWIND_ERROR_INTERNAL;
+      error_.error_code = BACKTRACE_UNWIND_ERROR_INTERNAL;
     }
 
     sigaction(THREAD_SIGNAL, &oldact, nullptr);
@@ -218,9 +218,9 @@
   } else {
     // Check to see if the thread has disappeared.
     if (tgkill(Pid(), Tid(), 0) == -1 && errno == ESRCH) {
-      error_ = BACKTRACE_UNWIND_ERROR_THREAD_DOESNT_EXIST;
+      error_.error_code = BACKTRACE_UNWIND_ERROR_THREAD_DOESNT_EXIST;
     } else {
-      error_ = BACKTRACE_UNWIND_ERROR_THREAD_TIMEOUT;
+      error_.error_code = BACKTRACE_UNWIND_ERROR_THREAD_TIMEOUT;
       BACK_ASYNC_SAFE_LOGE("Timed out waiting for signal handler to get ucontext data.");
     }
   }
diff --git a/libbacktrace/BacktraceOffline.cpp b/libbacktrace/BacktraceOffline.cpp
index 641f712..30845a2 100644
--- a/libbacktrace/BacktraceOffline.cpp
+++ b/libbacktrace/BacktraceOffline.cpp
@@ -174,11 +174,11 @@
 bool BacktraceOffline::Unwind(size_t num_ignore_frames, ucontext_t* context) {
   if (context == nullptr) {
     BACK_LOGW("The context is needed for offline backtracing.");
-    error_ = BACKTRACE_UNWIND_ERROR_NO_CONTEXT;
+    error_.error_code = BACKTRACE_UNWIND_ERROR_NO_CONTEXT;
     return false;
   }
   context_ = context;
-  error_ = BACKTRACE_UNWIND_NO_ERROR;
+  error_.error_code = BACKTRACE_UNWIND_NO_ERROR;
 
   unw_addr_space_t addr_space = unw_create_addr_space(&accessors, 0);
   unw_cursor_t cursor;
@@ -186,25 +186,38 @@
   if (ret != 0) {
     BACK_LOGW("unw_init_remote failed %d", ret);
     unw_destroy_addr_space(addr_space);
-    error_ = BACKTRACE_UNWIND_ERROR_SETUP_FAILED;
+    error_.error_code = BACKTRACE_UNWIND_ERROR_SETUP_FAILED;
     return false;
   }
   size_t num_frames = 0;
-  do {
+  while (true) {
     unw_word_t pc;
     ret = unw_get_reg(&cursor, UNW_REG_IP, &pc);
     if (ret < 0) {
       BACK_LOGW("Failed to read IP %d", ret);
+      error_.error_code = BACKTRACE_UNWIND_ERROR_ACCESS_REG_FAILED;
+      error_.error_info.regno = UNW_REG_IP;
       break;
     }
     unw_word_t sp;
     ret = unw_get_reg(&cursor, UNW_REG_SP, &sp);
     if (ret < 0) {
       BACK_LOGW("Failed to read SP %d", ret);
+      error_.error_code = BACKTRACE_UNWIND_ERROR_ACCESS_REG_FAILED;
+      error_.error_info.regno = UNW_REG_SP;
       break;
     }
 
     if (num_ignore_frames == 0) {
+      backtrace_map_t map;
+      FillInMap(pc, &map);
+      if (map.start == 0 || (map.flags & PROT_EXEC) == 0) {
+        // .eh_frame and .ARM.exidx doesn't know how to unwind from instructions setting up or
+        // destroying stack frames. It can lead to wrong callchains, which may contain pcs outside
+        // executable mapping areas. Stop unwinding once this is detected.
+        error_.error_code = BACKTRACE_UNWIND_ERROR_MAP_MISSING;
+        break;
+      }
       frames_.resize(num_frames + 1);
       backtrace_frame_data_t* frame = &frames_[num_frames];
       frame->num = num_frames;
@@ -217,15 +230,24 @@
         prev->stack_size = frame->sp - prev->sp;
       }
       frame->func_name = GetFunctionName(frame->pc, &frame->func_offset);
-      FillInMap(frame->pc, &frame->map);
+      frame->map = map;
       num_frames++;
     } else {
       num_ignore_frames--;
     }
     is_debug_frame_used_ = false;
     ret = unw_step(&cursor);
-  } while (ret > 0 && num_frames < MAX_BACKTRACE_FRAMES);
-
+    if (ret <= 0) {
+      if (error_.error_code == BACKTRACE_UNWIND_NO_ERROR) {
+        error_.error_code = BACKTRACE_UNWIND_ERROR_EXECUTE_DWARF_INSTRUCTION_FAILED;
+      }
+      break;
+    }
+    if (num_frames == MAX_BACKTRACE_FRAMES) {
+      error_.error_code = BACKTRACE_UNWIND_ERROR_EXCEED_MAX_FRAMES_LIMIT;
+      break;
+    }
+  }
   unw_destroy_addr_space(addr_space);
   context_ = nullptr;
   return true;
@@ -259,7 +281,17 @@
     return read_size;
   }
   read_size = stack_space_.Read(addr, buffer, bytes);
-  return read_size;
+  if (read_size != 0) {
+    return read_size;
+  }
+  // In some libraries (like /system/lib64/libskia.so), some CIE entries in .eh_frame use
+  // augmentation "P", which makes libunwind/libunwindstack try to read personality routine in
+  // memory. However, that is not available in offline unwinding. Work around this by returning
+  // all zero data.
+  error_.error_code = BACKTRACE_UNWIND_ERROR_ACCESS_MEM_FAILED;
+  error_.error_info.addr = addr;
+  memset(buffer, 0, bytes);
+  return bytes;
 }
 
 bool BacktraceOffline::FindProcInfo(unw_addr_space_t addr_space, uint64_t ip,
@@ -267,13 +299,17 @@
   backtrace_map_t map;
   FillInMap(ip, &map);
   if (!BacktraceMap::IsValid(map)) {
+    error_.error_code = BACKTRACE_UNWIND_ERROR_FIND_PROC_INFO_FAILED;
     return false;
   }
   const std::string& filename = map.name;
   DebugFrameInfo* debug_frame = GetDebugFrameInFile(filename);
   if (debug_frame == nullptr) {
+    error_.error_code = BACKTRACE_UNWIND_ERROR_FIND_PROC_INFO_FAILED;
     return false;
   }
+  // Each FindProcInfo() is a new attempt to unwind, so reset the reason.
+  error_.error_code = BACKTRACE_UNWIND_NO_ERROR;
 
   eh_frame_hdr_space_.Clear();
   eh_frame_space_.Clear();
@@ -290,6 +326,23 @@
   // entry, it thinks that an ip address hits an entry when (entry.addr <= ip < next_entry.addr).
   // To prevent ip addresses hit in .eh_frame/.debug_frame being regarded as addresses hit in
   // .ARM.exidx, we need to check .eh_frame/.debug_frame first.
+
+  // Check .debug_frame/.gnu_debugdata before .eh_frame, because .debug_frame can unwind from
+  // instructions setting up or destroying stack frames, while .eh_frame can't.
+  if (!is_debug_frame_used_ && (debug_frame->has_debug_frame || debug_frame->has_gnu_debugdata)) {
+    is_debug_frame_used_ = true;
+    unw_dyn_info_t di;
+    unw_word_t segbase = map.start - debug_frame->min_vaddr;
+    // TODO: http://b/32916571
+    // TODO: Do it ourselves is more efficient than calling libunwind functions.
+    int found = dwarf_find_debug_frame(0, &di, ip, segbase, filename.c_str(), map.start, map.end);
+    if (found == 1) {
+      int ret = dwarf_search_unwind_table(addr_space, ip, &di, proc_info, need_unwind_info, this);
+      if (ret == 0) {
+        return true;
+      }
+    }
+  }
   if (debug_frame->has_eh_frame) {
     if (ip_vaddr >= debug_frame->eh_frame.min_func_vaddr &&
         ip_vaddr < debug_frame->text_end_vaddr) {
@@ -319,20 +372,6 @@
       }
     }
   }
-  if (!is_debug_frame_used_ && (debug_frame->has_debug_frame || debug_frame->has_gnu_debugdata)) {
-    is_debug_frame_used_ = true;
-    unw_dyn_info_t di;
-    unw_word_t segbase = map.start - debug_frame->min_vaddr;
-    // TODO: http://b/32916571
-    // TODO: Do it ourselves is more efficient than calling libunwind functions.
-    int found = dwarf_find_debug_frame(0, &di, ip, segbase, filename.c_str(), map.start, map.end);
-    if (found == 1) {
-      int ret = dwarf_search_unwind_table(addr_space, ip, &di, proc_info, need_unwind_info, this);
-      if (ret == 0) {
-        return true;
-      }
-    }
-  }
 
   if (debug_frame->has_arm_exidx) {
     auto& func_vaddrs = debug_frame->arm_exidx.func_vaddr_array;
@@ -367,6 +406,7 @@
       }
     }
   }
+  error_.error_code = BACKTRACE_UNWIND_ERROR_FIND_PROC_INFO_FAILED;
   return false;
 }
 
@@ -548,6 +588,10 @@
   UNUSED(value);
   result = false;
 #endif
+  if (!result) {
+    error_.error_code = BACKTRACE_UNWIND_ERROR_ACCESS_REG_FAILED;
+    error_.error_info.regno = reg;
+  }
   return result;
 }
 
@@ -586,14 +630,14 @@
   return debug_frame;
 }
 
-static bool OmitEncodedValue(uint8_t encode, const uint8_t*& p) {
+static bool OmitEncodedValue(uint8_t encode, const uint8_t*& p, bool is_elf64) {
   if (encode == DW_EH_PE_omit) {
     return 0;
   }
   uint8_t format = encode & 0x0f;
   switch (format) {
     case DW_EH_PE_ptr:
-      p += sizeof(unw_word_t);
+      p += is_elf64 ? 8 : 4;
       break;
     case DW_EH_PE_uleb128:
     case DW_EH_PE_sleb128:
@@ -621,7 +665,7 @@
 }
 
 static bool GetFdeTableOffsetInEhFrameHdr(const std::vector<uint8_t>& data,
-                                          uint64_t* table_offset_in_eh_frame_hdr) {
+                                          uint64_t* table_offset_in_eh_frame_hdr, bool is_elf64) {
   const uint8_t* p = data.data();
   const uint8_t* end = p + data.size();
   if (p + 4 > end) {
@@ -639,7 +683,8 @@
     return false;
   }
 
-  if (!OmitEncodedValue(eh_frame_ptr_encode, p) || !OmitEncodedValue(fde_count_encode, p)) {
+  if (!OmitEncodedValue(eh_frame_ptr_encode, p, is_elf64) ||
+      !OmitEncodedValue(fde_count_encode, p, is_elf64)) {
     return false;
   }
   if (p >= end) {
@@ -649,11 +694,214 @@
   return true;
 }
 
+static uint64_t ReadFromBuffer(const uint8_t*& p, size_t size) {
+  uint64_t result = 0;
+  int shift = 0;
+  while (size-- > 0) {
+    uint64_t tmp = *p++;
+    result |= tmp << shift;
+    shift += 8;
+  }
+  return result;
+}
+
+static uint64_t ReadSignValueFromBuffer(const uint8_t*& p, size_t size) {
+  uint64_t result = 0;
+  int shift = 0;
+  for (size_t i = 0; i < size; ++i) {
+    uint64_t tmp = *p++;
+    result |= tmp << shift;
+    shift += 8;
+  }
+  if (*(p - 1) & 0x80) {
+    result |= (-1ULL) << (size * 8);
+  }
+  return result;
+}
+
+static const char* ReadStrFromBuffer(const uint8_t*& p) {
+  const char* result = reinterpret_cast<const char*>(p);
+  p += strlen(result) + 1;
+  return result;
+}
+
+static int64_t ReadLEB128FromBuffer(const uint8_t*& p) {
+  int64_t result = 0;
+  int64_t tmp;
+  int shift = 0;
+  while (*p & 0x80) {
+    tmp = *p & 0x7f;
+    result |= tmp << shift;
+    shift += 7;
+    p++;
+  }
+  tmp = *p;
+  result |= tmp << shift;
+  if (*p & 0x40) {
+    result |= -((tmp & 0x40) << shift);
+  }
+  p++;
+  return result;
+}
+
+static uint64_t ReadULEB128FromBuffer(const uint8_t*& p) {
+  uint64_t result = 0;
+  uint64_t tmp;
+  int shift = 0;
+  while (*p & 0x80) {
+    tmp = *p & 0x7f;
+    result |= tmp << shift;
+    shift += 7;
+    p++;
+  }
+  tmp = *p;
+  result |= tmp << shift;
+  p++;
+  return result;
+}
+
+static uint64_t ReadEhEncoding(const uint8_t*& p, uint8_t encoding, bool is_elf64,
+                               uint64_t section_vaddr, const uint8_t* section_begin) {
+  const uint8_t* init_addr = p;
+  uint64_t result = 0;
+  switch (encoding & 0x0f) {
+    case DW_EH_PE_absptr:
+      result = ReadFromBuffer(p, is_elf64 ? 8 : 4);
+      break;
+    case DW_EH_PE_omit:
+      result = 0;
+      break;
+    case DW_EH_PE_uleb128:
+      result = ReadULEB128FromBuffer(p);
+      break;
+    case DW_EH_PE_udata2:
+      result = ReadFromBuffer(p, 2);
+      break;
+    case DW_EH_PE_udata4:
+      result = ReadFromBuffer(p, 4);
+      break;
+    case DW_EH_PE_udata8:
+      result = ReadFromBuffer(p, 8);
+      break;
+    case DW_EH_PE_sleb128:
+      result = ReadLEB128FromBuffer(p);
+      break;
+    case DW_EH_PE_sdata2:
+      result = ReadSignValueFromBuffer(p, 2);
+      break;
+    case DW_EH_PE_sdata4:
+      result = ReadSignValueFromBuffer(p, 4);
+      break;
+    case DW_EH_PE_sdata8:
+      result = ReadSignValueFromBuffer(p, 8);
+      break;
+  }
+  switch (encoding & 0xf0) {
+    case DW_EH_PE_pcrel:
+      result += init_addr - section_begin + section_vaddr;
+      break;
+    case DW_EH_PE_datarel:
+      result += section_vaddr;
+      break;
+  }
+  return result;
+}
+
+static bool BuildEhFrameHdr(DebugFrameInfo* info, bool is_elf64) {
+  // For each fde entry, collect its (func_vaddr, fde_vaddr) pair.
+  std::vector<std::pair<uint64_t, uint64_t>> index_table;
+  // Map form cie_offset to fde encoding.
+  std::unordered_map<size_t, uint8_t> cie_map;
+  const uint8_t* eh_frame_begin = info->eh_frame.data.data();
+  const uint8_t* eh_frame_end = eh_frame_begin + info->eh_frame.data.size();
+  const uint8_t* p = eh_frame_begin;
+  uint64_t eh_frame_vaddr = info->eh_frame.vaddr;
+  while (p < eh_frame_end) {
+    const uint8_t* unit_begin = p;
+    uint64_t unit_len = ReadFromBuffer(p, 4);
+    size_t secbytes = 4;
+    if (unit_len == 0xffffffff) {
+      unit_len = ReadFromBuffer(p, 8);
+      secbytes = 8;
+    }
+    const uint8_t* unit_end = p + unit_len;
+    uint64_t cie_id = ReadFromBuffer(p, secbytes);
+    if (cie_id == 0) {
+      // This is a CIE.
+      // Read version
+      uint8_t version = *p++;
+      // Read augmentation
+      const char* augmentation = ReadStrFromBuffer(p);
+      if (version >= 4) {
+        // Read address size and segment size
+        p += 2;
+      }
+      // Read code alignment factor
+      ReadULEB128FromBuffer(p);
+      // Read data alignment factor
+      ReadLEB128FromBuffer(p);
+      // Read return address register
+      if (version == 1) {
+        p++;
+      } else {
+        ReadULEB128FromBuffer(p);
+      }
+      uint8_t fde_pointer_encoding = 0;
+      if (augmentation[0] == 'z') {
+        // Read augmentation length.
+        ReadULEB128FromBuffer(p);
+        for (int i = 1; augmentation[i] != '\0'; ++i) {
+          char c = augmentation[i];
+          if (c == 'R') {
+            fde_pointer_encoding = *p++;
+          } else if (c == 'P') {
+            // Read personality handler
+            uint8_t encoding = *p++;
+            OmitEncodedValue(encoding, p, is_elf64);
+          } else if (c == 'L') {
+            // Read lsda encoding
+            p++;
+          }
+        }
+      }
+      cie_map[unit_begin - eh_frame_begin] = fde_pointer_encoding;
+    } else {
+      // This is an FDE.
+      size_t cie_offset = p - secbytes - eh_frame_begin - cie_id;
+      auto it = cie_map.find(cie_offset);
+      if (it != cie_map.end()) {
+        uint8_t fde_pointer_encoding = it->second;
+        uint64_t initial_location =
+            ReadEhEncoding(p, fde_pointer_encoding, is_elf64, eh_frame_vaddr, eh_frame_begin);
+        uint64_t fde_vaddr = unit_begin - eh_frame_begin + eh_frame_vaddr;
+        index_table.push_back(std::make_pair(initial_location, fde_vaddr));
+      }
+    }
+    p = unit_end;
+  }
+  if (index_table.empty()) {
+    return false;
+  }
+  std::sort(index_table.begin(), index_table.end());
+  info->eh_frame.hdr_vaddr = 0;
+  info->eh_frame.hdr_data.resize(index_table.size() * 8);
+  uint32_t* ptr = reinterpret_cast<uint32_t*>(info->eh_frame.hdr_data.data());
+  for (auto& pair : index_table) {
+    *ptr++ = static_cast<uint32_t>(pair.first - info->eh_frame.hdr_vaddr);
+    *ptr++ = static_cast<uint32_t>(pair.second - info->eh_frame.hdr_vaddr);
+  }
+  info->eh_frame.fde_table_offset = 0;
+  info->eh_frame.min_func_vaddr = index_table[0].first;
+  return true;
+}
+
 template <class ELFT>
 DebugFrameInfo* ReadDebugFrameFromELFFile(const llvm::object::ELFFile<ELFT>* elf) {
   DebugFrameInfo* result = new DebugFrameInfo;
+  result->eh_frame.hdr_vaddr = 0;
   result->text_end_vaddr = std::numeric_limits<uint64_t>::max();
 
+  bool is_elf64 = (elf->getHeader()->getFileClass() == llvm::ELF::ELFCLASS64);
   bool has_eh_frame_hdr = false;
   bool has_eh_frame = false;
 
@@ -673,8 +921,7 @@
               data->data(), data->data() + data->size());
 
           uint64_t fde_table_offset;
-          if (GetFdeTableOffsetInEhFrameHdr(result->eh_frame.hdr_data,
-                                             &fde_table_offset)) {
+          if (GetFdeTableOffsetInEhFrameHdr(result->eh_frame.hdr_data, &fde_table_offset, is_elf64)) {
             result->eh_frame.fde_table_offset = fde_table_offset;
             // Make sure we have at least one entry in fde_table.
             if (fde_table_offset + 2 * sizeof(int32_t) <= data->size()) {
@@ -731,6 +978,18 @@
     }
   }
 
+  if (has_eh_frame) {
+    if (!has_eh_frame_hdr) {
+      // Some libraries (like /vendor/lib64/egl/eglSubDriverAndroid.so) contain empty
+      // .eh_frame_hdr.
+      if (BuildEhFrameHdr(result, is_elf64)) {
+        has_eh_frame_hdr = true;
+      }
+    }
+    if (has_eh_frame_hdr) {
+      result->has_eh_frame = true;
+    }
+  }
   if (has_eh_frame_hdr && has_eh_frame) {
     result->has_eh_frame = true;
   }
diff --git a/libbacktrace/BacktraceOffline.h b/libbacktrace/BacktraceOffline.h
index 70a9842..fcde379 100644
--- a/libbacktrace/BacktraceOffline.h
+++ b/libbacktrace/BacktraceOffline.h
@@ -32,9 +32,7 @@
   uint64_t end;
   const uint8_t* data;
 
-  Space() {
-    Clear();
-  }
+  Space() { Clear(); }
 
   void Clear();
   size_t Read(uint64_t addr, uint8_t* buffer, size_t size);
diff --git a/libbacktrace/UnwindCurrent.cpp b/libbacktrace/UnwindCurrent.cpp
index 2c87fa8..3ccf13c 100644
--- a/libbacktrace/UnwindCurrent.cpp
+++ b/libbacktrace/UnwindCurrent.cpp
@@ -81,7 +81,7 @@
     int ret = unw_getcontext(&context_);
     if (ret < 0) {
       BACK_LOGW("unw_getcontext failed %d", ret);
-      error_ = BACKTRACE_UNWIND_ERROR_SETUP_FAILED;
+      error_.error_code = BACKTRACE_UNWIND_ERROR_SETUP_FAILED;
       return false;
     }
   } else {
@@ -93,7 +93,7 @@
   int ret = unw_init_local(cursor.get(), &context_);
   if (ret < 0) {
     BACK_LOGW("unw_init_local failed %d", ret);
-    error_ = BACKTRACE_UNWIND_ERROR_SETUP_FAILED;
+    error_.error_code = BACKTRACE_UNWIND_ERROR_SETUP_FAILED;
     return false;
   }
   initialized_ = true;
diff --git a/libbacktrace/UnwindPtrace.cpp b/libbacktrace/UnwindPtrace.cpp
index 87282ef..2155b8a 100644
--- a/libbacktrace/UnwindPtrace.cpp
+++ b/libbacktrace/UnwindPtrace.cpp
@@ -62,7 +62,7 @@
   addr_space_ = unw_create_addr_space(&_UPT_accessors, 0);
   if (!addr_space_) {
     BACK_LOGW("unw_create_addr_space failed.");
-    error_ = BACKTRACE_UNWIND_ERROR_SETUP_FAILED;
+    error_.error_code = BACKTRACE_UNWIND_ERROR_SETUP_FAILED;
     return false;
   }
 
@@ -72,7 +72,7 @@
   upt_info_ = reinterpret_cast<struct UPT_info*>(_UPT_create(Tid()));
   if (!upt_info_) {
     BACK_LOGW("Failed to create upt info.");
-    error_ = BACKTRACE_UNWIND_ERROR_SETUP_FAILED;
+    error_.error_code = BACKTRACE_UNWIND_ERROR_SETUP_FAILED;
     return false;
   }
 
@@ -82,15 +82,15 @@
 bool UnwindPtrace::Unwind(size_t num_ignore_frames, ucontext_t* ucontext) {
   if (GetMap() == nullptr) {
     // Without a map object, we can't do anything.
-    error_ = BACKTRACE_UNWIND_ERROR_MAP_MISSING;
+    error_.error_code = BACKTRACE_UNWIND_ERROR_MAP_MISSING;
     return false;
   }
 
-  error_ = BACKTRACE_UNWIND_NO_ERROR;
+  error_.error_code = BACKTRACE_UNWIND_NO_ERROR;
 
   if (ucontext) {
     BACK_LOGW("Unwinding from a specified context not supported yet.");
-    error_ = BACKTRACE_UNWIND_ERROR_UNSUPPORTED_OPERATION;
+    error_.error_code = BACKTRACE_UNWIND_ERROR_UNSUPPORTED_OPERATION;
     return false;
   }
 
@@ -102,7 +102,7 @@
   int ret = unw_init_remote(&cursor, addr_space_, upt_info_);
   if (ret < 0) {
     BACK_LOGW("unw_init_remote failed %d", ret);
-    error_ = BACKTRACE_UNWIND_ERROR_SETUP_FAILED;
+    error_.error_code = BACKTRACE_UNWIND_ERROR_SETUP_FAILED;
     return false;
   }
 
diff --git a/libbacktrace/UnwindStack.cpp b/libbacktrace/UnwindStack.cpp
index 56a6c68..b0345a1 100644
--- a/libbacktrace/UnwindStack.cpp
+++ b/libbacktrace/UnwindStack.cpp
@@ -50,6 +50,7 @@
   auto process_memory = stack_map->process_memory();
   unwindstack::Unwinder unwinder(MAX_BACKTRACE_FRAMES + num_ignore_frames, stack_map->stack_maps(),
                                  regs, stack_map->process_memory());
+  unwinder.SetJitDebug(stack_map->GetJitDebug(), regs->Arch());
   unwinder.Unwind(skip_names, &stack_map->GetSuffixesToIgnore());
 
   if (num_ignore_frames >= unwinder.NumFrames()) {
@@ -102,7 +103,7 @@
     regs.reset(unwindstack::Regs::CreateFromUcontext(unwindstack::Regs::CurrentArch(), ucontext));
   }
 
-  error_ = BACKTRACE_UNWIND_NO_ERROR;
+  error_.error_code = BACKTRACE_UNWIND_NO_ERROR;
   std::vector<std::string> skip_names{"libunwindstack.so", "libbacktrace.so"};
   return Backtrace::Unwind(regs.get(), GetMap(), &frames_, num_ignore_frames, &skip_names);
 }
@@ -122,7 +123,7 @@
     regs.reset(unwindstack::Regs::CreateFromUcontext(unwindstack::Regs::CurrentArch(), context));
   }
 
-  error_ = BACKTRACE_UNWIND_NO_ERROR;
+  error_.error_code = BACKTRACE_UNWIND_NO_ERROR;
   return Backtrace::Unwind(regs.get(), GetMap(), &frames_, num_ignore_frames, nullptr);
 }
 
diff --git a/libbacktrace/UnwindStackMap.cpp b/libbacktrace/UnwindStackMap.cpp
index 836a774..93406dc 100644
--- a/libbacktrace/UnwindStackMap.cpp
+++ b/libbacktrace/UnwindStackMap.cpp
@@ -18,6 +18,9 @@
 #include <stdlib.h>
 #include <sys/types.h>
 
+#include <string>
+#include <vector>
+
 #include <backtrace/BacktraceMap.h>
 #include <unwindstack/Elf.h>
 #include <unwindstack/MapInfo.h>
@@ -39,6 +42,10 @@
   // Create the process memory object.
   process_memory_ = unwindstack::Memory::CreateProcessMemory(pid_);
 
+  // Create a JitDebug object for getting jit unwind information.
+  std::vector<std::string> search_libs_{"libart.so", "libartd.so"};
+  jit_debug_.reset(new unwindstack::JitDebug(process_memory_, search_libs_));
+
   if (!stack_maps_->Parse()) {
     return false;
   }
diff --git a/libbacktrace/UnwindStackMap.h b/libbacktrace/UnwindStackMap.h
index 2f63655..12c5909 100644
--- a/libbacktrace/UnwindStackMap.h
+++ b/libbacktrace/UnwindStackMap.h
@@ -23,6 +23,7 @@
 #include <memory>
 
 #include <backtrace/BacktraceMap.h>
+#include <unwindstack/JitDebug.h>
 #include <unwindstack/Maps.h>
 
 class UnwindStackMap : public BacktraceMap {
@@ -41,11 +42,14 @@
 
   const std::shared_ptr<unwindstack::Memory>& process_memory() { return process_memory_; }
 
+  unwindstack::JitDebug* GetJitDebug() { return jit_debug_.get(); }
+
  protected:
   uint64_t GetLoadBias(size_t index) override;
 
   std::unique_ptr<unwindstack::Maps> stack_maps_;
   std::shared_ptr<unwindstack::Memory> process_memory_;
+  std::unique_ptr<unwindstack::JitDebug> jit_debug_;
 };
 
 #endif  // _LIBBACKTRACE_UNWINDSTACK_MAP_H
diff --git a/libbacktrace/backtrace_offline_test.cpp b/libbacktrace/backtrace_offline_test.cpp
index 9ba2b1c..e92bc61 100644
--- a/libbacktrace/backtrace_offline_test.cpp
+++ b/libbacktrace/backtrace_offline_test.cpp
@@ -252,13 +252,41 @@
         return false;
       }
       HexStringToRawData(&line[pos], &testdata->unw_context, size);
-#if defined(__arm__)
     } else if (android::base::StartsWith(line, "regs:")) {
-      uint64_t pc;
-      uint64_t sp;
-      sscanf(line.c_str(), "regs: pc: %" SCNx64 " sp: %" SCNx64, &pc, &sp);
-      testdata->unw_context.regs[13] = sp;
-      testdata->unw_context.regs[15] = pc;
+      std::vector<std::string> strs = android::base::Split(line.substr(6), " ");
+      if (strs.size() % 2 != 0) {
+        return false;
+      }
+      std::vector<std::pair<std::string, uint64_t>> items;
+      for (size_t i = 0; i + 1 < strs.size(); i += 2) {
+        if (!android::base::EndsWith(strs[i], ":")) {
+          return false;
+        }
+        uint64_t value = std::stoul(strs[i + 1], nullptr, 16);
+        items.push_back(std::make_pair(strs[i].substr(0, strs[i].size() - 1), value));
+      }
+#if defined(__arm__)
+      for (auto& item : items) {
+        if (item.first == "sp") {
+          testdata->unw_context.regs[13] = item.second;
+        } else if (item.first == "pc") {
+          testdata->unw_context.regs[15] = item.second;
+        } else {
+          return false;
+        }
+      }
+#elif defined(__aarch64__)
+      for (auto& item : items) {
+        if (item.first == "pc") {
+          testdata->unw_context.uc_mcontext.pc = item.second;
+        } else if (item.first == "sp") {
+          testdata->unw_context.uc_mcontext.sp = item.second;
+        } else if (item.first == "x29") {
+          testdata->unw_context.uc_mcontext.regs[UNW_AARCH64_X29] = item.second;
+        } else {
+          return false;
+        }
+      }
 #endif
     } else if (android::base::StartsWith(line, "stack:")) {
       size_t size;
@@ -397,6 +425,8 @@
     std::string name = FunctionNameForAddress(vaddr_in_file, testdata.symbols);
     ASSERT_EQ(name, testdata.symbols[i].name);
   }
+  ASSERT_TRUE(backtrace->GetError().error_code == BACKTRACE_UNWIND_ERROR_ACCESS_MEM_FAILED ||
+              backtrace->GetError().error_code == BACKTRACE_UNWIND_ERROR_MAP_MISSING);
 }
 
 // This test tests the situation that ranges of functions covered by .eh_frame and .ARM.exidx
@@ -412,3 +442,21 @@
 TEST(libbacktrace, offline_try_armexidx_after_debug_frame) {
   LibUnwindingTest("arm", "offline_testdata_for_libGLESv2_adreno", "libGLESv2_adreno.so");
 }
+
+TEST(libbacktrace, offline_cie_with_P_augmentation) {
+  // Make sure we can unwind through functions with CIE entry containing P augmentation, which
+  // makes unwinding library reading personality handler from memory. One example is
+  // /system/lib64/libskia.so.
+  LibUnwindingTest("arm64", "offline_testdata_for_libskia", "libskia.so");
+}
+
+TEST(libbacktrace, offline_empty_eh_frame_hdr) {
+  // Make sure we can unwind through libraries with empty .eh_frame_hdr section. One example is
+  // /vendor/lib64/egl/eglSubDriverAndroid.so.
+  LibUnwindingTest("arm64", "offline_testdata_for_eglSubDriverAndroid", "eglSubDriverAndroid.so");
+}
+
+TEST(libbacktrace, offline_max_frames_limit) {
+  // The length of callchain can reach 256 when recording an application.
+  ASSERT_GE(MAX_BACKTRACE_FRAMES, 256);
+}
diff --git a/libbacktrace/backtrace_test.cpp b/libbacktrace/backtrace_test.cpp
index 890ab3f..57b7553 100644
--- a/libbacktrace/backtrace_test.cpp
+++ b/libbacktrace/backtrace_test.cpp
@@ -189,7 +189,7 @@
       Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
   ASSERT_TRUE(backtrace.get() != nullptr);
   ASSERT_TRUE(backtrace->Unwind(0));
-  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError());
+  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError().error_code);
 
   VerifyLevelDump(backtrace.get());
 }
@@ -211,7 +211,7 @@
       Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
   ASSERT_TRUE(backtrace.get() != nullptr);
   ASSERT_TRUE(backtrace->Unwind(0));
-  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError());
+  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError().error_code);
 
   VerifyMaxDump(backtrace.get());
 }
@@ -241,7 +241,7 @@
   std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), getpid()));
   ASSERT_TRUE(backtrace.get() != nullptr);
   ASSERT_TRUE(backtrace->Unwind(0));
-  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError());
+  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError().error_code);
 
   ASSERT_TRUE(backtrace->NumFrames() != 0);
   for (const auto& frame : *backtrace ) {
@@ -292,19 +292,19 @@
       Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
   ASSERT_TRUE(all.get() != nullptr);
   ASSERT_TRUE(all->Unwind(0));
-  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, all->GetError());
+  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, all->GetError().error_code);
 
   std::unique_ptr<Backtrace> ign1(
       Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
   ASSERT_TRUE(ign1.get() != nullptr);
   ASSERT_TRUE(ign1->Unwind(1));
-  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, ign1->GetError());
+  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, ign1->GetError().error_code);
 
   std::unique_ptr<Backtrace> ign2(
       Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
   ASSERT_TRUE(ign2.get() != nullptr);
   ASSERT_TRUE(ign2->Unwind(2));
-  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, ign2->GetError());
+  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, ign2->GetError().error_code);
 
   VerifyIgnoreFrames(all.get(), ign1.get(), ign2.get(), "VerifyLevelIgnoreFrames");
 }
@@ -340,7 +340,7 @@
       std::unique_ptr<Backtrace> backtrace(create_func(pid, tid, map.get()));
       ASSERT_TRUE(backtrace.get() != nullptr);
       ASSERT_TRUE(backtrace->Unwind(0));
-      ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError());
+      ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError().error_code);
       if (ReadyFunc(backtrace.get())) {
         VerifyFunc(backtrace.get(), create_func, map_create_func);
         verified = true;
@@ -389,12 +389,12 @@
   std::unique_ptr<Backtrace> ign1(create_func(bt_all->Pid(), BACKTRACE_CURRENT_THREAD, map.get()));
   ASSERT_TRUE(ign1.get() != nullptr);
   ASSERT_TRUE(ign1->Unwind(1));
-  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, ign1->GetError());
+  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, ign1->GetError().error_code);
 
   std::unique_ptr<Backtrace> ign2(create_func(bt_all->Pid(), BACKTRACE_CURRENT_THREAD, map.get()));
   ASSERT_TRUE(ign2.get() != nullptr);
   ASSERT_TRUE(ign2->Unwind(2));
-  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, ign2->GetError());
+  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, ign2->GetError().error_code);
 
   VerifyIgnoreFrames(bt_all, ign1.get(), ign2.get(), nullptr);
 }
@@ -480,7 +480,7 @@
   std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), gettid()));
   ASSERT_TRUE(backtrace.get() != nullptr);
   ASSERT_TRUE(backtrace->Unwind(0));
-  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError());
+  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError().error_code);
 
   VerifyLevelDump(backtrace.get());
 }
@@ -493,7 +493,7 @@
   std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), gettid()));
   ASSERT_TRUE(backtrace.get() != nullptr);
   ASSERT_TRUE(backtrace->Unwind(0));
-  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError());
+  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError().error_code);
 
   VerifyMaxDump(backtrace.get());
 }
@@ -535,7 +535,7 @@
   std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), thread_data.tid));
   ASSERT_TRUE(backtrace.get() != nullptr);
   ASSERT_TRUE(backtrace->Unwind(0));
-  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError());
+  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError().error_code);
 
   VerifyLevelDump(backtrace.get());
 
@@ -575,17 +575,17 @@
   std::unique_ptr<Backtrace> all(Backtrace::Create(getpid(), thread_data.tid));
   ASSERT_TRUE(all.get() != nullptr);
   ASSERT_TRUE(all->Unwind(0));
-  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, all->GetError());
+  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, all->GetError().error_code);
 
   std::unique_ptr<Backtrace> ign1(Backtrace::Create(getpid(), thread_data.tid));
   ASSERT_TRUE(ign1.get() != nullptr);
   ASSERT_TRUE(ign1->Unwind(1));
-  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, ign1->GetError());
+  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, ign1->GetError().error_code);
 
   std::unique_ptr<Backtrace> ign2(Backtrace::Create(getpid(), thread_data.tid));
   ASSERT_TRUE(ign2.get() != nullptr);
   ASSERT_TRUE(ign2->Unwind(2));
-  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, ign2->GetError());
+  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, ign2->GetError().error_code);
 
   VerifyIgnoreFrames(all.get(), ign1.get(), ign2.get(), nullptr);
 
@@ -616,7 +616,7 @@
   std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), thread_data.tid));
   ASSERT_TRUE(backtrace.get() != nullptr);
   ASSERT_TRUE(backtrace->Unwind(0));
-  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError());
+  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError().error_code);
 
   VerifyMaxDump(backtrace.get());
 
@@ -713,21 +713,21 @@
   Backtrace* back1 = Backtrace::Create(getpid(), BACKTRACE_CURRENT_THREAD, map1);
   ASSERT_TRUE(back1 != nullptr);
   EXPECT_TRUE(back1->Unwind(0));
-  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, back1->GetError());
+  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, back1->GetError().error_code);
   delete back1;
   delete map1;
 
   Backtrace* back2 = Backtrace::Create(getpid(), BACKTRACE_CURRENT_THREAD, map2);
   ASSERT_TRUE(back2 != nullptr);
   EXPECT_TRUE(back2->Unwind(0));
-  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, back2->GetError());
+  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, back2->GetError().error_code);
   delete back2;
   delete map2;
 
   Backtrace* back3 = Backtrace::Create(getpid(), BACKTRACE_CURRENT_THREAD, map3);
   ASSERT_TRUE(back3 != nullptr);
   EXPECT_TRUE(back3->Unwind(0));
-  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, back3->GetError());
+  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, back3->GetError().error_code);
   delete back3;
   delete map3;
 }
@@ -1331,7 +1331,7 @@
                                                          BACKTRACE_CURRENT_THREAD));
   ASSERT_TRUE(backtrace.get() != nullptr);
   ASSERT_TRUE(backtrace->Unwind(0));
-  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError());
+  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError().error_code);
 
   size_t frame_num;
   ASSERT_TRUE(FindFuncFrameInBacktrace(backtrace.get(), test_func, &frame_num));
@@ -1388,7 +1388,7 @@
     std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, BACKTRACE_CURRENT_THREAD));
     ASSERT_TRUE(backtrace.get() != nullptr);
     ASSERT_TRUE(backtrace->Unwind(0));
-    ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError());
+    ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError().error_code);
 
     size_t frame_num;
     if (FindFuncFrameInBacktrace(backtrace.get(),
@@ -1417,7 +1417,7 @@
       Backtrace::Create(BACKTRACE_CURRENT_PROCESS, 99999999));
   ASSERT_TRUE(backtrace.get() != nullptr);
   ASSERT_FALSE(backtrace->Unwind(0));
-  ASSERT_EQ(BACKTRACE_UNWIND_ERROR_THREAD_DOESNT_EXIST, backtrace->GetError());
+  ASSERT_EQ(BACKTRACE_UNWIND_ERROR_THREAD_DOESNT_EXIST, backtrace->GetError().error_code);
 }
 
 TEST(libbacktrace, local_get_function_name_before_unwind) {
@@ -1785,7 +1785,7 @@
     Backtrace* backtrace = Backtrace::Create(pid, tid, map.get());
     ASSERT_TRUE(backtrace != nullptr);
     ASSERT_TRUE(backtrace->Unwind(0));
-    ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError());
+    ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError().error_code);
     delete backtrace;
   }
   size_t stable_pss = GetPssBytes();
@@ -1796,7 +1796,7 @@
     Backtrace* backtrace = Backtrace::Create(pid, tid, map.get());
     ASSERT_TRUE(backtrace != nullptr);
     ASSERT_TRUE(backtrace->Unwind(0));
-    ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError());
+    ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError().error_code);
     delete backtrace;
   }
   size_t new_pss = GetPssBytes();
diff --git a/libbacktrace/include/backtrace/Backtrace.h b/libbacktrace/include/backtrace/Backtrace.h
index e073533..5922664 100644
--- a/libbacktrace/include/backtrace/Backtrace.h
+++ b/libbacktrace/include/backtrace/Backtrace.h
@@ -34,7 +34,7 @@
 typedef uint32_t word_t;
 #endif
 
-enum BacktraceUnwindError : uint32_t {
+enum BacktraceUnwindErrorCode : uint32_t {
   BACKTRACE_UNWIND_NO_ERROR,
   // Something failed while trying to perform the setup to begin the unwind.
   BACKTRACE_UNWIND_ERROR_SETUP_FAILED,
@@ -50,6 +50,29 @@
   BACKTRACE_UNWIND_ERROR_UNSUPPORTED_OPERATION,
   // Attempt to do an offline unwind without a context.
   BACKTRACE_UNWIND_ERROR_NO_CONTEXT,
+  // The count of frames exceed MAX_BACKTRACE_FRAMES.
+  BACKTRACE_UNWIND_ERROR_EXCEED_MAX_FRAMES_LIMIT,
+  // Failed to read memory.
+  BACKTRACE_UNWIND_ERROR_ACCESS_MEM_FAILED,
+  // Failed to read registers.
+  BACKTRACE_UNWIND_ERROR_ACCESS_REG_FAILED,
+  // Failed to find a function in debug sections.
+  BACKTRACE_UNWIND_ERROR_FIND_PROC_INFO_FAILED,
+  // Failed to execute dwarf instructions in debug sections.
+  BACKTRACE_UNWIND_ERROR_EXECUTE_DWARF_INSTRUCTION_FAILED,
+};
+
+struct BacktraceUnwindError {
+  enum BacktraceUnwindErrorCode error_code;
+
+  union {
+    // for BACKTRACE_UNWIND_ERROR_ACCESS_MEM_FAILED
+    uint64_t addr;
+    // for BACKTRACE_UNWIND_ERROR_ACCESS_REG_FAILED
+    uint64_t regno;
+  } error_info;
+
+  BacktraceUnwindError() : error_code(BACKTRACE_UNWIND_NO_ERROR) {}
 };
 
 struct backtrace_frame_data_t {
diff --git a/libbacktrace/include/backtrace/backtrace_constants.h b/libbacktrace/include/backtrace/backtrace_constants.h
index 373a1e5..1a2da36 100644
--- a/libbacktrace/include/backtrace/backtrace_constants.h
+++ b/libbacktrace/include/backtrace/backtrace_constants.h
@@ -25,6 +25,6 @@
 // current thread of the specified pid.
 #define BACKTRACE_CURRENT_THREAD (-1)
 
-#define MAX_BACKTRACE_FRAMES 64
+#define MAX_BACKTRACE_FRAMES 256
 
 #endif // _BACKTRACE_BACKTRACE_CONSTANTS_H
diff --git a/libbacktrace/testdata/arm64/eglSubDriverAndroid.so b/libbacktrace/testdata/arm64/eglSubDriverAndroid.so
new file mode 100644
index 0000000..10ce06b
--- /dev/null
+++ b/libbacktrace/testdata/arm64/eglSubDriverAndroid.so
Binary files differ
diff --git a/libbacktrace/testdata/arm64/libskia.so b/libbacktrace/testdata/arm64/libskia.so
new file mode 100644
index 0000000..ef1a6a1
--- /dev/null
+++ b/libbacktrace/testdata/arm64/libskia.so
Binary files differ
diff --git a/libbacktrace/testdata/arm64/offline_testdata_for_eglSubDriverAndroid b/libbacktrace/testdata/arm64/offline_testdata_for_eglSubDriverAndroid
new file mode 100644
index 0000000..dfad172
--- /dev/null
+++ b/libbacktrace/testdata/arm64/offline_testdata_for_eglSubDriverAndroid
@@ -0,0 +1,6 @@
+pid: 12276 tid: 12303
+regs: pc: 7b8c027f64 sp: 7b8c157010 x29: 7b8c157040
+map: start: 7b8c01e000 end: 7b8c030000 offset: 0 load_bias: 0 flags: 5 name: /vendor/lib64/egl/eglSubDriverAndroid.so
+stack: start: 7b8c157048 end: 7b8c157050 size: 8 547e028c7b000000
+function: start: 9ed8 end: a1b0 name: EglAndroidWindowSurface::Initialize(EglAndroidConfig*, int const*)
+function: start: 9dcc end: 9ed8 name: EglAndroidWindowSurface::Create(ANativeWindow*, EglAndroidConfig*, EglAndroidWindowSurface**, int const*)
diff --git a/libbacktrace/testdata/arm64/offline_testdata_for_libskia b/libbacktrace/testdata/arm64/offline_testdata_for_libskia
new file mode 100644
index 0000000..1027c55
--- /dev/null
+++ b/libbacktrace/testdata/arm64/offline_testdata_for_libskia
@@ -0,0 +1,6 @@
+pid: 32232 tid: 32233
+regs: pc: 7c25189a0c sp: 7b8c154b50 x29: 7b8c154bb0
+map: start: 7c24c80000 end: 7c25413000 offset: 0 load_bias: 5f000 flags: 5 name: /system/lib64/libskia.so
+stack: start: 7b8c154bb8 end: 7b8c154bc0 size: 8 ec43f2247c000000
+function: start: 568970 end: 568c08 name: SkScalerContext_FreeType::generateImage(SkGlyph const&)
+function: start: 30330c end: 3044b0 name: SkScalerContext::getImage(SkGlyph const&)
diff --git a/libcutils/Android.bp b/libcutils/Android.bp
index 9cba109..6d00dc6 100644
--- a/libcutils/Android.bp
+++ b/libcutils/Android.bp
@@ -36,7 +36,7 @@
     export_include_dirs: ["include"],
     target: {
         vendor: {
-            export_include_dirs: ["include_vndk"],
+            override_export_include_dirs: ["include_vndk"],
         },
         linux_bionic: {
             enabled: true,
diff --git a/libcutils/fs_config.cpp b/libcutils/fs_config.cpp
index f45472e..7c03663 100644
--- a/libcutils/fs_config.cpp
+++ b/libcutils/fs_config.cpp
@@ -185,11 +185,16 @@
     { 00755, AID_SYSTEM,    AID_GRAPHICS,  CAP_MASK_LONG(CAP_SYS_NICE),
                                               "system/bin/surfaceflinger" },
 
-    // Support hostapd administering a network interface.
+    // Support hostapd administering a network interface (Old Path: <= O-MR1 release).
     { 00755, AID_WIFI,      AID_WIFI,      CAP_MASK_LONG(CAP_NET_ADMIN) |
                                            CAP_MASK_LONG(CAP_NET_RAW),
                                               "vendor/bin/hostapd" },
 
+    // Support hostapd administering a network interface (New Path: >= P release).
+    { 00750, AID_WIFI,      AID_WIFI,      CAP_MASK_LONG(CAP_NET_ADMIN) |
+                                           CAP_MASK_LONG(CAP_NET_RAW),
+                                              "vendor/bin/hw/hostapd" },
+
     // Support Bluetooth legacy hal accessing /sys/class/rfkill
     // Support RT scheduling in Bluetooth
     { 00700, AID_BLUETOOTH, AID_BLUETOOTH, CAP_MASK_LONG(CAP_NET_ADMIN) |
diff --git a/libcutils/include/private/android_filesystem_config.h b/libcutils/include/private/android_filesystem_config.h
index 2ecf5bc..5753e49 100644
--- a/libcutils/include/private/android_filesystem_config.h
+++ b/libcutils/include/private/android_filesystem_config.h
@@ -122,6 +122,9 @@
 #define AID_AUTOMOTIVE_EVS 1062  /* Automotive rear and surround view system */
 #define AID_LOWPAN 1063          /* LoWPAN subsystem */
 #define AID_HSM 1064             /* hardware security module subsystem */
+#define AID_RESERVED_DISK 1065   /* GID that has access to reserved disk space */
+#define AID_STATSD 1066          /* statsd daemon */
+#define AID_INCIDENTD 1067       /* incidentd daemon */
 /* Changes to this file must be made in AOSP, *not* in internal branches. */
 
 #define AID_SHELL 2000 /* adb and debug shell user */
diff --git a/libcutils/tests/fs_config.cpp b/libcutils/tests/fs_config.cpp
index 391adb6..d5dc66a 100644
--- a/libcutils/tests/fs_config.cpp
+++ b/libcutils/tests/fs_config.cpp
@@ -81,7 +81,7 @@
         }
 
         // check if path is <partition>/
-        if (android::base::StartsWith(path, prefix.c_str())) {
+        if (android::base::StartsWith(path, prefix)) {
             // rebuild path to be system/<partition>/... to check for alias
             path = alternate + path.substr(prefix.size());
             for (second = 0; second < paths.size(); ++second) {
@@ -97,7 +97,7 @@
         }
 
         // check if path is system/<partition>/
-        if (android::base::StartsWith(path, alternate.c_str())) {
+        if (android::base::StartsWith(path, alternate)) {
             // rebuild path to be <partition>/... to check for alias
             path = prefix + path.substr(alternate.size());
             for (second = 0; second < paths.size(); ++second) {
diff --git a/libcutils/uevent.cpp b/libcutils/uevent.cpp
index a84e5b0..2dfceed 100644
--- a/libcutils/uevent.cpp
+++ b/libcutils/uevent.cpp
@@ -27,54 +27,6 @@
 
 #include <linux/netlink.h>
 
-#include <fstream>
-
-#include <private/android_filesystem_config.h>
-
-namespace {
-
-// Returns the uid of root in the current user namespace.
-// Returns AID_OVERFLOWUID if the root user is not mapped in the current
-// namespace.
-// Returns 0 if the kernel is not user namespace-aware (for backwards
-// compatibility) or if AID_OVERFLOWUID could not be validated to match what the
-// kernel would return.
-uid_t GetRootUid() {
-    constexpr uid_t kParentRootUid = 0;
-
-    std::ifstream uid_map_file("/proc/self/uid_map");
-    if (!uid_map_file) {
-        // The kernel does not support user namespaces.
-        return kParentRootUid;
-    }
-
-    uid_t current_namespace_uid, parent_namespace_uid;
-    uint32_t length;
-    while (uid_map_file >> current_namespace_uid >> parent_namespace_uid >> length) {
-        // Since kParentRootUid is 0, it should be the first entry in the mapped
-        // range.
-        if (parent_namespace_uid != kParentRootUid || length < 1) continue;
-        return current_namespace_uid;
-    }
-
-    // Sanity check: verify that the overflow UID is the one to be returned by
-    // the kernel.
-    std::ifstream overflowuid_file("/proc/sys/kernel/overflowuid");
-    if (!overflowuid_file) {
-        // It's better to return 0 in case we cannot make sure that the overflow
-        // UID matches.
-        return kParentRootUid;
-    }
-    uid_t kernel_overflow_uid;
-    if (!(overflowuid_file >> kernel_overflow_uid) || kernel_overflow_uid != AID_OVERFLOWUID)
-        return kParentRootUid;
-
-    // root is unmapped, use the kernel "overflow" uid.
-    return AID_OVERFLOWUID;
-}
-
-}  // namespace
-
 extern "C" {
 
 /**
@@ -99,7 +51,6 @@
 }
 
 ssize_t uevent_kernel_recv(int socket, void* buffer, size_t length, bool require_group, uid_t* uid) {
-    static const uid_t root_uid = GetRootUid();
     struct iovec iov = {buffer, length};
     struct sockaddr_nl addr;
     char control[CMSG_SPACE(sizeof(struct ucred))];
@@ -122,10 +73,6 @@
 
     cred = (struct ucred*)CMSG_DATA(cmsg);
     *uid = cred->uid;
-    if (cred->uid != root_uid) {
-        /* ignoring netlink message from non-root user */
-        goto out;
-    }
 
     if (addr.nl_pid != 0) {
         /* ignore non-kernel */
diff --git a/liblog/Android.bp b/liblog/Android.bp
index d5bb29e..eae0b10 100644
--- a/liblog/Android.bp
+++ b/liblog/Android.bp
@@ -55,7 +55,7 @@
             enabled: true,
         },
         vendor: {
-            export_include_dirs: ["include_vndk"],
+            override_export_include_dirs: ["include_vndk"],
         },
     },
 }
@@ -80,10 +80,6 @@
                 address: false,
             },
         },
-        android_arm: {
-            // TODO: This is to work around b/24465209. Remove after root cause is fixed
-            ldflags: ["-Wl,--hash-style=both"],
-        },
         windows: {
             srcs: ["uio.c"],
             enabled: true,
diff --git a/liblog/include/log/log_main.h b/liblog/include/log/log_main.h
index 339a06d..21fc7cc 100644
--- a/liblog/include/log/log_main.h
+++ b/liblog/include/log/log_main.h
@@ -17,6 +17,8 @@
 #ifndef _LIBS_LOG_LOG_MAIN_H
 #define _LIBS_LOG_LOG_MAIN_H
 
+#include <stdbool.h>
+
 #include <android/log.h>
 #include <sys/cdefs.h>
 
@@ -175,10 +177,10 @@
 #if LOG_NDEBUG
 #define ALOGV(...)          \
   do {                      \
-    if (0) {                \
+    if (false) {            \
       __ALOGV(__VA_ARGS__); \
     }                       \
-  } while (0)
+  } while (false)
 #else
 #define ALOGV(...) __ALOGV(__VA_ARGS__)
 #endif
diff --git a/liblog/tests/Android.mk b/liblog/tests/Android.mk
index 39b52ac..cfa849b 100644
--- a/liblog/tests/Android.mk
+++ b/liblog/tests/Android.mk
@@ -24,13 +24,12 @@
 test_tags := tests
 
 benchmark_c_flags := \
-    -Ibionic/tests \
-    -Wall -Wextra \
+    -Wall \
+    -Wextra \
     -Werror \
     -fno-builtin \
 
 benchmark_src_files := \
-    benchmark_main.cpp \
     liblog_benchmark.cpp
 
 # Build benchmarks for the device. Run with:
@@ -41,7 +40,7 @@
 LOCAL_CFLAGS += $(benchmark_c_flags)
 LOCAL_SHARED_LIBRARIES += liblog libm libbase
 LOCAL_SRC_FILES := $(benchmark_src_files)
-include $(BUILD_NATIVE_TEST)
+include $(BUILD_NATIVE_BENCHMARK)
 
 # -----------------------------------------------------------------------------
 # Unit tests.
diff --git a/liblog/tests/AndroidTest.xml b/liblog/tests/AndroidTest.xml
index 427f2b4..7b64433 100644
--- a/liblog/tests/AndroidTest.xml
+++ b/liblog/tests/AndroidTest.xml
@@ -14,6 +14,7 @@
      limitations under the License.
 -->
 <configuration description="Config for CTS Logging Library test cases">
+    <option name="test-suite-tag" value="cts" />
     <option name="config-descriptor:metadata" key="component" value="systems" />
     <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
         <option name="cleanup" value="true" />
diff --git a/liblog/tests/benchmark.h b/liblog/tests/benchmark.h
deleted file mode 100644
index e9280f6..0000000
--- a/liblog/tests/benchmark.h
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Copyright (C) 2012-2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include <vector>
-
-#ifndef BIONIC_BENCHMARK_H_
-#define BIONIC_BENCHMARK_H_
-
-namespace testing {
-
-class Benchmark;
-template <typename T> class BenchmarkWantsArg;
-template <typename T> class BenchmarkWithArg;
-
-void BenchmarkRegister(Benchmark* bm);
-int PrettyPrintInt(char* str, int len, unsigned int arg);
-
-class Benchmark {
- public:
-  Benchmark(const char* name, void (*fn)(int)) : name_(strdup(name)), fn_(fn) {
-    BenchmarkRegister(this);
-  }
-  explicit Benchmark(const char* name) : name_(strdup(name)), fn_(NULL) {}
-
-  virtual ~Benchmark() {
-    free(name_);
-  }
-
-  const char* Name() { return name_; }
-  virtual const char* ArgName() { return NULL; }
-  virtual void RunFn(int iterations) { fn_(iterations); }
-
- protected:
-  char* name_;
-
- private:
-  void (*fn_)(int);
-};
-
-template <typename T>
-class BenchmarkWantsArgBase : public Benchmark {
- public:
-  BenchmarkWantsArgBase(const char* name, void (*fn)(int, T)) : Benchmark(name) {
-    fn_arg_ = fn;
-  }
-
-  BenchmarkWantsArgBase<T>* Arg(const char* arg_name, T arg) {
-    BenchmarkRegister(new BenchmarkWithArg<T>(name_, fn_arg_, arg_name, arg));
-    return this;
-  }
-
- protected:
-  virtual void RunFn(int) { printf("can't run arg benchmark %s without arg\n", Name()); }
-  void (*fn_arg_)(int, T);
-};
-
-template <typename T>
-class BenchmarkWithArg : public BenchmarkWantsArg<T> {
- public:
-  BenchmarkWithArg(const char* name, void (*fn)(int, T), const char* arg_name, T arg) :
-      BenchmarkWantsArg<T>(name, fn), arg_(arg) {
-    arg_name_ = strdup(arg_name);
-  }
-
-  virtual ~BenchmarkWithArg() {
-    free(arg_name_);
-  }
-
-  virtual const char* ArgName() { return arg_name_; }
-
- protected:
-  virtual void RunFn(int iterations) { BenchmarkWantsArg<T>::fn_arg_(iterations, arg_); }
-
- private:
-  T arg_;
-  char* arg_name_;
-};
-
-template <typename T>
-class BenchmarkWantsArg : public BenchmarkWantsArgBase<T> {
- public:
-  BenchmarkWantsArg<T>(const char* name, void (*fn)(int, T)) :
-    BenchmarkWantsArgBase<T>(name, fn) { }
-};
-
-template <>
-class BenchmarkWantsArg<int> : public BenchmarkWantsArgBase<int> {
- public:
-  BenchmarkWantsArg<int>(const char* name, void (*fn)(int, int)) :
-    BenchmarkWantsArgBase<int>(name, fn) { }
-
-  BenchmarkWantsArg<int>* Arg(int arg) {
-    char arg_name[100];
-    PrettyPrintInt(arg_name, sizeof(arg_name), arg);
-    BenchmarkRegister(new BenchmarkWithArg<int>(name_, fn_arg_, arg_name, arg));
-    return this;
-  }
-};
-
-static inline Benchmark* BenchmarkFactory(const char* name, void (*fn)(int)) {
-  return new Benchmark(name, fn);
-}
-
-template <typename T>
-static inline BenchmarkWantsArg<T>* BenchmarkFactory(const char* name, void (*fn)(int, T)) {
-  return new BenchmarkWantsArg<T>(name, fn);
-}
-
-}  // namespace testing
-
-template <typename T>
-static inline void BenchmarkAddArg(::testing::Benchmark* b, const char* name, T arg) {
-  ::testing::BenchmarkWantsArg<T>* ba;
-  ba = static_cast< ::testing::BenchmarkWantsArg<T>* >(b);
-  ba->Arg(name, arg);
-}
-
-void SetBenchmarkBytesProcessed(uint64_t);
-void ResetBenchmarkTiming(void);
-void StopBenchmarkTiming(void);
-void StartBenchmarkTiming(void);
-void StartBenchmarkTiming(uint64_t);
-void StopBenchmarkTiming(uint64_t);
-
-#define BENCHMARK(f) \
-    static ::testing::Benchmark* _benchmark_##f __attribute__((unused)) = /* NOLINT */ \
-        (::testing::Benchmark*)::testing::BenchmarkFactory(#f, f) /* NOLINT */
-
-#endif // BIONIC_BENCHMARK_H_
diff --git a/liblog/tests/benchmark_main.cpp b/liblog/tests/benchmark_main.cpp
deleted file mode 100644
index 7367f1b..0000000
--- a/liblog/tests/benchmark_main.cpp
+++ /dev/null
@@ -1,247 +0,0 @@
-/*
- * Copyright (C) 2012-2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <benchmark.h>
-
-#include <inttypes.h>
-#include <math.h>
-#include <regex.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <map>
-#include <string>
-#include <vector>
-
-static uint64_t gBytesProcessed;
-static uint64_t gBenchmarkTotalTimeNs;
-static uint64_t gBenchmarkTotalTimeNsSquared;
-static uint64_t gBenchmarkNum;
-static uint64_t gBenchmarkStartTimeNs;
-
-typedef std::vector< ::testing::Benchmark*> BenchmarkList;
-static BenchmarkList* gBenchmarks;
-
-static int Round(int n) {
-  int base = 1;
-  while (base * 10 < n) {
-    base *= 10;
-  }
-  if (n < 2 * base) {
-    return 2 * base;
-  }
-  if (n < 5 * base) {
-    return 5 * base;
-  }
-  return 10 * base;
-}
-
-static uint64_t NanoTime() {
-  struct timespec t;
-  t.tv_sec = t.tv_nsec = 0;
-  clock_gettime(CLOCK_MONOTONIC, &t);
-  return static_cast<uint64_t>(t.tv_sec) * 1000000000ULL + t.tv_nsec;
-}
-
-namespace testing {
-
-int PrettyPrintInt(char* str, int len, unsigned int arg) {
-  if (arg >= (1 << 30) && arg % (1 << 30) == 0) {
-    return snprintf(str, len, "%uGi", arg / (1 << 30));
-  } else if (arg >= (1 << 20) && arg % (1 << 20) == 0) {
-    return snprintf(str, len, "%uMi", arg / (1 << 20));
-  } else if (arg >= (1 << 10) && arg % (1 << 10) == 0) {
-    return snprintf(str, len, "%uKi", arg / (1 << 10));
-  } else if (arg >= 1000000000 && arg % 1000000000 == 0) {
-    return snprintf(str, len, "%uG", arg / 1000000000);
-  } else if (arg >= 1000000 && arg % 1000000 == 0) {
-    return snprintf(str, len, "%uM", arg / 1000000);
-  } else if (arg >= 1000 && arg % 1000 == 0) {
-    return snprintf(str, len, "%uK", arg / 1000);
-  } else {
-    return snprintf(str, len, "%u", arg);
-  }
-}
-
-bool ShouldRun(Benchmark* b, int argc, char* argv[]) {
-  if (argc == 1) {
-    return true;  // With no arguments, we run all benchmarks.
-  }
-  // Otherwise, we interpret each argument as a regular expression and
-  // see if any of our benchmarks match.
-  for (int i = 1; i < argc; i++) {
-    regex_t re;
-    if (regcomp(&re, argv[i], 0) != 0) {
-      fprintf(stderr, "couldn't compile \"%s\" as a regular expression!\n",
-              argv[i]);
-      exit(EXIT_FAILURE);
-    }
-    int match = regexec(&re, b->Name(), 0, NULL, 0);
-    regfree(&re);
-    if (match != REG_NOMATCH) {
-      return true;
-    }
-  }
-  return false;
-}
-
-void BenchmarkRegister(Benchmark* b) {
-  if (gBenchmarks == NULL) {
-    gBenchmarks = new BenchmarkList;
-  }
-  gBenchmarks->push_back(b);
-}
-
-void RunRepeatedly(Benchmark* b, int iterations) {
-  gBytesProcessed = 0;
-  ResetBenchmarkTiming();
-  uint64_t StartTimeNs = NanoTime();
-  b->RunFn(iterations);
-  // Catch us if we fail to log anything.
-  if ((gBenchmarkTotalTimeNs == 0) && (StartTimeNs != 0) &&
-      (gBenchmarkStartTimeNs == 0)) {
-    gBenchmarkTotalTimeNs = NanoTime() - StartTimeNs;
-  }
-}
-
-void Run(Benchmark* b) {
-  // run once in case it's expensive
-  unsigned iterations = 1;
-  uint64_t s = NanoTime();
-  RunRepeatedly(b, iterations);
-  s = NanoTime() - s;
-  while (s < 2e9 && gBenchmarkTotalTimeNs < 1e9 && iterations < 1e9) {
-    unsigned last = iterations;
-    if (gBenchmarkTotalTimeNs / iterations == 0) {
-      iterations = 1e9;
-    } else {
-      iterations = 1e9 / (gBenchmarkTotalTimeNs / iterations);
-    }
-    iterations =
-        std::max(last + 1, std::min(iterations + iterations / 2, 100 * last));
-    iterations = Round(iterations);
-    s = NanoTime();
-    RunRepeatedly(b, iterations);
-    s = NanoTime() - s;
-  }
-
-  char throughput[100];
-  throughput[0] = '\0';
-  if (gBenchmarkTotalTimeNs > 0 && gBytesProcessed > 0) {
-    double mib_processed = static_cast<double>(gBytesProcessed) / 1e6;
-    double seconds = static_cast<double>(gBenchmarkTotalTimeNs) / 1e9;
-    snprintf(throughput, sizeof(throughput), " %8.2f MiB/s",
-             mib_processed / seconds);
-  }
-
-  char full_name[100];
-  snprintf(full_name, sizeof(full_name), "%s%s%s", b->Name(),
-           b->ArgName() ? "/" : "", b->ArgName() ? b->ArgName() : "");
-
-  uint64_t mean = gBenchmarkTotalTimeNs / iterations;
-  uint64_t sdev = 0;
-  if (gBenchmarkNum == iterations) {
-    mean = gBenchmarkTotalTimeNs / gBenchmarkNum;
-    uint64_t nXvariance = gBenchmarkTotalTimeNsSquared * gBenchmarkNum -
-                          (gBenchmarkTotalTimeNs * gBenchmarkTotalTimeNs);
-    sdev = (sqrt((double)nXvariance) / gBenchmarkNum / gBenchmarkNum) + 0.5;
-  }
-  if (mean > (10000 * sdev)) {
-    printf("%-25s %10" PRIu64 " %10" PRIu64 "%s\n", full_name,
-           static_cast<uint64_t>(iterations), mean, throughput);
-  } else {
-    printf("%-25s %10" PRIu64 " %10" PRIu64 "(\317\203%" PRIu64 ")%s\n",
-           full_name, static_cast<uint64_t>(iterations), mean, sdev, throughput);
-  }
-  fflush(stdout);
-}
-
-}  // namespace testing
-
-void SetBenchmarkBytesProcessed(uint64_t x) {
-  gBytesProcessed = x;
-}
-
-void ResetBenchmarkTiming() {
-  gBenchmarkStartTimeNs = 0;
-  gBenchmarkTotalTimeNs = 0;
-  gBenchmarkTotalTimeNsSquared = 0;
-  gBenchmarkNum = 0;
-}
-
-void StopBenchmarkTiming(void) {
-  if (gBenchmarkStartTimeNs != 0) {
-    int64_t diff = NanoTime() - gBenchmarkStartTimeNs;
-    gBenchmarkTotalTimeNs += diff;
-    gBenchmarkTotalTimeNsSquared += diff * diff;
-    ++gBenchmarkNum;
-  }
-  gBenchmarkStartTimeNs = 0;
-}
-
-void StartBenchmarkTiming(void) {
-  if (gBenchmarkStartTimeNs == 0) {
-    gBenchmarkStartTimeNs = NanoTime();
-  }
-}
-
-void StopBenchmarkTiming(uint64_t NanoTime) {
-  if (gBenchmarkStartTimeNs != 0) {
-    int64_t diff = NanoTime - gBenchmarkStartTimeNs;
-    gBenchmarkTotalTimeNs += diff;
-    gBenchmarkTotalTimeNsSquared += diff * diff;
-    if (NanoTime != 0) {
-      ++gBenchmarkNum;
-    }
-  }
-  gBenchmarkStartTimeNs = 0;
-}
-
-void StartBenchmarkTiming(uint64_t NanoTime) {
-  if (gBenchmarkStartTimeNs == 0) {
-    gBenchmarkStartTimeNs = NanoTime;
-  }
-}
-
-int main(int argc, char* argv[]) {
-  if (gBenchmarks->empty()) {
-    fprintf(stderr, "No benchmarks registered!\n");
-    exit(EXIT_FAILURE);
-  }
-
-  bool need_header = true;
-  for (auto b : *gBenchmarks) {
-    if (ShouldRun(b, argc, argv)) {
-      if (need_header) {
-        printf("%-25s %10s %10s\n", "", "iterations", "ns/op");
-        fflush(stdout);
-        need_header = false;
-      }
-      Run(b);
-    }
-  }
-
-  if (need_header) {
-    fprintf(stderr, "No matching benchmarks!\n");
-    fprintf(stderr, "Available benchmarks:\n");
-    for (auto b : *gBenchmarks) {
-      fprintf(stderr, "  %s\n", b->Name());
-    }
-    exit(EXIT_FAILURE);
-  }
-
-  return 0;
-}
diff --git a/liblog/tests/liblog_benchmark.cpp b/liblog/tests/liblog_benchmark.cpp
index c4bf959..c2f3f83 100644
--- a/liblog/tests/liblog_benchmark.cpp
+++ b/liblog/tests/liblog_benchmark.cpp
@@ -19,18 +19,20 @@
 #include <poll.h>
 #include <sys/endian.h>
 #include <sys/socket.h>
+#include <sys/syscall.h>
 #include <sys/types.h>
 #include <unistd.h>
 
 #include <unordered_set>
 
 #include <android-base/file.h>
+#include <benchmark/benchmark.h>
 #include <cutils/sockets.h>
 #include <log/event_tag_map.h>
 #include <log/log_transport.h>
 #include <private/android_logger.h>
 
-#include "benchmark.h"
+BENCHMARK_MAIN();
 
 // enhanced version of LOG_FAILURE_RETRY to add support for EAGAIN and
 // non-syscall libs. Since we are benchmarking, or using this in the emergency
@@ -51,15 +53,11 @@
  * the log at high pressure. Expect this to be less than double the process
  * wakeup time (2ms?)
  */
-static void BM_log_maximum_retry(int iters) {
-  StartBenchmarkTiming();
-
-  for (int i = 0; i < iters; ++i) {
-    LOG_FAILURE_RETRY(
-        __android_log_print(ANDROID_LOG_INFO, "BM_log_maximum_retry", "%d", i));
+static void BM_log_maximum_retry(benchmark::State& state) {
+  while (state.KeepRunning()) {
+    LOG_FAILURE_RETRY(__android_log_print(
+        ANDROID_LOG_INFO, "BM_log_maximum_retry", "%zu", state.iterations()));
   }
-
-  StopBenchmarkTiming();
 }
 BENCHMARK(BM_log_maximum_retry);
 
@@ -68,14 +66,11 @@
  * at high pressure. Expect this to be less than double the process wakeup
  * time (2ms?)
  */
-static void BM_log_maximum(int iters) {
-  StartBenchmarkTiming();
-
-  for (int i = 0; i < iters; ++i) {
-    __android_log_print(ANDROID_LOG_INFO, "BM_log_maximum", "%d", i);
+static void BM_log_maximum(benchmark::State& state) {
+  while (state.KeepRunning()) {
+    __android_log_print(ANDROID_LOG_INFO, "BM_log_maximum", "%zu",
+                        state.iterations());
   }
-
-  StopBenchmarkTiming();
 }
 BENCHMARK(BM_log_maximum);
 
@@ -87,36 +82,98 @@
   android_set_log_transport(LOGGER_DEFAULT);
 }
 
-static void BM_log_maximum_null(int iters) {
+static void BM_log_maximum_null(benchmark::State& state) {
   set_log_null();
-  BM_log_maximum(iters);
+  BM_log_maximum(state);
   set_log_default();
 }
 BENCHMARK(BM_log_maximum_null);
 
 /*
  *	Measure the time it takes to collect the time using
- * discrete acquisition (StartBenchmarkTiming() -> StopBenchmarkTiming())
+ * discrete acquisition (state.PauseTiming() to state.ResumeTiming())
  * under light load. Expect this to be a syscall period (2us) or
  * data read time if zero-syscall.
  *
  * vdso support in the kernel and the library can allow
- * clock_gettime to be zero-syscall.
+ * clock_gettime to be zero-syscall, but there there does remain some
+ * benchmarking overhead to pause and resume; assumptions are both are
+ * covered.
  */
-static void BM_clock_overhead(int iters) {
-  for (int i = 0; i < iters; ++i) {
-    StartBenchmarkTiming();
-    StopBenchmarkTiming();
+static void BM_clock_overhead(benchmark::State& state) {
+  while (state.KeepRunning()) {
+    state.PauseTiming();
+    state.ResumeTiming();
   }
 }
 BENCHMARK(BM_clock_overhead);
 
+static void do_clock_overhead(benchmark::State& state, clockid_t clk_id) {
+  timespec t;
+  while (state.KeepRunning()) {
+    clock_gettime(clk_id, &t);
+  }
+}
+
+static void BM_time_clock_gettime_REALTIME(benchmark::State& state) {
+  do_clock_overhead(state, CLOCK_REALTIME);
+}
+BENCHMARK(BM_time_clock_gettime_REALTIME);
+
+static void BM_time_clock_gettime_MONOTONIC(benchmark::State& state) {
+  do_clock_overhead(state, CLOCK_MONOTONIC);
+}
+BENCHMARK(BM_time_clock_gettime_MONOTONIC);
+
+static void BM_time_clock_gettime_MONOTONIC_syscall(benchmark::State& state) {
+  timespec t;
+  while (state.KeepRunning()) {
+    syscall(__NR_clock_gettime, CLOCK_MONOTONIC, &t);
+  }
+}
+BENCHMARK(BM_time_clock_gettime_MONOTONIC_syscall);
+
+static void BM_time_clock_gettime_MONOTONIC_RAW(benchmark::State& state) {
+  do_clock_overhead(state, CLOCK_MONOTONIC_RAW);
+}
+BENCHMARK(BM_time_clock_gettime_MONOTONIC_RAW);
+
+static void BM_time_clock_gettime_BOOTTIME(benchmark::State& state) {
+  do_clock_overhead(state, CLOCK_BOOTTIME);
+}
+BENCHMARK(BM_time_clock_gettime_BOOTTIME);
+
+static void BM_time_clock_getres_MONOTONIC(benchmark::State& state) {
+  timespec t;
+  while (state.KeepRunning()) {
+    clock_getres(CLOCK_MONOTONIC, &t);
+  }
+}
+BENCHMARK(BM_time_clock_getres_MONOTONIC);
+
+static void BM_time_clock_getres_MONOTONIC_syscall(benchmark::State& state) {
+  timespec t;
+  while (state.KeepRunning()) {
+    syscall(__NR_clock_getres, CLOCK_MONOTONIC, &t);
+  }
+}
+BENCHMARK(BM_time_clock_getres_MONOTONIC_syscall);
+
+static void BM_time_time(benchmark::State& state) {
+  while (state.KeepRunning()) {
+    time_t now;
+    now = time(&now);
+  }
+}
+BENCHMARK(BM_time_time);
+
 /*
  * Measure the time it takes to submit the android logging data to pstore
  */
-static void BM_pmsg_short(int iters) {
+static void BM_pmsg_short(benchmark::State& state) {
   int pstore_fd = TEMP_FAILURE_RETRY(open("/dev/pmsg0", O_WRONLY));
   if (pstore_fd < 0) {
+    state.SkipWithError("/dev/pmsg0");
     return;
   }
 
@@ -175,13 +232,12 @@
   newVec[2].iov_base = &buffer;
   newVec[2].iov_len = sizeof(buffer);
 
-  StartBenchmarkTiming();
-  for (int i = 0; i < iters; ++i) {
+  while (state.KeepRunning()) {
     ++snapshot;
     buffer.payload.data = htole32(snapshot);
     writev(pstore_fd, newVec, nr);
   }
-  StopBenchmarkTiming();
+  state.PauseTiming();
   close(pstore_fd);
 }
 BENCHMARK(BM_pmsg_short);
@@ -190,9 +246,10 @@
  * Measure the time it takes to submit the android logging data to pstore
  * best case aligned single block.
  */
-static void BM_pmsg_short_aligned(int iters) {
+static void BM_pmsg_short_aligned(benchmark::State& state) {
   int pstore_fd = TEMP_FAILURE_RETRY(open("/dev/pmsg0", O_WRONLY));
   if (pstore_fd < 0) {
+    state.SkipWithError("/dev/pmsg0");
     return;
   }
 
@@ -228,7 +285,8 @@
   memset(buf, 0, sizeof(buf));
   struct packet* buffer = (struct packet*)(((uintptr_t)buf + 7) & ~7);
   if (((uintptr_t)&buffer->pmsg_header) & 7) {
-    fprintf(stderr, "&buffer=0x%p iters=%d\n", &buffer->pmsg_header, iters);
+    fprintf(stderr, "&buffer=0x%p iterations=%zu\n", &buffer->pmsg_header,
+            state.iterations());
   }
 
   buffer->pmsg_header.magic = LOGGER_MAGIC;
@@ -247,15 +305,14 @@
   uint32_t snapshot = 0;
   buffer->payload.payload.data = htole32(snapshot);
 
-  StartBenchmarkTiming();
-  for (int i = 0; i < iters; ++i) {
+  while (state.KeepRunning()) {
     ++snapshot;
     buffer->payload.payload.data = htole32(snapshot);
     write(pstore_fd, &buffer->pmsg_header,
           sizeof(android_pmsg_log_header_t) + sizeof(android_log_header_t) +
               sizeof(android_log_event_int_t));
   }
-  StopBenchmarkTiming();
+  state.PauseTiming();
   close(pstore_fd);
 }
 BENCHMARK(BM_pmsg_short_aligned);
@@ -264,9 +321,10 @@
  * Measure the time it takes to submit the android logging data to pstore
  * best case aligned single block.
  */
-static void BM_pmsg_short_unaligned1(int iters) {
+static void BM_pmsg_short_unaligned1(benchmark::State& state) {
   int pstore_fd = TEMP_FAILURE_RETRY(open("/dev/pmsg0", O_WRONLY));
   if (pstore_fd < 0) {
+    state.SkipWithError("/dev/pmsg0");
     return;
   }
 
@@ -302,7 +360,8 @@
   memset(buf, 0, sizeof(buf));
   struct packet* buffer = (struct packet*)((((uintptr_t)buf + 7) & ~7) + 1);
   if ((((uintptr_t)&buffer->pmsg_header) & 7) != 1) {
-    fprintf(stderr, "&buffer=0x%p iters=%d\n", &buffer->pmsg_header, iters);
+    fprintf(stderr, "&buffer=0x%p iterations=%zu\n", &buffer->pmsg_header,
+            state.iterations());
   }
 
   buffer->pmsg_header.magic = LOGGER_MAGIC;
@@ -321,15 +380,14 @@
   uint32_t snapshot = 0;
   buffer->payload.payload.data = htole32(snapshot);
 
-  StartBenchmarkTiming();
-  for (int i = 0; i < iters; ++i) {
+  while (state.KeepRunning()) {
     ++snapshot;
     buffer->payload.payload.data = htole32(snapshot);
     write(pstore_fd, &buffer->pmsg_header,
           sizeof(android_pmsg_log_header_t) + sizeof(android_log_header_t) +
               sizeof(android_log_event_int_t));
   }
-  StopBenchmarkTiming();
+  state.PauseTiming();
   close(pstore_fd);
 }
 BENCHMARK(BM_pmsg_short_unaligned1);
@@ -338,9 +396,10 @@
  * Measure the time it takes to submit the android logging data to pstore
  * best case aligned single block.
  */
-static void BM_pmsg_long_aligned(int iters) {
+static void BM_pmsg_long_aligned(benchmark::State& state) {
   int pstore_fd = TEMP_FAILURE_RETRY(open("/dev/pmsg0", O_WRONLY));
   if (pstore_fd < 0) {
+    state.SkipWithError("/dev/pmsg0");
     return;
   }
 
@@ -376,7 +435,8 @@
   memset(buf, 0, sizeof(buf));
   struct packet* buffer = (struct packet*)(((uintptr_t)buf + 7) & ~7);
   if (((uintptr_t)&buffer->pmsg_header) & 7) {
-    fprintf(stderr, "&buffer=0x%p iters=%d\n", &buffer->pmsg_header, iters);
+    fprintf(stderr, "&buffer=0x%p iterations=%zu\n", &buffer->pmsg_header,
+            state.iterations());
   }
 
   buffer->pmsg_header.magic = LOGGER_MAGIC;
@@ -395,13 +455,12 @@
   uint32_t snapshot = 0;
   buffer->payload.payload.data = htole32(snapshot);
 
-  StartBenchmarkTiming();
-  for (int i = 0; i < iters; ++i) {
+  while (state.KeepRunning()) {
     ++snapshot;
     buffer->payload.payload.data = htole32(snapshot);
     write(pstore_fd, &buffer->pmsg_header, LOGGER_ENTRY_MAX_PAYLOAD);
   }
-  StopBenchmarkTiming();
+  state.PauseTiming();
   close(pstore_fd);
 }
 BENCHMARK(BM_pmsg_long_aligned);
@@ -410,9 +469,10 @@
  * Measure the time it takes to submit the android logging data to pstore
  * best case aligned single block.
  */
-static void BM_pmsg_long_unaligned1(int iters) {
+static void BM_pmsg_long_unaligned1(benchmark::State& state) {
   int pstore_fd = TEMP_FAILURE_RETRY(open("/dev/pmsg0", O_WRONLY));
   if (pstore_fd < 0) {
+    state.SkipWithError("/dev/pmsg0");
     return;
   }
 
@@ -448,7 +508,8 @@
   memset(buf, 0, sizeof(buf));
   struct packet* buffer = (struct packet*)((((uintptr_t)buf + 7) & ~7) + 1);
   if ((((uintptr_t)&buffer->pmsg_header) & 7) != 1) {
-    fprintf(stderr, "&buffer=0x%p iters=%d\n", &buffer->pmsg_header, iters);
+    fprintf(stderr, "&buffer=0x%p iterations=%zu\n", &buffer->pmsg_header,
+            state.iterations());
   }
 
   buffer->pmsg_header.magic = LOGGER_MAGIC;
@@ -467,22 +528,20 @@
   uint32_t snapshot = 0;
   buffer->payload.payload.data = htole32(snapshot);
 
-  StartBenchmarkTiming();
-  for (int i = 0; i < iters; ++i) {
+  while (state.KeepRunning()) {
     ++snapshot;
     buffer->payload.payload.data = htole32(snapshot);
     write(pstore_fd, &buffer->pmsg_header, LOGGER_ENTRY_MAX_PAYLOAD);
   }
-  StopBenchmarkTiming();
+  state.PauseTiming();
   close(pstore_fd);
 }
 BENCHMARK(BM_pmsg_long_unaligned1);
 
 /*
  *	Measure the time it takes to form sprintf plus time using
- * discrete acquisition (StartBenchmarkTiming() -> StopBenchmarkTiming())
- * under light load. Expect this to be a syscall period (2us) or sprintf
- * time if zero-syscall time.
+ * discrete acquisition under light load. Expect this to be a syscall period
+ * (2us) or sprintf time if zero-syscall time.
  */
 /* helper function */
 static void test_print(const char* fmt, ...) {
@@ -498,58 +557,55 @@
 #define logd_sleep() usleep(50)     // really allow logd to catch up
 
 /* performance test */
-static void BM_sprintf_overhead(int iters) {
-  for (int i = 0; i < iters; ++i) {
-    StartBenchmarkTiming();
-    test_print("BM_sprintf_overhead:%d", i);
-    StopBenchmarkTiming();
+static void BM_sprintf_overhead(benchmark::State& state) {
+  while (state.KeepRunning()) {
+    test_print("BM_sprintf_overhead:%zu", state.iterations());
+    state.PauseTiming();
     logd_yield();
+    state.ResumeTiming();
   }
 }
 BENCHMARK(BM_sprintf_overhead);
 
 /*
  *	Measure the time it takes to submit the android printing logging call
- * using discrete acquisition discrete acquisition (StartBenchmarkTiming() ->
- * StopBenchmarkTiming()) under light load. Expect this to be a dozen or so
- * syscall periods (40us) plus time to run *printf
+ * using discrete acquisition discrete acquisition under light load. Expect
+ * this to be a dozen or so syscall periods (40us) plus time to run *printf
  */
-static void BM_log_print_overhead(int iters) {
-  for (int i = 0; i < iters; ++i) {
-    StartBenchmarkTiming();
-    __android_log_print(ANDROID_LOG_INFO, "BM_log_overhead", "%d", i);
-    StopBenchmarkTiming();
+static void BM_log_print_overhead(benchmark::State& state) {
+  while (state.KeepRunning()) {
+    __android_log_print(ANDROID_LOG_INFO, "BM_log_overhead", "%zu",
+                        state.iterations());
+    state.PauseTiming();
     logd_yield();
+    state.ResumeTiming();
   }
 }
 BENCHMARK(BM_log_print_overhead);
 
 /*
  *	Measure the time it takes to submit the android event logging call
- * using discrete acquisition (StartBenchmarkTiming() -> StopBenchmarkTiming())
- * under light load. Expect this to be a long path to logger to convert the
- * unknown tag (0) into a tagname (less than 200us).
+ * using discrete acquisition under light load. Expect this to be a long path
+ * to logger to convert the unknown tag (0) into a tagname (less than 200us).
  */
-static void BM_log_event_overhead(int iters) {
-  for (unsigned long long i = 0; i < (unsigned)iters; ++i) {
-    StartBenchmarkTiming();
+static void BM_log_event_overhead(benchmark::State& state) {
+  for (int64_t i = 0; state.KeepRunning(); ++i) {
     // log tag number 0 is not known, nor shall it ever be known
     __android_log_btwrite(0, EVENT_TYPE_LONG, &i, sizeof(i));
-    StopBenchmarkTiming();
+    state.PauseTiming();
     logd_yield();
+    state.ResumeTiming();
   }
 }
 BENCHMARK(BM_log_event_overhead);
 
 /*
  *	Measure the time it takes to submit the android event logging call
- * using discrete acquisition (StartBenchmarkTiming() -> StopBenchmarkTiming())
- * under light load with a known logtag.  Expect this to be a dozen or so
- * syscall periods (less than 40us)
+ * using discrete acquisition under light load with a known logtag.  Expect
+ * this to be a dozen or so syscall periods (less than 40us)
  */
-static void BM_log_event_overhead_42(int iters) {
-  for (unsigned long long i = 0; i < (unsigned)iters; ++i) {
-    StartBenchmarkTiming();
+static void BM_log_event_overhead_42(benchmark::State& state) {
+  for (int64_t i = 0; state.KeepRunning(); ++i) {
     // In system/core/logcat/event.logtags:
     // # These are used for testing, do not modify without updating
     // # tests/framework-tests/src/android/util/EventLogFunctionalTest.java.
@@ -557,40 +613,42 @@
     // # system/core/liblog/tests/liblog_test.cpp
     // 42    answer (to life the universe etc|3)
     __android_log_btwrite(42, EVENT_TYPE_LONG, &i, sizeof(i));
-    StopBenchmarkTiming();
+    state.PauseTiming();
     logd_yield();
+    state.ResumeTiming();
   }
 }
 BENCHMARK(BM_log_event_overhead_42);
 
-static void BM_log_event_overhead_null(int iters) {
+static void BM_log_event_overhead_null(benchmark::State& state) {
   set_log_null();
-  BM_log_event_overhead(iters);
+  BM_log_event_overhead(state);
   set_log_default();
 }
 BENCHMARK(BM_log_event_overhead_null);
 
 /*
  *	Measure the time it takes to submit the android event logging call
- * using discrete acquisition (StartBenchmarkTiming() -> StopBenchmarkTiming())
- * under very-light load (<1% CPU utilization).
+ * using discrete acquisition under very-light load (<1% CPU utilization).
  */
-static void BM_log_light_overhead(int iters) {
-  for (unsigned long long i = 0; i < (unsigned)iters; ++i) {
-    StartBenchmarkTiming();
+static void BM_log_light_overhead(benchmark::State& state) {
+  for (int64_t i = 0; state.KeepRunning(); ++i) {
     __android_log_btwrite(0, EVENT_TYPE_LONG, &i, sizeof(i));
-    StopBenchmarkTiming();
+    state.PauseTiming();
     usleep(10000);
+    state.ResumeTiming();
   }
 }
 BENCHMARK(BM_log_light_overhead);
 
-static void BM_log_light_overhead_null(int iters) {
+static void BM_log_light_overhead_null(benchmark::State& state) {
   set_log_null();
-  BM_log_light_overhead(iters);
+  BM_log_light_overhead(state);
   set_log_default();
 }
-BENCHMARK(BM_log_light_overhead_null);
+// Default gets out of hand for this test, so we set a reasonable number of
+// iterations for a timely result.
+BENCHMARK(BM_log_light_overhead_null)->Iterations(500);
 
 static void caught_latency(int /*signum*/) {
   unsigned long long v = 0xDEADBEEFA55A5AA5ULL;
@@ -614,10 +672,12 @@
 
 /*
  *	Measure the time it takes for the logd posting call to acquire the
- * timestamp to place into the internal record. Expect this to be less than
- * 4 syscalls (3us).
+ * timestamp to place into the internal record.  Expect this to be less than
+ * 4 syscalls (3us).  This test uses manual injection of timing because it is
+ * comparing the timestamp at send, and then picking up the corresponding log
+ * end-to-end long path from logd to see what actual timestamp was submitted.
  */
-static void BM_log_latency(int iters) {
+static void BM_log_latency(benchmark::State& state) {
   pid_t pid = getpid();
 
   struct logger_list* logger_list =
@@ -631,7 +691,8 @@
   signal(SIGALRM, caught_latency);
   alarm(alarm_time);
 
-  for (int j = 0, i = 0; i < iters && j < 10 * iters; ++i, ++j) {
+  for (size_t j = 0; state.KeepRunning() && j < 10 * state.iterations(); ++j) {
+  retry:  // We allow transitory errors (logd overloaded) to be retried.
     log_time ts;
     LOG_FAILURE_RETRY((ts = log_time(CLOCK_REALTIME),
                        android_btWriteLog(0, EVENT_TYPE_LONG, &ts, sizeof(ts))));
@@ -642,7 +703,7 @@
       alarm(alarm_time);
 
       if (ret <= 0) {
-        iters = i;
+        state.SkipWithError("android_logger_list_read");
         break;
       }
       if ((log_msg.entry.len != (4 + 1 + 8)) ||
@@ -658,7 +719,7 @@
       log_time tx(eventData + 4 + 1);
       if (ts != tx) {
         if (0xDEADBEEFA55A5AA5ULL == caught_convert(eventData + 4 + 1)) {
-          iters = i;
+          state.SkipWithError("signal");
           break;
         }
         continue;
@@ -666,12 +727,8 @@
 
       uint64_t start = ts.nsec();
       uint64_t end = log_msg.nsec();
-      if (end >= start) {
-        StartBenchmarkTiming(start);
-        StopBenchmarkTiming(end);
-      } else {
-        --i;
-      }
+      if (end < start) goto retry;
+      state.SetIterationTime((end - start) / (double)NS_PER_SEC);
       break;
     }
   }
@@ -681,7 +738,9 @@
 
   android_logger_list_free(logger_list);
 }
-BENCHMARK(BM_log_latency);
+// Default gets out of hand for this test, so we set a reasonable number of
+// iterations for a timely result.
+BENCHMARK(BM_log_latency)->UseManualTime()->Iterations(200);
 
 static void caught_delay(int /*signum*/) {
   unsigned long long v = 0xDEADBEEFA55A5AA6ULL;
@@ -693,7 +752,7 @@
  *	Measure the time it takes for the logd posting call to make it into
  * the logs. Expect this to be less than double the process wakeup time (2ms).
  */
-static void BM_log_delay(int iters) {
+static void BM_log_delay(benchmark::State& state) {
   pid_t pid = getpid();
 
   struct logger_list* logger_list =
@@ -707,9 +766,7 @@
   signal(SIGALRM, caught_delay);
   alarm(alarm_time);
 
-  StartBenchmarkTiming();
-
-  for (int i = 0; i < iters; ++i) {
+  while (state.KeepRunning()) {
     log_time ts(CLOCK_REALTIME);
 
     LOG_FAILURE_RETRY(android_btWriteLog(0, EVENT_TYPE_LONG, &ts, sizeof(ts)));
@@ -720,7 +777,7 @@
       alarm(alarm_time);
 
       if (ret <= 0) {
-        iters = i;
+        state.SkipWithError("android_logger_list_read");
         break;
       }
       if ((log_msg.entry.len != (4 + 1 + 8)) ||
@@ -736,7 +793,7 @@
       log_time tx(eventData + 4 + 1);
       if (ts != tx) {
         if (0xDEADBEEFA55A5AA6ULL == caught_convert(eventData + 4 + 1)) {
-          iters = i;
+          state.SkipWithError("signal");
           break;
         }
         continue;
@@ -745,12 +802,11 @@
       break;
     }
   }
+  state.PauseTiming();
 
   signal(SIGALRM, SIG_DFL);
   alarm(0);
 
-  StopBenchmarkTiming();
-
   android_logger_list_free(logger_list);
 }
 BENCHMARK(BM_log_delay);
@@ -758,45 +814,33 @@
 /*
  *	Measure the time it takes for __android_log_is_loggable.
  */
-static void BM_is_loggable(int iters) {
+static void BM_is_loggable(benchmark::State& state) {
   static const char logd[] = "logd";
 
-  StartBenchmarkTiming();
-
-  for (int i = 0; i < iters; ++i) {
+  while (state.KeepRunning()) {
     __android_log_is_loggable_len(ANDROID_LOG_WARN, logd, strlen(logd),
                                   ANDROID_LOG_VERBOSE);
   }
-
-  StopBenchmarkTiming();
 }
 BENCHMARK(BM_is_loggable);
 
 /*
  *	Measure the time it takes for android_log_clockid.
  */
-static void BM_clockid(int iters) {
-  StartBenchmarkTiming();
-
-  for (int i = 0; i < iters; ++i) {
+static void BM_clockid(benchmark::State& state) {
+  while (state.KeepRunning()) {
     android_log_clockid();
   }
-
-  StopBenchmarkTiming();
 }
 BENCHMARK(BM_clockid);
 
 /*
  *	Measure the time it takes for __android_log_security.
  */
-static void BM_security(int iters) {
-  StartBenchmarkTiming();
-
-  for (int i = 0; i < iters; ++i) {
+static void BM_security(benchmark::State& state) {
+  while (state.KeepRunning()) {
     __android_log_security();
   }
-
-  StopBenchmarkTiming();
 }
 BENCHMARK(BM_security);
 
@@ -824,21 +868,17 @@
 /*
  *	Measure the time it takes for android_lookupEventTag_len
  */
-static void BM_lookupEventTag(int iters) {
+static void BM_lookupEventTag(benchmark::State& state) {
   prechargeEventMap();
 
   std::unordered_set<uint32_t>::const_iterator it = set.begin();
 
-  StartBenchmarkTiming();
-
-  for (int i = 0; i < iters; ++i) {
+  while (state.KeepRunning()) {
     size_t len;
     android_lookupEventTag_len(map, &len, (*it));
     ++it;
     if (it == set.end()) it = set.begin();
   }
-
-  StopBenchmarkTiming();
 }
 BENCHMARK(BM_lookupEventTag);
 
@@ -847,7 +887,7 @@
  */
 static uint32_t notTag = 1;
 
-static void BM_lookupEventTag_NOT(int iters) {
+static void BM_lookupEventTag_NOT(benchmark::State& state) {
   prechargeEventMap();
 
   while (set.find(notTag) != set.end()) {
@@ -855,15 +895,11 @@
     if (notTag >= USHRT_MAX) notTag = 1;
   }
 
-  StartBenchmarkTiming();
-
-  for (int i = 0; i < iters; ++i) {
+  while (state.KeepRunning()) {
     size_t len;
     android_lookupEventTag_len(map, &len, notTag);
   }
 
-  StopBenchmarkTiming();
-
   ++notTag;
   if (notTag >= USHRT_MAX) notTag = 1;
 }
@@ -872,42 +908,38 @@
 /*
  *	Measure the time it takes for android_lookupEventFormat_len
  */
-static void BM_lookupEventFormat(int iters) {
+static void BM_lookupEventFormat(benchmark::State& state) {
   prechargeEventMap();
 
   std::unordered_set<uint32_t>::const_iterator it = set.begin();
 
-  StartBenchmarkTiming();
-
-  for (int i = 0; i < iters; ++i) {
+  while (state.KeepRunning()) {
     size_t len;
     android_lookupEventFormat_len(map, &len, (*it));
     ++it;
     if (it == set.end()) it = set.begin();
   }
-
-  StopBenchmarkTiming();
 }
 BENCHMARK(BM_lookupEventFormat);
 
 /*
  *	Measure the time it takes for android_lookupEventTagNum plus above
  */
-static void BM_lookupEventTagNum(int iters) {
+static void BM_lookupEventTagNum(benchmark::State& state) {
   prechargeEventMap();
 
   std::unordered_set<uint32_t>::const_iterator it = set.begin();
 
-  for (int i = 0; i < iters; ++i) {
+  while (state.KeepRunning()) {
     size_t len;
     const char* name = android_lookupEventTag_len(map, &len, (*it));
     std::string Name(name, len);
     const char* format = android_lookupEventFormat_len(map, &len, (*it));
     std::string Format(format, len);
-    StartBenchmarkTiming();
+    state.ResumeTiming();
     android_lookupEventTagNum(map, Name.c_str(), Format.c_str(),
                               ANDROID_LOG_UNKNOWN);
-    StopBenchmarkTiming();
+    state.PauseTiming();
     ++it;
     if (it == set.end()) it = set.begin();
   }
@@ -943,7 +975,7 @@
   close(sock);
 }
 
-static void BM_lookupEventTagNum_logd_new(int iters) {
+static void BM_lookupEventTagNum_logd_new(benchmark::State& state) {
   fprintf(stderr,
           "WARNING: "
           "This test can cause logd to grow in size and hit DOS limiter\n");
@@ -965,7 +997,7 @@
     data_event_log_tags = empty_event_log_tags;
   }
 
-  for (int i = 0; i < iters; ++i) {
+  while (state.KeepRunning()) {
     char buffer[256];
     memset(buffer, 0, sizeof(buffer));
     log_time now(CLOCK_MONOTONIC);
@@ -973,9 +1005,9 @@
     snprintf(name, sizeof(name), "a%" PRIu64, now.nsec());
     snprintf(buffer, sizeof(buffer), "getEventTag name=%s format=\"(new|1)\"",
              name);
-    StartBenchmarkTiming();
+    state.ResumeTiming();
     send_to_control(buffer, sizeof(buffer));
-    StopBenchmarkTiming();
+    state.PauseTiming();
   }
 
   // Restore copies (logd still know about them, until crash or reboot)
@@ -1002,12 +1034,12 @@
 }
 BENCHMARK(BM_lookupEventTagNum_logd_new);
 
-static void BM_lookupEventTagNum_logd_existing(int iters) {
+static void BM_lookupEventTagNum_logd_existing(benchmark::State& state) {
   prechargeEventMap();
 
   std::unordered_set<uint32_t>::const_iterator it = set.begin();
 
-  for (int i = 0; i < iters; ++i) {
+  while (state.KeepRunning()) {
     size_t len;
     const char* name = android_lookupEventTag_len(map, &len, (*it));
     std::string Name(name, len);
@@ -1018,9 +1050,9 @@
     snprintf(buffer, sizeof(buffer), "getEventTag name=%s format=\"%s\"",
              Name.c_str(), Format.c_str());
 
-    StartBenchmarkTiming();
+    state.ResumeTiming();
     send_to_control(buffer, sizeof(buffer));
-    StopBenchmarkTiming();
+    state.PauseTiming();
     ++it;
     if (it == set.end()) it = set.begin();
   }
diff --git a/libnativeloader/Android.bp b/libnativeloader/Android.bp
index 4b21edc..17983bc 100644
--- a/libnativeloader/Android.bp
+++ b/libnativeloader/Android.bp
@@ -19,4 +19,8 @@
         "-fvisibility=hidden",
     ],
     export_include_dirs: ["include"],
+    required: [
+        "llndk.libraries.txt",
+        "vndksp.libraries.txt",
+    ],
 }
diff --git a/libnativeloader/native_loader.cpp b/libnativeloader/native_loader.cpp
index f3c70de..6ddec4d 100644
--- a/libnativeloader/native_loader.cpp
+++ b/libnativeloader/native_loader.cpp
@@ -24,12 +24,15 @@
 #include "cutils/properties.h"
 #include "log/log.h"
 #endif
+#include <dirent.h>
+#include <sys/types.h>
 #include "nativebridge/native_bridge.h"
 
 #include <algorithm>
-#include <vector>
-#include <string>
+#include <memory>
 #include <mutex>
+#include <string>
+#include <vector>
 
 #include <android-base/file.h>
 #include <android-base/macros.h>
@@ -82,15 +85,20 @@
   native_bridge_namespace_t* native_bridge_ns_;
 };
 
-static constexpr const char* kPublicNativeLibrariesSystemConfigPathFromRoot =
-                                  "/etc/public.libraries.txt";
-static constexpr const char* kPublicNativeLibrariesVendorConfig =
-                                  "/vendor/etc/public.libraries.txt";
-static constexpr const char* kLlndkNativeLibrariesSystemConfigPathFromRoot =
-                                  "/etc/llndk.libraries.txt";
-static constexpr const char* kVndkspNativeLibrariesSystemConfigPathFromRoot =
-                                  "/etc/vndksp.libraries.txt";
-
+static constexpr const char kPublicNativeLibrariesSystemConfigPathFromRoot[] =
+    "/etc/public.libraries.txt";
+static constexpr const char kPublicNativeLibrariesExtensionConfigPrefix[] = "public.libraries-";
+static constexpr const size_t kPublicNativeLibrariesExtensionConfigPrefixLen =
+    sizeof(kPublicNativeLibrariesExtensionConfigPrefix) - 1;
+static constexpr const char kPublicNativeLibrariesExtensionConfigSuffix[] = ".txt";
+static constexpr const size_t kPublicNativeLibrariesExtensionConfigSuffixLen =
+    sizeof(kPublicNativeLibrariesExtensionConfigSuffix) - 1;
+static constexpr const char kPublicNativeLibrariesVendorConfig[] =
+    "/vendor/etc/public.libraries.txt";
+static constexpr const char kLlndkNativeLibrariesSystemConfigPathFromRoot[] =
+    "/etc/llndk.libraries.txt";
+static constexpr const char kVndkspNativeLibrariesSystemConfigPathFromRoot[] =
+    "/etc/vndksp.libraries.txt";
 
 // The device may be configured to have the vendor libraries loaded to a separate namespace.
 // For historical reasons this namespace was named sphal but effectively it is intended
@@ -133,6 +141,9 @@
   file_name->insert(insert_pos, vndk_version_str());
 }
 
+static const std::function<bool(const std::string&, std::string*)> always_true =
+    [](const std::string&, std::string*) { return true; };
+
 class LibraryNamespaces {
  public:
   LibraryNamespaces() : initialized_(false) { }
@@ -337,9 +348,54 @@
             root_dir + kVndkspNativeLibrariesSystemConfigPathFromRoot;
 
     std::string error_msg;
-    LOG_ALWAYS_FATAL_IF(!ReadConfig(public_native_libraries_system_config, &sonames, &error_msg),
-                        "Error reading public native library list from \"%s\": %s",
-                        public_native_libraries_system_config.c_str(), error_msg.c_str());
+    LOG_ALWAYS_FATAL_IF(
+        !ReadConfig(public_native_libraries_system_config, &sonames, always_true, &error_msg),
+        "Error reading public native library list from \"%s\": %s",
+        public_native_libraries_system_config.c_str(), error_msg.c_str());
+
+    // read /system/etc/public.libraries-<companyname>.txt which contain partner defined
+    // system libs that are exposed to apps. The libs in the txt files must be
+    // named as lib<name>.<companyname>.so.
+    std::string dirname = base::Dirname(public_native_libraries_system_config);
+    std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(dirname.c_str()), closedir);
+    if (dir != nullptr) {
+      // Failing to opening the dir is not an error, which can happen in
+      // webview_zygote.
+      struct dirent* ent;
+      while ((ent = readdir(dir.get())) != nullptr) {
+        if (ent->d_type != DT_REG && ent->d_type != DT_LNK) {
+          continue;
+        }
+        const std::string filename(ent->d_name);
+        if (android::base::StartsWith(filename, kPublicNativeLibrariesExtensionConfigPrefix) &&
+            android::base::EndsWith(filename, kPublicNativeLibrariesExtensionConfigSuffix)) {
+          const size_t start = kPublicNativeLibrariesExtensionConfigPrefixLen;
+          const size_t end = filename.size() - kPublicNativeLibrariesExtensionConfigSuffixLen;
+          const std::string company_name = filename.substr(start, end - start);
+          const std::string config_file_path = dirname + "/" + filename;
+          LOG_ALWAYS_FATAL_IF(
+              company_name.empty(),
+              "Error extracting company name from public native library list file path \"%s\"",
+              config_file_path.c_str());
+          LOG_ALWAYS_FATAL_IF(
+              !ReadConfig(
+                  config_file_path, &sonames,
+                  [&company_name](const std::string& soname, std::string* error_msg) {
+                    if (android::base::StartsWith(soname, "lib") &&
+                        android::base::EndsWith(soname, "." + company_name + ".so")) {
+                      return true;
+                    } else {
+                      *error_msg = "Library name \"" + soname +
+                                   "\" does not end with the company name: " + company_name + ".";
+                      return false;
+                    }
+                  },
+                  &error_msg),
+              "Error reading public native library list from \"%s\": %s", config_file_path.c_str(),
+              error_msg.c_str());
+        }
+      }
+    }
 
     // Insert VNDK version to llndk and vndksp config file names.
     insert_vndk_version_str(&llndk_native_libraries_system_config);
@@ -374,16 +430,16 @@
     system_public_libraries_ = base::Join(sonames, ':');
 
     sonames.clear();
-    ReadConfig(llndk_native_libraries_system_config, &sonames);
+    ReadConfig(llndk_native_libraries_system_config, &sonames, always_true);
     system_llndk_libraries_ = base::Join(sonames, ':');
 
     sonames.clear();
-    ReadConfig(vndksp_native_libraries_system_config, &sonames);
+    ReadConfig(vndksp_native_libraries_system_config, &sonames, always_true);
     system_vndksp_libraries_ = base::Join(sonames, ':');
 
     sonames.clear();
     // This file is optional, quietly ignore if the file does not exist.
-    ReadConfig(kPublicNativeLibrariesVendorConfig, &sonames);
+    ReadConfig(kPublicNativeLibrariesVendorConfig, &sonames, always_true, nullptr);
 
     vendor_public_libraries_ = base::Join(sonames, ':');
   }
@@ -394,6 +450,8 @@
 
  private:
   bool ReadConfig(const std::string& configFile, std::vector<std::string>* sonames,
+                  const std::function<bool(const std::string& /* soname */,
+                                           std::string* /* error_msg */)>& check_soname,
                   std::string* error_msg = nullptr) {
     // Read list of public native libraries from the config file.
     std::string file_content;
@@ -430,7 +488,11 @@
         trimmed_line.resize(space_pos);
       }
 
-      sonames->push_back(trimmed_line);
+      if (check_soname(trimmed_line, error_msg)) {
+        sonames->push_back(trimmed_line);
+      } else {
+        return false;
+      }
     }
 
     return true;
@@ -600,22 +662,51 @@
     return handle;
   }
 #else
-  UNUSED(env, target_sdk_version, class_loader, library_path);
-  *needs_native_bridge = false;
-  void* handle = dlopen(path, RTLD_NOW);
-  if (handle == nullptr) {
-    if (NativeBridgeIsSupported(path)) {
-      *needs_native_bridge = true;
-      handle = NativeBridgeLoadLibrary(path, RTLD_NOW);
-      if (handle == nullptr) {
-        *error_msg = NativeBridgeGetError();
-      }
+  UNUSED(env, target_sdk_version, class_loader);
+
+  // Do some best effort to emulate library-path support. It will not
+  // work for dependencies.
+  //
+  // Note: null has a special meaning and must be preserved.
+  std::string c_library_path;  // Empty string by default.
+  if (library_path != nullptr && path != nullptr && path[0] != '/') {
+    ScopedUtfChars library_path_utf_chars(env, library_path);
+    c_library_path = library_path_utf_chars.c_str();
+  }
+
+  std::vector<std::string> library_paths = base::Split(c_library_path, ":");
+
+  for (const std::string& lib_path : library_paths) {
+    *needs_native_bridge = false;
+    const char* path_arg;
+    std::string complete_path;
+    if (path == nullptr) {
+      // Preserve null.
+      path_arg = nullptr;
     } else {
-      *needs_native_bridge = false;
+      complete_path = lib_path;
+      if (!complete_path.empty()) {
+        complete_path.append("/");
+      }
+      complete_path.append(path);
+      path_arg = complete_path.c_str();
+    }
+    void* handle = dlopen(path_arg, RTLD_NOW);
+    if (handle != nullptr) {
+      return handle;
+    }
+    if (NativeBridgeIsSupported(path_arg)) {
+      *needs_native_bridge = true;
+      handle = NativeBridgeLoadLibrary(path_arg, RTLD_NOW);
+      if (handle != nullptr) {
+        return handle;
+      }
+      *error_msg = NativeBridgeGetError();
+    } else {
       *error_msg = dlerror();
     }
   }
-  return handle;
+  return nullptr;
 #endif
 }
 
diff --git a/libnativeloader/test/Android.bp b/libnativeloader/test/Android.bp
new file mode 100644
index 0000000..2d33704
--- /dev/null
+++ b/libnativeloader/test/Android.bp
@@ -0,0 +1,48 @@
+//
+// 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_library {
+    name: "libfoo.oem1",
+    srcs: ["test.cpp"],
+    cflags : ["-DLIBNAME=\"libfoo.oem1.so\""],
+    shared_libs: [
+        "libbase",
+    ],
+}
+cc_library {
+    name: "libbar.oem1",
+    srcs: ["test.cpp"],
+    cflags : ["-DLIBNAME=\"libbar.oem1.so\""],
+    shared_libs: [
+        "libbase",
+    ],
+}
+cc_library {
+    name: "libfoo.oem2",
+    srcs: ["test.cpp"],
+    cflags : ["-DLIBNAME=\"libfoo.oem2.so\""],
+    shared_libs: [
+        "libbase",
+    ],
+}
+cc_library {
+    name: "libbar.oem2",
+    srcs: ["test.cpp"],
+    cflags : ["-DLIBNAME=\"libbar.oem2.so\""],
+    shared_libs: [
+        "libbase",
+    ],
+}
diff --git a/libnativeloader/test/Android.mk b/libnativeloader/test/Android.mk
new file mode 100644
index 0000000..4c3da4a
--- /dev/null
+++ b/libnativeloader/test/Android.mk
@@ -0,0 +1,30 @@
+#
+# 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 := public.libraries-oem1.txt
+LOCAL_SRC_FILES:= $(LOCAL_MODULE)
+LOCAL_MODULE_CLASS := ETC
+LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)
+include $(BUILD_PREBUILT)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := public.libraries-oem2.txt
+LOCAL_SRC_FILES:= $(LOCAL_MODULE)
+LOCAL_MODULE_CLASS := ETC
+LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)
+include $(BUILD_PREBUILT)
diff --git a/libnativeloader/test/public.libraries-oem1.txt b/libnativeloader/test/public.libraries-oem1.txt
new file mode 100644
index 0000000..f9433e2
--- /dev/null
+++ b/libnativeloader/test/public.libraries-oem1.txt
@@ -0,0 +1,2 @@
+libfoo.oem1.so
+libbar.oem1.so
diff --git a/libnativeloader/test/public.libraries-oem2.txt b/libnativeloader/test/public.libraries-oem2.txt
new file mode 100644
index 0000000..de6bdb0
--- /dev/null
+++ b/libnativeloader/test/public.libraries-oem2.txt
@@ -0,0 +1,2 @@
+libfoo.oem2.so
+libbar.oem2.so
diff --git a/debuggerd/libdebuggerd/test/ptrace_fake.h b/libnativeloader/test/test.cpp
similarity index 69%
rename from debuggerd/libdebuggerd/test/ptrace_fake.h
rename to libnativeloader/test/test.cpp
index fdbb663..b166928 100644
--- a/debuggerd/libdebuggerd/test/ptrace_fake.h
+++ b/libnativeloader/test/test.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2015 The Android Open Source Project
+ * 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.
@@ -13,12 +13,9 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+#define LOG_TAG "oemlib"
+#include <android-base/logging.h>
 
-#ifndef _DEBUGGERD_TEST_PTRACE_FAKE_H
-#define _DEBUGGERD_TEST_PTRACE_FAKE_H
-
-#include <signal.h>
-
-void ptrace_set_fake_getsiginfo(const siginfo_t&);
-
-#endif // _DEBUGGERD_TEST_PTRACE_FAKE_H
+static __attribute__((constructor)) void test_lib_init() {
+  LOG(DEBUG) << LIBNAME << " loaded";
+}
diff --git a/libsuspend/Android.bp b/libsuspend/Android.bp
index 32f1e1f..b3e36c2 100644
--- a/libsuspend/Android.bp
+++ b/libsuspend/Android.bp
@@ -9,11 +9,12 @@
 
     srcs: [
         "autosuspend.c",
-        "autosuspend_wakeup_count.c",
+        "autosuspend_wakeup_count.cpp",
     ],
     export_include_dirs: ["include"],
     local_include_dirs: ["include"],
     shared_libs: [
+        "libbase",
         "liblog",
         "libcutils",
     ],
diff --git a/libsuspend/autosuspend.c b/libsuspend/autosuspend.c
index 96e1c10..09fc061 100644
--- a/libsuspend/autosuspend.c
+++ b/libsuspend/autosuspend.c
@@ -28,8 +28,7 @@
 static bool autosuspend_enabled;
 static bool autosuspend_inited;
 
-static int autosuspend_init(void)
-{
+static int autosuspend_init(void) {
     if (autosuspend_inited) {
         return 0;
     }
@@ -40,19 +39,18 @@
     }
 
     if (!autosuspend_ops) {
-        ALOGE("failed to initialize autosuspend\n");
+        ALOGE("failed to initialize autosuspend");
         return -1;
     }
 
 out:
     autosuspend_inited = true;
 
-    ALOGV("autosuspend initialized\n");
+    ALOGV("autosuspend initialized");
     return 0;
 }
 
-int autosuspend_enable(void)
-{
+int autosuspend_enable(void) {
     int ret;
 
     ret = autosuspend_init();
@@ -60,7 +58,7 @@
         return ret;
     }
 
-    ALOGV("autosuspend_enable\n");
+    ALOGV("autosuspend_enable");
 
     if (autosuspend_enabled) {
         return 0;
@@ -75,8 +73,7 @@
     return 0;
 }
 
-int autosuspend_disable(void)
-{
+int autosuspend_disable(void) {
     int ret;
 
     ret = autosuspend_init();
@@ -84,7 +81,7 @@
         return ret;
     }
 
-    ALOGV("autosuspend_disable\n");
+    ALOGV("autosuspend_disable");
 
     if (!autosuspend_enabled) {
         return 0;
@@ -98,3 +95,16 @@
     autosuspend_enabled = false;
     return 0;
 }
+
+void autosuspend_set_wakeup_callback(void (*func)(bool success)) {
+    int ret;
+
+    ret = autosuspend_init();
+    if (ret) {
+        return;
+    }
+
+    ALOGV("set_wakeup_callback");
+
+    autosuspend_ops->set_wakeup_callback(func);
+}
diff --git a/libsuspend/autosuspend_ops.h b/libsuspend/autosuspend_ops.h
index 698e25b..357b828 100644
--- a/libsuspend/autosuspend_ops.h
+++ b/libsuspend/autosuspend_ops.h
@@ -20,10 +20,11 @@
 struct autosuspend_ops {
     int (*enable)(void);
     int (*disable)(void);
+    void (*set_wakeup_callback)(void (*func)(bool success));
 };
 
-struct autosuspend_ops *autosuspend_autosleep_init(void);
-struct autosuspend_ops *autosuspend_earlysuspend_init(void);
+__BEGIN_DECLS
 struct autosuspend_ops *autosuspend_wakeup_count_init(void);
+__END_DECLS
 
 #endif
diff --git a/libsuspend/autosuspend_wakeup_count.c b/libsuspend/autosuspend_wakeup_count.c
deleted file mode 100644
index 2da204a..0000000
--- a/libsuspend/autosuspend_wakeup_count.c
+++ /dev/null
@@ -1,215 +0,0 @@
-/*
- * Copyright (C) 2012 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.
- */
-
-#define LOG_TAG "libsuspend"
-//#define LOG_NDEBUG 0
-
-#include <errno.h>
-#include <fcntl.h>
-#include <pthread.h>
-#include <semaphore.h>
-#include <stddef.h>
-#include <stdbool.h>
-#include <string.h>
-#include <sys/param.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include <log/log.h>
-
-#include "autosuspend_ops.h"
-
-#define SYS_POWER_STATE "/sys/power/state"
-#define SYS_POWER_WAKEUP_COUNT "/sys/power/wakeup_count"
-
-#define BASE_SLEEP_TIME 100000
-
-static int state_fd;
-static int wakeup_count_fd;
-static pthread_t suspend_thread;
-static sem_t suspend_lockout;
-static const char *sleep_state = "mem";
-static void (*wakeup_func)(bool success) = NULL;
-static int sleep_time = BASE_SLEEP_TIME;
-
-static void update_sleep_time(bool success) {
-    if (success) {
-        sleep_time = BASE_SLEEP_TIME;
-        return;
-    }
-    // double sleep time after each failure up to one minute
-    sleep_time = MIN(sleep_time * 2, 60000000);
-}
-
-static void *suspend_thread_func(void *arg __attribute__((unused)))
-{
-    char buf[80];
-    char wakeup_count[20];
-    int wakeup_count_len;
-    int ret;
-    bool success = true;
-
-    while (1) {
-        update_sleep_time(success);
-        usleep(sleep_time);
-        success = false;
-        ALOGV("%s: read wakeup_count\n", __func__);
-        lseek(wakeup_count_fd, 0, SEEK_SET);
-        wakeup_count_len = TEMP_FAILURE_RETRY(read(wakeup_count_fd, wakeup_count,
-                sizeof(wakeup_count)));
-        if (wakeup_count_len < 0) {
-            strerror_r(errno, buf, sizeof(buf));
-            ALOGE("Error reading from %s: %s\n", SYS_POWER_WAKEUP_COUNT, buf);
-            wakeup_count_len = 0;
-            continue;
-        }
-        if (!wakeup_count_len) {
-            ALOGE("Empty wakeup count\n");
-            continue;
-        }
-
-        ALOGV("%s: wait\n", __func__);
-        ret = sem_wait(&suspend_lockout);
-        if (ret < 0) {
-            strerror_r(errno, buf, sizeof(buf));
-            ALOGE("Error waiting on semaphore: %s\n", buf);
-            continue;
-        }
-
-        ALOGV("%s: write %*s to wakeup_count\n", __func__, wakeup_count_len, wakeup_count);
-        ret = TEMP_FAILURE_RETRY(write(wakeup_count_fd, wakeup_count, wakeup_count_len));
-        if (ret < 0) {
-            strerror_r(errno, buf, sizeof(buf));
-            ALOGE("Error writing to %s: %s\n", SYS_POWER_WAKEUP_COUNT, buf);
-        } else {
-            ALOGV("%s: write %s to %s\n", __func__, sleep_state, SYS_POWER_STATE);
-            ret = TEMP_FAILURE_RETRY(write(state_fd, sleep_state, strlen(sleep_state)));
-            if (ret >= 0) {
-                success = true;
-            }
-            void (*func)(bool success) = wakeup_func;
-            if (func != NULL) {
-                (*func)(success);
-            }
-        }
-
-        ALOGV("%s: release sem\n", __func__);
-        ret = sem_post(&suspend_lockout);
-        if (ret < 0) {
-            strerror_r(errno, buf, sizeof(buf));
-            ALOGE("Error releasing semaphore: %s\n", buf);
-        }
-    }
-    return NULL;
-}
-
-static int autosuspend_wakeup_count_enable(void)
-{
-    char buf[80];
-    int ret;
-
-    ALOGV("autosuspend_wakeup_count_enable\n");
-
-    ret = sem_post(&suspend_lockout);
-
-    if (ret < 0) {
-        strerror_r(errno, buf, sizeof(buf));
-        ALOGE("Error changing semaphore: %s\n", buf);
-    }
-
-    ALOGV("autosuspend_wakeup_count_enable done\n");
-
-    return ret;
-}
-
-static int autosuspend_wakeup_count_disable(void)
-{
-    char buf[80];
-    int ret;
-
-    ALOGV("autosuspend_wakeup_count_disable\n");
-
-    ret = sem_wait(&suspend_lockout);
-
-    if (ret < 0) {
-        strerror_r(errno, buf, sizeof(buf));
-        ALOGE("Error changing semaphore: %s\n", buf);
-    }
-
-    ALOGV("autosuspend_wakeup_count_disable done\n");
-
-    return ret;
-}
-
-void set_wakeup_callback(void (*func)(bool success))
-{
-    if (wakeup_func != NULL) {
-        ALOGE("Duplicate wakeup callback applied, keeping original");
-        return;
-    }
-    wakeup_func = func;
-}
-
-struct autosuspend_ops autosuspend_wakeup_count_ops = {
-        .enable = autosuspend_wakeup_count_enable,
-        .disable = autosuspend_wakeup_count_disable,
-};
-
-struct autosuspend_ops *autosuspend_wakeup_count_init(void)
-{
-    int ret;
-    char buf[80];
-
-    state_fd = TEMP_FAILURE_RETRY(open(SYS_POWER_STATE, O_RDWR));
-    if (state_fd < 0) {
-        strerror_r(errno, buf, sizeof(buf));
-        ALOGE("Error opening %s: %s\n", SYS_POWER_STATE, buf);
-        goto err_open_state;
-    }
-
-    wakeup_count_fd = TEMP_FAILURE_RETRY(open(SYS_POWER_WAKEUP_COUNT, O_RDWR));
-    if (wakeup_count_fd < 0) {
-        strerror_r(errno, buf, sizeof(buf));
-        ALOGE("Error opening %s: %s\n", SYS_POWER_WAKEUP_COUNT, buf);
-        goto err_open_wakeup_count;
-    }
-
-    ret = sem_init(&suspend_lockout, 0, 0);
-    if (ret < 0) {
-        strerror_r(errno, buf, sizeof(buf));
-        ALOGE("Error creating semaphore: %s\n", buf);
-        goto err_sem_init;
-    }
-    ret = pthread_create(&suspend_thread, NULL, suspend_thread_func, NULL);
-    if (ret) {
-        strerror_r(ret, buf, sizeof(buf));
-        ALOGE("Error creating thread: %s\n", buf);
-        goto err_pthread_create;
-    }
-
-    ALOGI("Selected wakeup count\n");
-    return &autosuspend_wakeup_count_ops;
-
-err_pthread_create:
-    sem_destroy(&suspend_lockout);
-err_sem_init:
-    close(wakeup_count_fd);
-err_open_wakeup_count:
-    close(state_fd);
-err_open_state:
-    return NULL;
-}
diff --git a/libsuspend/autosuspend_wakeup_count.cpp b/libsuspend/autosuspend_wakeup_count.cpp
new file mode 100644
index 0000000..cfca765
--- /dev/null
+++ b/libsuspend/autosuspend_wakeup_count.cpp
@@ -0,0 +1,198 @@
+/*
+ * Copyright (C) 2012 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.
+ */
+
+#define LOG_TAG "libsuspend"
+//#define LOG_NDEBUG 0
+
+#include <fcntl.h>
+#include <pthread.h>
+#include <semaphore.h>
+#include <stdbool.h>
+#include <stddef.h>
+#include <string.h>
+#include <sys/param.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/strings.h>
+
+#include "autosuspend_ops.h"
+
+#define BASE_SLEEP_TIME 100000
+#define MAX_SLEEP_TIME 60000000
+
+static int state_fd;
+static int wakeup_count_fd;
+
+using android::base::ReadFdToString;
+using android::base::Trim;
+using android::base::WriteStringToFd;
+
+static pthread_t suspend_thread;
+static sem_t suspend_lockout;
+static const char* sleep_state = "mem";
+static void (*wakeup_func)(bool success) = NULL;
+static int sleep_time = BASE_SLEEP_TIME;
+static constexpr char sys_power_state[] = "/sys/power/state";
+static constexpr char sys_power_wakeup_count[] = "/sys/power/wakeup_count";
+
+static void update_sleep_time(bool success) {
+    if (success) {
+        sleep_time = BASE_SLEEP_TIME;
+        return;
+    }
+    // double sleep time after each failure up to one minute
+    sleep_time = MIN(sleep_time * 2, MAX_SLEEP_TIME);
+}
+
+static void* suspend_thread_func(void* arg __attribute__((unused))) {
+    int ret;
+    bool success = true;
+
+    while (1) {
+        update_sleep_time(success);
+        usleep(sleep_time);
+        success = false;
+        LOG(VERBOSE) << "read wakeup_count";
+        lseek(wakeup_count_fd, 0, SEEK_SET);
+        std::string wakeup_count;
+        if (!ReadFdToString(wakeup_count_fd, &wakeup_count)) {
+            PLOG(ERROR) << "error reading from " << sys_power_wakeup_count;
+            continue;
+        }
+
+        wakeup_count = Trim(wakeup_count);
+        if (wakeup_count.empty()) {
+            LOG(ERROR) << "empty wakeup count";
+            continue;
+        }
+
+        LOG(VERBOSE) << "wait";
+        ret = sem_wait(&suspend_lockout);
+        if (ret < 0) {
+            PLOG(ERROR) << "error waiting on semaphore";
+            continue;
+        }
+
+        LOG(VERBOSE) << "write " << wakeup_count << " to wakeup_count";
+        if (WriteStringToFd(wakeup_count, wakeup_count_fd)) {
+            LOG(VERBOSE) << "write " << sleep_state << " to " << sys_power_state;
+            success = WriteStringToFd(sleep_state, state_fd);
+
+            void (*func)(bool success) = wakeup_func;
+            if (func != NULL) {
+                (*func)(success);
+            }
+        } else {
+            PLOG(ERROR) << "error writing to " << sys_power_wakeup_count;
+        }
+
+        LOG(VERBOSE) << "release sem";
+        ret = sem_post(&suspend_lockout);
+        if (ret < 0) {
+            PLOG(ERROR) << "error releasing semaphore";
+        }
+    }
+    return NULL;
+}
+
+static int autosuspend_wakeup_count_enable(void) {
+    int ret;
+
+    LOG(VERBOSE) << "autosuspend_wakeup_count_enable";
+
+    ret = sem_post(&suspend_lockout);
+
+    if (ret < 0) {
+        PLOG(ERROR) << "error changing semaphore";
+    }
+
+    LOG(VERBOSE) << "autosuspend_wakeup_count_enable done";
+
+    return ret;
+}
+
+static int autosuspend_wakeup_count_disable(void) {
+    int ret;
+
+    LOG(VERBOSE) << "autosuspend_wakeup_count_disable";
+
+    ret = sem_wait(&suspend_lockout);
+
+    if (ret < 0) {
+        PLOG(ERROR) << "error changing semaphore";
+    }
+
+    LOG(VERBOSE) << "autosuspend_wakeup_count_disable done";
+
+    return ret;
+}
+
+static void autosuspend_set_wakeup_callback(void (*func)(bool success)) {
+    if (wakeup_func != NULL) {
+        LOG(ERROR) << "duplicate wakeup callback applied, keeping original";
+        return;
+    }
+    wakeup_func = func;
+}
+
+struct autosuspend_ops autosuspend_wakeup_count_ops = {
+    .enable = autosuspend_wakeup_count_enable,
+    .disable = autosuspend_wakeup_count_disable,
+    .set_wakeup_callback = autosuspend_set_wakeup_callback,
+};
+
+struct autosuspend_ops* autosuspend_wakeup_count_init(void) {
+    int ret;
+
+    state_fd = TEMP_FAILURE_RETRY(open(sys_power_state, O_RDWR));
+    if (state_fd < 0) {
+        PLOG(ERROR) << "error opening " << sys_power_state;
+        goto err_open_state;
+    }
+
+    wakeup_count_fd = TEMP_FAILURE_RETRY(open(sys_power_wakeup_count, O_RDWR));
+    if (wakeup_count_fd < 0) {
+        PLOG(ERROR) << "error opening " << sys_power_wakeup_count;
+        goto err_open_wakeup_count;
+    }
+
+    ret = sem_init(&suspend_lockout, 0, 0);
+    if (ret < 0) {
+        PLOG(ERROR) << "error creating semaphore";
+        goto err_sem_init;
+    }
+    ret = pthread_create(&suspend_thread, NULL, suspend_thread_func, NULL);
+    if (ret) {
+        LOG(ERROR) << "error creating thread: " << strerror(ret);
+        goto err_pthread_create;
+    }
+
+    LOG(INFO) << "selected wakeup count";
+    return &autosuspend_wakeup_count_ops;
+
+err_pthread_create:
+    sem_destroy(&suspend_lockout);
+err_sem_init:
+    close(wakeup_count_fd);
+err_open_wakeup_count:
+    close(state_fd);
+err_open_state:
+    return NULL;
+}
diff --git a/libsuspend/include/suspend/autosuspend.h b/libsuspend/include/suspend/autosuspend.h
index 59188a8..e130ca3 100644
--- a/libsuspend/include/suspend/autosuspend.h
+++ b/libsuspend/include/suspend/autosuspend.h
@@ -51,7 +51,7 @@
  * success is true if the suspend was sucessful and false if the suspend
  * aborted due to some reason.
  */
-void set_wakeup_callback(void (*func)(bool success));
+void autosuspend_set_wakeup_callback(void (*func)(bool success));
 
 __END_DECLS
 
diff --git a/libsystem/include/system/graphics.h b/libsystem/include/system/graphics.h
index 1a99187..657370b 100644
--- a/libsystem/include/system/graphics.h
+++ b/libsystem/include/system/graphics.h
@@ -257,6 +257,11 @@
     float minLuminance;
 };
 
+struct android_cta861_3_metadata {
+    float maxContentLightLevel;
+    float maxFrameAverageLightLevel;
+};
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/libunwindstack/Android.bp b/libunwindstack/Android.bp
index 21dd306..9389b40 100644
--- a/libunwindstack/Android.bp
+++ b/libunwindstack/Android.bp
@@ -55,6 +55,7 @@
         "Elf.cpp",
         "ElfInterface.cpp",
         "ElfInterfaceArm.cpp",
+        "JitDebug.cpp",
         "Log.cpp",
         "MapInfo.cpp",
         "Maps.cpp",
@@ -128,6 +129,7 @@
         "tests/ElfInterfaceTest.cpp",
         "tests/ElfTest.cpp",
         "tests/ElfTestUtils.cpp",
+        "tests/JitDebugTest.cpp",
         "tests/LogFake.cpp",
         "tests/MapInfoGetElfTest.cpp",
         "tests/MapInfoGetLoadBiasTest.cpp",
@@ -136,6 +138,7 @@
         "tests/MemoryFake.cpp",
         "tests/MemoryFileTest.cpp",
         "tests/MemoryLocalTest.cpp",
+        "tests/MemoryOfflineTest.cpp",
         "tests/MemoryRangeTest.cpp",
         "tests/MemoryRemoteTest.cpp",
         "tests/MemoryTest.cpp",
@@ -167,6 +170,9 @@
     data: [
         "tests/files/elf32.xz",
         "tests/files/elf64.xz",
+        "tests/files/offline/jit_debug_arm32/*",
+        "tests/files/offline/jit_debug_x86_32/*",
+        "tests/files/offline/gnu_debugdata_arm32/*",
         "tests/files/offline/straddle_arm32/*",
         "tests/files/offline/straddle_arm64/*",
     ],
@@ -213,6 +219,15 @@
     ],
 }
 
+cc_binary {
+    name: "unwind_for_offline",
+    defaults: ["libunwindstack_tools"],
+
+    srcs: [
+        "tools/unwind_for_offline.cpp",
+    ],
+}
+
 // Generates the elf data for use in the tests for .gnu_debugdata frames.
 // Once these files are generated, use the xz command to compress the data.
 cc_binary_host {
diff --git a/libunwindstack/Elf.cpp b/libunwindstack/Elf.cpp
index f486e23..220e549 100644
--- a/libunwindstack/Elf.cpp
+++ b/libunwindstack/Elf.cpp
@@ -79,6 +79,7 @@
   uint64_t load_bias;
   if (gnu->Init(&load_bias)) {
     gnu->InitHeaders();
+    interface_->SetGnuDebugdataInterface(gnu);
   } else {
     // Free all of the memory associated with the gnu_debugdata section.
     gnu_debugdata_memory_.reset(nullptr);
@@ -102,6 +103,37 @@
                                                      addr, load_bias_, name, func_offset)));
 }
 
+bool Elf::GetGlobalVariable(const std::string& name, uint64_t* memory_address) {
+  if (!valid_) {
+    return false;
+  }
+
+  if (!interface_->GetGlobalVariable(name, memory_address) &&
+      (gnu_debugdata_interface_ == nullptr ||
+       !gnu_debugdata_interface_->GetGlobalVariable(name, memory_address))) {
+    return false;
+  }
+
+  // Adjust by the load bias.
+  if (*memory_address < load_bias_) {
+    return false;
+  }
+
+  *memory_address -= load_bias_;
+
+  // If this winds up in the dynamic section, then we might need to adjust
+  // the address.
+  uint64_t dynamic_end = interface_->dynamic_vaddr() + interface_->dynamic_size();
+  if (*memory_address >= interface_->dynamic_vaddr() && *memory_address < dynamic_end) {
+    if (interface_->dynamic_vaddr() > interface_->dynamic_offset()) {
+      *memory_address -= interface_->dynamic_vaddr() - interface_->dynamic_offset();
+    } else {
+      *memory_address += interface_->dynamic_offset() - interface_->dynamic_vaddr();
+    }
+  }
+  return true;
+}
+
 // The relative pc is always relative to the start of the map from which it comes.
 bool Elf::Step(uint64_t rel_pc, uint64_t adjusted_rel_pc, uint64_t elf_offset, Regs* regs,
                Memory* process_memory, bool* finished) {
@@ -115,17 +147,9 @@
     return true;
   }
 
-  // Adjust the load bias to get the real relative pc.
-  if (adjusted_rel_pc < load_bias_) {
-    return false;
-  }
-  adjusted_rel_pc -= load_bias_;
-
   // Lock during the step which can update information in the object.
   std::lock_guard<std::mutex> guard(lock_);
-  return interface_->Step(adjusted_rel_pc, regs, process_memory, finished) ||
-         (gnu_debugdata_interface_ &&
-          gnu_debugdata_interface_->Step(adjusted_rel_pc, regs, process_memory, finished));
+  return interface_->Step(adjusted_rel_pc, load_bias_, regs, process_memory, finished);
 }
 
 bool Elf::IsValidElf(Memory* memory) {
@@ -167,6 +191,23 @@
   }
 }
 
+bool Elf::IsValidPc(uint64_t pc) {
+  if (!valid_ || pc < load_bias_) {
+    return false;
+  }
+  pc -= load_bias_;
+
+  if (interface_->IsValidPc(pc)) {
+    return true;
+  }
+
+  if (gnu_debugdata_interface_ != nullptr && gnu_debugdata_interface_->IsValidPc(pc)) {
+    return true;
+  }
+
+  return false;
+}
+
 ElfInterface* Elf::CreateInterfaceFromMemory(Memory* memory) {
   if (!IsValidElf(memory)) {
     return nullptr;
diff --git a/libunwindstack/ElfInterface.cpp b/libunwindstack/ElfInterface.cpp
index 334cf76..0e3ab2c 100644
--- a/libunwindstack/ElfInterface.cpp
+++ b/libunwindstack/ElfInterface.cpp
@@ -43,6 +43,30 @@
   }
 }
 
+bool ElfInterface::IsValidPc(uint64_t pc) {
+  if (!pt_loads_.empty()) {
+    for (auto& entry : pt_loads_) {
+      uint64_t start = entry.second.table_offset;
+      uint64_t end = start + entry.second.table_size;
+      if (pc >= start && pc < end) {
+        return true;
+      }
+    }
+    return false;
+  }
+
+  // No PT_LOAD data, look for a fde for this pc in the section data.
+  if (debug_frame_ != nullptr && debug_frame_->GetFdeFromPc(pc) != nullptr) {
+    return true;
+  }
+
+  if (eh_frame_ != nullptr && eh_frame_->GetFdeFromPc(pc) != nullptr) {
+    return true;
+  }
+
+  return false;
+}
+
 Memory* ElfInterface::CreateGnuDebugdataMemory() {
   if (gnu_debugdata_offset_ == 0 || gnu_debugdata_size_ == 0) {
     return nullptr;
@@ -225,6 +249,10 @@
         return false;
       }
       dynamic_offset_ = phdr.p_offset;
+      if (!memory_->ReadField(offset, &phdr, &phdr.p_vaddr, sizeof(phdr.p_vaddr))) {
+        return false;
+      }
+      dynamic_vaddr_ = phdr.p_vaddr;
       if (!memory_->ReadField(offset, &phdr, &phdr.p_memsz, sizeof(phdr.p_memsz))) {
         return false;
       }
@@ -386,16 +414,43 @@
   return false;
 }
 
-bool ElfInterface::Step(uint64_t pc, Regs* regs, Memory* process_memory, bool* finished) {
+template <typename SymType>
+bool ElfInterface::GetGlobalVariableWithTemplate(const std::string& name, uint64_t* memory_address) {
+  if (symbols_.empty()) {
+    return false;
+  }
+
+  for (const auto symbol : symbols_) {
+    if (symbol->GetGlobal<SymType>(memory_, name, memory_address)) {
+      return true;
+    }
+  }
+  return false;
+}
+
+bool ElfInterface::Step(uint64_t pc, uint64_t load_bias, Regs* regs, Memory* process_memory,
+                        bool* finished) {
+  // Adjust the load bias to get the real relative pc.
+  if (pc < load_bias) {
+    return false;
+  }
+  uint64_t adjusted_pc = pc - load_bias;
+
   // Try the eh_frame first.
   DwarfSection* eh_frame = eh_frame_.get();
-  if (eh_frame != nullptr && eh_frame->Step(pc, regs, process_memory, finished)) {
+  if (eh_frame != nullptr && eh_frame->Step(adjusted_pc, regs, process_memory, finished)) {
     return true;
   }
 
   // Try the debug_frame next.
   DwarfSection* debug_frame = debug_frame_.get();
-  if (debug_frame != nullptr && debug_frame->Step(pc, regs, process_memory, finished)) {
+  if (debug_frame != nullptr && debug_frame->Step(adjusted_pc, regs, process_memory, finished)) {
+    return true;
+  }
+
+  // Finally try the gnu_debugdata interface, but always use a zero load bias.
+  if (gnu_debugdata_interface_ != nullptr &&
+      gnu_debugdata_interface_->Step(pc, 0, regs, process_memory, finished)) {
     return true;
   }
   return false;
@@ -438,6 +493,9 @@
 template bool ElfInterface::GetFunctionNameWithTemplate<Elf64_Sym>(uint64_t, uint64_t, std::string*,
                                                                    uint64_t*);
 
+template bool ElfInterface::GetGlobalVariableWithTemplate<Elf32_Sym>(const std::string&, uint64_t*);
+template bool ElfInterface::GetGlobalVariableWithTemplate<Elf64_Sym>(const std::string&, uint64_t*);
+
 template void ElfInterface::GetMaxSizeWithTemplate<Elf32_Ehdr>(Memory*, uint64_t*);
 template void ElfInterface::GetMaxSizeWithTemplate<Elf64_Ehdr>(Memory*, uint64_t*);
 
diff --git a/libunwindstack/ElfInterfaceArm.cpp b/libunwindstack/ElfInterfaceArm.cpp
index 9841e24..5d99bd7 100644
--- a/libunwindstack/ElfInterfaceArm.cpp
+++ b/libunwindstack/ElfInterfaceArm.cpp
@@ -92,16 +92,24 @@
   return true;
 }
 
-bool ElfInterfaceArm::Step(uint64_t pc, Regs* regs, Memory* process_memory, bool* finished) {
+bool ElfInterfaceArm::Step(uint64_t pc, uint64_t load_bias, Regs* regs, Memory* process_memory,
+                           bool* finished) {
   // Dwarf unwind information is precise about whether a pc is covered or not,
   // but arm unwind information only has ranges of pc. In order to avoid
   // incorrectly doing a bad unwind using arm unwind information for a
   // different function, always try and unwind with the dwarf information first.
-  return ElfInterface32::Step(pc, regs, process_memory, finished) ||
-         StepExidx(pc, regs, process_memory, finished);
+  return ElfInterface32::Step(pc, load_bias, regs, process_memory, finished) ||
+         StepExidx(pc, load_bias, regs, process_memory, finished);
 }
 
-bool ElfInterfaceArm::StepExidx(uint64_t pc, Regs* regs, Memory* process_memory, bool* finished) {
+bool ElfInterfaceArm::StepExidx(uint64_t pc, uint64_t load_bias, Regs* regs, Memory* process_memory,
+                                bool* finished) {
+  // Adjust the load bias to get the real relative pc.
+  if (pc < load_bias) {
+    return false;
+  }
+  pc -= load_bias;
+
   RegsArm* regs_arm = reinterpret_cast<RegsArm*>(regs);
   uint64_t entry_offset;
   if (!FindEntry(pc, &entry_offset)) {
diff --git a/libunwindstack/ElfInterfaceArm.h b/libunwindstack/ElfInterfaceArm.h
index eeb2e17..9c067ba 100644
--- a/libunwindstack/ElfInterfaceArm.h
+++ b/libunwindstack/ElfInterfaceArm.h
@@ -70,9 +70,11 @@
 
   bool HandleType(uint64_t offset, uint32_t type, uint64_t load_bias) override;
 
-  bool Step(uint64_t pc, Regs* regs, Memory* process_memory, bool* finished) override;
+  bool Step(uint64_t pc, uint64_t load_bias, Regs* regs, Memory* process_memory,
+            bool* finished) override;
 
-  bool StepExidx(uint64_t pc, Regs* regs, Memory* process_memory, bool* finished);
+  bool StepExidx(uint64_t pc, uint64_t load_bias, Regs* regs, Memory* process_memory,
+                 bool* finished);
 
   uint64_t start_offset() { return start_offset_; }
 
diff --git a/libunwindstack/JitDebug.cpp b/libunwindstack/JitDebug.cpp
new file mode 100644
index 0000000..d1dc0e6
--- /dev/null
+++ b/libunwindstack/JitDebug.cpp
@@ -0,0 +1,246 @@
+/*
+ * 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 <stdint.h>
+#include <sys/mman.h>
+
+#include <memory>
+#include <vector>
+
+#include <unwindstack/Elf.h>
+#include <unwindstack/JitDebug.h>
+#include <unwindstack/Maps.h>
+#include <unwindstack/Memory.h>
+
+// This implements the JIT Compilation Interface.
+// See https://sourceware.org/gdb/onlinedocs/gdb/JIT-Interface.html
+
+namespace unwindstack {
+
+struct JITCodeEntry32Pack {
+  uint32_t next;
+  uint32_t prev;
+  uint32_t symfile_addr;
+  uint64_t symfile_size;
+} __attribute__((packed));
+
+struct JITCodeEntry32Pad {
+  uint32_t next;
+  uint32_t prev;
+  uint32_t symfile_addr;
+  uint32_t pad;
+  uint64_t symfile_size;
+};
+
+struct JITCodeEntry64 {
+  uint64_t next;
+  uint64_t prev;
+  uint64_t symfile_addr;
+  uint64_t symfile_size;
+};
+
+struct JITDescriptorHeader {
+  uint32_t version;
+  uint32_t action_flag;
+};
+
+struct JITDescriptor32 {
+  JITDescriptorHeader header;
+  uint32_t relevant_entry;
+  uint32_t first_entry;
+};
+
+struct JITDescriptor64 {
+  JITDescriptorHeader header;
+  uint64_t relevant_entry;
+  uint64_t first_entry;
+};
+
+JitDebug::JitDebug(std::shared_ptr<Memory>& memory) : memory_(memory) {}
+
+JitDebug::JitDebug(std::shared_ptr<Memory>& memory, std::vector<std::string>& search_libs)
+    : memory_(memory), search_libs_(search_libs) {}
+
+JitDebug::~JitDebug() {
+  for (auto* elf : elf_list_) {
+    delete elf;
+  }
+}
+
+uint64_t JitDebug::ReadDescriptor32(uint64_t addr) {
+  JITDescriptor32 desc;
+  if (!memory_->ReadFully(addr, &desc, sizeof(desc))) {
+    return 0;
+  }
+
+  if (desc.header.version != 1 || desc.first_entry == 0) {
+    // Either unknown version, or no jit entries.
+    return 0;
+  }
+
+  return desc.first_entry;
+}
+
+uint64_t JitDebug::ReadDescriptor64(uint64_t addr) {
+  JITDescriptor64 desc;
+  if (!memory_->ReadFully(addr, &desc, sizeof(desc))) {
+    return 0;
+  }
+
+  if (desc.header.version != 1 || desc.first_entry == 0) {
+    // Either unknown version, or no jit entries.
+    return 0;
+  }
+
+  return desc.first_entry;
+}
+
+uint64_t JitDebug::ReadEntry32Pack(uint64_t* start, uint64_t* size) {
+  JITCodeEntry32Pack code;
+  if (!memory_->ReadFully(entry_addr_, &code, sizeof(code))) {
+    return 0;
+  }
+
+  *start = code.symfile_addr;
+  *size = code.symfile_size;
+  return code.next;
+}
+
+uint64_t JitDebug::ReadEntry32Pad(uint64_t* start, uint64_t* size) {
+  JITCodeEntry32Pad code;
+  if (!memory_->ReadFully(entry_addr_, &code, sizeof(code))) {
+    return 0;
+  }
+
+  *start = code.symfile_addr;
+  *size = code.symfile_size;
+  return code.next;
+}
+
+uint64_t JitDebug::ReadEntry64(uint64_t* start, uint64_t* size) {
+  JITCodeEntry64 code;
+  if (!memory_->ReadFully(entry_addr_, &code, sizeof(code))) {
+    return 0;
+  }
+
+  *start = code.symfile_addr;
+  *size = code.symfile_size;
+  return code.next;
+}
+
+void JitDebug::SetArch(ArchEnum arch) {
+  switch (arch) {
+    case ARCH_X86:
+      read_descriptor_func_ = &JitDebug::ReadDescriptor32;
+      read_entry_func_ = &JitDebug::ReadEntry32Pack;
+      break;
+
+    case ARCH_ARM:
+    case ARCH_MIPS:
+      read_descriptor_func_ = &JitDebug::ReadDescriptor32;
+      read_entry_func_ = &JitDebug::ReadEntry32Pad;
+      break;
+
+    case ARCH_ARM64:
+    case ARCH_X86_64:
+    case ARCH_MIPS64:
+      read_descriptor_func_ = &JitDebug::ReadDescriptor64;
+      read_entry_func_ = &JitDebug::ReadEntry64;
+      break;
+    case ARCH_UNKNOWN:
+      abort();
+  }
+}
+
+void JitDebug::Init(Maps* maps) {
+  if (initialized_) {
+    return;
+  }
+  // Regardless of what happens below, consider the init finished.
+  initialized_ = true;
+
+  std::string descriptor_name("__jit_debug_descriptor");
+  for (MapInfo* info : *maps) {
+    if (!(info->flags & PROT_EXEC) || !(info->flags & PROT_READ) || info->offset != 0) {
+      continue;
+    }
+
+    if (!search_libs_.empty()) {
+      bool found = false;
+      const char* lib = basename(info->name.c_str());
+      for (std::string& name : search_libs_) {
+        if (strcmp(name.c_str(), lib) == 0) {
+          found = true;
+          break;
+        }
+      }
+      if (!found) {
+        continue;
+      }
+    }
+
+    Elf* elf = info->GetElf(memory_, true);
+    uint64_t descriptor_addr;
+    if (elf->GetGlobalVariable(descriptor_name, &descriptor_addr)) {
+      // Search for the first non-zero entry.
+      descriptor_addr += info->start;
+      entry_addr_ = (this->*read_descriptor_func_)(descriptor_addr);
+      if (entry_addr_ != 0) {
+        break;
+      }
+    }
+  }
+}
+
+Elf* JitDebug::GetElf(Maps* maps, uint64_t pc) {
+  // Use a single lock, this object should be used so infrequently that
+  // a fine grain lock is unnecessary.
+  std::lock_guard<std::mutex> guard(lock_);
+  if (!initialized_) {
+    Init(maps);
+  }
+
+  // Search the existing elf object first.
+  for (Elf* elf : elf_list_) {
+    if (elf->IsValidPc(pc)) {
+      return elf;
+    }
+  }
+
+  while (entry_addr_ != 0) {
+    uint64_t start;
+    uint64_t size;
+    entry_addr_ = (this->*read_entry_func_)(&start, &size);
+
+    Elf* elf = new Elf(new MemoryRange(memory_, start, size, 0));
+    elf->Init(true);
+    if (!elf->valid()) {
+      // The data is not formatted in a way we understand, do not attempt
+      // to process any other entries.
+      entry_addr_ = 0;
+      delete elf;
+      return nullptr;
+    }
+    elf_list_.push_back(elf);
+
+    if (elf->IsValidPc(pc)) {
+      return elf;
+    }
+  }
+  return nullptr;
+}
+
+}  // namespace unwindstack
diff --git a/libunwindstack/MapInfo.cpp b/libunwindstack/MapInfo.cpp
index 51bce8e..89fe038 100644
--- a/libunwindstack/MapInfo.cpp
+++ b/libunwindstack/MapInfo.cpp
@@ -122,13 +122,21 @@
 }
 
 uint64_t MapInfo::GetLoadBias(const std::shared_ptr<Memory>& process_memory) {
+  uint64_t cur_load_bias = load_bias.load();
+  if (cur_load_bias != static_cast<uint64_t>(-1)) {
+    return cur_load_bias;
+  }
+
   {
     // Make sure no other thread is trying to add the elf to this map.
     std::lock_guard<std::mutex> guard(mutex_);
     if (elf != nullptr) {
       if (elf->valid()) {
-        return elf->GetLoadBias();
+        cur_load_bias = elf->GetLoadBias();
+        load_bias = cur_load_bias;
+        return cur_load_bias;
       } else {
+        load_bias = 0;
         return 0;
       }
     }
@@ -137,7 +145,9 @@
   // Call lightweight static function that will only read enough of the
   // elf data to get the load bias.
   std::unique_ptr<Memory> memory(CreateMemory(process_memory));
-  return Elf::GetLoadBias(memory.get());
+  cur_load_bias = Elf::GetLoadBias(memory.get());
+  load_bias = cur_load_bias;
+  return cur_load_bias;
 }
 
 }  // namespace unwindstack
diff --git a/libunwindstack/Maps.cpp b/libunwindstack/Maps.cpp
index 56370c1..4c16212 100644
--- a/libunwindstack/Maps.cpp
+++ b/libunwindstack/Maps.cpp
@@ -202,6 +202,13 @@
   return return_value;
 }
 
+void Maps::Add(uint64_t start, uint64_t end, uint64_t offset, uint64_t flags,
+               const std::string& name, uint64_t load_bias) {
+  MapInfo* map_info = new MapInfo(start, end, offset, flags, name);
+  map_info->load_bias = load_bias;
+  maps_.push_back(map_info);
+}
+
 Maps::~Maps() {
   for (auto& map : maps_) {
     delete map;
@@ -235,61 +242,4 @@
   return "/proc/" + std::to_string(pid_) + "/maps";
 }
 
-bool OfflineMaps::Parse() {
-  // Format of maps information:
-  //   <uint64_t> StartOffset
-  //   <uint64_t> EndOffset
-  //   <uint64_t> offset
-  //   <uint16_t> flags
-  //   <uint16_t> MapNameLength
-  //   <VariableLengthValue> MapName
-  android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(file_.c_str(), O_RDONLY)));
-  if (fd == -1) {
-    return false;
-  }
-
-  std::vector<char> name;
-  while (true) {
-    uint64_t start;
-    ssize_t bytes = TEMP_FAILURE_RETRY(read(fd, &start, sizeof(start)));
-    if (bytes == 0) {
-      break;
-    }
-    if (bytes == -1 || bytes != sizeof(start)) {
-      return false;
-    }
-    uint64_t end;
-    bytes = TEMP_FAILURE_RETRY(read(fd, &end, sizeof(end)));
-    if (bytes == -1 || bytes != sizeof(end)) {
-      return false;
-    }
-    uint64_t offset;
-    bytes = TEMP_FAILURE_RETRY(read(fd, &offset, sizeof(offset)));
-    if (bytes == -1 || bytes != sizeof(offset)) {
-      return false;
-    }
-    uint16_t flags;
-    bytes = TEMP_FAILURE_RETRY(read(fd, &flags, sizeof(flags)));
-    if (bytes == -1 || bytes != sizeof(flags)) {
-      return false;
-    }
-    uint16_t len;
-    bytes = TEMP_FAILURE_RETRY(read(fd, &len, sizeof(len)));
-    if (bytes == -1 || bytes != sizeof(len)) {
-      return false;
-    }
-    if (len > 0) {
-      name.resize(len);
-      bytes = TEMP_FAILURE_RETRY(read(fd, name.data(), len));
-      if (bytes == -1 || bytes != len) {
-        return false;
-      }
-      maps_.push_back(new MapInfo(start, end, offset, flags, std::string(name.data(), len)));
-    } else {
-      maps_.push_back(new MapInfo(start, end, offset, flags, ""));
-    }
-  }
-  return true;
-}
-
 }  // namespace unwindstack
diff --git a/libunwindstack/Memory.cpp b/libunwindstack/Memory.cpp
index 1f3c6c3..d4ba680 100644
--- a/libunwindstack/Memory.cpp
+++ b/libunwindstack/Memory.cpp
@@ -35,10 +35,6 @@
 namespace unwindstack {
 
 static size_t ProcessVmRead(pid_t pid, uint64_t remote_src, void* dst, size_t len) {
-  struct iovec dst_iov = {
-      .iov_base = dst,
-      .iov_len = len,
-  };
 
   // Split up the remote read across page boundaries.
   // From the manpage:
@@ -49,39 +45,49 @@
   //   perform a partial transfer that splits a single iovec element.
   constexpr size_t kMaxIovecs = 64;
   struct iovec src_iovs[kMaxIovecs];
-  size_t iovecs_used = 0;
 
   uint64_t cur = remote_src;
+  size_t total_read = 0;
   while (len > 0) {
-    if (iovecs_used == kMaxIovecs) {
-      errno = EINVAL;
-      return 0;
+    struct iovec dst_iov = {
+        .iov_base = &reinterpret_cast<uint8_t*>(dst)[total_read], .iov_len = len,
+    };
+
+    size_t iovecs_used = 0;
+    while (len > 0) {
+      if (iovecs_used == kMaxIovecs) {
+        break;
+      }
+
+      // struct iovec uses void* for iov_base.
+      if (cur >= UINTPTR_MAX) {
+        errno = EFAULT;
+        return total_read;
+      }
+
+      src_iovs[iovecs_used].iov_base = reinterpret_cast<void*>(cur);
+
+      uintptr_t misalignment = cur & (getpagesize() - 1);
+      size_t iov_len = getpagesize() - misalignment;
+      iov_len = std::min(iov_len, len);
+
+      len -= iov_len;
+      if (__builtin_add_overflow(cur, iov_len, &cur)) {
+        errno = EFAULT;
+        return total_read;
+      }
+
+      src_iovs[iovecs_used].iov_len = iov_len;
+      ++iovecs_used;
     }
 
-    // struct iovec uses void* for iov_base.
-    if (cur >= UINTPTR_MAX) {
-      errno = EFAULT;
-      return 0;
+    ssize_t rc = process_vm_readv(pid, &dst_iov, 1, src_iovs, iovecs_used, 0);
+    if (rc == -1) {
+      return total_read;
     }
-
-    src_iovs[iovecs_used].iov_base = reinterpret_cast<void*>(cur);
-
-    uintptr_t misalignment = cur & (getpagesize() - 1);
-    size_t iov_len = getpagesize() - misalignment;
-    iov_len = std::min(iov_len, len);
-
-    len -= iov_len;
-    if (__builtin_add_overflow(cur, iov_len, &cur)) {
-      errno = EFAULT;
-      return 0;
-    }
-
-    src_iovs[iovecs_used].iov_len = iov_len;
-    ++iovecs_used;
+    total_read += rc;
   }
-
-  ssize_t rc = process_vm_readv(pid, &dst_iov, 1, src_iovs, iovecs_used, 0);
-  return rc == -1 ? 0 : rc;
+  return total_read;
 }
 
 static bool PtraceReadLong(pid_t pid, uint64_t addr, long* value) {
@@ -339,4 +345,26 @@
   return memory_->Read(addr, dst, size);
 }
 
+MemoryOfflineParts::~MemoryOfflineParts() {
+  for (auto memory : memories_) {
+    delete memory;
+  }
+}
+
+size_t MemoryOfflineParts::Read(uint64_t addr, void* dst, size_t size) {
+  if (memories_.empty()) {
+    return 0;
+  }
+
+  // Do a read on each memory object, no support for reading across the
+  // different memory objects.
+  for (MemoryOffline* memory : memories_) {
+    size_t bytes = memory->Read(addr, dst, size);
+    if (bytes != 0) {
+      return bytes;
+    }
+  }
+  return 0;
+}
+
 }  // namespace unwindstack
diff --git a/libunwindstack/RegsArm.cpp b/libunwindstack/RegsArm.cpp
index 34f29bd..d05c3e2 100644
--- a/libunwindstack/RegsArm.cpp
+++ b/libunwindstack/RegsArm.cpp
@@ -37,10 +37,6 @@
 }
 
 uint64_t RegsArm::GetAdjustedPc(uint64_t rel_pc, Elf* elf) {
-  if (!elf->valid()) {
-    return rel_pc;
-  }
-
   uint64_t load_bias = elf->GetLoadBias();
   if (rel_pc < load_bias) {
     return rel_pc;
diff --git a/libunwindstack/Symbols.cpp b/libunwindstack/Symbols.cpp
index b4b92d6..25def40 100644
--- a/libunwindstack/Symbols.cpp
+++ b/libunwindstack/Symbols.cpp
@@ -108,8 +108,35 @@
   return return_value;
 }
 
+template <typename SymType>
+bool Symbols::GetGlobal(Memory* elf_memory, const std::string& name, uint64_t* memory_address) {
+  uint64_t cur_offset = offset_;
+  while (cur_offset + entry_size_ <= end_) {
+    SymType entry;
+    if (!elf_memory->ReadFully(cur_offset, &entry, sizeof(entry))) {
+      return false;
+    }
+    cur_offset += entry_size_;
+
+    if (entry.st_shndx != SHN_UNDEF && ELF32_ST_TYPE(entry.st_info) == STT_OBJECT &&
+        ELF32_ST_BIND(entry.st_info) == STB_GLOBAL) {
+      uint64_t str_offset = str_offset_ + entry.st_name;
+      if (str_offset < str_end_) {
+        std::string symbol;
+        if (elf_memory->ReadString(str_offset, &symbol, str_end_ - str_offset) && symbol == name) {
+          *memory_address = entry.st_value;
+          return true;
+        }
+      }
+    }
+  }
+  return false;
+}
+
 // Instantiate all of the needed template functions.
 template bool Symbols::GetName<Elf32_Sym>(uint64_t, uint64_t, Memory*, std::string*, uint64_t*);
 template bool Symbols::GetName<Elf64_Sym>(uint64_t, uint64_t, Memory*, std::string*, uint64_t*);
 
+template bool Symbols::GetGlobal<Elf32_Sym>(Memory*, const std::string&, uint64_t*);
+template bool Symbols::GetGlobal<Elf64_Sym>(Memory*, const std::string&, uint64_t*);
 }  // namespace unwindstack
diff --git a/libunwindstack/Symbols.h b/libunwindstack/Symbols.h
index 689144b..7d239c1 100644
--- a/libunwindstack/Symbols.h
+++ b/libunwindstack/Symbols.h
@@ -47,6 +47,9 @@
   bool GetName(uint64_t addr, uint64_t load_bias, Memory* elf_memory, std::string* name,
                uint64_t* func_offset);
 
+  template <typename SymType>
+  bool GetGlobal(Memory* elf_memory, const std::string& name, uint64_t* memory_address);
+
   void ClearCache() {
     symbols_.clear();
     cur_offset_ = offset_;
diff --git a/libunwindstack/UcontextX86_64.h b/libunwindstack/UcontextX86_64.h
index d689796..2b8bdc4 100644
--- a/libunwindstack/UcontextX86_64.h
+++ b/libunwindstack/UcontextX86_64.h
@@ -38,6 +38,7 @@
 struct x86_64_stack_t {
   uint64_t ss_sp;    // void __user*
   int32_t ss_flags;  // int
+  int32_t pad;
   uint64_t ss_size;  // size_t
 };
 
diff --git a/libunwindstack/Unwinder.cpp b/libunwindstack/Unwinder.cpp
index a83f85b..b0a1c0c 100644
--- a/libunwindstack/Unwinder.cpp
+++ b/libunwindstack/Unwinder.cpp
@@ -27,12 +27,13 @@
 #include <android-base/stringprintf.h>
 
 #include <unwindstack/Elf.h>
+#include <unwindstack/JitDebug.h>
 #include <unwindstack/MapInfo.h>
 #include <unwindstack/Unwinder.h>
 
 namespace unwindstack {
 
-void Unwinder::FillInFrame(MapInfo* map_info, Elf* elf, uint64_t adjusted_rel_pc) {
+void Unwinder::FillInFrame(MapInfo* map_info, Elf* elf, uint64_t adjusted_rel_pc, uint64_t func_pc) {
   size_t frame_num = frames_.size();
   frames_.resize(frame_num + 1);
   FrameData* frame = &frames_.at(frame_num);
@@ -53,7 +54,7 @@
   frame->map_flags = map_info->flags;
   frame->map_load_bias = elf->GetLoadBias();
 
-  if (!elf->GetFunctionName(frame->rel_pc, &frame->function_name, &frame->function_offset)) {
+  if (!elf->GetFunctionName(func_pc, &frame->function_name, &frame->function_offset)) {
     frame->function_name = "";
     frame->function_offset = 0;
   }
@@ -79,17 +80,20 @@
 
   bool return_address_attempt = false;
   bool adjust_pc = false;
+  std::unique_ptr<JitDebug> jit_debug;
   for (; frames_.size() < max_frames_;) {
     uint64_t cur_pc = regs_->pc();
     uint64_t cur_sp = regs_->sp();
 
     MapInfo* map_info = maps_->Find(regs_->pc());
     uint64_t rel_pc;
+    uint64_t adjusted_pc;
     uint64_t adjusted_rel_pc;
     Elf* elf;
     if (map_info == nullptr) {
       rel_pc = regs_->pc();
       adjusted_rel_pc = rel_pc;
+      adjusted_pc = rel_pc;
     } else {
       if (ShouldStop(map_suffixes_to_ignore, map_info->name)) {
         break;
@@ -97,16 +101,30 @@
       elf = map_info->GetElf(process_memory_, true);
       rel_pc = elf->GetRelPc(regs_->pc(), map_info);
       if (adjust_pc) {
-        adjusted_rel_pc = regs_->GetAdjustedPc(rel_pc, elf);
+        adjusted_pc = regs_->GetAdjustedPc(rel_pc, elf);
       } else {
-        adjusted_rel_pc = rel_pc;
+        adjusted_pc = rel_pc;
+      }
+      adjusted_rel_pc = adjusted_pc;
+
+      // If the pc is in an invalid elf file, try and get an Elf object
+      // using the jit debug information.
+      if (!elf->valid() && jit_debug_ != nullptr) {
+        uint64_t adjusted_jit_pc = regs_->pc() - (rel_pc - adjusted_pc);
+        Elf* jit_elf = jit_debug_->GetElf(maps_, adjusted_jit_pc);
+        if (jit_elf != nullptr) {
+          // The jit debug information requires a non relative adjusted pc.
+          adjusted_pc = adjusted_jit_pc;
+          adjusted_rel_pc = adjusted_pc - map_info->start;
+          elf = jit_elf;
+        }
       }
     }
 
     if (map_info == nullptr || initial_map_names_to_skip == nullptr ||
         std::find(initial_map_names_to_skip->begin(), initial_map_names_to_skip->end(),
                   basename(map_info->name.c_str())) == initial_map_names_to_skip->end()) {
-      FillInFrame(map_info, elf, adjusted_rel_pc);
+      FillInFrame(map_info, elf, adjusted_rel_pc, adjusted_pc);
 
       // Once a frame is added, stop skipping frames.
       initial_map_names_to_skip = nullptr;
@@ -134,7 +152,7 @@
           in_device_map = true;
         } else {
           bool finished;
-          stepped = elf->Step(rel_pc, adjusted_rel_pc, map_info->elf_offset, regs_,
+          stepped = elf->Step(rel_pc, adjusted_pc, map_info->elf_offset, regs_,
                               process_memory_.get(), &finished);
           if (stepped && finished) {
             break;
@@ -174,13 +192,13 @@
   if (frame_num >= frames_.size()) {
     return "";
   }
-  return FormatFrame(frames_[frame_num], regs_->Format32Bit());
+  return FormatFrame(frames_[frame_num], regs_->Is32Bit());
 }
 
-std::string Unwinder::FormatFrame(const FrameData& frame, bool bits32) {
+std::string Unwinder::FormatFrame(const FrameData& frame, bool is32bit) {
   std::string data;
 
-  if (bits32) {
+  if (is32bit) {
     data += android::base::StringPrintf("  #%02zu pc %08" PRIx64, frame.num, frame.rel_pc);
   } else {
     data += android::base::StringPrintf("  #%02zu pc %016" PRIx64, frame.num, frame.rel_pc);
@@ -208,4 +226,9 @@
   return data;
 }
 
+void Unwinder::SetJitDebug(JitDebug* jit_debug, ArchEnum arch) {
+  jit_debug->SetArch(arch);
+  jit_debug_ = jit_debug;
+}
+
 }  // namespace unwindstack
diff --git a/libunwindstack/include/unwindstack/Elf.h b/libunwindstack/include/unwindstack/Elf.h
index a85e5f4..5f34391 100644
--- a/libunwindstack/include/unwindstack/Elf.h
+++ b/libunwindstack/include/unwindstack/Elf.h
@@ -59,6 +59,8 @@
 
   bool GetFunctionName(uint64_t addr, std::string* name, uint64_t* func_offset);
 
+  bool GetGlobalVariable(const std::string& name, uint64_t* memory_address);
+
   uint64_t GetRelPc(uint64_t pc, const MapInfo* map_info);
 
   bool Step(uint64_t rel_pc, uint64_t adjusted_rel_pc, uint64_t elf_offset, Regs* regs,
@@ -68,6 +70,8 @@
 
   uint64_t GetLoadBias() { return load_bias_; }
 
+  bool IsValidPc(uint64_t pc);
+
   bool valid() { return valid_; }
 
   uint32_t machine_type() { return machine_type_; }
diff --git a/libunwindstack/include/unwindstack/ElfInterface.h b/libunwindstack/include/unwindstack/ElfInterface.h
index 5cfe74d..faa61ee 100644
--- a/libunwindstack/include/unwindstack/ElfInterface.h
+++ b/libunwindstack/include/unwindstack/ElfInterface.h
@@ -60,7 +60,12 @@
   virtual bool GetFunctionName(uint64_t addr, uint64_t load_bias, std::string* name,
                                uint64_t* offset) = 0;
 
-  virtual bool Step(uint64_t rel_pc, Regs* regs, Memory* process_memory, bool* finished);
+  virtual bool GetGlobalVariable(const std::string& name, uint64_t* memory_address) = 0;
+
+  virtual bool Step(uint64_t rel_pc, uint64_t load_bias, Regs* regs, Memory* process_memory,
+                    bool* finished);
+
+  virtual bool IsValidPc(uint64_t pc);
 
   Memory* CreateGnuDebugdataMemory();
 
@@ -68,7 +73,10 @@
 
   const std::unordered_map<uint64_t, LoadInfo>& pt_loads() { return pt_loads_; }
 
+  void SetGnuDebugdataInterface(ElfInterface* interface) { gnu_debugdata_interface_ = interface; }
+
   uint64_t dynamic_offset() { return dynamic_offset_; }
+  uint64_t dynamic_vaddr() { return dynamic_vaddr_; }
   uint64_t dynamic_size() { return dynamic_size_; }
   uint64_t eh_frame_hdr_offset() { return eh_frame_hdr_offset_; }
   uint64_t eh_frame_hdr_size() { return eh_frame_hdr_size_; }
@@ -105,6 +113,9 @@
   bool GetFunctionNameWithTemplate(uint64_t addr, uint64_t load_bias, std::string* name,
                                    uint64_t* func_offset);
 
+  template <typename SymType>
+  bool GetGlobalVariableWithTemplate(const std::string& name, uint64_t* memory_address);
+
   virtual bool HandleType(uint64_t, uint32_t, uint64_t) { return false; }
 
   template <typename EhdrType>
@@ -115,6 +126,7 @@
 
   // Stored elf data.
   uint64_t dynamic_offset_ = 0;
+  uint64_t dynamic_vaddr_ = 0;
   uint64_t dynamic_size_ = 0;
 
   uint64_t eh_frame_hdr_offset_ = 0;
@@ -134,6 +146,8 @@
 
   std::unique_ptr<DwarfSection> eh_frame_;
   std::unique_ptr<DwarfSection> debug_frame_;
+  // The Elf object owns the gnu_debugdata interface object.
+  ElfInterface* gnu_debugdata_interface_ = nullptr;
 
   std::vector<Symbols*> symbols_;
 };
@@ -158,6 +172,10 @@
     return ElfInterface::GetFunctionNameWithTemplate<Elf32_Sym>(addr, load_bias, name, func_offset);
   }
 
+  bool GetGlobalVariable(const std::string& name, uint64_t* memory_address) override {
+    return ElfInterface::GetGlobalVariableWithTemplate<Elf32_Sym>(name, memory_address);
+  }
+
   static void GetMaxSize(Memory* memory, uint64_t* size) {
     GetMaxSizeWithTemplate<Elf32_Ehdr>(memory, size);
   }
@@ -183,6 +201,10 @@
     return ElfInterface::GetFunctionNameWithTemplate<Elf64_Sym>(addr, load_bias, name, func_offset);
   }
 
+  bool GetGlobalVariable(const std::string& name, uint64_t* memory_address) override {
+    return ElfInterface::GetGlobalVariableWithTemplate<Elf64_Sym>(name, memory_address);
+  }
+
   static void GetMaxSize(Memory* memory, uint64_t* size) {
     GetMaxSizeWithTemplate<Elf64_Ehdr>(memory, size);
   }
diff --git a/libunwindstack/include/unwindstack/JitDebug.h b/libunwindstack/include/unwindstack/JitDebug.h
new file mode 100644
index 0000000..0bcd0b0
--- /dev/null
+++ b/libunwindstack/include/unwindstack/JitDebug.h
@@ -0,0 +1,69 @@
+/*
+ * 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 _LIBUNWINDSTACK_JIT_DEBUG_H
+#define _LIBUNWINDSTACK_JIT_DEBUG_H
+
+#include <stdint.h>
+
+#include <memory>
+#include <mutex>
+#include <string>
+#include <vector>
+
+namespace unwindstack {
+
+// Forward declarations.
+class Elf;
+class Maps;
+class Memory;
+enum ArchEnum : uint8_t;
+
+class JitDebug {
+ public:
+  explicit JitDebug(std::shared_ptr<Memory>& memory);
+  JitDebug(std::shared_ptr<Memory>& memory, std::vector<std::string>& search_libs);
+  ~JitDebug();
+
+  Elf* GetElf(Maps* maps, uint64_t pc);
+
+  void SetArch(ArchEnum arch);
+
+ private:
+  void Init(Maps* maps);
+
+  std::shared_ptr<Memory> memory_;
+  uint64_t entry_addr_ = 0;
+  bool initialized_ = false;
+  std::vector<Elf*> elf_list_;
+  std::vector<std::string> search_libs_;
+
+  std::mutex lock_;
+
+  uint64_t (JitDebug::*read_descriptor_func_)(uint64_t) = nullptr;
+  uint64_t (JitDebug::*read_entry_func_)(uint64_t*, uint64_t*) = nullptr;
+
+  uint64_t ReadDescriptor32(uint64_t);
+  uint64_t ReadDescriptor64(uint64_t);
+
+  uint64_t ReadEntry32Pack(uint64_t* start, uint64_t* size);
+  uint64_t ReadEntry32Pad(uint64_t* start, uint64_t* size);
+  uint64_t ReadEntry64(uint64_t* start, uint64_t* size);
+};
+
+}  // namespace unwindstack
+
+#endif  // _LIBUNWINDSTACK_JIT_DEBUG_H
diff --git a/libunwindstack/include/unwindstack/MapInfo.h b/libunwindstack/include/unwindstack/MapInfo.h
index 6f8ceca..22e48f7 100644
--- a/libunwindstack/include/unwindstack/MapInfo.h
+++ b/libunwindstack/include/unwindstack/MapInfo.h
@@ -19,6 +19,7 @@
 
 #include <stdint.h>
 
+#include <atomic>
 #include <mutex>
 #include <string>
 
@@ -33,7 +34,12 @@
   MapInfo() = default;
   MapInfo(uint64_t start, uint64_t end) : start(start), end(end) {}
   MapInfo(uint64_t start, uint64_t end, uint64_t offset, uint64_t flags, const std::string& name)
-      : start(start), end(end), offset(offset), flags(flags), name(name) {}
+      : start(start),
+        end(end),
+        offset(offset),
+        flags(flags),
+        name(name),
+        load_bias(static_cast<uint64_t>(-1)) {}
   ~MapInfo() { delete elf; }
 
   uint64_t start = 0;
@@ -48,6 +54,8 @@
   // instead of a portion of the file.
   uint64_t elf_offset = 0;
 
+  std::atomic_uint64_t load_bias;
+
   // This function guarantees it will never return nullptr.
   Elf* GetElf(const std::shared_ptr<Memory>& process_memory, bool init_gnu_debugdata = false);
 
diff --git a/libunwindstack/include/unwindstack/Maps.h b/libunwindstack/include/unwindstack/Maps.h
index 34fef7f..17a2d28 100644
--- a/libunwindstack/include/unwindstack/Maps.h
+++ b/libunwindstack/include/unwindstack/Maps.h
@@ -42,6 +42,9 @@
 
   virtual const std::string GetMapsFile() const { return ""; }
 
+  void Add(uint64_t start, uint64_t end, uint64_t offset, uint64_t flags, const std::string& name,
+           uint64_t load_bias);
+
   typedef std::vector<MapInfo*>::iterator iterator;
   iterator begin() { return maps_.begin(); }
   iterator end() { return maps_.end(); }
@@ -100,14 +103,6 @@
   const std::string file_;
 };
 
-class OfflineMaps : public FileMaps {
- public:
-  OfflineMaps(const std::string& file) : FileMaps(file) {}
-  virtual ~OfflineMaps() = default;
-
-  bool Parse() override;
-};
-
 }  // namespace unwindstack
 
 #endif  // _LIBUNWINDSTACK_MAPS_H
diff --git a/libunwindstack/include/unwindstack/Memory.h b/libunwindstack/include/unwindstack/Memory.h
index 94ceaab..19bce04 100644
--- a/libunwindstack/include/unwindstack/Memory.h
+++ b/libunwindstack/include/unwindstack/Memory.h
@@ -151,6 +151,19 @@
   std::unique_ptr<MemoryRange> memory_;
 };
 
+class MemoryOfflineParts : public Memory {
+ public:
+  MemoryOfflineParts() = default;
+  virtual ~MemoryOfflineParts();
+
+  void Add(MemoryOffline* memory) { memories_.push_back(memory); }
+
+  size_t Read(uint64_t addr, void* dst, size_t size) override;
+
+ private:
+  std::vector<MemoryOffline*> memories_;
+};
+
 }  // namespace unwindstack
 
 #endif  // _LIBUNWINDSTACK_MEMORY_H
diff --git a/libunwindstack/include/unwindstack/Regs.h b/libunwindstack/include/unwindstack/Regs.h
index 613682f..1904d4d 100644
--- a/libunwindstack/include/unwindstack/Regs.h
+++ b/libunwindstack/include/unwindstack/Regs.h
@@ -51,7 +51,7 @@
 
   virtual ArchEnum Arch() = 0;
 
-  virtual bool Format32Bit() = 0;
+  virtual bool Is32Bit() = 0;
 
   virtual void* RawData() = 0;
   virtual uint64_t pc() = 0;
@@ -94,7 +94,7 @@
   void set_pc(AddressType pc) { pc_ = pc; }
   void set_sp(AddressType sp) { sp_ = sp; }
 
-  bool Format32Bit() override { return sizeof(AddressType) == sizeof(uint32_t); }
+  bool Is32Bit() override { return sizeof(AddressType) == sizeof(uint32_t); }
 
   inline AddressType& operator[](size_t reg) { return regs_[reg]; }
 
diff --git a/libunwindstack/include/unwindstack/Unwinder.h b/libunwindstack/include/unwindstack/Unwinder.h
index b64d460..5adec4f 100644
--- a/libunwindstack/include/unwindstack/Unwinder.h
+++ b/libunwindstack/include/unwindstack/Unwinder.h
@@ -32,6 +32,8 @@
 
 // Forward declarations.
 class Elf;
+class JitDebug;
+enum ArchEnum : uint8_t;
 
 struct FrameData {
   size_t num;
@@ -67,16 +69,19 @@
   const std::vector<FrameData>& frames() { return frames_; }
 
   std::string FormatFrame(size_t frame_num);
-  static std::string FormatFrame(const FrameData& frame, bool bits32);
+  static std::string FormatFrame(const FrameData& frame, bool is32bit);
+
+  void SetJitDebug(JitDebug* jit_debug, ArchEnum arch);
 
  private:
-  void FillInFrame(MapInfo* map_info, Elf* elf, uint64_t adjusted_rel_pc);
+  void FillInFrame(MapInfo* map_info, Elf* elf, uint64_t adjusted_rel_pc, uint64_t adjusted_pc);
 
   size_t max_frames_;
   Maps* maps_;
   Regs* regs_;
   std::vector<FrameData> frames_;
   std::shared_ptr<Memory> process_memory_;
+  JitDebug* jit_debug_ = nullptr;
 };
 
 }  // namespace unwindstack
diff --git a/libunwindstack/tests/ElfFake.cpp b/libunwindstack/tests/ElfFake.cpp
index b94a8a4..ae9da5e 100644
--- a/libunwindstack/tests/ElfFake.cpp
+++ b/libunwindstack/tests/ElfFake.cpp
@@ -43,7 +43,16 @@
   return true;
 }
 
-bool ElfInterfaceFake::Step(uint64_t, Regs* regs, Memory*, bool* finished) {
+bool ElfInterfaceFake::GetGlobalVariable(const std::string& global, uint64_t* offset) {
+  auto entry = globals_.find(global);
+  if (entry == globals_.end()) {
+    return false;
+  }
+  *offset = entry->second;
+  return true;
+}
+
+bool ElfInterfaceFake::Step(uint64_t, uint64_t, Regs* regs, Memory*, bool* finished) {
   if (steps_.empty()) {
     return false;
   }
diff --git a/libunwindstack/tests/ElfFake.h b/libunwindstack/tests/ElfFake.h
index 565b13f..099026c 100644
--- a/libunwindstack/tests/ElfFake.h
+++ b/libunwindstack/tests/ElfFake.h
@@ -21,6 +21,7 @@
 
 #include <deque>
 #include <string>
+#include <unordered_map>
 
 #include <unwindstack/Elf.h>
 #include <unwindstack/ElfInterface.h>
@@ -55,6 +56,9 @@
   void FakeSetLoadBias(uint64_t load_bias) { load_bias_ = load_bias; }
 
   void FakeSetInterface(ElfInterface* interface) { interface_.reset(interface); }
+  void FakeSetGnuDebugdataInterface(ElfInterface* interface) {
+    gnu_debugdata_interface_.reset(interface);
+  }
 };
 
 class ElfInterfaceFake : public ElfInterface {
@@ -67,9 +71,13 @@
   bool GetSoname(std::string*) override { return false; }
 
   bool GetFunctionName(uint64_t, uint64_t, std::string*, uint64_t*) override;
+  bool GetGlobalVariable(const std::string&, uint64_t*) override;
 
-  bool Step(uint64_t, Regs*, Memory*, bool*) override;
+  bool Step(uint64_t, uint64_t, Regs*, Memory*, bool*) override;
 
+  void FakeSetGlobalVariable(const std::string& global, uint64_t offset) {
+    globals_[global] = offset;
+  }
 
   static void FakePushFunctionData(const FunctionData data) { functions_.push_back(data); }
   static void FakePushStepData(const StepData data) { steps_.push_back(data); }
@@ -80,6 +88,8 @@
   }
 
  private:
+  std::unordered_map<std::string, uint64_t> globals_;
+
   static std::deque<FunctionData> functions_;
   static std::deque<StepData> steps_;
 };
diff --git a/libunwindstack/tests/ElfInterfaceArmTest.cpp b/libunwindstack/tests/ElfInterfaceArmTest.cpp
index 5f7cf60..e6763ab 100644
--- a/libunwindstack/tests/ElfInterfaceArmTest.cpp
+++ b/libunwindstack/tests/ElfInterfaceArmTest.cpp
@@ -302,7 +302,7 @@
 
   // FindEntry fails.
   bool finished;
-  ASSERT_FALSE(interface.StepExidx(0x7000, nullptr, nullptr, &finished));
+  ASSERT_FALSE(interface.StepExidx(0x7000, 0, nullptr, nullptr, &finished));
 
   // ExtractEntry should fail.
   interface.FakeSetStartOffset(0x1000);
@@ -315,20 +315,26 @@
   regs[ARM_REG_LR] = 0x20000;
   regs.set_sp(regs[ARM_REG_SP]);
   regs.set_pc(0x1234);
-  ASSERT_FALSE(interface.StepExidx(0x7000, &regs, &process_memory_, &finished));
+  ASSERT_FALSE(interface.StepExidx(0x7000, 0, &regs, &process_memory_, &finished));
 
   // Eval should fail.
   memory_.SetData32(0x1004, 0x81000000);
-  ASSERT_FALSE(interface.StepExidx(0x7000, &regs, &process_memory_, &finished));
+  ASSERT_FALSE(interface.StepExidx(0x7000, 0, &regs, &process_memory_, &finished));
 
   // Everything should pass.
   memory_.SetData32(0x1004, 0x80b0b0b0);
-  ASSERT_TRUE(interface.StepExidx(0x7000, &regs, &process_memory_, &finished));
+  ASSERT_TRUE(interface.StepExidx(0x7000, 0, &regs, &process_memory_, &finished));
   ASSERT_FALSE(finished);
   ASSERT_EQ(0x1000U, regs.sp());
   ASSERT_EQ(0x1000U, regs[ARM_REG_SP]);
   ASSERT_EQ(0x20000U, regs.pc());
   ASSERT_EQ(0x20000U, regs[ARM_REG_PC]);
+
+  // Load bias is non-zero.
+  ASSERT_TRUE(interface.StepExidx(0x8000, 0x1000, &regs, &process_memory_, &finished));
+
+  // Pc too small.
+  ASSERT_FALSE(interface.StepExidx(0x8000, 0x9000, &regs, &process_memory_, &finished));
 }
 
 TEST_F(ElfInterfaceArmTest, StepExidx_pc_set) {
@@ -349,7 +355,7 @@
 
   // Everything should pass.
   bool finished;
-  ASSERT_TRUE(interface.StepExidx(0x7000, &regs, &process_memory_, &finished));
+  ASSERT_TRUE(interface.StepExidx(0x7000, 0, &regs, &process_memory_, &finished));
   ASSERT_FALSE(finished);
   ASSERT_EQ(0x10004U, regs.sp());
   ASSERT_EQ(0x10004U, regs[ARM_REG_SP]);
@@ -372,7 +378,7 @@
   regs.set_pc(0x1234);
 
   bool finished;
-  ASSERT_TRUE(interface.StepExidx(0x7000, &regs, &process_memory_, &finished));
+  ASSERT_TRUE(interface.StepExidx(0x7000, 0, &regs, &process_memory_, &finished));
   ASSERT_TRUE(finished);
   ASSERT_EQ(0x10000U, regs.sp());
   ASSERT_EQ(0x10000U, regs[ARM_REG_SP]);
@@ -394,7 +400,7 @@
   regs.set_pc(0x1234);
 
   bool finished;
-  ASSERT_TRUE(interface.StepExidx(0x7000, &regs, &process_memory_, &finished));
+  ASSERT_TRUE(interface.StepExidx(0x7000, 0, &regs, &process_memory_, &finished));
   ASSERT_TRUE(finished);
   ASSERT_EQ(0x10000U, regs.sp());
   ASSERT_EQ(0x10000U, regs[ARM_REG_SP]);
@@ -420,7 +426,7 @@
   regs.set_pc(0x1234);
 
   bool finished;
-  ASSERT_TRUE(interface.StepExidx(0x7000, &regs, &process_memory_, &finished));
+  ASSERT_TRUE(interface.StepExidx(0x7000, 0, &regs, &process_memory_, &finished));
   ASSERT_TRUE(finished);
   ASSERT_EQ(0U, regs.pc());
 
@@ -432,7 +438,7 @@
   regs.set_sp(regs[ARM_REG_SP]);
   regs.set_pc(0x1234);
 
-  ASSERT_TRUE(interface.StepExidx(0x7000, &regs, &process_memory_, &finished));
+  ASSERT_TRUE(interface.StepExidx(0x7000, 0, &regs, &process_memory_, &finished));
   ASSERT_TRUE(finished);
   ASSERT_EQ(0U, regs.pc());
 }
diff --git a/libunwindstack/tests/ElfInterfaceTest.cpp b/libunwindstack/tests/ElfInterfaceTest.cpp
index e138c3a..042c5fb 100644
--- a/libunwindstack/tests/ElfInterfaceTest.cpp
+++ b/libunwindstack/tests/ElfInterfaceTest.cpp
@@ -958,4 +958,189 @@
   InitSectionHeadersOffsets<Elf64_Ehdr, Elf64_Shdr, ElfInterface64>();
 }
 
+TEST_F(ElfInterfaceTest, is_valid_pc_from_pt_load) {
+  std::unique_ptr<ElfInterface> elf(new ElfInterface32(&memory_));
+
+  Elf32_Ehdr ehdr;
+  memset(&ehdr, 0, sizeof(ehdr));
+  ehdr.e_phoff = 0x100;
+  ehdr.e_phnum = 1;
+  ehdr.e_phentsize = sizeof(Elf32_Phdr);
+  memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+  Elf32_Phdr phdr;
+  memset(&phdr, 0, sizeof(phdr));
+  phdr.p_type = PT_LOAD;
+  phdr.p_vaddr = 0;
+  phdr.p_memsz = 0x10000;
+  phdr.p_flags = PF_R | PF_X;
+  phdr.p_align = 0x1000;
+  memory_.SetMemory(0x100, &phdr, sizeof(phdr));
+
+  uint64_t load_bias = 0;
+  ASSERT_TRUE(elf->Init(&load_bias));
+  EXPECT_EQ(0U, load_bias);
+  EXPECT_TRUE(elf->IsValidPc(0));
+  EXPECT_TRUE(elf->IsValidPc(0x5000));
+  EXPECT_TRUE(elf->IsValidPc(0xffff));
+  EXPECT_FALSE(elf->IsValidPc(0x10000));
+}
+
+TEST_F(ElfInterfaceTest, is_valid_pc_from_pt_load_non_zero_load_bias) {
+  std::unique_ptr<ElfInterface> elf(new ElfInterface32(&memory_));
+
+  Elf32_Ehdr ehdr;
+  memset(&ehdr, 0, sizeof(ehdr));
+  ehdr.e_phoff = 0x100;
+  ehdr.e_phnum = 1;
+  ehdr.e_phentsize = sizeof(Elf32_Phdr);
+  memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+  Elf32_Phdr phdr;
+  memset(&phdr, 0, sizeof(phdr));
+  phdr.p_type = PT_LOAD;
+  phdr.p_vaddr = 0x2000;
+  phdr.p_memsz = 0x10000;
+  phdr.p_flags = PF_R | PF_X;
+  phdr.p_align = 0x1000;
+  memory_.SetMemory(0x100, &phdr, sizeof(phdr));
+
+  uint64_t load_bias = 0;
+  ASSERT_TRUE(elf->Init(&load_bias));
+  EXPECT_EQ(0x2000U, load_bias);
+  EXPECT_FALSE(elf->IsValidPc(0));
+  EXPECT_FALSE(elf->IsValidPc(0x1000));
+  EXPECT_FALSE(elf->IsValidPc(0x1fff));
+  EXPECT_TRUE(elf->IsValidPc(0x2000));
+  EXPECT_TRUE(elf->IsValidPc(0x5000));
+  EXPECT_TRUE(elf->IsValidPc(0x11fff));
+  EXPECT_FALSE(elf->IsValidPc(0x12000));
+}
+
+TEST_F(ElfInterfaceTest, is_valid_pc_from_debug_frame) {
+  std::unique_ptr<ElfInterface> elf(new ElfInterface32(&memory_));
+
+  uint64_t sh_offset = 0x100;
+
+  Elf32_Ehdr ehdr;
+  memset(&ehdr, 0, sizeof(ehdr));
+  ehdr.e_shstrndx = 1;
+  ehdr.e_shoff = sh_offset;
+  ehdr.e_shentsize = sizeof(Elf32_Shdr);
+  ehdr.e_shnum = 3;
+  memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+  Elf32_Shdr shdr;
+  memset(&shdr, 0, sizeof(shdr));
+  shdr.sh_type = SHT_NULL;
+  memory_.SetMemory(sh_offset, &shdr, sizeof(shdr));
+
+  sh_offset += sizeof(shdr);
+  memset(&shdr, 0, sizeof(shdr));
+  shdr.sh_type = SHT_STRTAB;
+  shdr.sh_name = 1;
+  shdr.sh_offset = 0x500;
+  shdr.sh_size = 0x100;
+  memory_.SetMemory(sh_offset, &shdr, sizeof(shdr));
+  memory_.SetMemory(0x500, ".debug_frame");
+
+  sh_offset += sizeof(shdr);
+  memset(&shdr, 0, sizeof(shdr));
+  shdr.sh_type = SHT_PROGBITS;
+  shdr.sh_name = 0;
+  shdr.sh_addr = 0x600;
+  shdr.sh_offset = 0x600;
+  shdr.sh_size = 0x200;
+  memory_.SetMemory(sh_offset, &shdr, sizeof(shdr));
+
+  // CIE 32.
+  memory_.SetData32(0x600, 0xfc);
+  memory_.SetData32(0x604, 0xffffffff);
+  memory_.SetData8(0x608, 1);
+  memory_.SetData8(0x609, '\0');
+  memory_.SetData8(0x60a, 0x4);
+  memory_.SetData8(0x60b, 0x4);
+  memory_.SetData8(0x60c, 0x1);
+
+  // FDE 32.
+  memory_.SetData32(0x700, 0xfc);
+  memory_.SetData32(0x704, 0);
+  memory_.SetData32(0x708, 0x2100);
+  memory_.SetData32(0x70c, 0x200);
+
+  uint64_t load_bias = 0;
+  ASSERT_TRUE(elf->Init(&load_bias));
+  elf->InitHeaders();
+  EXPECT_EQ(0U, load_bias);
+  EXPECT_FALSE(elf->IsValidPc(0));
+  EXPECT_FALSE(elf->IsValidPc(0x20ff));
+  EXPECT_TRUE(elf->IsValidPc(0x2100));
+  EXPECT_TRUE(elf->IsValidPc(0x2200));
+  EXPECT_TRUE(elf->IsValidPc(0x22ff));
+  EXPECT_FALSE(elf->IsValidPc(0x2300));
+}
+
+TEST_F(ElfInterfaceTest, is_valid_pc_from_eh_frame) {
+  std::unique_ptr<ElfInterface> elf(new ElfInterface32(&memory_));
+
+  uint64_t sh_offset = 0x100;
+
+  Elf32_Ehdr ehdr;
+  memset(&ehdr, 0, sizeof(ehdr));
+  ehdr.e_shstrndx = 1;
+  ehdr.e_shoff = sh_offset;
+  ehdr.e_shentsize = sizeof(Elf32_Shdr);
+  ehdr.e_shnum = 3;
+  memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+  Elf32_Shdr shdr;
+  memset(&shdr, 0, sizeof(shdr));
+  shdr.sh_type = SHT_NULL;
+  memory_.SetMemory(sh_offset, &shdr, sizeof(shdr));
+
+  sh_offset += sizeof(shdr);
+  memset(&shdr, 0, sizeof(shdr));
+  shdr.sh_type = SHT_STRTAB;
+  shdr.sh_name = 1;
+  shdr.sh_offset = 0x500;
+  shdr.sh_size = 0x100;
+  memory_.SetMemory(sh_offset, &shdr, sizeof(shdr));
+  memory_.SetMemory(0x500, ".eh_frame");
+
+  sh_offset += sizeof(shdr);
+  memset(&shdr, 0, sizeof(shdr));
+  shdr.sh_type = SHT_PROGBITS;
+  shdr.sh_name = 0;
+  shdr.sh_addr = 0x600;
+  shdr.sh_offset = 0x600;
+  shdr.sh_size = 0x200;
+  memory_.SetMemory(sh_offset, &shdr, sizeof(shdr));
+
+  // CIE 32.
+  memory_.SetData32(0x600, 0xfc);
+  memory_.SetData32(0x604, 0);
+  memory_.SetData8(0x608, 1);
+  memory_.SetData8(0x609, '\0');
+  memory_.SetData8(0x60a, 0x4);
+  memory_.SetData8(0x60b, 0x4);
+  memory_.SetData8(0x60c, 0x1);
+
+  // FDE 32.
+  memory_.SetData32(0x700, 0xfc);
+  memory_.SetData32(0x704, 0x104);
+  memory_.SetData32(0x708, 0x20f8);
+  memory_.SetData32(0x70c, 0x200);
+
+  uint64_t load_bias = 0;
+  ASSERT_TRUE(elf->Init(&load_bias));
+  elf->InitHeaders();
+  EXPECT_EQ(0U, load_bias);
+  EXPECT_FALSE(elf->IsValidPc(0));
+  EXPECT_FALSE(elf->IsValidPc(0x27ff));
+  EXPECT_TRUE(elf->IsValidPc(0x2800));
+  EXPECT_TRUE(elf->IsValidPc(0x2900));
+  EXPECT_TRUE(elf->IsValidPc(0x29ff));
+  EXPECT_FALSE(elf->IsValidPc(0x2a00));
+}
+
 }  // namespace unwindstack
diff --git a/libunwindstack/tests/ElfTest.cpp b/libunwindstack/tests/ElfTest.cpp
index 7491d40..7e6a62a 100644
--- a/libunwindstack/tests/ElfTest.cpp
+++ b/libunwindstack/tests/ElfTest.cpp
@@ -346,7 +346,14 @@
   void InitHeaders() override {}
   bool GetSoname(std::string*) override { return false; }
   bool GetFunctionName(uint64_t, uint64_t, std::string*, uint64_t*) override { return false; }
-  MOCK_METHOD4(Step, bool(uint64_t, Regs*, Memory*, bool*));
+
+  MOCK_METHOD5(Step, bool(uint64_t, uint64_t, Regs*, Memory*, bool*));
+  MOCK_METHOD2(GetGlobalVariable, bool(const std::string&, uint64_t*));
+  MOCK_METHOD1(IsValidPc, bool(uint64_t));
+
+  void MockSetDynamicOffset(uint64_t offset) { dynamic_offset_ = offset; }
+  void MockSetDynamicVaddr(uint64_t vaddr) { dynamic_vaddr_ = vaddr; }
+  void MockSetDynamicSize(uint64_t size) { dynamic_size_ = size; }
 };
 
 TEST_F(ElfTest, step_in_interface) {
@@ -361,7 +368,7 @@
   MemoryFake process_memory;
 
   bool finished;
-  EXPECT_CALL(*interface, Step(0x1000, &regs, &process_memory, &finished))
+  EXPECT_CALL(*interface, Step(0x1000, 0, &regs, &process_memory, &finished))
       .WillOnce(::testing::Return(true));
 
   ASSERT_TRUE(elf.Step(0x1004, 0x1000, 0x2000, &regs, &process_memory, &finished));
@@ -378,14 +385,200 @@
   elf.FakeSetInterface(interface);
   MemoryFake process_memory;
 
-  // Invalid relative pc given load_bias.
   bool finished;
-  ASSERT_FALSE(elf.Step(0x1004, 0x1000, 0x2000, &regs, &process_memory, &finished));
-
-  EXPECT_CALL(*interface, Step(0x3300, &regs, &process_memory, &finished))
+  EXPECT_CALL(*interface, Step(0x7300, 0x4000, &regs, &process_memory, &finished))
       .WillOnce(::testing::Return(true));
 
   ASSERT_TRUE(elf.Step(0x7304, 0x7300, 0x2000, &regs, &process_memory, &finished));
 }
 
+TEST_F(ElfTest, get_global_invalid_elf) {
+  ElfFake elf(memory_);
+  elf.FakeSetValid(false);
+
+  std::string global("something");
+  uint64_t offset;
+  ASSERT_FALSE(elf.GetGlobalVariable(global, &offset));
+}
+
+TEST_F(ElfTest, get_global_valid_not_in_interface) {
+  ElfFake elf(memory_);
+  elf.FakeSetValid(true);
+  elf.FakeSetLoadBias(0);
+
+  ElfInterfaceMock* interface = new ElfInterfaceMock(memory_);
+  elf.FakeSetInterface(interface);
+
+  uint64_t offset;
+  std::string global("something");
+  EXPECT_CALL(*interface, GetGlobalVariable(global, &offset)).WillOnce(::testing::Return(false));
+
+  ASSERT_FALSE(elf.GetGlobalVariable(global, &offset));
+}
+
+TEST_F(ElfTest, get_global_valid_below_load_bias) {
+  ElfFake elf(memory_);
+  elf.FakeSetValid(true);
+  elf.FakeSetLoadBias(0x1000);
+
+  ElfInterfaceMock* interface = new ElfInterfaceMock(memory_);
+  elf.FakeSetInterface(interface);
+
+  uint64_t offset;
+  std::string global("something");
+  EXPECT_CALL(*interface, GetGlobalVariable(global, &offset))
+      .WillOnce(::testing::DoAll(::testing::SetArgPointee<1>(0x300), ::testing::Return(true)));
+
+  ASSERT_FALSE(elf.GetGlobalVariable(global, &offset));
+}
+
+TEST_F(ElfTest, get_global_valid_dynamic_zero) {
+  ElfFake elf(memory_);
+  elf.FakeSetValid(true);
+  elf.FakeSetLoadBias(0);
+
+  ElfInterfaceMock* interface = new ElfInterfaceMock(memory_);
+  elf.FakeSetInterface(interface);
+
+  ElfInterfaceMock* gnu_interface = new ElfInterfaceMock(memory_);
+  elf.FakeSetGnuDebugdataInterface(gnu_interface);
+
+  uint64_t offset;
+  std::string global("something");
+  EXPECT_CALL(*interface, GetGlobalVariable(global, &offset)).WillOnce(::testing::Return(false));
+
+  EXPECT_CALL(*gnu_interface, GetGlobalVariable(global, &offset))
+      .WillOnce(::testing::DoAll(::testing::SetArgPointee<1>(0x500), ::testing::Return(true)));
+
+  ASSERT_TRUE(elf.GetGlobalVariable(global, &offset));
+  EXPECT_EQ(0x500U, offset);
+}
+
+TEST_F(ElfTest, get_global_valid_in_gnu_debugdata_dynamic_zero) {
+  ElfFake elf(memory_);
+  elf.FakeSetValid(true);
+  elf.FakeSetLoadBias(0);
+
+  ElfInterfaceMock* interface = new ElfInterfaceMock(memory_);
+  elf.FakeSetInterface(interface);
+
+  uint64_t offset;
+  std::string global("something");
+  EXPECT_CALL(*interface, GetGlobalVariable(global, &offset))
+      .WillOnce(::testing::DoAll(::testing::SetArgPointee<1>(0x300), ::testing::Return(true)));
+
+  ASSERT_TRUE(elf.GetGlobalVariable(global, &offset));
+  EXPECT_EQ(0x300U, offset);
+}
+
+TEST_F(ElfTest, get_global_valid_dynamic_zero_non_zero_load_bias) {
+  ElfFake elf(memory_);
+  elf.FakeSetValid(true);
+  elf.FakeSetLoadBias(0x100);
+
+  ElfInterfaceMock* interface = new ElfInterfaceMock(memory_);
+  elf.FakeSetInterface(interface);
+
+  uint64_t offset;
+  std::string global("something");
+  EXPECT_CALL(*interface, GetGlobalVariable(global, &offset))
+      .WillOnce(::testing::DoAll(::testing::SetArgPointee<1>(0x300), ::testing::Return(true)));
+
+  ASSERT_TRUE(elf.GetGlobalVariable(global, &offset));
+  EXPECT_EQ(0x200U, offset);
+}
+
+TEST_F(ElfTest, get_global_valid_dynamic_adjust_negative) {
+  ElfFake elf(memory_);
+  elf.FakeSetValid(true);
+  elf.FakeSetLoadBias(0);
+
+  ElfInterfaceMock* interface = new ElfInterfaceMock(memory_);
+  interface->MockSetDynamicOffset(0x400);
+  interface->MockSetDynamicVaddr(0x800);
+  interface->MockSetDynamicSize(0x100);
+  elf.FakeSetInterface(interface);
+
+  uint64_t offset;
+  std::string global("something");
+  EXPECT_CALL(*interface, GetGlobalVariable(global, &offset))
+      .WillOnce(::testing::DoAll(::testing::SetArgPointee<1>(0x850), ::testing::Return(true)));
+
+  ASSERT_TRUE(elf.GetGlobalVariable(global, &offset));
+  EXPECT_EQ(0x450U, offset);
+}
+
+TEST_F(ElfTest, get_global_valid_dynamic_adjust_positive) {
+  ElfFake elf(memory_);
+  elf.FakeSetValid(true);
+  elf.FakeSetLoadBias(0);
+
+  ElfInterfaceMock* interface = new ElfInterfaceMock(memory_);
+  interface->MockSetDynamicOffset(0x1000);
+  interface->MockSetDynamicVaddr(0x800);
+  interface->MockSetDynamicSize(0x100);
+  elf.FakeSetInterface(interface);
+
+  uint64_t offset;
+  std::string global("something");
+  EXPECT_CALL(*interface, GetGlobalVariable(global, &offset))
+      .WillOnce(::testing::DoAll(::testing::SetArgPointee<1>(0x850), ::testing::Return(true)));
+
+  ASSERT_TRUE(elf.GetGlobalVariable(global, &offset));
+  EXPECT_EQ(0x1050U, offset);
+}
+
+TEST_F(ElfTest, is_valid_pc_elf_invalid) {
+  ElfFake elf(memory_);
+  elf.FakeSetValid(false);
+  elf.FakeSetLoadBias(0);
+
+  EXPECT_FALSE(elf.IsValidPc(0x100));
+  EXPECT_FALSE(elf.IsValidPc(0x200));
+}
+
+TEST_F(ElfTest, is_valid_pc_interface) {
+  ElfFake elf(memory_);
+  elf.FakeSetValid(true);
+  elf.FakeSetLoadBias(0);
+
+  ElfInterfaceMock* interface = new ElfInterfaceMock(memory_);
+  elf.FakeSetInterface(interface);
+
+  EXPECT_CALL(*interface, IsValidPc(0x1500)).WillOnce(::testing::Return(true));
+
+  EXPECT_TRUE(elf.IsValidPc(0x1500));
+}
+
+TEST_F(ElfTest, is_valid_pc_non_zero_load_bias) {
+  ElfFake elf(memory_);
+  elf.FakeSetValid(true);
+  elf.FakeSetLoadBias(0x1000);
+
+  ElfInterfaceMock* interface = new ElfInterfaceMock(memory_);
+  elf.FakeSetInterface(interface);
+
+  EXPECT_CALL(*interface, IsValidPc(0x500)).WillOnce(::testing::Return(true));
+
+  EXPECT_FALSE(elf.IsValidPc(0x100));
+  EXPECT_FALSE(elf.IsValidPc(0x200));
+  EXPECT_TRUE(elf.IsValidPc(0x1500));
+}
+
+TEST_F(ElfTest, is_valid_pc_from_gnu_debugdata) {
+  ElfFake elf(memory_);
+  elf.FakeSetValid(true);
+  elf.FakeSetLoadBias(0);
+
+  ElfInterfaceMock* interface = new ElfInterfaceMock(memory_);
+  elf.FakeSetInterface(interface);
+  ElfInterfaceMock* gnu_interface = new ElfInterfaceMock(memory_);
+  elf.FakeSetGnuDebugdataInterface(gnu_interface);
+
+  EXPECT_CALL(*interface, IsValidPc(0x1500)).WillOnce(::testing::Return(false));
+  EXPECT_CALL(*gnu_interface, IsValidPc(0x1500)).WillOnce(::testing::Return(true));
+
+  EXPECT_TRUE(elf.IsValidPc(0x1500));
+}
+
 }  // namespace unwindstack
diff --git a/libunwindstack/tests/JitDebugTest.cpp b/libunwindstack/tests/JitDebugTest.cpp
new file mode 100644
index 0000000..1a50989
--- /dev/null
+++ b/libunwindstack/tests/JitDebugTest.cpp
@@ -0,0 +1,409 @@
+/*
+ * 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.
+ */
+
+#include <elf.h>
+#include <string.h>
+
+#include <memory>
+#include <vector>
+
+#include <gtest/gtest.h>
+
+#include <unwindstack/Elf.h>
+#include <unwindstack/JitDebug.h>
+#include <unwindstack/MapInfo.h>
+#include <unwindstack/Maps.h>
+#include <unwindstack/Memory.h>
+
+#include "ElfFake.h"
+#include "MemoryFake.h"
+
+namespace unwindstack {
+
+class JitDebugTest : public ::testing::Test {
+ protected:
+  void SetUp() override {
+    memory_ = new MemoryFake;
+    process_memory_.reset(memory_);
+
+    jit_debug_.reset(new JitDebug(process_memory_));
+    jit_debug_->SetArch(ARCH_ARM);
+
+    maps_.reset(
+        new BufferMaps("1000-4000 ---s 00000000 00:00 0\n"
+                       "4000-6000 r--s 00000000 00:00 0\n"
+                       "6000-8000 -w-s 00000000 00:00 0\n"
+                       "a000-c000 --xp 00000000 00:00 0\n"
+                       "c000-f000 rwxp 00000000 00:00 0\n"
+                       "f000-11000 r-xp 00000000 00:00 0\n"
+                       "12000-14000 r-xp 00000000 00:00 0\n"
+                       "100000-110000 rw-p 0000000 00:00 0\n"
+                       "200000-210000 rw-p 0000000 00:00 0\n"));
+    ASSERT_TRUE(maps_->Parse());
+
+    MapInfo* map_info = maps_->Get(3);
+    ASSERT_TRUE(map_info != nullptr);
+    elf_memories_.push_back(new MemoryFake);
+    ElfFake* elf = new ElfFake(elf_memories_.back());
+    elf->FakeSetValid(true);
+    ElfInterfaceFake* interface = new ElfInterfaceFake(elf_memories_.back());
+    elf->FakeSetInterface(interface);
+    interface->FakeSetGlobalVariable("__jit_debug_descriptor", 0x800);
+    map_info->elf = elf;
+
+    map_info = maps_->Get(5);
+    ASSERT_TRUE(map_info != nullptr);
+    elf_memories_.push_back(new MemoryFake);
+    elf = new ElfFake(elf_memories_.back());
+    elf->FakeSetValid(true);
+    interface = new ElfInterfaceFake(elf_memories_.back());
+    elf->FakeSetInterface(interface);
+    interface->FakeSetGlobalVariable("__jit_debug_descriptor", 0x800);
+    map_info->elf = elf;
+
+    map_info = maps_->Get(6);
+    ASSERT_TRUE(map_info != nullptr);
+    elf_memories_.push_back(new MemoryFake);
+    elf = new ElfFake(elf_memories_.back());
+    elf->FakeSetValid(true);
+    interface = new ElfInterfaceFake(elf_memories_.back());
+    elf->FakeSetInterface(interface);
+    interface->FakeSetGlobalVariable("__jit_debug_descriptor", 0x800);
+    map_info->elf = elf;
+  }
+
+  template <typename EhdrType, typename ShdrType>
+  void CreateElf(uint64_t offset, uint8_t class_type, uint8_t machine_type, uint32_t pc,
+                 uint32_t size) {
+    EhdrType ehdr;
+    memset(&ehdr, 0, sizeof(ehdr));
+    uint64_t sh_offset = sizeof(ehdr);
+    memcpy(ehdr.e_ident, ELFMAG, SELFMAG);
+    ehdr.e_ident[EI_CLASS] = class_type;
+    ehdr.e_machine = machine_type;
+    ehdr.e_shstrndx = 1;
+    ehdr.e_shoff = sh_offset;
+    ehdr.e_shentsize = sizeof(ShdrType);
+    ehdr.e_shnum = 3;
+    memory_->SetMemory(offset, &ehdr, sizeof(ehdr));
+
+    ShdrType shdr;
+    memset(&shdr, 0, sizeof(shdr));
+    shdr.sh_type = SHT_NULL;
+    memory_->SetMemory(offset + sh_offset, &shdr, sizeof(shdr));
+
+    sh_offset += sizeof(shdr);
+    memset(&shdr, 0, sizeof(shdr));
+    shdr.sh_type = SHT_STRTAB;
+    shdr.sh_name = 1;
+    shdr.sh_offset = 0x500;
+    shdr.sh_size = 0x100;
+    memory_->SetMemory(offset + sh_offset, &shdr, sizeof(shdr));
+    memory_->SetMemory(offset + 0x500, ".debug_frame");
+
+    sh_offset += sizeof(shdr);
+    memset(&shdr, 0, sizeof(shdr));
+    shdr.sh_type = SHT_PROGBITS;
+    shdr.sh_name = 0;
+    shdr.sh_addr = 0x600;
+    shdr.sh_offset = 0x600;
+    shdr.sh_size = 0x200;
+    memory_->SetMemory(offset + sh_offset, &shdr, sizeof(shdr));
+
+    // Now add a single cie/fde.
+    uint64_t dwarf_offset = offset + 0x600;
+    if (class_type == ELFCLASS32) {
+      // CIE 32 information.
+      memory_->SetData32(dwarf_offset, 0xfc);
+      memory_->SetData32(dwarf_offset + 0x4, 0xffffffff);
+      memory_->SetData8(dwarf_offset + 0x8, 1);
+      memory_->SetData8(dwarf_offset + 0x9, '\0');
+      memory_->SetData8(dwarf_offset + 0xa, 0x4);
+      memory_->SetData8(dwarf_offset + 0xb, 0x4);
+      memory_->SetData8(dwarf_offset + 0xc, 0x1);
+
+      // FDE 32 information.
+      memory_->SetData32(dwarf_offset + 0x100, 0xfc);
+      memory_->SetData32(dwarf_offset + 0x104, 0);
+      memory_->SetData32(dwarf_offset + 0x108, pc);
+      memory_->SetData32(dwarf_offset + 0x10c, size);
+    } else {
+      // CIE 64 information.
+      memory_->SetData32(dwarf_offset, 0xffffffff);
+      memory_->SetData64(dwarf_offset + 4, 0xf4);
+      memory_->SetData64(dwarf_offset + 0xc, 0xffffffffffffffffULL);
+      memory_->SetData8(dwarf_offset + 0x14, 1);
+      memory_->SetData8(dwarf_offset + 0x15, '\0');
+      memory_->SetData8(dwarf_offset + 0x16, 0x4);
+      memory_->SetData8(dwarf_offset + 0x17, 0x4);
+      memory_->SetData8(dwarf_offset + 0x18, 0x1);
+
+      // FDE 64 information.
+      memory_->SetData32(dwarf_offset + 0x100, 0xffffffff);
+      memory_->SetData64(dwarf_offset + 0x104, 0xf4);
+      memory_->SetData64(dwarf_offset + 0x10c, 0);
+      memory_->SetData64(dwarf_offset + 0x114, pc);
+      memory_->SetData64(dwarf_offset + 0x11c, size);
+    }
+  }
+
+  void WriteDescriptor32(uint64_t addr, uint32_t entry);
+  void WriteDescriptor64(uint64_t addr, uint64_t entry);
+  void WriteEntry32Pack(uint64_t addr, uint32_t prev, uint32_t next, uint32_t elf_addr,
+                        uint64_t elf_size);
+  void WriteEntry32Pad(uint64_t addr, uint32_t prev, uint32_t next, uint32_t elf_addr,
+                       uint64_t elf_size);
+  void WriteEntry64(uint64_t addr, uint64_t prev, uint64_t next, uint64_t elf_addr,
+                    uint64_t elf_size);
+
+  std::shared_ptr<Memory> process_memory_;
+  MemoryFake* memory_;
+  std::vector<MemoryFake*> elf_memories_;
+  std::unique_ptr<JitDebug> jit_debug_;
+  std::unique_ptr<BufferMaps> maps_;
+};
+
+void JitDebugTest::WriteDescriptor32(uint64_t addr, uint32_t entry) {
+  // Format of the 32 bit JITDescriptor structure:
+  //   uint32_t version
+  memory_->SetData32(addr, 1);
+  //   uint32_t action_flag
+  memory_->SetData32(addr + 4, 0);
+  //   uint32_t relevant_entry
+  memory_->SetData32(addr + 8, 0);
+  //   uint32_t first_entry
+  memory_->SetData32(addr + 12, entry);
+}
+
+void JitDebugTest::WriteDescriptor64(uint64_t addr, uint64_t entry) {
+  // Format of the 64 bit JITDescriptor structure:
+  //   uint32_t version
+  memory_->SetData32(addr, 1);
+  //   uint32_t action_flag
+  memory_->SetData32(addr + 4, 0);
+  //   uint64_t relevant_entry
+  memory_->SetData64(addr + 8, 0);
+  //   uint64_t first_entry
+  memory_->SetData64(addr + 16, entry);
+}
+
+void JitDebugTest::WriteEntry32Pack(uint64_t addr, uint32_t prev, uint32_t next, uint32_t elf_addr,
+                                    uint64_t elf_size) {
+  // Format of the 32 bit JITCodeEntry structure:
+  //   uint32_t next
+  memory_->SetData32(addr, next);
+  //   uint32_t prev
+  memory_->SetData32(addr + 4, prev);
+  //   uint32_t symfile_addr
+  memory_->SetData32(addr + 8, elf_addr);
+  //   uint64_t symfile_size
+  memory_->SetData64(addr + 12, elf_size);
+}
+
+void JitDebugTest::WriteEntry32Pad(uint64_t addr, uint32_t prev, uint32_t next, uint32_t elf_addr,
+                                   uint64_t elf_size) {
+  // Format of the 32 bit JITCodeEntry structure:
+  //   uint32_t next
+  memory_->SetData32(addr, next);
+  //   uint32_t prev
+  memory_->SetData32(addr + 4, prev);
+  //   uint32_t symfile_addr
+  memory_->SetData32(addr + 8, elf_addr);
+  //   uint32_t pad
+  memory_->SetData32(addr + 12, 0);
+  //   uint64_t symfile_size
+  memory_->SetData64(addr + 16, elf_size);
+}
+
+void JitDebugTest::WriteEntry64(uint64_t addr, uint64_t prev, uint64_t next, uint64_t elf_addr,
+                                uint64_t elf_size) {
+  // Format of the 64 bit JITCodeEntry structure:
+  //   uint64_t next
+  memory_->SetData64(addr, next);
+  //   uint64_t prev
+  memory_->SetData64(addr + 8, prev);
+  //   uint64_t symfile_addr
+  memory_->SetData64(addr + 16, elf_addr);
+  //   uint64_t symfile_size
+  memory_->SetData64(addr + 24, elf_size);
+}
+
+TEST_F(JitDebugTest, get_elf_invalid) {
+  Elf* elf = jit_debug_->GetElf(maps_.get(), 0x1500);
+  ASSERT_TRUE(elf == nullptr);
+}
+
+TEST_F(JitDebugTest, get_elf_no_global_variable) {
+  maps_.reset(new BufferMaps(""));
+  Elf* elf = jit_debug_->GetElf(maps_.get(), 0x1500);
+  ASSERT_TRUE(elf == nullptr);
+}
+
+TEST_F(JitDebugTest, get_elf_no_valid_descriptor_in_memory) {
+  CreateElf<Elf32_Ehdr, Elf32_Shdr>(0x4000, ELFCLASS32, EM_ARM, 0x1500, 0x200);
+
+  Elf* elf = jit_debug_->GetElf(maps_.get(), 0x1500);
+  ASSERT_TRUE(elf == nullptr);
+}
+
+TEST_F(JitDebugTest, get_elf_no_valid_code_entry) {
+  CreateElf<Elf32_Ehdr, Elf32_Shdr>(0x4000, ELFCLASS32, EM_ARM, 0x1500, 0x200);
+
+  WriteDescriptor32(0xf800, 0x200000);
+
+  Elf* elf = jit_debug_->GetElf(maps_.get(), 0x1500);
+  ASSERT_TRUE(elf == nullptr);
+}
+
+TEST_F(JitDebugTest, get_elf_invalid_descriptor_first_entry) {
+  CreateElf<Elf32_Ehdr, Elf32_Shdr>(0x4000, ELFCLASS32, EM_ARM, 0x1500, 0x200);
+
+  WriteDescriptor32(0xf800, 0);
+
+  Elf* elf = jit_debug_->GetElf(maps_.get(), 0x1500);
+  ASSERT_TRUE(elf == nullptr);
+}
+
+TEST_F(JitDebugTest, get_elf_invalid_descriptor_version) {
+  CreateElf<Elf32_Ehdr, Elf32_Shdr>(0x4000, ELFCLASS32, EM_ARM, 0x1500, 0x200);
+
+  WriteDescriptor32(0xf800, 0x20000);
+  // Set the version to an invalid value.
+  memory_->SetData32(0xf800, 2);
+
+  Elf* elf = jit_debug_->GetElf(maps_.get(), 0x1500);
+  ASSERT_TRUE(elf == nullptr);
+}
+
+TEST_F(JitDebugTest, get_elf_32) {
+  CreateElf<Elf32_Ehdr, Elf32_Shdr>(0x4000, ELFCLASS32, EM_ARM, 0x1500, 0x200);
+
+  WriteDescriptor32(0xf800, 0x200000);
+  WriteEntry32Pad(0x200000, 0, 0, 0x4000, 0x1000);
+
+  Elf* elf = jit_debug_->GetElf(maps_.get(), 0x1500);
+  ASSERT_TRUE(elf != nullptr);
+
+  // Clear the memory and verify all of the data is cached.
+  memory_->Clear();
+  Elf* elf2 = jit_debug_->GetElf(maps_.get(), 0x1500);
+  ASSERT_TRUE(elf2 != nullptr);
+  EXPECT_EQ(elf, elf2);
+}
+
+TEST_F(JitDebugTest, get_multiple_jit_debug_descriptors_valid) {
+  CreateElf<Elf32_Ehdr, Elf32_Shdr>(0x4000, ELFCLASS32, EM_ARM, 0x1500, 0x200);
+  CreateElf<Elf32_Ehdr, Elf32_Shdr>(0x5000, ELFCLASS32, EM_ARM, 0x2000, 0x300);
+
+  WriteDescriptor32(0xf800, 0x200000);
+  WriteEntry32Pad(0x200000, 0, 0, 0x4000, 0x1000);
+  WriteDescriptor32(0x12800, 0x201000);
+  WriteEntry32Pad(0x201000, 0, 0, 0x5000, 0x1000);
+
+  ASSERT_TRUE(jit_debug_->GetElf(maps_.get(), 0x1500) != nullptr);
+  ASSERT_TRUE(jit_debug_->GetElf(maps_.get(), 0x2000) == nullptr);
+
+  // Now clear the descriptor entry for the first one.
+  WriteDescriptor32(0xf800, 0);
+  jit_debug_.reset(new JitDebug(process_memory_));
+  jit_debug_->SetArch(ARCH_ARM);
+
+  ASSERT_TRUE(jit_debug_->GetElf(maps_.get(), 0x1500) == nullptr);
+  ASSERT_TRUE(jit_debug_->GetElf(maps_.get(), 0x2000) != nullptr);
+}
+
+TEST_F(JitDebugTest, get_elf_x86) {
+  CreateElf<Elf32_Ehdr, Elf32_Shdr>(0x4000, ELFCLASS32, EM_ARM, 0x1500, 0x200);
+
+  WriteDescriptor32(0xf800, 0x200000);
+  WriteEntry32Pack(0x200000, 0, 0, 0x4000, 0x1000);
+
+  jit_debug_->SetArch(ARCH_X86);
+  Elf* elf = jit_debug_->GetElf(maps_.get(), 0x1500);
+  ASSERT_TRUE(elf != nullptr);
+
+  // Clear the memory and verify all of the data is cached.
+  memory_->Clear();
+  Elf* elf2 = jit_debug_->GetElf(maps_.get(), 0x1500);
+  ASSERT_TRUE(elf2 != nullptr);
+  EXPECT_EQ(elf, elf2);
+}
+
+TEST_F(JitDebugTest, get_elf_64) {
+  CreateElf<Elf64_Ehdr, Elf64_Shdr>(0x4000, ELFCLASS64, EM_AARCH64, 0x1500, 0x200);
+
+  WriteDescriptor64(0xf800, 0x200000);
+  WriteEntry64(0x200000, 0, 0, 0x4000, 0x1000);
+
+  jit_debug_->SetArch(ARCH_ARM64);
+  Elf* elf = jit_debug_->GetElf(maps_.get(), 0x1500);
+  ASSERT_TRUE(elf != nullptr);
+
+  // Clear the memory and verify all of the data is cached.
+  memory_->Clear();
+  Elf* elf2 = jit_debug_->GetElf(maps_.get(), 0x1500);
+  ASSERT_TRUE(elf2 != nullptr);
+  EXPECT_EQ(elf, elf2);
+}
+
+TEST_F(JitDebugTest, get_elf_multiple_entries) {
+  CreateElf<Elf32_Ehdr, Elf32_Shdr>(0x4000, ELFCLASS32, EM_ARM, 0x1500, 0x200);
+  CreateElf<Elf32_Ehdr, Elf32_Shdr>(0x5000, ELFCLASS32, EM_ARM, 0x2300, 0x400);
+
+  WriteDescriptor32(0xf800, 0x200000);
+  WriteEntry32Pad(0x200000, 0, 0x200100, 0x4000, 0x1000);
+  WriteEntry32Pad(0x200100, 0x200100, 0, 0x5000, 0x1000);
+
+  Elf* elf_2 = jit_debug_->GetElf(maps_.get(), 0x2400);
+  ASSERT_TRUE(elf_2 != nullptr);
+
+  Elf* elf_1 = jit_debug_->GetElf(maps_.get(), 0x1600);
+  ASSERT_TRUE(elf_1 != nullptr);
+
+  // Clear the memory and verify all of the data is cached.
+  memory_->Clear();
+  EXPECT_EQ(elf_1, jit_debug_->GetElf(maps_.get(), 0x1500));
+  EXPECT_EQ(elf_1, jit_debug_->GetElf(maps_.get(), 0x16ff));
+  EXPECT_EQ(elf_2, jit_debug_->GetElf(maps_.get(), 0x2300));
+  EXPECT_EQ(elf_2, jit_debug_->GetElf(maps_.get(), 0x26ff));
+  EXPECT_EQ(nullptr, jit_debug_->GetElf(maps_.get(), 0x1700));
+  EXPECT_EQ(nullptr, jit_debug_->GetElf(maps_.get(), 0x2700));
+}
+
+TEST_F(JitDebugTest, get_elf_search_libs) {
+  CreateElf<Elf32_Ehdr, Elf32_Shdr>(0x4000, ELFCLASS32, EM_ARM, 0x1500, 0x200);
+
+  WriteDescriptor32(0xf800, 0x200000);
+  WriteEntry32Pad(0x200000, 0, 0, 0x4000, 0x1000);
+
+  // Only search a given named list of libs.
+  std::vector<std::string> libs{"libart.so"};
+  jit_debug_.reset(new JitDebug(process_memory_, libs));
+  jit_debug_->SetArch(ARCH_ARM);
+  EXPECT_TRUE(jit_debug_->GetElf(maps_.get(), 0x1500) == nullptr);
+
+  // Change the name of the map that includes the value and verify this works.
+  MapInfo* map_info = maps_->Get(5);
+  map_info->name = "/system/lib/libart.so";
+  jit_debug_.reset(new JitDebug(process_memory_, libs));
+  // Make sure that clearing our copy of the libs doesn't affect the
+  // JitDebug object.
+  libs.clear();
+  jit_debug_->SetArch(ARCH_ARM);
+  EXPECT_TRUE(jit_debug_->GetElf(maps_.get(), 0x1500) != nullptr);
+}
+
+}  // namespace unwindstack
diff --git a/libunwindstack/tests/MapInfoGetLoadBiasTest.cpp b/libunwindstack/tests/MapInfoGetLoadBiasTest.cpp
index 44a73a8..631036b 100644
--- a/libunwindstack/tests/MapInfoGetLoadBiasTest.cpp
+++ b/libunwindstack/tests/MapInfoGetLoadBiasTest.cpp
@@ -68,12 +68,23 @@
   EXPECT_EQ(0U, info.GetLoadBias(process_memory_));
 }
 
+TEST_F(MapInfoGetLoadBiasTest, load_bias_cached_from_elf) {
+  map_info_->elf = elf_container_.release();
+
+  elf_->FakeSetLoadBias(0);
+  EXPECT_EQ(0U, map_info_->GetLoadBias(process_memory_));
+
+  elf_->FakeSetLoadBias(0x1000);
+  EXPECT_EQ(0U, map_info_->GetLoadBias(process_memory_));
+}
+
 TEST_F(MapInfoGetLoadBiasTest, elf_exists) {
   map_info_->elf = elf_container_.release();
 
   elf_->FakeSetLoadBias(0);
   EXPECT_EQ(0U, map_info_->GetLoadBias(process_memory_));
 
+  map_info_->load_bias = static_cast<uint64_t>(-1);
   elf_->FakeSetLoadBias(0x1000);
   EXPECT_EQ(0x1000U, map_info_->GetLoadBias(process_memory_));
 }
@@ -141,6 +152,15 @@
   EXPECT_EQ(0xe000U, map_info_->GetLoadBias(process_memory_));
 }
 
+TEST_F(MapInfoGetLoadBiasTest, elf_exists_in_memory_cached) {
+  InitElfData(memory_, map_info_->start);
+
+  EXPECT_EQ(0xe000U, map_info_->GetLoadBias(process_memory_));
+
+  memory_->Clear();
+  EXPECT_EQ(0xe000U, map_info_->GetLoadBias(process_memory_));
+}
+
 TEST_F(MapInfoGetLoadBiasTest, multiple_thread_elf_exists_in_memory) {
   InitElfData(memory_, map_info_->start);
 
diff --git a/libunwindstack/tests/MapsTest.cpp b/libunwindstack/tests/MapsTest.cpp
index 8dc884f..9622ba5 100644
--- a/libunwindstack/tests/MapsTest.cpp
+++ b/libunwindstack/tests/MapsTest.cpp
@@ -44,6 +44,24 @@
   }
 }
 
+TEST(MapsTest, map_add) {
+  Maps maps;
+
+  maps.Add(0x1000, 0x2000, 0, PROT_READ, "fake_map", 0);
+  maps.Add(0x3000, 0x4000, 0x10, 0, "", 0x1234);
+  maps.Add(0x5000, 0x6000, 1, 2, "fake_map2", static_cast<uint64_t>(-1));
+
+  ASSERT_EQ(3U, maps.Total());
+  MapInfo* info = maps.Get(0);
+  ASSERT_EQ(0x1000U, info->start);
+  ASSERT_EQ(0x2000U, info->end);
+  ASSERT_EQ(0U, info->offset);
+  ASSERT_EQ(PROT_READ, info->flags);
+  ASSERT_EQ("fake_map", info->name);
+  ASSERT_EQ(0U, info->elf_offset);
+  ASSERT_EQ(0U, info->load_bias.load());
+}
+
 TEST(MapsTest, verify_parse_line) {
   MapInfo info;
 
diff --git a/libunwindstack/tests/MemoryOfflineTest.cpp b/libunwindstack/tests/MemoryOfflineTest.cpp
new file mode 100644
index 0000000..14d58e6
--- /dev/null
+++ b/libunwindstack/tests/MemoryOfflineTest.cpp
@@ -0,0 +1,67 @@
+/*
+ * 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 <vector>
+
+#include <gtest/gtest.h>
+
+#include <android-base/file.h>
+#include <android-base/test_utils.h>
+#include <unwindstack/Memory.h>
+
+namespace unwindstack {
+
+class MemoryOfflineTest : public ::testing::Test {
+ protected:
+  void SetUp() override {
+    for (size_t i = 0; i < 1024; ++i) {
+      data.push_back(i & 0xff);
+    }
+
+    ASSERT_TRUE(android::base::WriteFully(temp_file.fd, &offset, sizeof(offset)));
+    ASSERT_TRUE(android::base::WriteFully(temp_file.fd, data.data(), data.size()));
+
+    memory = std::make_unique<MemoryOffline>();
+    ASSERT_TRUE(memory != nullptr);
+
+    ASSERT_TRUE(memory->Init(temp_file.path, 0));
+  }
+
+  TemporaryFile temp_file;
+  uint64_t offset = 4096;
+  std::vector<char> data;
+  std::unique_ptr<MemoryOffline> memory;
+};
+
+TEST_F(MemoryOfflineTest, read_boundaries) {
+  char buf = '\0';
+  ASSERT_EQ(0U, memory->Read(offset - 1, &buf, 1));
+  ASSERT_EQ(0U, memory->Read(offset + data.size(), &buf, 1));
+  ASSERT_EQ(1U, memory->Read(offset, &buf, 1));
+  ASSERT_EQ(buf, data.front());
+  ASSERT_EQ(1U, memory->Read(offset + data.size() - 1, &buf, 1));
+  ASSERT_EQ(buf, data.back());
+}
+
+TEST_F(MemoryOfflineTest, read_values) {
+  std::vector<char> buf;
+  buf.resize(2 * data.size());
+  ASSERT_EQ(data.size(), memory->Read(offset, buf.data(), buf.size()));
+  buf.resize(data.size());
+  ASSERT_EQ(buf, data);
+}
+
+}  // namespace unwindstack
diff --git a/libunwindstack/tests/MemoryRemoteTest.cpp b/libunwindstack/tests/MemoryRemoteTest.cpp
index f5492a2..fb56e8a 100644
--- a/libunwindstack/tests/MemoryRemoteTest.cpp
+++ b/libunwindstack/tests/MemoryRemoteTest.cpp
@@ -79,6 +79,35 @@
   ASSERT_TRUE(Detach(pid));
 }
 
+TEST_F(MemoryRemoteTest, read_large) {
+  static constexpr size_t kTotalPages = 245;
+  std::vector<uint8_t> src(kTotalPages * getpagesize());
+  for (size_t i = 0; i < kTotalPages; i++) {
+    memset(&src[i * getpagesize()], i, getpagesize());
+  }
+
+  pid_t pid;
+  if ((pid = fork()) == 0) {
+    while (true)
+      ;
+    exit(1);
+  }
+  ASSERT_LT(0, pid);
+  TestScopedPidReaper reap(pid);
+
+  ASSERT_TRUE(Attach(pid));
+
+  MemoryRemote remote(pid);
+
+  std::vector<uint8_t> dst(kTotalPages * getpagesize());
+  ASSERT_TRUE(remote.ReadFully(reinterpret_cast<uint64_t>(src.data()), dst.data(), src.size()));
+  for (size_t i = 0; i < kTotalPages * getpagesize(); i++) {
+    ASSERT_EQ(i / getpagesize(), dst[i]) << "Failed at byte " << i;
+  }
+
+  ASSERT_TRUE(Detach(pid));
+}
+
 TEST_F(MemoryRemoteTest, read_partial) {
   char* mapping = static_cast<char*>(
       mmap(nullptr, 4 * getpagesize(), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
diff --git a/libunwindstack/tests/RegsFake.h b/libunwindstack/tests/RegsFake.h
index b81b2ca..8f7d913 100644
--- a/libunwindstack/tests/RegsFake.h
+++ b/libunwindstack/tests/RegsFake.h
@@ -45,7 +45,7 @@
 
   void IterateRegisters(std::function<void(const char*, uint64_t)>) override {}
 
-  bool Format32Bit() { return false; }
+  bool Is32Bit() { return false; }
 
   uint64_t GetAdjustedPc(uint64_t rel_pc, Elf*) override { return rel_pc - 2; }
 
diff --git a/libunwindstack/tests/RegsTest.cpp b/libunwindstack/tests/RegsTest.cpp
index 3f84890..15d5458 100644
--- a/libunwindstack/tests/RegsTest.cpp
+++ b/libunwindstack/tests/RegsTest.cpp
@@ -188,7 +188,7 @@
 
   regs_arm.set_pc(0x1500);
   EXPECT_EQ(0x500U, invalid_elf->GetRelPc(regs_arm.pc(), &map_info));
-  EXPECT_EQ(0x500U, regs_arm.GetAdjustedPc(0x500U, invalid_elf));
+  EXPECT_EQ(0x4fcU, regs_arm.GetAdjustedPc(0x500U, invalid_elf));
 
   regs_arm64.set_pc(0x1600);
   EXPECT_EQ(0x600U, invalid_elf->GetRelPc(regs_arm64.pc(), &map_info));
diff --git a/libunwindstack/tests/SymbolsTest.cpp b/libunwindstack/tests/SymbolsTest.cpp
index da258a6..45a7b58 100644
--- a/libunwindstack/tests/SymbolsTest.cpp
+++ b/libunwindstack/tests/SymbolsTest.cpp
@@ -330,9 +330,69 @@
   ASSERT_EQ(3U, func_offset);
 }
 
+TYPED_TEST_P(SymbolsTest, get_global) {
+  uint64_t start_offset = 0x1000;
+  uint64_t str_offset = 0xa000;
+  Symbols symbols(start_offset, 4 * sizeof(TypeParam), sizeof(TypeParam), str_offset, 0x1000);
+
+  TypeParam sym;
+  memset(&sym, 0, sizeof(sym));
+  sym.st_shndx = SHN_COMMON;
+  sym.st_info = STT_OBJECT | (STB_GLOBAL << 4);
+  sym.st_name = 0x100;
+  this->memory_.SetMemory(start_offset, &sym, sizeof(sym));
+  this->memory_.SetMemory(str_offset + 0x100, "global_0");
+
+  start_offset += sizeof(sym);
+  memset(&sym, 0, sizeof(sym));
+  sym.st_shndx = SHN_COMMON;
+  sym.st_info = STT_FUNC;
+  sym.st_name = 0x200;
+  sym.st_value = 0x10000;
+  sym.st_size = 0x100;
+  this->memory_.SetMemory(start_offset, &sym, sizeof(sym));
+  this->memory_.SetMemory(str_offset + 0x200, "function_0");
+
+  start_offset += sizeof(sym);
+  memset(&sym, 0, sizeof(sym));
+  sym.st_shndx = SHN_COMMON;
+  sym.st_info = STT_OBJECT | (STB_GLOBAL << 4);
+  sym.st_name = 0x300;
+  this->memory_.SetMemory(start_offset, &sym, sizeof(sym));
+  this->memory_.SetMemory(str_offset + 0x300, "global_1");
+
+  start_offset += sizeof(sym);
+  memset(&sym, 0, sizeof(sym));
+  sym.st_shndx = SHN_COMMON;
+  sym.st_info = STT_FUNC;
+  sym.st_name = 0x400;
+  sym.st_value = 0x12000;
+  sym.st_size = 0x100;
+  this->memory_.SetMemory(start_offset, &sym, sizeof(sym));
+  this->memory_.SetMemory(str_offset + 0x400, "function_1");
+
+  uint64_t offset;
+  EXPECT_TRUE(symbols.GetGlobal<TypeParam>(&this->memory_, "global_0", &offset));
+  EXPECT_TRUE(symbols.GetGlobal<TypeParam>(&this->memory_, "global_1", &offset));
+  EXPECT_TRUE(symbols.GetGlobal<TypeParam>(&this->memory_, "global_0", &offset));
+  EXPECT_TRUE(symbols.GetGlobal<TypeParam>(&this->memory_, "global_1", &offset));
+
+  EXPECT_FALSE(symbols.GetGlobal<TypeParam>(&this->memory_, "function_0", &offset));
+  EXPECT_FALSE(symbols.GetGlobal<TypeParam>(&this->memory_, "function_1", &offset));
+
+  std::string name;
+  EXPECT_TRUE(symbols.GetName<TypeParam>(0x10002, 0, &this->memory_, &name, &offset));
+  EXPECT_EQ("function_0", name);
+  EXPECT_EQ(2U, offset);
+
+  EXPECT_TRUE(symbols.GetName<TypeParam>(0x12004, 0, &this->memory_, &name, &offset));
+  EXPECT_EQ("function_1", name);
+  EXPECT_EQ(4U, offset);
+}
+
 REGISTER_TYPED_TEST_CASE_P(SymbolsTest, function_bounds_check, no_symbol, multiple_entries,
                            multiple_entries_nonstandard_size, load_bias, symtab_value_out_of_bounds,
-                           symtab_read_cached);
+                           symtab_read_cached, get_global);
 
 typedef ::testing::Types<Elf32_Sym, Elf64_Sym> SymbolsTestTypes;
 INSTANTIATE_TYPED_TEST_CASE_P(, SymbolsTest, SymbolsTestTypes);
diff --git a/libunwindstack/tests/UnwindOfflineTest.cpp b/libunwindstack/tests/UnwindOfflineTest.cpp
index 962f744..582ac18 100644
--- a/libunwindstack/tests/UnwindOfflineTest.cpp
+++ b/libunwindstack/tests/UnwindOfflineTest.cpp
@@ -25,14 +25,17 @@
 #include <string>
 #include <vector>
 
+#include <unwindstack/JitDebug.h>
 #include <unwindstack/Maps.h>
 #include <unwindstack/Memory.h>
 #include <unwindstack/RegsArm.h>
 #include <unwindstack/RegsArm64.h>
+#include <unwindstack/RegsX86.h>
 #include <unwindstack/Unwinder.h>
 
 #include "MachineArm.h"
 #include "MachineArm64.h"
+#include "MachineX86.h"
 
 #include "ElfTestUtils.h"
 
@@ -92,7 +95,55 @@
       "  #00 pc 0001a9f8  libc.so (abort+63)\n"
       "  #01 pc 00006a1b  libbase.so (_ZN7android4base14DefaultAborterEPKc+6)\n"
       "  #02 pc 00007441  libbase.so (_ZN7android4base10LogMessageD2Ev+748)\n"
-      "  #03 pc 00015149  /does/not/exist/libhidlbase.so\n",
+      "  #03 pc 00015147  /does/not/exist/libhidlbase.so\n",
+      frame_info);
+}
+
+TEST(UnwindOfflineTest, pc_in_gnu_debugdata_arm32) {
+  std::string dir(TestGetFileDirectory() + "offline/gnu_debugdata_arm32/");
+
+  MemoryOffline* memory = new MemoryOffline;
+  ASSERT_TRUE(memory->Init((dir + "stack.data").c_str(), 0));
+
+  FILE* fp = fopen((dir + "regs.txt").c_str(), "r");
+  ASSERT_TRUE(fp != nullptr);
+  RegsArm regs;
+  uint64_t reg_value;
+  ASSERT_EQ(1, fscanf(fp, "pc: %" SCNx64 "\n", &reg_value));
+  regs[ARM_REG_PC] = reg_value;
+  ASSERT_EQ(1, fscanf(fp, "sp: %" SCNx64 "\n", &reg_value));
+  regs[ARM_REG_SP] = reg_value;
+  regs.SetFromRaw();
+  fclose(fp);
+
+  fp = fopen((dir + "maps.txt").c_str(), "r");
+  ASSERT_TRUE(fp != nullptr);
+  // The file is guaranteed to be less than 4096 bytes.
+  std::vector<char> buffer(4096);
+  ASSERT_NE(0U, fread(buffer.data(), 1, buffer.size(), fp));
+  fclose(fp);
+
+  BufferMaps maps(buffer.data());
+  ASSERT_TRUE(maps.Parse());
+
+  ASSERT_EQ(ARCH_ARM, regs.Arch());
+
+  std::shared_ptr<Memory> process_memory(memory);
+
+  char* cwd = getcwd(nullptr, 0);
+  ASSERT_EQ(0, chdir(dir.c_str()));
+  Unwinder unwinder(128, &maps, &regs, process_memory);
+  unwinder.Unwind();
+  ASSERT_EQ(0, chdir(cwd));
+  free(cwd);
+
+  std::string frame_info(DumpFrames(unwinder));
+  ASSERT_EQ(2U, unwinder.NumFrames()) << "Unwind:\n" << frame_info;
+  EXPECT_EQ(
+      "  #00 pc 0006dc49  libandroid_runtime.so "
+      "(_ZN7android14AndroidRuntime15javaThreadShellEPv+80)\n"
+      "  #01 pc 0006dce5  libandroid_runtime.so "
+      "(_ZN7android14AndroidRuntime19javaCreateThreadEtcEPFiPvES1_PKcijPS1_)\n",
       frame_info);
 }
 
@@ -152,4 +203,426 @@
       frame_info);
 }
 
+static void AddMemory(std::string file_name, MemoryOfflineParts* parts) {
+  MemoryOffline* memory = new MemoryOffline;
+  ASSERT_TRUE(memory->Init(file_name.c_str(), 0));
+  parts->Add(memory);
+}
+
+TEST(UnwindOfflineTest, jit_debug_x86_32) {
+  std::string dir(TestGetFileDirectory() + "offline/jit_debug_x86_32/");
+
+  MemoryOfflineParts* memory = new MemoryOfflineParts;
+  AddMemory(dir + "descriptor.data", memory);
+  AddMemory(dir + "stack.data", memory);
+  for (size_t i = 0; i < 7; i++) {
+    AddMemory(dir + "entry" + std::to_string(i) + ".data", memory);
+    AddMemory(dir + "jit" + std::to_string(i) + ".data", memory);
+  }
+
+  FILE* fp = fopen((dir + "regs.txt").c_str(), "r");
+  ASSERT_TRUE(fp != nullptr);
+  RegsX86 regs;
+  uint64_t reg_value;
+  ASSERT_EQ(1, fscanf(fp, "eax: %" SCNx64 "\n", &reg_value));
+  regs[X86_REG_EAX] = reg_value;
+  ASSERT_EQ(1, fscanf(fp, "ebx: %" SCNx64 "\n", &reg_value));
+  regs[X86_REG_EBX] = reg_value;
+  ASSERT_EQ(1, fscanf(fp, "ecx: %" SCNx64 "\n", &reg_value));
+  regs[X86_REG_ECX] = reg_value;
+  ASSERT_EQ(1, fscanf(fp, "edx: %" SCNx64 "\n", &reg_value));
+  regs[X86_REG_EDX] = reg_value;
+  ASSERT_EQ(1, fscanf(fp, "ebp: %" SCNx64 "\n", &reg_value));
+  regs[X86_REG_EBP] = reg_value;
+  ASSERT_EQ(1, fscanf(fp, "edi: %" SCNx64 "\n", &reg_value));
+  regs[X86_REG_EDI] = reg_value;
+  ASSERT_EQ(1, fscanf(fp, "esi: %" SCNx64 "\n", &reg_value));
+  regs[X86_REG_ESI] = reg_value;
+  ASSERT_EQ(1, fscanf(fp, "esp: %" SCNx64 "\n", &reg_value));
+  regs[X86_REG_ESP] = reg_value;
+  ASSERT_EQ(1, fscanf(fp, "eip: %" SCNx64 "\n", &reg_value));
+  regs[X86_REG_EIP] = reg_value;
+  regs.SetFromRaw();
+  fclose(fp);
+
+  fp = fopen((dir + "maps.txt").c_str(), "r");
+  ASSERT_TRUE(fp != nullptr);
+  // The file is guaranteed to be less than 4096 bytes.
+  std::vector<char> buffer(4096);
+  ASSERT_NE(0U, fread(buffer.data(), 1, buffer.size(), fp));
+  fclose(fp);
+
+  BufferMaps maps(buffer.data());
+  ASSERT_TRUE(maps.Parse());
+
+  ASSERT_EQ(ARCH_X86, regs.Arch());
+
+  std::shared_ptr<Memory> process_memory(memory);
+
+  char* cwd = getcwd(nullptr, 0);
+  ASSERT_EQ(0, chdir(dir.c_str()));
+  JitDebug jit_debug(process_memory);
+  Unwinder unwinder(128, &maps, &regs, process_memory);
+  unwinder.SetJitDebug(&jit_debug, regs.Arch());
+  unwinder.Unwind();
+  ASSERT_EQ(0, chdir(cwd));
+  free(cwd);
+
+  std::string frame_info(DumpFrames(unwinder));
+  ASSERT_EQ(69U, unwinder.NumFrames()) << "Unwind:\n" << frame_info;
+  EXPECT_EQ(
+      "  #00 pc 00068fb8  libarttestd.so (_ZN3artL13CauseSegfaultEv+72)\n"
+      "  #01 pc 00067f00  libarttestd.so (Java_Main_unwindInProcess+10032)\n"
+      "  #02 pc 000021a8 (offset 0x2000)  137-cfi.odex (boolean Main.unwindInProcess(boolean, int, "
+      "boolean)+136)\n"
+      "  #03 pc 0000fe81  anonymous:ee74c000 (boolean Main.bar(boolean)+65)\n"
+      "  #04 pc 006ad4d2  libartd.so (art_quick_invoke_stub+338)\n"
+      "  #05 pc 00146ab5  libartd.so "
+      "(_ZN3art9ArtMethod6InvokeEPNS_6ThreadEPjjPNS_6JValueEPKc+885)\n"
+      "  #06 pc 0039cf0d  libartd.so "
+      "(_ZN3art11interpreter34ArtInterpreterToCompiledCodeBridgeEPNS_6ThreadEPNS_9ArtMethodEPNS_"
+      "11ShadowFrameEtPNS_6JValueE+653)\n"
+      "  #07 pc 00392552  libartd.so "
+      "(_ZN3art11interpreterL7ExecuteEPNS_6ThreadERKNS_20CodeItemDataAccessorERNS_11ShadowFrameENS_"
+      "6JValueEb+354)\n"
+      "  #08 pc 0039399a  libartd.so "
+      "(_ZN3art11interpreter30EnterInterpreterFromEntryPointEPNS_6ThreadERKNS_"
+      "20CodeItemDataAccessorEPNS_11ShadowFrameE+234)\n"
+      "  #09 pc 00684362  libartd.so (artQuickToInterpreterBridge+1058)\n"
+      "  #10 pc 006b35bd  libartd.so (art_quick_to_interpreter_bridge+77)\n"
+      "  #11 pc 0000fe04  anonymous:ee74c000 (int Main.compare(Main, Main)+52)\n"
+      "  #12 pc 006ad4d2  libartd.so (art_quick_invoke_stub+338)\n"
+      "  #13 pc 00146ab5  libartd.so "
+      "(_ZN3art9ArtMethod6InvokeEPNS_6ThreadEPjjPNS_6JValueEPKc+885)\n"
+      "  #14 pc 0039cf0d  libartd.so "
+      "(_ZN3art11interpreter34ArtInterpreterToCompiledCodeBridgeEPNS_6ThreadEPNS_9ArtMethodEPNS_"
+      "11ShadowFrameEtPNS_6JValueE+653)\n"
+      "  #15 pc 00392552  libartd.so "
+      "(_ZN3art11interpreterL7ExecuteEPNS_6ThreadERKNS_20CodeItemDataAccessorERNS_11ShadowFrameENS_"
+      "6JValueEb+354)\n"
+      "  #16 pc 0039399a  libartd.so "
+      "(_ZN3art11interpreter30EnterInterpreterFromEntryPointEPNS_6ThreadERKNS_"
+      "20CodeItemDataAccessorEPNS_11ShadowFrameE+234)\n"
+      "  #17 pc 00684362  libartd.so (artQuickToInterpreterBridge+1058)\n"
+      "  #18 pc 006b35bd  libartd.so (art_quick_to_interpreter_bridge+77)\n"
+      "  #19 pc 0000fd3c  anonymous:ee74c000 (int Main.compare(java.lang.Object, "
+      "java.lang.Object)+108)\n"
+      "  #20 pc 006ad4d2  libartd.so (art_quick_invoke_stub+338)\n"
+      "  #21 pc 00146ab5  libartd.so "
+      "(_ZN3art9ArtMethod6InvokeEPNS_6ThreadEPjjPNS_6JValueEPKc+885)\n"
+      "  #22 pc 0039cf0d  libartd.so "
+      "(_ZN3art11interpreter34ArtInterpreterToCompiledCodeBridgeEPNS_6ThreadEPNS_9ArtMethodEPNS_"
+      "11ShadowFrameEtPNS_6JValueE+653)\n"
+      "  #23 pc 00392552  libartd.so "
+      "(_ZN3art11interpreterL7ExecuteEPNS_6ThreadERKNS_20CodeItemDataAccessorERNS_11ShadowFrameENS_"
+      "6JValueEb+354)\n"
+      "  #24 pc 0039399a  libartd.so "
+      "(_ZN3art11interpreter30EnterInterpreterFromEntryPointEPNS_6ThreadERKNS_"
+      "20CodeItemDataAccessorEPNS_11ShadowFrameE+234)\n"
+      "  #25 pc 00684362  libartd.so (artQuickToInterpreterBridge+1058)\n"
+      "  #26 pc 006b35bd  libartd.so (art_quick_to_interpreter_bridge+77)\n"
+      "  #27 pc 0000fbdc  anonymous:ee74c000 (int "
+      "java.util.Arrays.binarySearch0(java.lang.Object[], int, int, java.lang.Object, "
+      "java.util.Comparator)+332)\n"
+      "  #28 pc 006ad6a2  libartd.so (art_quick_invoke_static_stub+418)\n"
+      "  #29 pc 00146acb  libartd.so "
+      "(_ZN3art9ArtMethod6InvokeEPNS_6ThreadEPjjPNS_6JValueEPKc+907)\n"
+      "  #30 pc 0039cf0d  libartd.so "
+      "(_ZN3art11interpreter34ArtInterpreterToCompiledCodeBridgeEPNS_6ThreadEPNS_9ArtMethodEPNS_"
+      "11ShadowFrameEtPNS_6JValueE+653)\n"
+      "  #31 pc 00392552  libartd.so "
+      "(_ZN3art11interpreterL7ExecuteEPNS_6ThreadERKNS_20CodeItemDataAccessorERNS_11ShadowFrameENS_"
+      "6JValueEb+354)\n"
+      "  #32 pc 0039399a  libartd.so "
+      "(_ZN3art11interpreter30EnterInterpreterFromEntryPointEPNS_6ThreadERKNS_"
+      "20CodeItemDataAccessorEPNS_11ShadowFrameE+234)\n"
+      "  #33 pc 00684362  libartd.so (artQuickToInterpreterBridge+1058)\n"
+      "  #34 pc 006b35bd  libartd.so (art_quick_to_interpreter_bridge+77)\n"
+      "  #35 pc 0000f625  anonymous:ee74c000 (boolean Main.foo()+165)\n"
+      "  #36 pc 006ad4d2  libartd.so (art_quick_invoke_stub+338)\n"
+      "  #37 pc 00146ab5  libartd.so "
+      "(_ZN3art9ArtMethod6InvokeEPNS_6ThreadEPjjPNS_6JValueEPKc+885)\n"
+      "  #38 pc 0039cf0d  libartd.so "
+      "(_ZN3art11interpreter34ArtInterpreterToCompiledCodeBridgeEPNS_6ThreadEPNS_9ArtMethodEPNS_"
+      "11ShadowFrameEtPNS_6JValueE+653)\n"
+      "  #39 pc 00392552  libartd.so "
+      "(_ZN3art11interpreterL7ExecuteEPNS_6ThreadERKNS_20CodeItemDataAccessorERNS_11ShadowFrameENS_"
+      "6JValueEb+354)\n"
+      "  #40 pc 0039399a  libartd.so "
+      "(_ZN3art11interpreter30EnterInterpreterFromEntryPointEPNS_6ThreadERKNS_"
+      "20CodeItemDataAccessorEPNS_11ShadowFrameE+234)\n"
+      "  #41 pc 00684362  libartd.so (artQuickToInterpreterBridge+1058)\n"
+      "  #42 pc 006b35bd  libartd.so (art_quick_to_interpreter_bridge+77)\n"
+      "  #43 pc 0000eedc  anonymous:ee74c000 (void Main.runPrimary()+60)\n"
+      "  #44 pc 006ad4d2  libartd.so (art_quick_invoke_stub+338)\n"
+      "  #45 pc 00146ab5  libartd.so "
+      "(_ZN3art9ArtMethod6InvokeEPNS_6ThreadEPjjPNS_6JValueEPKc+885)\n"
+      "  #46 pc 0039cf0d  libartd.so "
+      "(_ZN3art11interpreter34ArtInterpreterToCompiledCodeBridgeEPNS_6ThreadEPNS_9ArtMethodEPNS_"
+      "11ShadowFrameEtPNS_6JValueE+653)\n"
+      "  #47 pc 00392552  libartd.so "
+      "(_ZN3art11interpreterL7ExecuteEPNS_6ThreadERKNS_20CodeItemDataAccessorERNS_11ShadowFrameENS_"
+      "6JValueEb+354)\n"
+      "  #48 pc 0039399a  libartd.so "
+      "(_ZN3art11interpreter30EnterInterpreterFromEntryPointEPNS_6ThreadERKNS_"
+      "20CodeItemDataAccessorEPNS_11ShadowFrameE+234)\n"
+      "  #49 pc 00684362  libartd.so (artQuickToInterpreterBridge+1058)\n"
+      "  #50 pc 006b35bd  libartd.so (art_quick_to_interpreter_bridge+77)\n"
+      "  #51 pc 0000ac22  anonymous:ee74c000 (void Main.main(java.lang.String[])+98)\n"
+      "  #52 pc 006ad6a2  libartd.so (art_quick_invoke_static_stub+418)\n"
+      "  #53 pc 00146acb  libartd.so "
+      "(_ZN3art9ArtMethod6InvokeEPNS_6ThreadEPjjPNS_6JValueEPKc+907)\n"
+      "  #54 pc 0039cf0d  libartd.so "
+      "(_ZN3art11interpreter34ArtInterpreterToCompiledCodeBridgeEPNS_6ThreadEPNS_9ArtMethodEPNS_"
+      "11ShadowFrameEtPNS_6JValueE+653)\n"
+      "  #55 pc 00392552  libartd.so "
+      "(_ZN3art11interpreterL7ExecuteEPNS_6ThreadERKNS_20CodeItemDataAccessorERNS_11ShadowFrameENS_"
+      "6JValueEb+354)\n"
+      "  #56 pc 0039399a  libartd.so "
+      "(_ZN3art11interpreter30EnterInterpreterFromEntryPointEPNS_6ThreadERKNS_"
+      "20CodeItemDataAccessorEPNS_11ShadowFrameE+234)\n"
+      "  #57 pc 00684362  libartd.so (artQuickToInterpreterBridge+1058)\n"
+      "  #58 pc 006b35bd  libartd.so (art_quick_to_interpreter_bridge+77)\n"
+      "  #59 pc 006ad6a2  libartd.so (art_quick_invoke_static_stub+418)\n"
+      "  #60 pc 00146acb  libartd.so "
+      "(_ZN3art9ArtMethod6InvokeEPNS_6ThreadEPjjPNS_6JValueEPKc+907)\n"
+      "  #61 pc 005aac95  libartd.so "
+      "(_ZN3artL18InvokeWithArgArrayERKNS_33ScopedObjectAccessAlreadyRunnableEPNS_9ArtMethodEPNS_"
+      "8ArgArrayEPNS_6JValueEPKc+85)\n"
+      "  #62 pc 005aab5a  libartd.so "
+      "(_ZN3art17InvokeWithVarArgsERKNS_33ScopedObjectAccessAlreadyRunnableEP8_jobjectP10_"
+      "jmethodIDPc+362)\n"
+      "  #63 pc 0048a3dd  libartd.so "
+      "(_ZN3art3JNI21CallStaticVoidMethodVEP7_JNIEnvP7_jclassP10_jmethodIDPc+125)\n"
+      "  #64 pc 0018448c  libartd.so "
+      "(_ZN3art8CheckJNI11CallMethodVEPKcP7_JNIEnvP8_jobjectP7_jclassP10_jmethodIDPcNS_"
+      "9Primitive4TypeENS_10InvokeTypeE+1964)\n"
+      "  #65 pc 0017cf06  libartd.so "
+      "(_ZN3art8CheckJNI21CallStaticVoidMethodVEP7_JNIEnvP7_jclassP10_jmethodIDPc+70)\n"
+      "  #66 pc 00001d8c  dalvikvm32 "
+      "(_ZN7_JNIEnv20CallStaticVoidMethodEP7_jclassP10_jmethodIDz+60)\n"
+      "  #67 pc 00001a80  dalvikvm32 (main+1312)\n"
+      "  #68 pc 00018275  libc.so\n",
+      frame_info);
+}
+
+TEST(UnwindOfflineTest, jit_debug_arm32) {
+  std::string dir(TestGetFileDirectory() + "offline/jit_debug_arm32/");
+
+  MemoryOfflineParts* memory = new MemoryOfflineParts;
+  AddMemory(dir + "descriptor.data", memory);
+  AddMemory(dir + "descriptor1.data", memory);
+  AddMemory(dir + "stack.data", memory);
+  for (size_t i = 0; i < 7; i++) {
+    AddMemory(dir + "entry" + std::to_string(i) + ".data", memory);
+    AddMemory(dir + "jit" + std::to_string(i) + ".data", memory);
+  }
+
+  FILE* fp = fopen((dir + "regs.txt").c_str(), "r");
+  ASSERT_TRUE(fp != nullptr);
+  RegsArm regs;
+  uint64_t reg_value;
+  ASSERT_EQ(1, fscanf(fp, "r0: %" SCNx64 "\n", &reg_value));
+  regs[ARM_REG_R0] = reg_value;
+  ASSERT_EQ(1, fscanf(fp, "r1: %" SCNx64 "\n", &reg_value));
+  regs[ARM_REG_R1] = reg_value;
+  ASSERT_EQ(1, fscanf(fp, "r2: %" SCNx64 "\n", &reg_value));
+  regs[ARM_REG_R2] = reg_value;
+  ASSERT_EQ(1, fscanf(fp, "r3: %" SCNx64 "\n", &reg_value));
+  regs[ARM_REG_R3] = reg_value;
+  ASSERT_EQ(1, fscanf(fp, "r4: %" SCNx64 "\n", &reg_value));
+  regs[ARM_REG_R4] = reg_value;
+  ASSERT_EQ(1, fscanf(fp, "r5: %" SCNx64 "\n", &reg_value));
+  regs[ARM_REG_R5] = reg_value;
+  ASSERT_EQ(1, fscanf(fp, "r6: %" SCNx64 "\n", &reg_value));
+  regs[ARM_REG_R6] = reg_value;
+  ASSERT_EQ(1, fscanf(fp, "r7: %" SCNx64 "\n", &reg_value));
+  regs[ARM_REG_R7] = reg_value;
+  ASSERT_EQ(1, fscanf(fp, "r8: %" SCNx64 "\n", &reg_value));
+  regs[ARM_REG_R8] = reg_value;
+  ASSERT_EQ(1, fscanf(fp, "r9: %" SCNx64 "\n", &reg_value));
+  regs[ARM_REG_R9] = reg_value;
+  ASSERT_EQ(1, fscanf(fp, "r10: %" SCNx64 "\n", &reg_value));
+  regs[ARM_REG_R10] = reg_value;
+  ASSERT_EQ(1, fscanf(fp, "r11: %" SCNx64 "\n", &reg_value));
+  regs[ARM_REG_R11] = reg_value;
+  ASSERT_EQ(1, fscanf(fp, "ip: %" SCNx64 "\n", &reg_value));
+  regs[ARM_REG_R12] = reg_value;
+  ASSERT_EQ(1, fscanf(fp, "sp: %" SCNx64 "\n", &reg_value));
+  regs[ARM_REG_SP] = reg_value;
+  ASSERT_EQ(1, fscanf(fp, "lr: %" SCNx64 "\n", &reg_value));
+  regs[ARM_REG_LR] = reg_value;
+  ASSERT_EQ(1, fscanf(fp, "pc: %" SCNx64 "\n", &reg_value));
+  regs[ARM_REG_PC] = reg_value;
+  regs.SetFromRaw();
+  fclose(fp);
+
+  fp = fopen((dir + "maps.txt").c_str(), "r");
+  ASSERT_TRUE(fp != nullptr);
+  // The file is guaranteed to be less than 4096 bytes.
+  std::vector<char> buffer(4096);
+  ASSERT_NE(0U, fread(buffer.data(), 1, buffer.size(), fp));
+  fclose(fp);
+
+  BufferMaps maps(buffer.data());
+  ASSERT_TRUE(maps.Parse());
+
+  ASSERT_EQ(ARCH_ARM, regs.Arch());
+
+  std::shared_ptr<Memory> process_memory(memory);
+
+  char* cwd = getcwd(nullptr, 0);
+  ASSERT_EQ(0, chdir(dir.c_str()));
+  JitDebug jit_debug(process_memory);
+  Unwinder unwinder(128, &maps, &regs, process_memory);
+  unwinder.SetJitDebug(&jit_debug, regs.Arch());
+  unwinder.Unwind();
+  ASSERT_EQ(0, chdir(cwd));
+  free(cwd);
+
+  std::string frame_info(DumpFrames(unwinder));
+  ASSERT_EQ(76U, unwinder.NumFrames()) << "Unwind:\n" << frame_info;
+  EXPECT_EQ(
+      "  #00 pc 00018a5e  libarttestd.so (Java_Main_unwindInProcess+865)\n"
+      "  #01 pc 0000212d (offset 0x2000)  137-cfi.odex (boolean Main.unwindInProcess(boolean, int, "
+      "boolean)+92)\n"
+      "  #02 pc 00011cb1  anonymous:e2796000 (boolean Main.bar(boolean)+72)\n"
+      "  #03 pc 00462175  libartd.so (art_quick_invoke_stub_internal+68)\n"
+      "  #04 pc 00467129  libartd.so (art_quick_invoke_stub+228)\n"
+      "  #05 pc 000bf7a9  libartd.so "
+      "(_ZN3art9ArtMethod6InvokeEPNS_6ThreadEPjjPNS_6JValueEPKc+864)\n"
+      "  #06 pc 00247833  libartd.so "
+      "(_ZN3art11interpreter34ArtInterpreterToCompiledCodeBridgeEPNS_6ThreadEPNS_9ArtMethodEPNS_"
+      "11ShadowFrameEtPNS_6JValueE+382)\n"
+      "  #07 pc 0022e935  libartd.so "
+      "(_ZN3art11interpreterL7ExecuteEPNS_6ThreadERKNS_20CodeItemDataAccessorERNS_11ShadowFrameENS_"
+      "6JValueEb+244)\n"
+      "  #08 pc 0022f71d  libartd.so "
+      "(_ZN3art11interpreter30EnterInterpreterFromEntryPointEPNS_6ThreadERKNS_"
+      "20CodeItemDataAccessorEPNS_11ShadowFrameE+128)\n"
+      "  #09 pc 00442865  libartd.so (artQuickToInterpreterBridge+796)\n"
+      "  #10 pc 004666ff  libartd.so (art_quick_to_interpreter_bridge+30)\n"
+      "  #11 pc 00011c31  anonymous:e2796000 (int Main.compare(Main, Main)+64)\n"
+      "  #12 pc 00462175  libartd.so (art_quick_invoke_stub_internal+68)\n"
+      "  #13 pc 00467129  libartd.so (art_quick_invoke_stub+228)\n"
+      "  #14 pc 000bf7a9  libartd.so "
+      "(_ZN3art9ArtMethod6InvokeEPNS_6ThreadEPjjPNS_6JValueEPKc+864)\n"
+      "  #15 pc 00247833  libartd.so "
+      "(_ZN3art11interpreter34ArtInterpreterToCompiledCodeBridgeEPNS_6ThreadEPNS_9ArtMethodEPNS_"
+      "11ShadowFrameEtPNS_6JValueE+382)\n"
+      "  #16 pc 0022e935  libartd.so "
+      "(_ZN3art11interpreterL7ExecuteEPNS_6ThreadERKNS_20CodeItemDataAccessorERNS_11ShadowFrameENS_"
+      "6JValueEb+244)\n"
+      "  #17 pc 0022f71d  libartd.so "
+      "(_ZN3art11interpreter30EnterInterpreterFromEntryPointEPNS_6ThreadERKNS_"
+      "20CodeItemDataAccessorEPNS_11ShadowFrameE+128)\n"
+      "  #18 pc 00442865  libartd.so (artQuickToInterpreterBridge+796)\n"
+      "  #19 pc 004666ff  libartd.so (art_quick_to_interpreter_bridge+30)\n"
+      "  #20 pc 00011b77  anonymous:e2796000 (int Main.compare(java.lang.Object, "
+      "java.lang.Object)+118)\n"
+      "  #21 pc 00462175  libartd.so (art_quick_invoke_stub_internal+68)\n"
+      "  #22 pc 00467129  libartd.so (art_quick_invoke_stub+228)\n"
+      "  #23 pc 000bf7a9  libartd.so "
+      "(_ZN3art9ArtMethod6InvokeEPNS_6ThreadEPjjPNS_6JValueEPKc+864)\n"
+      "  #24 pc 00247833  libartd.so "
+      "(_ZN3art11interpreter34ArtInterpreterToCompiledCodeBridgeEPNS_6ThreadEPNS_9ArtMethodEPNS_"
+      "11ShadowFrameEtPNS_6JValueE+382)\n"
+      "  #25 pc 0022e935  libartd.so "
+      "(_ZN3art11interpreterL7ExecuteEPNS_6ThreadERKNS_20CodeItemDataAccessorERNS_11ShadowFrameENS_"
+      "6JValueEb+244)\n"
+      "  #26 pc 0022f71d  libartd.so "
+      "(_ZN3art11interpreter30EnterInterpreterFromEntryPointEPNS_6ThreadERKNS_"
+      "20CodeItemDataAccessorEPNS_11ShadowFrameE+128)\n"
+      "  #27 pc 00442865  libartd.so (artQuickToInterpreterBridge+796)\n"
+      "  #28 pc 004666ff  libartd.so (art_quick_to_interpreter_bridge+30)\n"
+      "  #29 pc 00011a29  anonymous:e2796000 (int "
+      "java.util.Arrays.binarySearch0(java.lang.Object[], int, int, java.lang.Object, "
+      "java.util.Comparator)+304)\n"
+      "  #30 pc 00462175  libartd.so (art_quick_invoke_stub_internal+68)\n"
+      "  #31 pc 0046722f  libartd.so (art_quick_invoke_static_stub+226)\n"
+      "  #32 pc 000bf7bb  libartd.so "
+      "(_ZN3art9ArtMethod6InvokeEPNS_6ThreadEPjjPNS_6JValueEPKc+882)\n"
+      "  #33 pc 00247833  libartd.so "
+      "(_ZN3art11interpreter34ArtInterpreterToCompiledCodeBridgeEPNS_6ThreadEPNS_9ArtMethodEPNS_"
+      "11ShadowFrameEtPNS_6JValueE+382)\n"
+      "  #34 pc 0022e935  libartd.so "
+      "(_ZN3art11interpreterL7ExecuteEPNS_6ThreadERKNS_20CodeItemDataAccessorERNS_11ShadowFrameENS_"
+      "6JValueEb+244)\n"
+      "  #35 pc 0022f71d  libartd.so "
+      "(_ZN3art11interpreter30EnterInterpreterFromEntryPointEPNS_6ThreadERKNS_"
+      "20CodeItemDataAccessorEPNS_11ShadowFrameE+128)\n"
+      "  #36 pc 00442865  libartd.so (artQuickToInterpreterBridge+796)\n"
+      "  #37 pc 004666ff  libartd.so (art_quick_to_interpreter_bridge+30)\n"
+      "  #38 pc 0001139b  anonymous:e2796000 (boolean Main.foo()+178)\n"
+      "  #39 pc 00462175  libartd.so (art_quick_invoke_stub_internal+68)\n"
+      "  #40 pc 00467129  libartd.so (art_quick_invoke_stub+228)\n"
+      "  #41 pc 000bf7a9  libartd.so "
+      "(_ZN3art9ArtMethod6InvokeEPNS_6ThreadEPjjPNS_6JValueEPKc+864)\n"
+      "  #42 pc 00247833  libartd.so "
+      "(_ZN3art11interpreter34ArtInterpreterToCompiledCodeBridgeEPNS_6ThreadEPNS_9ArtMethodEPNS_"
+      "11ShadowFrameEtPNS_6JValueE+382)\n"
+      "  #43 pc 0022e935  libartd.so "
+      "(_ZN3art11interpreterL7ExecuteEPNS_6ThreadERKNS_20CodeItemDataAccessorERNS_11ShadowFrameENS_"
+      "6JValueEb+244)\n"
+      "  #44 pc 0022f71d  libartd.so "
+      "(_ZN3art11interpreter30EnterInterpreterFromEntryPointEPNS_6ThreadERKNS_"
+      "20CodeItemDataAccessorEPNS_11ShadowFrameE+128)\n"
+      "  #45 pc 00442865  libartd.so (artQuickToInterpreterBridge+796)\n"
+      "  #46 pc 004666ff  libartd.so (art_quick_to_interpreter_bridge+30)\n"
+      "  #47 pc 00010aa7  anonymous:e2796000 (void Main.runPrimary()+70)\n"
+      "  #48 pc 00462175  libartd.so (art_quick_invoke_stub_internal+68)\n"
+      "  #49 pc 00467129  libartd.so (art_quick_invoke_stub+228)\n"
+      "  #50 pc 000bf7a9  libartd.so "
+      "(_ZN3art9ArtMethod6InvokeEPNS_6ThreadEPjjPNS_6JValueEPKc+864)\n"
+      "  #51 pc 00247833  libartd.so "
+      "(_ZN3art11interpreter34ArtInterpreterToCompiledCodeBridgeEPNS_6ThreadEPNS_9ArtMethodEPNS_"
+      "11ShadowFrameEtPNS_6JValueE+382)\n"
+      "  #52 pc 0022e935  libartd.so "
+      "(_ZN3art11interpreterL7ExecuteEPNS_6ThreadERKNS_20CodeItemDataAccessorERNS_11ShadowFrameENS_"
+      "6JValueEb+244)\n"
+      "  #53 pc 0022f71d  libartd.so "
+      "(_ZN3art11interpreter30EnterInterpreterFromEntryPointEPNS_6ThreadERKNS_"
+      "20CodeItemDataAccessorEPNS_11ShadowFrameE+128)\n"
+      "  #54 pc 00442865  libartd.so (artQuickToInterpreterBridge+796)\n"
+      "  #55 pc 004666ff  libartd.so (art_quick_to_interpreter_bridge+30)\n"
+      "  #56 pc 0000ba99  anonymous:e2796000 (void Main.main(java.lang.String[])+144)\n"
+      "  #57 pc 00462175  libartd.so (art_quick_invoke_stub_internal+68)\n"
+      "  #58 pc 0046722f  libartd.so (art_quick_invoke_static_stub+226)\n"
+      "  #59 pc 000bf7bb  libartd.so "
+      "(_ZN3art9ArtMethod6InvokeEPNS_6ThreadEPjjPNS_6JValueEPKc+882)\n"
+      "  #60 pc 00247833  libartd.so "
+      "(_ZN3art11interpreter34ArtInterpreterToCompiledCodeBridgeEPNS_6ThreadEPNS_9ArtMethodEPNS_"
+      "11ShadowFrameEtPNS_6JValueE+382)\n"
+      "  #61 pc 0022e935  libartd.so "
+      "(_ZN3art11interpreterL7ExecuteEPNS_6ThreadERKNS_20CodeItemDataAccessorERNS_11ShadowFrameENS_"
+      "6JValueEb+244)\n"
+      "  #62 pc 0022f71d  libartd.so "
+      "(_ZN3art11interpreter30EnterInterpreterFromEntryPointEPNS_6ThreadERKNS_"
+      "20CodeItemDataAccessorEPNS_11ShadowFrameE+128)\n"
+      "  #63 pc 00442865  libartd.so (artQuickToInterpreterBridge+796)\n"
+      "  #64 pc 004666ff  libartd.so (art_quick_to_interpreter_bridge+30)\n"
+      "  #65 pc 00462175  libartd.so (art_quick_invoke_stub_internal+68)\n"
+      "  #66 pc 0046722f  libartd.so (art_quick_invoke_static_stub+226)\n"
+      "  #67 pc 000bf7bb  libartd.so "
+      "(_ZN3art9ArtMethod6InvokeEPNS_6ThreadEPjjPNS_6JValueEPKc+882)\n"
+      "  #68 pc 003b292d  libartd.so "
+      "(_ZN3artL18InvokeWithArgArrayERKNS_33ScopedObjectAccessAlreadyRunnableEPNS_9ArtMethodEPNS_"
+      "8ArgArrayEPNS_6JValueEPKc+52)\n"
+      "  #69 pc 003b26c3  libartd.so "
+      "(_ZN3art17InvokeWithVarArgsERKNS_33ScopedObjectAccessAlreadyRunnableEP8_jobjectP10_"
+      "jmethodIDSt9__va_list+210)\n"
+      "  #70 pc 00308411  libartd.so "
+      "(_ZN3art3JNI21CallStaticVoidMethodVEP7_JNIEnvP7_jclassP10_jmethodIDSt9__va_list+76)\n"
+      "  #71 pc 000e6a9f  libartd.so "
+      "(_ZN3art8CheckJNI11CallMethodVEPKcP7_JNIEnvP8_jobjectP7_jclassP10_jmethodIDSt9__va_listNS_"
+      "9Primitive4TypeENS_10InvokeTypeE+1486)\n"
+      "  #72 pc 000e19b9  libartd.so "
+      "(_ZN3art8CheckJNI21CallStaticVoidMethodVEP7_JNIEnvP7_jclassP10_jmethodIDSt9__va_list+40)\n"
+      "  #73 pc 0000159f  dalvikvm32 "
+      "(_ZN7_JNIEnv20CallStaticVoidMethodEP7_jclassP10_jmethodIDz+30)\n"
+      "  #74 pc 00001349  dalvikvm32 (main+896)\n"
+      "  #75 pc 000850c9  libc.so\n",
+      frame_info);
+}
+
 }  // namespace unwindstack
diff --git a/libunwindstack/tests/files/offline/gnu_debugdata_arm32/libandroid_runtime.so b/libunwindstack/tests/files/offline/gnu_debugdata_arm32/libandroid_runtime.so
new file mode 100644
index 0000000..e4283e6
--- /dev/null
+++ b/libunwindstack/tests/files/offline/gnu_debugdata_arm32/libandroid_runtime.so
Binary files differ
diff --git a/libunwindstack/tests/files/offline/gnu_debugdata_arm32/maps.txt b/libunwindstack/tests/files/offline/gnu_debugdata_arm32/maps.txt
new file mode 100644
index 0000000..1bcddb6
--- /dev/null
+++ b/libunwindstack/tests/files/offline/gnu_debugdata_arm32/maps.txt
@@ -0,0 +1 @@
+f1f10000-f2049000 r-xp 00000000 00:00 0   libandroid_runtime.so
diff --git a/libunwindstack/tests/files/offline/gnu_debugdata_arm32/regs.txt b/libunwindstack/tests/files/offline/gnu_debugdata_arm32/regs.txt
new file mode 100644
index 0000000..c6a93dc
--- /dev/null
+++ b/libunwindstack/tests/files/offline/gnu_debugdata_arm32/regs.txt
@@ -0,0 +1,2 @@
+pc: f1f6dc49
+sp: d8fe6930
diff --git a/libunwindstack/tests/files/offline/gnu_debugdata_arm32/stack.data b/libunwindstack/tests/files/offline/gnu_debugdata_arm32/stack.data
new file mode 100644
index 0000000..19cdf2d
--- /dev/null
+++ b/libunwindstack/tests/files/offline/gnu_debugdata_arm32/stack.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/137-cfi.odex b/libunwindstack/tests/files/offline/jit_debug_arm32/137-cfi.odex
new file mode 100644
index 0000000..35a6bc5
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/137-cfi.odex
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/dalvikvm32 b/libunwindstack/tests/files/offline/jit_debug_arm32/dalvikvm32
new file mode 100644
index 0000000..def299e
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/dalvikvm32
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/descriptor.data b/libunwindstack/tests/files/offline/jit_debug_arm32/descriptor.data
new file mode 100644
index 0000000..7b876b5
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/descriptor.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/descriptor1.data b/libunwindstack/tests/files/offline/jit_debug_arm32/descriptor1.data
new file mode 100644
index 0000000..3c468d6
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/descriptor1.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/entry0.data b/libunwindstack/tests/files/offline/jit_debug_arm32/entry0.data
new file mode 100644
index 0000000..2c7689b
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/entry0.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/entry1.data b/libunwindstack/tests/files/offline/jit_debug_arm32/entry1.data
new file mode 100644
index 0000000..22a35b8
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/entry1.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/entry2.data b/libunwindstack/tests/files/offline/jit_debug_arm32/entry2.data
new file mode 100644
index 0000000..61f3927
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/entry2.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/entry3.data b/libunwindstack/tests/files/offline/jit_debug_arm32/entry3.data
new file mode 100644
index 0000000..1a37628
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/entry3.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/entry4.data b/libunwindstack/tests/files/offline/jit_debug_arm32/entry4.data
new file mode 100644
index 0000000..7ef62ca
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/entry4.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/entry5.data b/libunwindstack/tests/files/offline/jit_debug_arm32/entry5.data
new file mode 100644
index 0000000..6d27c89
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/entry5.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/entry6.data b/libunwindstack/tests/files/offline/jit_debug_arm32/entry6.data
new file mode 100644
index 0000000..bfbceea
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/entry6.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/jit0.data b/libunwindstack/tests/files/offline/jit_debug_arm32/jit0.data
new file mode 100644
index 0000000..b78848e
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/jit0.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/jit1.data b/libunwindstack/tests/files/offline/jit_debug_arm32/jit1.data
new file mode 100644
index 0000000..8f927ac
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/jit1.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/jit2.data b/libunwindstack/tests/files/offline/jit_debug_arm32/jit2.data
new file mode 100644
index 0000000..1d1dfca
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/jit2.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/jit3.data b/libunwindstack/tests/files/offline/jit_debug_arm32/jit3.data
new file mode 100644
index 0000000..89aeb43
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/jit3.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/jit4.data b/libunwindstack/tests/files/offline/jit_debug_arm32/jit4.data
new file mode 100644
index 0000000..e076934
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/jit4.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/jit5.data b/libunwindstack/tests/files/offline/jit_debug_arm32/jit5.data
new file mode 100644
index 0000000..17d6041
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/jit5.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/jit6.data b/libunwindstack/tests/files/offline/jit_debug_arm32/jit6.data
new file mode 100644
index 0000000..aaff037
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/jit6.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/libart.so b/libunwindstack/tests/files/offline/jit_debug_arm32/libart.so
new file mode 100644
index 0000000..0527893
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/libart.so
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/libartd.so b/libunwindstack/tests/files/offline/jit_debug_arm32/libartd.so
new file mode 100644
index 0000000..8559056
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/libartd.so
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/libarttestd.so b/libunwindstack/tests/files/offline/jit_debug_arm32/libarttestd.so
new file mode 100644
index 0000000..06dbf10
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/libarttestd.so
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/libc.so b/libunwindstack/tests/files/offline/jit_debug_arm32/libc.so
new file mode 100644
index 0000000..9894e66
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/libc.so
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/maps.txt b/libunwindstack/tests/files/offline/jit_debug_arm32/maps.txt
new file mode 100644
index 0000000..f25c781
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/maps.txt
@@ -0,0 +1,8 @@
+ab0d3000-ab0d8000 r-xp 0 00:00 0   dalvikvm32
+dfe4e000-dfe7b000 r-xp 0 00:00 0   libarttestd.so
+e0447000-e0448000 r-xp 2000 00:00 0   137-cfi.odex
+e2796000-e4796000 r-xp 0 00:00 0   anonymous:e2796000
+e648e000-e690f000 r-xp 00000000 00:00 0  libart.so
+ed306000-ed801000 r-xp 0 00:00 0   libartd.so
+eda88000-edb23000 r-xp 0 00:00 0   libc.so
+ede4e000-ede50000 r-xp 0 00:00 0   anonymous:ede4e000
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/regs.txt b/libunwindstack/tests/files/offline/jit_debug_arm32/regs.txt
new file mode 100644
index 0000000..0e20066
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/regs.txt
@@ -0,0 +1,16 @@
+r0: dfe7c0f8
+r1: 0
+r2: 0
+r3: 40000000
+r4: e051ffb4
+r5: 0
+r6: e051ffc0
+r7: ede514e8
+r8: ff85d1a8
+r9: ed9210c0
+r10: 58
+r11: 0
+ip: edb26d04
+sp: ff85d180
+lr: edaff5af
+pc: dfe66a5e
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/stack.data b/libunwindstack/tests/files/offline/jit_debug_arm32/stack.data
new file mode 100644
index 0000000..b2ff14e
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/stack.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_x86_32/137-cfi.odex b/libunwindstack/tests/files/offline/jit_debug_x86_32/137-cfi.odex
new file mode 100644
index 0000000..870ac0a
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_x86_32/137-cfi.odex
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_x86_32/dalvikvm32 b/libunwindstack/tests/files/offline/jit_debug_x86_32/dalvikvm32
new file mode 100644
index 0000000..76ffad9
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_x86_32/dalvikvm32
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_x86_32/descriptor.data b/libunwindstack/tests/files/offline/jit_debug_x86_32/descriptor.data
new file mode 100644
index 0000000..466dae2
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_x86_32/descriptor.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_x86_32/entry0.data b/libunwindstack/tests/files/offline/jit_debug_x86_32/entry0.data
new file mode 100644
index 0000000..3a725e8
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_x86_32/entry0.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_x86_32/entry1.data b/libunwindstack/tests/files/offline/jit_debug_x86_32/entry1.data
new file mode 100644
index 0000000..767550f
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_x86_32/entry1.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_x86_32/entry2.data b/libunwindstack/tests/files/offline/jit_debug_x86_32/entry2.data
new file mode 100644
index 0000000..e7e492e
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_x86_32/entry2.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_x86_32/entry3.data b/libunwindstack/tests/files/offline/jit_debug_x86_32/entry3.data
new file mode 100644
index 0000000..65f9cd4
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_x86_32/entry3.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_x86_32/entry4.data b/libunwindstack/tests/files/offline/jit_debug_x86_32/entry4.data
new file mode 100644
index 0000000..30aa28c
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_x86_32/entry4.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_x86_32/entry5.data b/libunwindstack/tests/files/offline/jit_debug_x86_32/entry5.data
new file mode 100644
index 0000000..3c89673
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_x86_32/entry5.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_x86_32/entry6.data b/libunwindstack/tests/files/offline/jit_debug_x86_32/entry6.data
new file mode 100644
index 0000000..9c9b83c
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_x86_32/entry6.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_x86_32/jit0.data b/libunwindstack/tests/files/offline/jit_debug_x86_32/jit0.data
new file mode 100644
index 0000000..eaad142
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_x86_32/jit0.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_x86_32/jit1.data b/libunwindstack/tests/files/offline/jit_debug_x86_32/jit1.data
new file mode 100644
index 0000000..d534816
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_x86_32/jit1.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_x86_32/jit2.data b/libunwindstack/tests/files/offline/jit_debug_x86_32/jit2.data
new file mode 100644
index 0000000..dbeb886
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_x86_32/jit2.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_x86_32/jit3.data b/libunwindstack/tests/files/offline/jit_debug_x86_32/jit3.data
new file mode 100644
index 0000000..bf2142d
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_x86_32/jit3.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_x86_32/jit4.data b/libunwindstack/tests/files/offline/jit_debug_x86_32/jit4.data
new file mode 100644
index 0000000..e2ba1b0
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_x86_32/jit4.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_x86_32/jit5.data b/libunwindstack/tests/files/offline/jit_debug_x86_32/jit5.data
new file mode 100644
index 0000000..c27ba54
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_x86_32/jit5.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_x86_32/jit6.data b/libunwindstack/tests/files/offline/jit_debug_x86_32/jit6.data
new file mode 100644
index 0000000..5fc8fae
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_x86_32/jit6.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_x86_32/libartd.so b/libunwindstack/tests/files/offline/jit_debug_x86_32/libartd.so
new file mode 100644
index 0000000..70352db
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_x86_32/libartd.so
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_x86_32/libarttestd.so b/libunwindstack/tests/files/offline/jit_debug_x86_32/libarttestd.so
new file mode 100644
index 0000000..e72e673
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_x86_32/libarttestd.so
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_x86_32/libc.so b/libunwindstack/tests/files/offline/jit_debug_x86_32/libc.so
new file mode 100644
index 0000000..9c78790
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_x86_32/libc.so
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_x86_32/maps.txt b/libunwindstack/tests/files/offline/jit_debug_x86_32/maps.txt
new file mode 100644
index 0000000..db4f9f7
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_x86_32/maps.txt
@@ -0,0 +1,6 @@
+56573000-56577000 r-xp 0 00:00 0   dalvikvm32
+eb833000-eb8cc000 r-xp 0 00:00 0   libarttestd.so
+ec606000-ec607000 r-xp 2000 00:00 0   137-cfi.odex
+ee74c000-f074c000 r-xp 0 00:00 0   anonymous:ee74c000
+f6be1000-f732b000 r-xp 0 00:00 0   libartd.so
+f734b000-f74fc000 r-xp 0 00:00 0   libc.so
diff --git a/libunwindstack/tests/files/offline/jit_debug_x86_32/regs.txt b/libunwindstack/tests/files/offline/jit_debug_x86_32/regs.txt
new file mode 100644
index 0000000..f68305b
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_x86_32/regs.txt
@@ -0,0 +1,9 @@
+eax: eb8cccd0
+ebx: eb8cccd0
+ecx: ff
+edx: ffeb2ca8
+ebp: ffeb5298
+edi: ffeb5c08
+esi: ffeb5c00
+esp: ffeb5280
+eip: eb89bfb8
diff --git a/libunwindstack/tests/files/offline/jit_debug_x86_32/stack.data b/libunwindstack/tests/files/offline/jit_debug_x86_32/stack.data
new file mode 100644
index 0000000..c345762
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_x86_32/stack.data
Binary files differ
diff --git a/libunwindstack/tools/unwind.cpp b/libunwindstack/tools/unwind.cpp
index 81bedb7..07e48af 100644
--- a/libunwindstack/tools/unwind.cpp
+++ b/libunwindstack/tools/unwind.cpp
@@ -27,6 +27,7 @@
 #include <unistd.h>
 
 #include <unwindstack/Elf.h>
+#include <unwindstack/JitDebug.h>
 #include <unwindstack/Maps.h>
 #include <unwindstack/Memory.h>
 #include <unwindstack/Regs.h>
@@ -90,6 +91,8 @@
 
   auto process_memory = unwindstack::Memory::CreateProcessMemory(pid);
   unwindstack::Unwinder unwinder(128, &remote_maps, regs, process_memory);
+  unwindstack::JitDebug jit_debug(process_memory);
+  unwinder.SetJitDebug(&jit_debug, regs->Arch());
   unwinder.Unwind();
 
   // Print the frames.
diff --git a/libunwindstack/tools/unwind_for_offline.cpp b/libunwindstack/tools/unwind_for_offline.cpp
new file mode 100644
index 0000000..74868d4
--- /dev/null
+++ b/libunwindstack/tools/unwind_for_offline.cpp
@@ -0,0 +1,269 @@
+/*
+ * 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.
+ */
+
+#define _GNU_SOURCE 1
+#include <errno.h>
+#include <inttypes.h>
+#include <signal.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ptrace.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <algorithm>
+#include <memory>
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+#include <unwindstack/Elf.h>
+#include <unwindstack/JitDebug.h>
+#include <unwindstack/Maps.h>
+#include <unwindstack/Memory.h>
+#include <unwindstack/Regs.h>
+#include <unwindstack/Unwinder.h>
+
+#include <android-base/stringprintf.h>
+
+struct map_info_t {
+  uint64_t start;
+  uint64_t end;
+  uint64_t offset;
+  std::string name;
+};
+
+static bool Attach(pid_t pid) {
+  if (ptrace(PTRACE_ATTACH, pid, 0, 0) == -1) {
+    return false;
+  }
+
+  // Allow at least 1 second to attach properly.
+  for (size_t i = 0; i < 1000; i++) {
+    siginfo_t si;
+    if (ptrace(PTRACE_GETSIGINFO, pid, 0, &si) == 0) {
+      return true;
+    }
+    usleep(1000);
+  }
+  printf("%d: Failed to stop.\n", pid);
+  return false;
+}
+
+bool SaveRegs(unwindstack::Regs* regs) {
+  std::unique_ptr<FILE, decltype(&fclose)> fp(fopen("regs.txt", "w+"), &fclose);
+  if (fp == nullptr) {
+    printf("Failed to create file regs.txt.\n");
+    return false;
+  }
+  regs->IterateRegisters([&fp](const char* name, uint64_t value) {
+    fprintf(fp.get(), "%s: %" PRIx64 "\n", name, value);
+  });
+
+  return true;
+}
+
+bool SaveStack(pid_t pid, uint64_t sp_start, uint64_t sp_end) {
+  std::unique_ptr<FILE, decltype(&fclose)> fp(fopen("stack.data", "w+"), &fclose);
+  if (fp == nullptr) {
+    printf("Failed to create stack.data.\n");
+    return false;
+  }
+
+  size_t bytes = fwrite(&sp_start, 1, sizeof(sp_start), fp.get());
+  if (bytes != sizeof(sp_start)) {
+    perror("Failed to write all data.");
+    return false;
+  }
+
+  std::vector<uint8_t> buffer(sp_end - sp_start);
+  auto process_memory = unwindstack::Memory::CreateProcessMemory(pid);
+  if (!process_memory->Read(sp_start, buffer.data(), buffer.size())) {
+    printf("Unable to read stack data.\n");
+    return false;
+  }
+
+  bytes = fwrite(buffer.data(), 1, buffer.size(), fp.get());
+  if (bytes != buffer.size()) {
+    printf("Failed to write all stack data: stack size %zu, written %zu\n", buffer.size(), bytes);
+    return 1;
+  }
+
+  return true;
+}
+
+bool CreateElfFromMemory(std::shared_ptr<unwindstack::Memory>& memory, map_info_t* info) {
+  std::string cur_name;
+  if (info->name.empty()) {
+    cur_name = android::base::StringPrintf("anonymous:%" PRIx64, info->start);
+  } else {
+    cur_name = basename(info->name.c_str());
+    cur_name = android::base::StringPrintf("%s:%" PRIx64, basename(info->name.c_str()), info->start);
+  }
+
+  std::unique_ptr<FILE, decltype(&fclose)> output(fopen(cur_name.c_str(), "w+"), &fclose);
+  if (output == nullptr) {
+    printf("Cannot create %s\n", cur_name.c_str());
+    return false;
+  }
+  std::vector<uint8_t> buffer(info->end - info->start);
+  // If this is a mapped in file, it might not be possible to read the entire
+  // map, so read all that is readable.
+  size_t bytes = memory->Read(info->start, buffer.data(), buffer.size());
+  if (bytes == 0) {
+    printf("Cannot read data from address %" PRIx64 " length %zu\n", info->start, buffer.size());
+    return false;
+  }
+  size_t bytes_written = fwrite(buffer.data(), 1, bytes, output.get());
+  if (bytes_written != bytes) {
+    printf("Failed to write all data to file: bytes read %zu, written %zu\n", bytes, bytes_written);
+    return false;
+  }
+
+  // Replace the name with the new name.
+  info->name = cur_name;
+
+  return true;
+}
+
+bool CopyElfFromFile(map_info_t* info) {
+  std::unique_ptr<FILE, decltype(&fclose)> fp(fopen(info->name.c_str(), "r"), &fclose);
+  if (fp == nullptr) {
+    return false;
+  }
+
+  std::string cur_name = basename(info->name.c_str());
+  std::unique_ptr<FILE, decltype(&fclose)> output(fopen(cur_name.c_str(), "w+"), &fclose);
+  if (output == nullptr) {
+    printf("Cannot create file %s\n", cur_name.c_str());
+    return false;
+  }
+  std::vector<uint8_t> buffer(10000);
+  size_t bytes;
+  while ((bytes = fread(buffer.data(), 1, buffer.size(), fp.get())) > 0) {
+    size_t bytes_written = fwrite(buffer.data(), 1, bytes, output.get());
+    if (bytes_written != bytes) {
+      printf("Bytes written doesn't match bytes read: read %zu, written %zu\n", bytes,
+             bytes_written);
+      return false;
+    }
+  }
+
+  // Replace the name with the new name.
+  info->name = cur_name;
+
+  return true;
+}
+
+int SaveData(pid_t pid) {
+  unwindstack::Regs* regs = unwindstack::Regs::RemoteGet(pid);
+  if (regs == nullptr) {
+    printf("Unable to get remote reg data.\n");
+    return 1;
+  }
+
+  unwindstack::RemoteMaps maps(pid);
+  if (!maps.Parse()) {
+    printf("Unable to parse maps.\n");
+    return 1;
+  }
+
+  // Save the current state of the registers.
+  if (!SaveRegs(regs)) {
+    return 1;
+  }
+
+  // Do an unwind so we know how much of the stack to save, and what
+  // elf files are involved.
+  uint64_t sp = regs->sp();
+  auto process_memory = unwindstack::Memory::CreateProcessMemory(pid);
+  unwindstack::JitDebug jit_debug(process_memory);
+  unwindstack::Unwinder unwinder(1024, &maps, regs, process_memory);
+  unwinder.SetJitDebug(&jit_debug, regs->Arch());
+  unwinder.Unwind();
+
+  std::unordered_map<uint64_t, map_info_t> maps_by_start;
+  uint64_t last_sp;
+  for (auto frame : unwinder.frames()) {
+    last_sp = frame.sp;
+    if (maps_by_start.count(frame.map_start) == 0) {
+      auto info = &maps_by_start[frame.map_start];
+      info->start = frame.map_start;
+      info->end = frame.map_end;
+      info->offset = frame.map_offset;
+      info->name = frame.map_name;
+      if (!CopyElfFromFile(info)) {
+        // Try to create the elf from memory, this will handle cases where
+        // the data only exists in memory such as vdso data on x86.
+        if (!CreateElfFromMemory(process_memory, info)) {
+          return 1;
+        }
+      }
+    }
+  }
+
+  for (size_t i = 0; i < unwinder.NumFrames(); i++) {
+    printf("%s\n", unwinder.FormatFrame(i).c_str());
+  }
+
+  if (!SaveStack(pid, sp, last_sp)) {
+    return 1;
+  }
+
+  std::vector<std::pair<uint64_t, map_info_t>> sorted_maps(maps_by_start.begin(),
+                                                           maps_by_start.end());
+  std::sort(sorted_maps.begin(), sorted_maps.end(),
+            [](auto& a, auto& b) { return a.first < b.first; });
+
+  std::unique_ptr<FILE, decltype(&fclose)> fp(fopen("maps.txt", "w+"), &fclose);
+  if (fp == nullptr) {
+    printf("Failed to create maps.txt.\n");
+    return false;
+  }
+
+  for (auto& element : sorted_maps) {
+    map_info_t& map = element.second;
+    fprintf(fp.get(), "%" PRIx64 "-%" PRIx64 " r-xp %" PRIx64 " 00:00 0", map.start, map.end,
+            map.offset);
+    if (!map.name.empty()) {
+      fprintf(fp.get(), "   %s", map.name.c_str());
+    }
+    fprintf(fp.get(), "\n");
+  }
+
+  return 0;
+}
+
+int main(int argc, char** argv) {
+  if (argc != 2) {
+    printf("Usage: unwind_for_offline <PID>\n");
+    return 1;
+  }
+
+  pid_t pid = atoi(argv[1]);
+  if (!Attach(pid)) {
+    printf("Failed to attach to pid %d: %s\n", pid, strerror(errno));
+    return 1;
+  }
+
+  int return_code = SaveData(pid);
+
+  ptrace(PTRACE_DETACH, pid, 0, 0);
+
+  return return_code;
+}
diff --git a/libunwindstack/tools/unwind_info.cpp b/libunwindstack/tools/unwind_info.cpp
index a00b2ee..7f2d11d 100644
--- a/libunwindstack/tools/unwind_info.cpp
+++ b/libunwindstack/tools/unwind_info.cpp
@@ -87,7 +87,7 @@
   for (const DwarfFde* fde : *section) {
     // Sometimes there are entries that have empty length, skip those since
     // they don't contain any interesting information.
-    if (fde->pc_start == fde->pc_end) {
+    if (fde == nullptr || fde->pc_start == fde->pc_end) {
       continue;
     }
     printf("\n  PC 0x%" PRIx64, fde->pc_start + load_bias);
diff --git a/libusbhost/include/usbhost/usbhost.h b/libusbhost/include/usbhost/usbhost.h
index 86cc873..7e62542 100644
--- a/libusbhost/include/usbhost/usbhost.h
+++ b/libusbhost/include/usbhost/usbhost.h
@@ -140,6 +140,23 @@
 /* Returns a pointer to device descriptor */
 const struct usb_device_descriptor* usb_device_get_device_descriptor(struct usb_device *device);
 
+/* Returns a USB descriptor string for the given string ID.
+ * Return value: < 0 on error.  0 on success.
+ * The string is returned in ucs2_out in USB-native UCS-2 encoding.
+ *
+ * parameters:
+ *  id - the string descriptor index.
+ *  timeout - in milliseconds (see Documentation/driver-api/usb/usb.rst)
+ *  ucs2_out - Must point to null on call.
+ *             Will be filled in with a buffer on success.
+ *             If this is non-null on return, it must be free()d.
+ *  response_size - size, in bytes, of ucs-2 string in ucs2_out.
+ *                  The size isn't guaranteed to include null termination.
+ * Call free() to free the result when you are done with it.
+ */
+int usb_device_get_string_ucs2(struct usb_device* device, int id, int timeout, void** ucs2_out,
+                               size_t* response_size);
+
 /* Returns the length in bytes read into the raw descriptors array */
 size_t usb_device_get_descriptors_length(const struct usb_device* device);
 
@@ -149,6 +166,7 @@
 /* Returns a USB descriptor string for the given string ID.
  * Used to implement usb_device_get_manufacturer_name,
  * usb_device_get_product_name and usb_device_get_serial.
+ * Returns ascii - non ascii characters will be replaced with '?'.
  * Call free() to free the result when you are done with it.
  */
 char* usb_device_get_string(struct usb_device *device, int id, int timeout);
diff --git a/libusbhost/usbhost.c b/libusbhost/usbhost.c
index b8c5ca1..07d60e9 100644
--- a/libusbhost/usbhost.c
+++ b/libusbhost/usbhost.c
@@ -475,17 +475,30 @@
     return device->desc;
 }
 
-char* usb_device_get_string(struct usb_device *device, int id, int timeout)
-{
-    char string[256];
-    __u16 buffer[MAX_STRING_DESCRIPTOR_LENGTH / sizeof(__u16)];
+/* Returns a USB descriptor string for the given string ID.
+ * Return value: < 0 on error.  0 on success.
+ * The string is returned in ucs2_out in USB-native UCS-2 encoding.
+ *
+ * parameters:
+ *  id - the string descriptor index.
+ *  timeout - in milliseconds (see Documentation/driver-api/usb/usb.rst)
+ *  ucs2_out - Must point to null on call.
+ *             Will be filled in with a buffer on success.
+ *             If this is non-null on return, it must be free()d.
+ *  response_size - size, in bytes, of ucs-2 string in ucs2_out.
+ *                  The size isn't guaranteed to include null termination.
+ * Call free() to free the result when you are done with it.
+ */
+int usb_device_get_string_ucs2(struct usb_device* device, int id, int timeout, void** ucs2_out,
+                               size_t* response_size) {
     __u16 languages[MAX_STRING_DESCRIPTOR_LENGTH / sizeof(__u16)];
-    int i, result;
+    char response[MAX_STRING_DESCRIPTOR_LENGTH];
+    int result;
     int languageCount = 0;
 
-    if (id == 0) return NULL;
+    if (id == 0) return -1;
+    if (*ucs2_out != NULL) return -1;
 
-    string[0] = 0;
     memset(languages, 0, sizeof(languages));
 
     // read list of supported languages
@@ -496,25 +509,54 @@
     if (result > 0)
         languageCount = (result - 2) / 2;
 
-    for (i = 1; i <= languageCount; i++) {
-        memset(buffer, 0, sizeof(buffer));
+    for (int i = 1; i <= languageCount; i++) {
+        memset(response, 0, sizeof(response));
 
-        result = usb_device_control_transfer(device,
-                USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE, USB_REQ_GET_DESCRIPTOR,
-                (USB_DT_STRING << 8) | id, languages[i], buffer, sizeof(buffer),
-                timeout);
-        if (result > 0) {
-            int i;
-            // skip first word, and copy the rest to the string, changing shorts to bytes.
-            result /= 2;
-            for (i = 1; i < result; i++)
-                string[i - 1] = buffer[i];
-            string[i - 1] = 0;
-            return strdup(string);
+        result = usb_device_control_transfer(
+            device, USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE, USB_REQ_GET_DESCRIPTOR,
+            (USB_DT_STRING << 8) | id, languages[i], response, sizeof(response), timeout);
+        if (result >= 2) {  // string contents begin at offset 2.
+            int descriptor_len = result - 2;
+            char* out = malloc(descriptor_len + 3);
+            if (out == NULL) {
+                return -1;
+            }
+            memcpy(out, response + 2, descriptor_len);
+            // trail with three additional NULLs, so that there's guaranteed
+            // to be a UCS-2 NULL character beyond whatever USB returned.
+            // The returned string length is still just what USB returned.
+            memset(out + descriptor_len, '\0', 3);
+            *ucs2_out = (void*)out;
+            *response_size = descriptor_len;
+            return 0;
         }
     }
+    return -1;
+}
 
-    return NULL;
+/* Warning: previously this blindly returned the lower 8 bits of
+ * every UCS-2 character in a USB descriptor.  Now it will replace
+ * values > 127 with ascii '?'.
+ */
+char* usb_device_get_string(struct usb_device* device, int id, int timeout) {
+    char* ascii_string = NULL;
+    size_t raw_string_len = 0;
+    size_t i;
+    if (usb_device_get_string_ucs2(device, id, timeout, (void**)&ascii_string, &raw_string_len) < 0)
+        return NULL;
+    if (ascii_string == NULL) return NULL;
+    for (i = 0; i < raw_string_len / 2; ++i) {
+        // wire format for USB is always little-endian.
+        char lower = ascii_string[2 * i];
+        char upper = ascii_string[2 * i + 1];
+        if (upper || (lower & 0x80)) {
+            ascii_string[i] = '?';
+        } else {
+            ascii_string[i] = lower;
+        }
+    }
+    ascii_string[i] = '\0';
+    return ascii_string;
 }
 
 char* usb_device_get_manufacturer_name(struct usb_device *device, int timeout)
diff --git a/libutils/include/utils/Atomic.h b/libutils/include/utils/Atomic.h
index 7eb476c..0f592fe 100644
--- a/libutils/include/utils/Atomic.h
+++ b/libutils/include/utils/Atomic.h
@@ -17,6 +17,8 @@
 #ifndef ANDROID_UTILS_ATOMIC_H
 #define ANDROID_UTILS_ATOMIC_H
 
+// DO NOT USE: Please instead use std::atomic
+
 #include <cutils/atomic.h>
 
 #endif // ANDROID_UTILS_ATOMIC_H
diff --git a/libutils/include/utils/BitSet.h b/libutils/include/utils/BitSet.h
index 8c61293..8abfb1a 100644
--- a/libutils/include/utils/BitSet.h
+++ b/libutils/include/utils/BitSet.h
@@ -22,6 +22,8 @@
 
 /*
  * Contains some bit manipulation helpers.
+ *
+ * DO NOT USE: std::bitset<32> or std::bitset<64> preferred
  */
 
 namespace android {
diff --git a/libutils/include/utils/Condition.h b/libutils/include/utils/Condition.h
index 3019a21..9bf82eb 100644
--- a/libutils/include/utils/Condition.h
+++ b/libutils/include/utils/Condition.h
@@ -34,6 +34,8 @@
 namespace android {
 // ---------------------------------------------------------------------------
 
+// DO NOT USE: please use std::condition_variable instead.
+
 /*
  * Condition variable class.  The implementation is system-dependent.
  *
diff --git a/libutils/include/utils/Debug.h b/libutils/include/utils/Debug.h
index 08893bd..4cbb462 100644
--- a/libutils/include/utils/Debug.h
+++ b/libutils/include/utils/Debug.h
@@ -29,20 +29,12 @@
 #define COMPILE_TIME_ASSERT(_exp) \
     template class CompileTimeAssert< (_exp) >;
 #endif
+
+// DO NOT USE: Please use static_assert instead
 #define COMPILE_TIME_ASSERT_FUNCTION_SCOPE(_exp) \
     CompileTimeAssert<( _exp )>();
 
 // ---------------------------------------------------------------------------
-
-#ifdef __cplusplus
-template<bool C, typename LSH, typename RHS> struct CompileTimeIfElse;
-template<typename LHS, typename RHS> 
-struct CompileTimeIfElse<true,  LHS, RHS> { typedef LHS TYPE; };
-template<typename LHS, typename RHS> 
-struct CompileTimeIfElse<false, LHS, RHS> { typedef RHS TYPE; };
-#endif
-
-// ---------------------------------------------------------------------------
 }; // namespace android
 
 #endif // ANDROID_UTILS_DEBUG_H
diff --git a/libutils/include/utils/Flattenable.h b/libutils/include/utils/Flattenable.h
index 070c710..675e211 100644
--- a/libutils/include/utils/Flattenable.h
+++ b/libutils/include/utils/Flattenable.h
@@ -33,13 +33,13 @@
 public:
     template<size_t N>
     static size_t align(size_t size) {
-        COMPILE_TIME_ASSERT_FUNCTION_SCOPE( !(N & (N-1)) );
+        static_assert(!(N & (N - 1)), "Can only align to a power of 2.");
         return (size + (N-1)) & ~(N-1);
     }
 
     template<size_t N>
     static size_t align(void const*& buffer) {
-        COMPILE_TIME_ASSERT_FUNCTION_SCOPE( !(N & (N-1)) );
+        static_assert(!(N & (N - 1)), "Can only align to a power of 2.");
         uintptr_t b = uintptr_t(buffer);
         buffer = reinterpret_cast<void*>((uintptr_t(buffer) + (N-1)) & ~(N-1));
         return size_t(uintptr_t(buffer) - b);
diff --git a/libutils/include/utils/Functor.h b/libutils/include/utils/Functor.h
index 09ea614..3182a9c 100644
--- a/libutils/include/utils/Functor.h
+++ b/libutils/include/utils/Functor.h
@@ -21,6 +21,10 @@
 
 namespace  android {
 
+// DO NOT USE: please use
+// - C++ lambda
+// - class with well-defined and specific functionality and semantics
+
 class Functor {
 public:
     Functor() {}
diff --git a/libutils/include/utils/KeyedVector.h b/libutils/include/utils/KeyedVector.h
index f93ad6e..03bfe27 100644
--- a/libutils/include/utils/KeyedVector.h
+++ b/libutils/include/utils/KeyedVector.h
@@ -30,6 +30,8 @@
 
 namespace android {
 
+// DO NOT USE: please use std::map
+
 template <typename KEY, typename VALUE>
 class KeyedVector
 {
diff --git a/libutils/include/utils/List.h b/libutils/include/utils/List.h
index 403cd7f..daca016 100644
--- a/libutils/include/utils/List.h
+++ b/libutils/include/utils/List.h
@@ -37,6 +37,8 @@
  *
  * Objects added to the list are copied using the assignment operator,
  * so this must be defined.
+ *
+ * DO NOT USE: please use std::list<T>
  */
 template<typename T> 
 class List 
diff --git a/libutils/include/utils/Singleton.h b/libutils/include/utils/Singleton.h
index 9afedd4..bc47a5c 100644
--- a/libutils/include/utils/Singleton.h
+++ b/libutils/include/utils/Singleton.h
@@ -39,6 +39,11 @@
 #pragma clang diagnostic ignored "-Wundefined-var-template"
 #endif
 
+// DO NOT USE: Please use scoped static initialization. For instance:
+//     MyClass& getInstance() {
+//         static MyClass gInstance(...);
+//         return gInstance;
+//     }
 template <typename TYPE>
 class ANDROID_API Singleton
 {
diff --git a/libutils/include/utils/SortedVector.h b/libutils/include/utils/SortedVector.h
index 5b2a232..47c1376 100644
--- a/libutils/include/utils/SortedVector.h
+++ b/libutils/include/utils/SortedVector.h
@@ -30,6 +30,8 @@
 
 namespace android {
 
+// DO NOT USE: please use std::set
+
 template <class TYPE>
 class SortedVector : private SortedVectorImpl
 {
diff --git a/libutils/include/utils/String16.h b/libutils/include/utils/String16.h
index 15ed19f..5f0ce06 100644
--- a/libutils/include/utils/String16.h
+++ b/libutils/include/utils/String16.h
@@ -37,6 +37,8 @@
 
 class String8;
 
+// DO NOT USE: please use std::u16string
+
 //! This is a string holding UTF-16 characters.
 class String16
 {
diff --git a/libutils/include/utils/String8.h b/libutils/include/utils/String8.h
index 0225c6b..94ac32f 100644
--- a/libutils/include/utils/String8.h
+++ b/libutils/include/utils/String8.h
@@ -32,6 +32,8 @@
 
 class String16;
 
+// DO NOT USE: please use std::string
+
 //! This is a string holding UTF-8 characters. Does not allow the value more
 // than 0x10FFFF, which is not valid unicode codepoint.
 class String8
diff --git a/libutils/include/utils/Thread.h b/libutils/include/utils/Thread.h
index a261fc8..598298d 100644
--- a/libutils/include/utils/Thread.h
+++ b/libutils/include/utils/Thread.h
@@ -36,6 +36,8 @@
 namespace android {
 // ---------------------------------------------------------------------------
 
+// DO NOT USE: please use std::thread
+
 class Thread : virtual public RefBase
 {
 public:
diff --git a/libutils/include/utils/Vector.h b/libutils/include/utils/Vector.h
index 7e00123..a1a0234 100644
--- a/libutils/include/utils/Vector.h
+++ b/libutils/include/utils/Vector.h
@@ -49,6 +49,8 @@
  * The main templated vector class ensuring type safety
  * while making use of VectorImpl.
  * This is the class users want to use.
+ *
+ * DO NOT USE: please use std::vector
  */
 
 template <class TYPE>
diff --git a/libutils/include/utils/misc.h b/libutils/include/utils/misc.h
index 6cccec3..af5ea02 100644
--- a/libutils/include/utils/misc.h
+++ b/libutils/include/utils/misc.h
@@ -22,7 +22,9 @@
 
 #include <utils/Endian.h>
 
-/* get #of elements in a static array */
+/* get #of elements in a static array
+ * DO NOT USE: please use std::vector/std::array instead
+ */
 #ifndef NELEM
 # define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
 #endif
diff --git a/libziparchive/zip_archive.cc b/libziparchive/zip_archive.cc
index 5ccbcc2..f9f8c73 100644
--- a/libziparchive/zip_archive.cc
+++ b/libziparchive/zip_archive.cc
@@ -783,12 +783,12 @@
   // block device).
   //
   // Returns a valid FileWriter on success, |nullptr| if an error occurred.
-  static std::unique_ptr<FileWriter> Create(int fd, const ZipEntry* entry) {
+  static FileWriter Create(int fd, const ZipEntry* entry) {
     const uint32_t declared_length = entry->uncompressed_length;
     const off64_t current_offset = lseek64(fd, 0, SEEK_CUR);
     if (current_offset == -1) {
       ALOGW("Zip: unable to seek to current location on fd %d: %s", fd, strerror(errno));
-      return nullptr;
+      return FileWriter{};
     }
 
     int result = 0;
@@ -808,7 +808,7 @@
         ALOGW("Zip: unable to allocate %" PRId64 " bytes at offset %" PRId64 ": %s",
               static_cast<int64_t>(declared_length), static_cast<int64_t>(current_offset),
               strerror(errno));
-        return std::unique_ptr<FileWriter>(nullptr);
+        return FileWriter{};
       }
     }
 #endif  // __linux__
@@ -816,7 +816,7 @@
     struct stat sb;
     if (fstat(fd, &sb) == -1) {
       ALOGW("Zip: unable to fstat file: %s", strerror(errno));
-      return std::unique_ptr<FileWriter>(nullptr);
+      return FileWriter{};
     }
 
     // Block device doesn't support ftruncate(2).
@@ -825,13 +825,22 @@
       if (result == -1) {
         ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
               static_cast<int64_t>(declared_length + current_offset), strerror(errno));
-        return std::unique_ptr<FileWriter>(nullptr);
+        return FileWriter{};
       }
     }
 
-    return std::unique_ptr<FileWriter>(new FileWriter(fd, declared_length));
+    return FileWriter(fd, declared_length);
   }
 
+  FileWriter(FileWriter&& other)
+      : fd_(other.fd_),
+        declared_length_(other.declared_length_),
+        total_bytes_written_(other.total_bytes_written_) {
+    other.fd_ = -1;
+  }
+
+  bool IsValid() const { return fd_ != -1; }
+
   virtual bool Append(uint8_t* buf, size_t buf_size) override {
     if (total_bytes_written_ + buf_size > declared_length_) {
       ALOGW("Zip: Unexpected size " ZD " (declared) vs " ZD " (actual)", declared_length_,
@@ -850,10 +859,10 @@
   }
 
  private:
-  FileWriter(const int fd, const size_t declared_length)
+  explicit FileWriter(const int fd = -1, const size_t declared_length = 0)
       : Writer(), fd_(fd), declared_length_(declared_length), total_bytes_written_(0) {}
 
-  const int fd_;
+  int fd_;
   const size_t declared_length_;
   size_t total_bytes_written_;
 };
@@ -1066,17 +1075,17 @@
 }
 
 int32_t ExtractToMemory(ZipArchiveHandle handle, ZipEntry* entry, uint8_t* begin, uint32_t size) {
-  std::unique_ptr<zip_archive::Writer> writer(new MemoryWriter(begin, size));
-  return ExtractToWriter(handle, entry, writer.get());
+  MemoryWriter writer(begin, size);
+  return ExtractToWriter(handle, entry, &writer);
 }
 
 int32_t ExtractEntryToFile(ZipArchiveHandle handle, ZipEntry* entry, int fd) {
-  std::unique_ptr<zip_archive::Writer> writer(FileWriter::Create(fd, entry));
-  if (writer.get() == nullptr) {
+  auto writer = FileWriter::Create(fd, entry);
+  if (!writer.IsValid()) {
     return kIoError;
   }
 
-  return ExtractToWriter(handle, entry, writer.get());
+  return ExtractToWriter(handle, entry, &writer);
 }
 
 const char* ErrorCodeString(int32_t error_code) {
diff --git a/libziparchive/zip_archive_test.cc b/libziparchive/zip_archive_test.cc
index 374310b..ff73eb2 100644
--- a/libziparchive/zip_archive_test.cc
+++ b/libziparchive/zip_archive_test.cc
@@ -64,11 +64,6 @@
   return OpenArchive(abs_path.c_str(), handle);
 }
 
-static void AssertNameEquals(const std::string& name_str, const ZipString& name) {
-  ASSERT_EQ(name_str.size(), name.name_length);
-  ASSERT_EQ(0, memcmp(name_str.c_str(), name.name, name.name_length));
-}
-
 static void SetZipString(ZipString* zip_str, const std::string& str) {
   zip_str->name = reinterpret_cast<const uint8_t*>(str.c_str());
   zip_str->name_length = str.size();
@@ -117,132 +112,60 @@
   close(fd);
 }
 
-TEST(ziparchive, Iteration) {
+static void AssertIterationOrder(const ZipString* prefix, const ZipString* suffix,
+                                 const std::vector<std::string>& expected_names_sorted) {
   ZipArchiveHandle handle;
   ASSERT_EQ(0, OpenArchiveWrapper(kValidZip, &handle));
 
   void* iteration_cookie;
-  ASSERT_EQ(0, StartIteration(handle, &iteration_cookie, nullptr, nullptr));
+  ASSERT_EQ(0, StartIteration(handle, &iteration_cookie, prefix, suffix));
 
   ZipEntry data;
+  std::vector<std::string> names;
+
   ZipString name;
-
-  // b/c.txt
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("b/c.txt", name);
-
-  // b/d.txt
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("b/d.txt", name);
-
-  // a.txt
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("a.txt", name);
-
-  // b.txt
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("b.txt", name);
-
-  // b/
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("b/", name);
+  for (size_t i = 0; i < expected_names_sorted.size(); ++i) {
+    ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
+    names.push_back(std::string(reinterpret_cast<const char*>(name.name), name.name_length));
+  }
 
   // End of iteration.
   ASSERT_EQ(-1, Next(iteration_cookie, &data, &name));
-
   CloseArchive(handle);
+
+  // Assert that the names are as expected.
+  std::sort(names.begin(), names.end());
+  ASSERT_EQ(expected_names_sorted, names);
+}
+
+TEST(ziparchive, Iteration) {
+  static const std::vector<std::string> kExpectedMatchesSorted = {"a.txt", "b.txt", "b/", "b/c.txt",
+                                                                  "b/d.txt"};
+
+  AssertIterationOrder(nullptr, nullptr, kExpectedMatchesSorted);
 }
 
 TEST(ziparchive, IterationWithPrefix) {
-  ZipArchiveHandle handle;
-  ASSERT_EQ(0, OpenArchiveWrapper(kValidZip, &handle));
-
-  void* iteration_cookie;
   ZipString prefix("b/");
-  ASSERT_EQ(0, StartIteration(handle, &iteration_cookie, &prefix, nullptr));
+  static const std::vector<std::string> kExpectedMatchesSorted = {"b/", "b/c.txt", "b/d.txt"};
 
-  ZipEntry data;
-  ZipString name;
-
-  // b/c.txt
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("b/c.txt", name);
-
-  // b/d.txt
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("b/d.txt", name);
-
-  // b/
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("b/", name);
-
-  // End of iteration.
-  ASSERT_EQ(-1, Next(iteration_cookie, &data, &name));
-
-  CloseArchive(handle);
+  AssertIterationOrder(&prefix, nullptr, kExpectedMatchesSorted);
 }
 
 TEST(ziparchive, IterationWithSuffix) {
-  ZipArchiveHandle handle;
-  ASSERT_EQ(0, OpenArchiveWrapper(kValidZip, &handle));
-
-  void* iteration_cookie;
   ZipString suffix(".txt");
-  ASSERT_EQ(0, StartIteration(handle, &iteration_cookie, nullptr, &suffix));
+  static const std::vector<std::string> kExpectedMatchesSorted = {"a.txt", "b.txt", "b/c.txt",
+                                                                  "b/d.txt"};
 
-  ZipEntry data;
-  ZipString name;
-
-  // b/c.txt
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("b/c.txt", name);
-
-  // b/d.txt
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("b/d.txt", name);
-
-  // a.txt
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("a.txt", name);
-
-  // b.txt
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("b.txt", name);
-
-  // End of iteration.
-  ASSERT_EQ(-1, Next(iteration_cookie, &data, &name));
-
-  CloseArchive(handle);
+  AssertIterationOrder(nullptr, &suffix, kExpectedMatchesSorted);
 }
 
 TEST(ziparchive, IterationWithPrefixAndSuffix) {
-  ZipArchiveHandle handle;
-  ASSERT_EQ(0, OpenArchiveWrapper(kValidZip, &handle));
-
-  void* iteration_cookie;
   ZipString prefix("b");
   ZipString suffix(".txt");
-  ASSERT_EQ(0, StartIteration(handle, &iteration_cookie, &prefix, &suffix));
+  static const std::vector<std::string> kExpectedMatchesSorted = {"b.txt", "b/c.txt", "b/d.txt"};
 
-  ZipEntry data;
-  ZipString name;
-
-  // b/c.txt
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("b/c.txt", name);
-
-  // b/d.txt
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("b/d.txt", name);
-
-  // b.txt
-  ASSERT_EQ(0, Next(iteration_cookie, &data, &name));
-  AssertNameEquals("b.txt", name);
-
-  // End of iteration.
-  ASSERT_EQ(-1, Next(iteration_cookie, &data, &name));
-
-  CloseArchive(handle);
+  AssertIterationOrder(&prefix, &suffix, kExpectedMatchesSorted);
 }
 
 TEST(ziparchive, IterationWithBadPrefixAndSuffix) {
@@ -664,10 +587,11 @@
   // an entry whose name is "name" and whose size is 12 (contents =
   // "abdcdefghijk").
   ZipEntry entry;
-  ZipString empty_name;
-  SetZipString(&empty_name, "name");
+  ZipString name;
+  std::string name_str = "name";
+  SetZipString(&name, name_str);
 
-  ASSERT_EQ(0, FindEntry(handle, empty_name, &entry));
+  ASSERT_EQ(0, FindEntry(handle, name, &entry));
   ASSERT_EQ(static_cast<uint32_t>(12), entry.uncompressed_length);
 
   entry_out->resize(12);
@@ -687,7 +611,7 @@
   ASSERT_EQ('k', entry[11]);
 }
 
-TEST(ziparchive, InvalidDataDescriptors) {
+TEST(ziparchive, InvalidDataDescriptors_csize) {
   std::vector<uint8_t> invalid_csize = kDataDescriptorZipFile;
   invalid_csize[kCSizeOffset] = 0xfe;
 
@@ -696,13 +620,15 @@
   ExtractEntryToMemory(invalid_csize, &entry, &error_code);
 
   ASSERT_EQ(kInconsistentInformation, error_code);
+}
 
+TEST(ziparchive, InvalidDataDescriptors_size) {
   std::vector<uint8_t> invalid_size = kDataDescriptorZipFile;
-  invalid_csize[kSizeOffset] = 0xfe;
+  invalid_size[kSizeOffset] = 0xfe;
 
-  error_code = 0;
-  entry.clear();
-  ExtractEntryToMemory(invalid_csize, &entry, &error_code);
+  std::vector<uint8_t> entry;
+  int32_t error_code = 0;
+  ExtractEntryToMemory(invalid_size, &entry, &error_code);
 
   ASSERT_EQ(kInconsistentInformation, error_code);
 }
diff --git a/lmkd/Android.bp b/lmkd/Android.bp
index 3f8a503..2731596 100644
--- a/lmkd/Android.bp
+++ b/lmkd/Android.bp
@@ -10,4 +10,12 @@
     cflags: ["-Werror"],
 
     init_rc: ["lmkd.rc"],
+
+    product_variables: {
+        debuggable: {
+            cflags: [
+                "-DLMKD_TRACE_KILLS"
+            ],
+        },
+    },
 }
diff --git a/lmkd/lmkd.c b/lmkd/lmkd.c
index 5cfa2c8..c78461c 100644
--- a/lmkd/lmkd.c
+++ b/lmkd/lmkd.c
@@ -37,6 +37,25 @@
 #include <log/log.h>
 #include <processgroup/processgroup.h>
 
+/*
+ * Define LMKD_TRACE_KILLS to record lmkd kills in kernel traces
+ * to profile and correlate with OOM kills
+ */
+#ifdef LMKD_TRACE_KILLS
+
+#define ATRACE_TAG ATRACE_TAG_ALWAYS
+#include <cutils/trace.h>
+
+#define TRACE_KILL_START(pid) ATRACE_INT(__FUNCTION__, pid);
+#define TRACE_KILL_END()      ATRACE_INT(__FUNCTION__, 0);
+
+#else /* LMKD_TRACE_KILLS */
+
+#define TRACE_KILL_START(pid)
+#define TRACE_KILL_END()
+
+#endif /* LMKD_TRACE_KILLS */
+
 #ifndef __unused
 #define __unused __attribute__((__unused__))
 #endif
@@ -44,8 +63,6 @@
 #define MEMCG_SYSFS_PATH "/dev/memcg/"
 #define MEMCG_MEMORY_USAGE "/dev/memcg/memory.usage_in_bytes"
 #define MEMCG_MEMORYSW_USAGE "/dev/memcg/memory.memsw.usage_in_bytes"
-#define MEMPRESSURE_WATCH_MEDIUM_LEVEL "medium"
-#define MEMPRESSURE_WATCH_CRITICAL_LEVEL "critical"
 #define ZONEINFO_PATH "/proc/zoneinfo"
 #define LINE_MAX 128
 
@@ -72,26 +89,36 @@
 static int use_inkernel_interface = 1;
 static bool has_inkernel_module;
 
-/* memory pressure level medium event */
-static int mpevfd[2];
-#define CRITICAL_INDEX 1
-#define MEDIUM_INDEX 0
+/* memory pressure levels */
+enum vmpressure_level {
+    VMPRESS_LEVEL_LOW = 0,
+    VMPRESS_LEVEL_MEDIUM,
+    VMPRESS_LEVEL_CRITICAL,
+    VMPRESS_LEVEL_COUNT
+};
 
-static int medium_oomadj;
-static int critical_oomadj;
+static const char *level_name[] = {
+    "low",
+    "medium",
+    "critical"
+};
+
+static int level_oomadj[VMPRESS_LEVEL_COUNT];
+static int mpevfd[VMPRESS_LEVEL_COUNT];
 static bool debug_process_killing;
 static bool enable_pressure_upgrade;
 static int64_t upgrade_pressure;
 static int64_t downgrade_pressure;
 static bool is_go_device;
+static bool kill_heaviest_task;
 
 /* control socket listen and data */
 static int ctrl_lfd;
 static int ctrl_dfd = -1;
 static int ctrl_dfd_reopened; /* did we reopen ctrl conn on this loop? */
 
-/* 2 memory pressure levels, 1 ctrl listen socket, 1 ctrl data socket */
-#define MAX_EPOLL_EVENTS 4
+/* 3 memory pressure levels, 1 ctrl listen socket, 1 ctrl data socket */
+#define MAX_EPOLL_EVENTS 5
 static int epollfd;
 static int maxevents;
 
@@ -226,7 +253,7 @@
     return 0;
 }
 
-static void writefilestring(char *path, char *s) {
+static void writefilestring(const char *path, char *s) {
     int fd = open(path, O_WRONLY | O_CLOEXEC);
     int len = strlen(s);
     int ret;
@@ -586,8 +613,32 @@
     return (struct proc *)adjslot_tail(&procadjslot_list[ADJTOSLOT(oomadj)]);
 }
 
+static struct proc *proc_get_heaviest(int oomadj) {
+    struct adjslot_list *head = &procadjslot_list[ADJTOSLOT(oomadj)];
+    struct adjslot_list *curr = head->next;
+    struct proc *maxprocp = NULL;
+    int maxsize = 0;
+    while (curr != head) {
+        int pid = ((struct proc *)curr)->pid;
+        int tasksize = proc_get_size(pid);
+        if (tasksize <= 0) {
+            struct adjslot_list *next = curr->next;
+            pid_remove(pid);
+            curr = next;
+        } else {
+            if (tasksize > maxsize) {
+                maxsize = tasksize;
+                maxprocp = (struct proc *)curr;
+            }
+            curr = curr->next;
+        }
+    }
+    return maxprocp;
+}
+
 /* Kill one process specified by procp.  Returns the size of the process killed */
-static int kill_one_process(struct proc* procp, int min_score_adj, bool is_critical) {
+static int kill_one_process(struct proc* procp, int min_score_adj,
+                            enum vmpressure_level level) {
     int pid = procp->pid;
     uid_t uid = procp->uid;
     char *taskname;
@@ -606,14 +657,18 @@
         return -1;
     }
 
+    TRACE_KILL_START(pid);
+
+    r = kill(pid, SIGKILL);
     ALOGI(
         "Killing '%s' (%d), uid %d, adj %d\n"
         "   to free %ldkB because system is under %s memory pressure oom_adj %d\n",
-        taskname, pid, uid, procp->oomadj, tasksize * page_k, is_critical ? "critical" : "medium",
-        min_score_adj);
-    r = kill(pid, SIGKILL);
+        taskname, pid, uid, procp->oomadj, tasksize * page_k,
+        level_name[level], min_score_adj);
     pid_remove(pid);
 
+    TRACE_KILL_END();
+
     if (r) {
         ALOGE("kill(%d): errno=%d", procp->pid, errno);
         return -1;
@@ -626,19 +681,22 @@
  * Find a process to kill based on the current (possibly estimated) free memory
  * and cached memory sizes.  Returns the size of the killed processes.
  */
-static int find_and_kill_process(bool is_critical) {
+static int find_and_kill_process(enum vmpressure_level level) {
     int i;
     int killed_size = 0;
-    int min_score_adj = is_critical ? critical_oomadj : medium_oomadj;
+    int min_score_adj = level_oomadj[level];
 
     for (i = OOM_SCORE_ADJ_MAX; i >= min_score_adj; i--) {
         struct proc *procp;
 
 retry:
-        procp = proc_adj_lru(i);
+        if (kill_heaviest_task)
+            procp = proc_get_heaviest(i);
+        else
+            procp = proc_adj_lru(i);
 
         if (procp) {
-            killed_size = kill_one_process(procp, min_score_adj, is_critical);
+            killed_size = kill_one_process(procp, min_score_adj, level);
             if (killed_size < 0) {
                 goto retry;
             } else {
@@ -674,14 +732,23 @@
     return mem_usage;
 }
 
-static void mp_event_common(bool is_critical) {
+enum vmpressure_level upgrade_level(enum vmpressure_level level) {
+    return (enum vmpressure_level)((level < VMPRESS_LEVEL_CRITICAL) ?
+        level + 1 : level);
+}
+
+enum vmpressure_level downgrade_level(enum vmpressure_level level) {
+    return (enum vmpressure_level)((level > VMPRESS_LEVEL_LOW) ?
+        level - 1 : level);
+}
+
+static void mp_event_common(enum vmpressure_level level) {
     int ret;
     unsigned long long evcount;
-    int index = is_critical ? CRITICAL_INDEX : MEDIUM_INDEX;
     int64_t mem_usage, memsw_usage;
     int64_t mem_pressure;
 
-    ret = read(mpevfd[index], &evcount, sizeof(evcount));
+    ret = read(mpevfd[level], &evcount, sizeof(evcount));
     if (ret < 0)
         ALOGE("Error reading memory pressure event fd; errno=%d",
               errno);
@@ -689,18 +756,19 @@
     mem_usage = get_memory_usage(MEMCG_MEMORY_USAGE);
     memsw_usage = get_memory_usage(MEMCG_MEMORYSW_USAGE);
     if (memsw_usage < 0 || mem_usage < 0) {
-        find_and_kill_process(is_critical);
-        return;
+        goto do_kill;
     }
 
     // Calculate percent for swappinness.
     mem_pressure = (mem_usage * 100) / memsw_usage;
 
-    if (enable_pressure_upgrade && !is_critical) {
+    if (enable_pressure_upgrade && level != VMPRESS_LEVEL_CRITICAL) {
         // We are swapping too much.
         if (mem_pressure < upgrade_pressure) {
-            ALOGI("Event upgraded to critical.");
-            is_critical = true;
+            level = upgrade_level(level);
+            if (debug_process_killing) {
+                ALOGI("Event upgraded to %s", level_name[level]);
+            }
         }
     }
 
@@ -708,41 +776,51 @@
     // kill any process, since enough memory is available.
     if (mem_pressure > downgrade_pressure) {
         if (debug_process_killing) {
-            ALOGI("Ignore %s memory pressure", is_critical ? "critical" : "medium");
+            ALOGI("Ignore %s memory pressure", level_name[level]);
         }
         return;
-    } else if (is_critical && mem_pressure > upgrade_pressure) {
+    } else if (level == VMPRESS_LEVEL_CRITICAL &&
+               mem_pressure > upgrade_pressure) {
         if (debug_process_killing) {
             ALOGI("Downgrade critical memory pressure");
         }
-        // Downgrade event to medium, since enough memory available.
-        is_critical = false;
+        // Downgrade event, since enough memory available.
+        level = downgrade_level(level);
     }
 
-    if (find_and_kill_process(is_critical) == 0) {
+do_kill:
+    if (find_and_kill_process(level) == 0) {
         if (debug_process_killing) {
             ALOGI("Nothing to kill");
         }
     }
 }
 
-static void mp_event(uint32_t events __unused) {
-    mp_event_common(false);
+static void mp_event_low(uint32_t events __unused) {
+    mp_event_common(VMPRESS_LEVEL_LOW);
+}
+
+static void mp_event_medium(uint32_t events __unused) {
+    mp_event_common(VMPRESS_LEVEL_MEDIUM);
 }
 
 static void mp_event_critical(uint32_t events __unused) {
-    mp_event_common(true);
+    mp_event_common(VMPRESS_LEVEL_CRITICAL);
 }
 
-static int init_mp_common(char *levelstr, void *event_handler, bool is_critical)
-{
+static bool init_mp_common(void *event_handler, enum vmpressure_level level) {
     int mpfd;
     int evfd;
     int evctlfd;
     char buf[256];
     struct epoll_event epev;
     int ret;
-    int mpevfd_index = is_critical ? CRITICAL_INDEX : MEDIUM_INDEX;
+    const char *levelstr = level_name[level];
+
+    if (level_oomadj[level] > OOM_SCORE_ADJ_MAX) {
+        ALOGI("%s pressure events are disabled", levelstr);
+        return true;
+    }
 
     mpfd = open(MEMCG_SYSFS_PATH "memory.pressure_level", O_RDONLY | O_CLOEXEC);
     if (mpfd < 0) {
@@ -783,8 +861,8 @@
         goto err;
     }
     maxevents++;
-    mpevfd[mpevfd_index] = evfd;
-    return 0;
+    mpevfd[level] = evfd;
+    return true;
 
 err:
     close(evfd);
@@ -793,17 +871,7 @@
 err_open_evctlfd:
     close(mpfd);
 err_open_mpfd:
-    return -1;
-}
-
-static int init_mp_medium()
-{
-    return init_mp_common(MEMPRESSURE_WATCH_MEDIUM_LEVEL, (void *)&mp_event, false);
-}
-
-static int init_mp_critical()
-{
-    return init_mp_common(MEMPRESSURE_WATCH_CRITICAL_LEVEL, (void *)&mp_event_critical, true);
+    return false;
 }
 
 static int init(void) {
@@ -848,10 +916,13 @@
     if (use_inkernel_interface) {
         ALOGI("Using in-kernel low memory killer interface");
     } else {
-        ret = init_mp_medium();
-        ret |= init_mp_critical();
-        if (ret)
+        if (!init_mp_common((void *)&mp_event_low, VMPRESS_LEVEL_LOW) ||
+            !init_mp_common((void *)&mp_event_medium, VMPRESS_LEVEL_MEDIUM) ||
+            !init_mp_common((void *)&mp_event_critical,
+                            VMPRESS_LEVEL_CRITICAL)) {
             ALOGE("Kernel does not support memory pressure events or in-kernel low memory killer");
+            return -1;
+        }
     }
 
     for (i = 0; i <= ADJTOSLOT(OOM_SCORE_ADJ_MAX); i++) {
@@ -892,15 +963,29 @@
             .sched_priority = 1,
     };
 
-    medium_oomadj = property_get_int32("ro.lmk.medium", 800);
-    critical_oomadj = property_get_int32("ro.lmk.critical", 0);
+    /* By default disable low level vmpressure events */
+    level_oomadj[VMPRESS_LEVEL_LOW] =
+        property_get_int32("ro.lmk.low", OOM_SCORE_ADJ_MAX + 1);
+    level_oomadj[VMPRESS_LEVEL_MEDIUM] =
+        property_get_int32("ro.lmk.medium", 800);
+    level_oomadj[VMPRESS_LEVEL_CRITICAL] =
+        property_get_int32("ro.lmk.critical", 0);
     debug_process_killing = property_get_bool("ro.lmk.debug", false);
-    enable_pressure_upgrade = property_get_bool("ro.lmk.critical_upgrade", false);
-    upgrade_pressure = (int64_t)property_get_int32("ro.lmk.upgrade_pressure", 50);
-    downgrade_pressure = (int64_t)property_get_int32("ro.lmk.downgrade_pressure", 60);
+
+    /* By default disable upgrade/downgrade logic */
+    enable_pressure_upgrade =
+        property_get_bool("ro.lmk.critical_upgrade", false);
+    upgrade_pressure =
+        (int64_t)property_get_int32("ro.lmk.upgrade_pressure", 100);
+    downgrade_pressure =
+        (int64_t)property_get_int32("ro.lmk.downgrade_pressure", 100);
+    kill_heaviest_task =
+        property_get_bool("ro.lmk.kill_heaviest_task", true);
     is_go_device = property_get_bool("ro.config.low_ram", false);
 
-    mlockall(MCL_FUTURE);
+    if (mlockall(MCL_CURRENT | MCL_FUTURE))
+        ALOGW("mlockall failed: errno=%d", errno);
+
     sched_setscheduler(0, SCHED_FIFO, &param);
     if (!init())
         mainloop();
diff --git a/logd/LogAudit.cpp b/logd/LogAudit.cpp
index e17cdde..269db2f 100755
--- a/logd/LogAudit.cpp
+++ b/logd/LogAudit.cpp
@@ -45,7 +45,7 @@
         '0' + LOG_MAKEPRI(LOG_AUTH, LOG_PRI(PRI)) % 10, '>'
 
 LogAudit::LogAudit(LogBuffer* buf, LogReader* reader, int fdDmesg)
-    : SocketListener(mSock = getLogSocket(), false),
+    : SocketListener(getLogSocket(), false),
       logbuf(buf),
       reader(reader),
       fdDmesg(fdDmesg),
@@ -53,8 +53,7 @@
                                               BOOL_DEFAULT_TRUE)),
       events(__android_logger_property_get_bool("ro.logd.auditd.events",
                                                 BOOL_DEFAULT_TRUE)),
-      initialized(false),
-      tooFast(false) {
+      initialized(false) {
     static const char auditd_message[] = { KMSG_PRIORITY(LOG_INFO),
                                            'l',
                                            'o',
@@ -78,54 +77,12 @@
     write(fdDmesg, auditd_message, sizeof(auditd_message));
 }
 
-void LogAudit::checkRateLimit() {
-    // trim list for AUDIT_RATE_LIMIT_BURST_DURATION of history
-    log_time oldest(AUDIT_RATE_LIMIT_BURST_DURATION, 0);
-    bucket.emplace(android_log_clockid());
-    oldest = bucket.back() - oldest;
-    while (bucket.front() < oldest) bucket.pop();
-
-    static const size_t upperThreshold =
-        ((AUDIT_RATE_LIMIT_BURST_DURATION *
-          (AUDIT_RATE_LIMIT_DEFAULT + AUDIT_RATE_LIMIT_MAX)) +
-         1) /
-        2;
-    if (bucket.size() >= upperThreshold) {
-        // Hit peak, slow down source
-        if (!tooFast) {
-            tooFast = true;
-            audit_rate_limit(mSock, AUDIT_RATE_LIMIT_MAX);
-        }
-
-        // We do not need to hold on to the full set of timing data history,
-        // let's ensure it does not grow without bounds.  This also ensures
-        // that std::dequeue underneath behaves almost like a ring buffer.
-        do {
-            bucket.pop();
-        } while (bucket.size() >= upperThreshold);
-        return;
-    }
-
-    if (!tooFast) return;
-
-    static const size_t lowerThreshold =
-        AUDIT_RATE_LIMIT_BURST_DURATION * AUDIT_RATE_LIMIT_MAX;
-
-    if (bucket.size() >= lowerThreshold) return;
-
-    tooFast = false;
-    // Went below max sustained rate, allow source to speed up
-    audit_rate_limit(mSock, AUDIT_RATE_LIMIT_DEFAULT);
-}
-
 bool LogAudit::onDataAvailable(SocketClient* cli) {
     if (!initialized) {
         prctl(PR_SET_NAME, "logd.auditd");
         initialized = true;
     }
 
-    checkRateLimit();
-
     struct audit_message rep;
 
     rep.nlh.nlmsg_type = 0;
@@ -486,6 +443,5 @@
         audit_close(fd);
         fd = -1;
     }
-    (void)audit_rate_limit(fd, AUDIT_RATE_LIMIT_DEFAULT);
     return fd;
 }
diff --git a/logd/LogAudit.h b/logd/LogAudit.h
index 2bd02d4..5904966 100644
--- a/logd/LogAudit.h
+++ b/logd/LogAudit.h
@@ -18,7 +18,6 @@
 #define _LOGD_LOG_AUDIT_H__
 
 #include <map>
-#include <queue>
 
 #include <sysutils/SocketListener.h>
 
@@ -34,11 +33,6 @@
     bool events;
     bool initialized;
 
-    bool tooFast;
-    int mSock;
-    std::queue<log_time> bucket;
-    void checkRateLimit();
-
    public:
     LogAudit(LogBuffer* buf, LogReader* reader, int fdDmesg);
     int log(char* buf, size_t len);
diff --git a/logd/README.property b/logd/README.property
index de6767a..da5f96f 100644
--- a/logd/README.property
+++ b/logd/README.property
@@ -31,9 +31,9 @@
                                          resist increasing the log buffer.
 persist.logd.size.<buffer> number  ro    Size of the buffer for <buffer> log
 ro.logd.size.<buffer>      number svelte default for persist.logd.size.<buffer>
-ro.config.low_ram          bool   false  if true, logd.statistics, logd.kernel
-                                         default false, logd.size 64K instead
-                                         of 256K.
+ro.config.low_ram          bool   false  if true, logd.statistics,
+                                         ro.logd.kernel default false,
+                                         logd.size 64K instead of 256K.
 persist.logd.filter        string        Pruning filter to optimize content.
                                          At runtime use: logcat -P "<string>"
 ro.logd.filter       string "~! ~1000/!" default for persist.logd.filter.
diff --git a/logd/libaudit.c b/logd/libaudit.c
index dfd56f2..9d9a857 100644
--- a/logd/libaudit.c
+++ b/logd/libaudit.c
@@ -160,7 +160,8 @@
      * and the the mask set to AUDIT_STATUS_PID
      */
     status.pid = pid;
-    status.mask = AUDIT_STATUS_PID;
+    status.mask = AUDIT_STATUS_PID | AUDIT_STATUS_RATE_LIMIT;
+    status.rate_limit = AUDIT_RATE_LIMIT; /* audit entries per second */
 
     /* Let the kernel know this pid will be registering for audit events */
     rc = audit_send(fd, AUDIT_SET, &status, sizeof(status));
@@ -183,26 +184,6 @@
     return 0;
 }
 
-int audit_rate_limit(int fd, unsigned rate_limit) {
-    int rc;
-    struct audit_message rep;
-    struct audit_status status;
-
-    memset(&status, 0, sizeof(status));
-
-    status.mask = AUDIT_STATUS_RATE_LIMIT;
-    status.rate_limit = rate_limit; /* audit entries per second */
-
-    rc = audit_send(fd, AUDIT_SET, &status, sizeof(status));
-    if (rc < 0) {
-        return rc;
-    }
-
-    audit_get_reply(fd, &rep, GET_REPLY_NONBLOCKING, 0);
-
-    return 0;
-}
-
 int audit_open() {
     return socket(PF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_AUDIT);
 }
diff --git a/logd/libaudit.h b/logd/libaudit.h
index a2afe47..2a93ea3 100644
--- a/logd/libaudit.h
+++ b/logd/libaudit.h
@@ -89,22 +89,8 @@
  */
 extern int audit_setup(int fd, pid_t pid);
 
-/**
- * Sets the rate limit to receive audit netlink events from the kernel
- * @param fd
- *  The fd returned by a call to audit_open()
- * @param max_rate
- *  The cap of the maximum number of audit messages a second
- * @return
- *  This function returns 0 on success, -errno on error.
- */
-
-/* Guidelines to follow for dynamic rate_limit */
-#define AUDIT_RATE_LIMIT_DEFAULT 20        /* acceptable burst rate      */
-#define AUDIT_RATE_LIMIT_BURST_DURATION 10 /* number of seconds of burst */
-#define AUDIT_RATE_LIMIT_MAX 5             /* acceptable sustained rate  */
-
-extern int audit_rate_limit(int fd, unsigned rate_limit);
+/* Max audit messages per second  */
+#define AUDIT_RATE_LIMIT 5
 
 __END_DECLS
 
diff --git a/logd/main.cpp b/logd/main.cpp
index c8183f0..4af0d21 100644
--- a/logd/main.cpp
+++ b/logd/main.cpp
@@ -438,8 +438,8 @@
 
     int fdPmesg = -1;
     bool klogd = __android_logger_property_get_bool(
-        "logd.kernel", BOOL_DEFAULT_TRUE | BOOL_DEFAULT_FLAG_PERSIST |
-                           BOOL_DEFAULT_FLAG_ENG | BOOL_DEFAULT_FLAG_SVELTE);
+        "ro.logd.kernel",
+        BOOL_DEFAULT_TRUE | BOOL_DEFAULT_FLAG_ENG | BOOL_DEFAULT_FLAG_SVELTE);
     if (klogd) {
         static const char proc_kmsg[] = "/proc/kmsg";
         fdPmesg = android_get_control_file(proc_kmsg);
diff --git a/logd/tests/AndroidTest.xml b/logd/tests/AndroidTest.xml
index 8704611..84f0764 100644
--- a/logd/tests/AndroidTest.xml
+++ b/logd/tests/AndroidTest.xml
@@ -14,6 +14,7 @@
      limitations under the License.
 -->
 <configuration description="Config for CTS Logging Daemon test cases">
+    <option name="test-suite-tag" value="cts" />
     <option name="config-descriptor:metadata" key="component" value="systems" />
     <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
         <option name="cleanup" value="true" />
diff --git a/logd/tests/logd_test.cpp b/logd/tests/logd_test.cpp
index 9e1541b..7d7a22f 100644
--- a/logd/tests/logd_test.cpp
+++ b/logd/tests/logd_test.cpp
@@ -1195,51 +1195,14 @@
                           << "fail as this device is in a bad state, "
                           << "but is not strictly a unit test failure.";
     }
-    // sepolicy_rate_limiter_maximum
-    {  // maximum precharch test block.
-        static constexpr int rate = AUDIT_RATE_LIMIT_MAX;
-        static constexpr int duration = 2;
-        // Two seconds of a liveable sustained rate
-        EXPECT_EQ(rate * duration,
-                  count_avc(sepolicy_rate(rate, rate * duration)));
-    }
-    // sepolicy_rate_limiter_sub_burst
-    {  // maximum period below half way between sustainable and burst rate
-        static constexpr int threshold =
-            ((AUDIT_RATE_LIMIT_BURST_DURATION *
-              (AUDIT_RATE_LIMIT_DEFAULT + AUDIT_RATE_LIMIT_MAX)) +
-             1) /
-            2;
-        static constexpr int rate =
-            (threshold / AUDIT_RATE_LIMIT_BURST_DURATION) - 1;
-        static constexpr int duration = AUDIT_RATE_LIMIT_BURST_DURATION;
-        EXPECT_EQ(rate * duration,
-                  count_avc(sepolicy_rate(rate, rate * duration)));
-    }
-    // sepolicy_rate_limiter_spam
-    {  // hit avc: hard beyond reason block.
-        // maximum period of double the maximum burst rate
-        static constexpr int threshold =
-            ((AUDIT_RATE_LIMIT_BURST_DURATION *
-              (AUDIT_RATE_LIMIT_DEFAULT + AUDIT_RATE_LIMIT_MAX)) +
-             1) /
-            2;
-        static constexpr int rate = AUDIT_RATE_LIMIT_DEFAULT * 2;
-        static constexpr int duration = threshold / AUDIT_RATE_LIMIT_DEFAULT;
-        EXPECT_GE(
-            ((AUDIT_RATE_LIMIT_DEFAULT * duration) * 115) / 100,  // +15% margin
-            count_avc(sepolicy_rate(rate, rate * duration)));
-        // give logd another 3 seconds to react to the burst before checking
-        sepolicy_rate(rate, rate * 3);
-        // maximum period at double maximum burst rate (spam filter kicked in)
-        EXPECT_GE(threshold * 2,
-                  count_avc(sepolicy_rate(
-                      rate, rate * AUDIT_RATE_LIMIT_BURST_DURATION)));
-        // cool down, and check unspammy rate still works
-        sleep(2);
-        EXPECT_LE(AUDIT_RATE_LIMIT_BURST_DURATION - 1,  // allow _one_ lost
-                  count_avc(sepolicy_rate(1, AUDIT_RATE_LIMIT_BURST_DURATION)));
-    }
+
+    static const int rate = AUDIT_RATE_LIMIT;
+    static const int duration = 2;
+    // Two seconds of sustained denials. Depending on the overlap in the time
+    // window that the kernel is considering vs what this test is considering,
+    // allow some additional denials to prevent a flaky test.
+    EXPECT_LE(count_avc(sepolicy_rate(rate, rate * duration)),
+              rate * duration + rate);
 #else
     GTEST_LOG_(INFO) << "This test does nothing.\n";
 #endif
diff --git a/property_service/OWNERS b/property_service/OWNERS
new file mode 100644
index 0000000..babbe4d
--- /dev/null
+++ b/property_service/OWNERS
@@ -0,0 +1 @@
+tomcherry@google.com
diff --git a/property_service/libpropertyinfoparser/Android.bp b/property_service/libpropertyinfoparser/Android.bp
index 3e732b5..ea9b968 100644
--- a/property_service/libpropertyinfoparser/Android.bp
+++ b/property_service/libpropertyinfoparser/Android.bp
@@ -1,11 +1,10 @@
 cc_library_static {
     name: "libpropertyinfoparser",
+    host_supported: true,
+    vendor_available: true,
     srcs: ["property_info_parser.cpp"],
 
     cpp_std: "experimental",
-    sanitize: {
-        misc_undefined: ["signed-integer-overflow"],
-    },
     cppflags: [
         "-Wall",
         "-Wextra",
diff --git a/property_service/libpropertyinfoparser/include/property_info_parser/property_info_parser.h b/property_service/libpropertyinfoparser/include/property_info_parser/property_info_parser.h
index 8c3507e..0548021 100644
--- a/property_service/libpropertyinfoparser/include/property_info_parser/property_info_parser.h
+++ b/property_service/libpropertyinfoparser/include/property_info_parser/property_info_parser.h
@@ -18,6 +18,7 @@
 #define PROPERTY_INFO_PARSER_H
 
 #include <stdint.h>
+#include <stdlib.h>
 
 namespace android {
 namespace properties {
@@ -31,8 +32,8 @@
 
   // This is the context match for this node_; ~0u if it doesn't correspond to any.
   uint32_t context_index;
-  // This is the schema for this node_; ~0u if it doesn't correspond to any.
-  uint32_t schema_index;
+  // This is the type for this node_; ~0u if it doesn't correspond to any.
+  uint32_t type_index;
 };
 
 struct TrieNodeInternal {
@@ -60,7 +61,7 @@
   uint32_t minimum_supported_version;
   uint32_t size;
   uint32_t contexts_offset;
-  uint32_t schemas_offset;
+  uint32_t types_offset;
   uint32_t root_offset;
 };
 
@@ -102,7 +103,7 @@
   }
 
   uint32_t context_index() const { return node_property_entry()->context_index; }
-  uint32_t schema_index() const { return node_property_entry()->schema_index; }
+  uint32_t type_index() const { return node_property_entry()->type_index; }
 
   uint32_t num_child_nodes() const { return trie_node_base_->num_child_nodes; }
   TrieNode child_node(int n) const {
@@ -142,12 +143,11 @@
 
 class PropertyInfoArea : private SerializedData {
  public:
-  void GetPropertyInfoIndexes(const char* name, uint32_t* context_index,
-                              uint32_t* schema_index) const;
-  void GetPropertyInfo(const char* property, const char** context, const char** schema) const;
+  void GetPropertyInfoIndexes(const char* name, uint32_t* context_index, uint32_t* type_index) const;
+  void GetPropertyInfo(const char* property, const char** context, const char** type) const;
 
   int FindContextIndex(const char* context) const;
-  int FindSchemaIndex(const char* schema) const;
+  int FindTypeIndex(const char* type) const;
 
   const char* context(uint32_t index) const {
     uint32_t context_array_size_offset = contexts_offset();
@@ -155,10 +155,10 @@
     return data_base() + context_array[index];
   }
 
-  const char* schema(uint32_t index) const {
-    uint32_t schema_array_size_offset = schemas_offset();
-    const uint32_t* schema_array = uint32_array(schema_array_size_offset + sizeof(uint32_t));
-    return data_base() + schema_array[index];
+  const char* type(uint32_t index) const {
+    uint32_t type_array_size_offset = types_offset();
+    const uint32_t* type_array = uint32_array(type_array_size_offset + sizeof(uint32_t));
+    return data_base() + type_array[index];
   }
 
   uint32_t current_version() const { return header()->current_version; }
@@ -167,21 +167,21 @@
   uint32_t size() const { return SerializedData::size(); }
 
   uint32_t num_contexts() const { return uint32_array(contexts_offset())[0]; }
-  uint32_t num_schemas() const { return uint32_array(schemas_offset())[0]; }
+  uint32_t num_types() const { return uint32_array(types_offset())[0]; }
 
   TrieNode root_node() const { return trie(header()->root_offset); }
 
  private:
   void CheckPrefixMatch(const char* remaining_name, const TrieNode& trie_node,
-                        uint32_t* context_index, uint32_t* schema_index) const;
+                        uint32_t* context_index, uint32_t* type_index) const;
 
   const PropertyInfoAreaHeader* header() const {
     return reinterpret_cast<const PropertyInfoAreaHeader*>(data_base());
   }
   uint32_t contexts_offset() const { return header()->contexts_offset; }
   uint32_t contexts_array_offset() const { return contexts_offset() + sizeof(uint32_t); }
-  uint32_t schemas_offset() const { return header()->schemas_offset; }
-  uint32_t schemas_array_offset() const { return schemas_offset() + sizeof(uint32_t); }
+  uint32_t types_offset() const { return header()->types_offset; }
+  uint32_t types_array_offset() const { return types_offset() + sizeof(uint32_t); }
 
   TrieNode trie(uint32_t offset) const {
     if (offset != 0 && offset > size()) return TrieNode();
diff --git a/property_service/libpropertyinfoparser/property_info_parser.cpp b/property_service/libpropertyinfoparser/property_info_parser.cpp
index e53c625..489d81a 100644
--- a/property_service/libpropertyinfoparser/property_info_parser.cpp
+++ b/property_service/libpropertyinfoparser/property_info_parser.cpp
@@ -56,12 +56,12 @@
   });
 }
 
-// Binary search the list of schemas to find the index of a given schema string.
+// Binary search the list of types to find the index of a given type string.
 // Only should be used for TrieSerializer to construct the Trie.
-int PropertyInfoArea::FindSchemaIndex(const char* schema) const {
-  return Find(num_schemas(), [this, schema](auto array_offset) {
-    auto string_offset = uint32_array(schemas_array_offset())[array_offset];
-    return strcmp(c_string(string_offset), schema);
+int PropertyInfoArea::FindTypeIndex(const char* type) const {
+  return Find(num_types(), [this, type](auto array_offset) {
+    auto string_offset = uint32_array(types_array_offset())[array_offset];
+    return strcmp(c_string(string_offset), type);
   });
 }
 
@@ -89,24 +89,28 @@
 }
 
 void PropertyInfoArea::CheckPrefixMatch(const char* remaining_name, const TrieNode& trie_node,
-                                        uint32_t* context_index, uint32_t* schema_index) const {
+                                        uint32_t* context_index, uint32_t* type_index) const {
   const uint32_t remaining_name_size = strlen(remaining_name);
   for (uint32_t i = 0; i < trie_node.num_prefixes(); ++i) {
     auto prefix_len = trie_node.prefix(i)->namelen;
     if (prefix_len > remaining_name_size) continue;
 
     if (!strncmp(c_string(trie_node.prefix(i)->name_offset), remaining_name, prefix_len)) {
-      *context_index = trie_node.prefix(i)->context_index;
-      *schema_index = trie_node.prefix(i)->schema_index;
+      if (trie_node.prefix(i)->context_index != ~0u) {
+        *context_index = trie_node.prefix(i)->context_index;
+      }
+      if (trie_node.prefix(i)->type_index != ~0u) {
+        *type_index = trie_node.prefix(i)->type_index;
+      }
       return;
     }
   }
 }
 
 void PropertyInfoArea::GetPropertyInfoIndexes(const char* name, uint32_t* context_index,
-                                              uint32_t* schema_index) const {
+                                              uint32_t* type_index) const {
   uint32_t return_context_index = ~0u;
-  uint32_t return_schema_index = ~0u;
+  uint32_t return_type_index = ~0u;
   const char* remaining_name = name;
   auto trie_node = root_node();
   while (true) {
@@ -116,13 +120,13 @@
     if (trie_node.context_index() != ~0u) {
       return_context_index = trie_node.context_index();
     }
-    if (trie_node.schema_index() != ~0u) {
-      return_schema_index = trie_node.schema_index();
+    if (trie_node.type_index() != ~0u) {
+      return_type_index = trie_node.type_index();
     }
 
     // Check prefixes at this node.  This comes after the node check since these prefixes are by
     // definition longer than the node itself.
-    CheckPrefixMatch(remaining_name, trie_node, &return_context_index, &return_schema_index);
+    CheckPrefixMatch(remaining_name, trie_node, &return_context_index, &return_type_index);
 
     if (sep == nullptr) {
       break;
@@ -142,24 +146,36 @@
   // Check exact matches
   for (uint32_t i = 0; i < trie_node.num_exact_matches(); ++i) {
     if (!strcmp(c_string(trie_node.exact_match(i)->name_offset), remaining_name)) {
-      if (context_index != nullptr) *context_index = trie_node.exact_match(i)->context_index;
-      if (schema_index != nullptr) *schema_index = trie_node.exact_match(i)->schema_index;
+      if (context_index != nullptr) {
+        if (trie_node.exact_match(i)->context_index != ~0u) {
+          *context_index = trie_node.exact_match(i)->context_index;
+        } else {
+          *context_index = return_context_index;
+        }
+      }
+      if (type_index != nullptr) {
+        if (trie_node.exact_match(i)->type_index != ~0u) {
+          *type_index = trie_node.exact_match(i)->type_index;
+        } else {
+          *type_index = return_type_index;
+        }
+      }
       return;
     }
   }
   // Check prefix matches for prefixes not deliminated with '.'
-  CheckPrefixMatch(remaining_name, trie_node, &return_context_index, &return_schema_index);
+  CheckPrefixMatch(remaining_name, trie_node, &return_context_index, &return_type_index);
   // Return previously found prefix match.
   if (context_index != nullptr) *context_index = return_context_index;
-  if (schema_index != nullptr) *schema_index = return_schema_index;
+  if (type_index != nullptr) *type_index = return_type_index;
   return;
 }
 
 void PropertyInfoArea::GetPropertyInfo(const char* property, const char** context,
-                                       const char** schema) const {
+                                       const char** type) const {
   uint32_t context_index;
-  uint32_t schema_index;
-  GetPropertyInfoIndexes(property, &context_index, &schema_index);
+  uint32_t type_index;
+  GetPropertyInfoIndexes(property, &context_index, &type_index);
   if (context != nullptr) {
     if (context_index == ~0u) {
       *context = nullptr;
@@ -167,11 +183,11 @@
       *context = this->context(context_index);
     }
   }
-  if (schema != nullptr) {
-    if (schema_index == ~0u) {
-      *schema = nullptr;
+  if (type != nullptr) {
+    if (type_index == ~0u) {
+      *type = nullptr;
     } else {
-      *schema = this->schema(schema_index);
+      *type = this->type(type_index);
     }
   }
 }
diff --git a/property_service/libpropertyinfoserializer/Android.bp b/property_service/libpropertyinfoserializer/Android.bp
index 20e5e13..72ae19a 100644
--- a/property_service/libpropertyinfoserializer/Android.bp
+++ b/property_service/libpropertyinfoserializer/Android.bp
@@ -1,9 +1,8 @@
 cc_defaults {
     name: "propertyinfoserializer_defaults",
+    host_supported: true,
+    vendor_available: true,
     cpp_std: "experimental",
-    sanitize: {
-        misc_undefined: ["signed-integer-overflow"],
-    },
     cppflags: [
         "-Wall",
         "-Wextra",
@@ -19,6 +18,7 @@
     name: "libpropertyinfoserializer",
     defaults: ["propertyinfoserializer_defaults"],
     srcs: [
+        "property_info_file.cpp",
         "property_info_serializer.cpp",
         "trie_builder.cpp",
         "trie_serializer.cpp",
diff --git a/property_service/libpropertyinfoserializer/include/property_info_serializer/property_info_serializer.h b/property_service/libpropertyinfoserializer/include/property_info_serializer/property_info_serializer.h
index f7e708e..439813d 100644
--- a/property_service/libpropertyinfoserializer/include/property_info_serializer/property_info_serializer.h
+++ b/property_service/libpropertyinfoserializer/include/property_info_serializer/property_info_serializer.h
@@ -26,21 +26,25 @@
 struct PropertyInfoEntry {
   PropertyInfoEntry() {}
   template <typename T, typename U, typename V>
-  PropertyInfoEntry(T&& name, U&& context, V&& schema, bool exact_match)
+  PropertyInfoEntry(T&& name, U&& context, V&& type, bool exact_match)
       : name(std::forward<T>(name)),
         context(std::forward<U>(context)),
-        schema(std::forward<V>(schema)),
+        type(std::forward<V>(type)),
         exact_match(exact_match) {}
   std::string name;
   std::string context;
-  std::string schema;
+  std::string type;
   bool exact_match;
 };
 
 bool BuildTrie(const std::vector<PropertyInfoEntry>& property_info,
-               const std::string& default_context, const std::string& default_schema,
+               const std::string& default_context, const std::string& default_type,
                std::string* serialized_trie, std::string* error);
 
+void ParsePropertyInfoFile(const std::string& file_contents,
+                           std::vector<PropertyInfoEntry>* property_infos,
+                           std::vector<std::string>* errors);
+
 }  // namespace properties
 }  // namespace android
 
diff --git a/property_service/libpropertyinfoserializer/property_info_file.cpp b/property_service/libpropertyinfoserializer/property_info_file.cpp
new file mode 100644
index 0000000..2cdc62d
--- /dev/null
+++ b/property_service/libpropertyinfoserializer/property_info_file.cpp
@@ -0,0 +1,121 @@
+//
+// 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 <property_info_serializer/property_info_serializer.h>
+
+#include <android-base/strings.h>
+
+#include "space_tokenizer.h"
+
+using android::base::Join;
+using android::base::Split;
+using android::base::StartsWith;
+using android::base::Trim;
+
+namespace android {
+namespace properties {
+
+namespace {
+
+bool IsTypeValid(const std::vector<std::string>& type_strings) {
+  if (type_strings.empty()) {
+    return false;
+  }
+
+  // There must be at least one string following 'enum'
+  if (type_strings[0] == "enum") {
+    return type_strings.size() > 1;
+  }
+
+  // There should not be any string following any other types.
+  if (type_strings.size() != 1) {
+    return false;
+  }
+
+  // Check that the type matches one of remaining valid types.
+  static const char* const no_parameter_types[] = {"string", "bool",   "int",
+                                                   "uint",   "double", "size"};
+  for (const auto& type : no_parameter_types) {
+    if (type_strings[0] == type) {
+      return true;
+    }
+  }
+  return false;
+}
+
+bool ParsePropertyInfoLine(const std::string& line, PropertyInfoEntry* out, std::string* error) {
+  auto tokenizer = SpaceTokenizer(line);
+
+  auto property = tokenizer.GetNext();
+  if (property.empty()) {
+    *error = "Did not find a property entry in '" + line + "'";
+    return false;
+  }
+
+  auto context = tokenizer.GetNext();
+  if (context.empty()) {
+    *error = "Did not find a context entry in '" + line + "'";
+    return false;
+  }
+
+  // It is not an error to not find exact_match or a type, as older files will not contain them.
+  auto exact_match = tokenizer.GetNext();
+  // We reformat type to be space deliminated regardless of the input whitespace for easier storage
+  // and subsequent parsing.
+  auto type_strings = std::vector<std::string>{};
+  auto type = tokenizer.GetNext();
+  while (!type.empty()) {
+    type_strings.emplace_back(type);
+    type = tokenizer.GetNext();
+  }
+
+  if (!type_strings.empty() && !IsTypeValid(type_strings)) {
+    *error = "Type '" + Join(type_strings, " ") + "' is not valid";
+    return false;
+  }
+
+  *out = {property, context, Join(type_strings, " "), exact_match == "exact"};
+  return true;
+}
+
+}  // namespace
+
+void ParsePropertyInfoFile(const std::string& file_contents,
+                           std::vector<PropertyInfoEntry>* property_infos,
+                           std::vector<std::string>* errors) {
+  // Do not clear property_infos to allow this function to be called on multiple files, with
+  // their results concatenated.
+  errors->clear();
+
+  for (const auto& line : Split(file_contents, "\n")) {
+    auto trimmed_line = Trim(line);
+    if (trimmed_line.empty() || StartsWith(trimmed_line, "#")) {
+      continue;
+    }
+
+    auto property_info_entry = PropertyInfoEntry{};
+    auto parse_error = std::string{};
+    if (!ParsePropertyInfoLine(trimmed_line, &property_info_entry, &parse_error)) {
+      errors->emplace_back(parse_error);
+      continue;
+    }
+
+    property_infos->emplace_back(property_info_entry);
+  }
+}
+
+}  // namespace properties
+}  // namespace android
diff --git a/property_service/libpropertyinfoserializer/property_info_serializer.cpp b/property_service/libpropertyinfoserializer/property_info_serializer.cpp
index 656c96e..803657a 100644
--- a/property_service/libpropertyinfoserializer/property_info_serializer.cpp
+++ b/property_service/libpropertyinfoserializer/property_info_serializer.cpp
@@ -27,13 +27,13 @@
 namespace properties {
 
 bool BuildTrie(const std::vector<PropertyInfoEntry>& property_info,
-               const std::string& default_context, const std::string& default_schema,
+               const std::string& default_context, const std::string& default_type,
                std::string* serialized_trie, std::string* error) {
   // Check that names are legal first
-  auto trie_builder = TrieBuilder(default_context, default_schema);
+  auto trie_builder = TrieBuilder(default_context, default_type);
 
-  for (const auto& [name, context, schema, is_exact] : property_info) {
-    if (!trie_builder.AddToTrie(name, context, schema, is_exact, error)) {
+  for (const auto& [name, context, type, is_exact] : property_info) {
+    if (!trie_builder.AddToTrie(name, context, type, is_exact, error)) {
       return false;
     }
   }
diff --git a/property_service/libpropertyinfoserializer/property_info_serializer_test.cpp b/property_service/libpropertyinfoserializer/property_info_serializer_test.cpp
index b3fae26..f484550 100644
--- a/property_service/libpropertyinfoserializer/property_info_serializer_test.cpp
+++ b/property_service/libpropertyinfoserializer/property_info_serializer_test.cpp
@@ -46,7 +46,7 @@
   auto root_node = property_info_area->root_node();
   EXPECT_STREQ("root", root_node.name());
   EXPECT_STREQ("default", property_info_area->context(root_node.context_index()));
-  EXPECT_STREQ("default", property_info_area->schema(root_node.schema_index()));
+  EXPECT_STREQ("default", property_info_area->type(root_node.type_index()));
 
   EXPECT_EQ(0U, root_node.num_prefixes());
   EXPECT_EQ(0U, root_node.num_exact_matches());
@@ -59,7 +59,7 @@
 
   EXPECT_STREQ("test", test_node.name());
   EXPECT_STREQ("1st", property_info_area->context(test_node.context_index()));
-  EXPECT_STREQ("1st", property_info_area->schema(test_node.schema_index()));
+  EXPECT_STREQ("1st", property_info_area->type(test_node.type_index()));
 
   EXPECT_EQ(0U, test_node.num_child_nodes());
 
@@ -69,7 +69,7 @@
     EXPECT_STREQ("test", serialized_trie.data() + prefix->name_offset);
     EXPECT_EQ(4U, prefix->namelen);
     EXPECT_STREQ("2nd", property_info_area->context(prefix->context_index));
-    EXPECT_STREQ("2nd", property_info_area->schema(prefix->schema_index));
+    EXPECT_STREQ("2nd", property_info_area->type(prefix->type_index));
   }
 
   EXPECT_EQ(3U, test_node.num_exact_matches());
@@ -85,9 +85,9 @@
     EXPECT_STREQ("3rd", property_info_area->context(match2->context_index));
     EXPECT_STREQ("3rd", property_info_area->context(match3->context_index));
 
-    EXPECT_STREQ("3rd", property_info_area->schema(match1->schema_index));
-    EXPECT_STREQ("3rd", property_info_area->schema(match2->schema_index));
-    EXPECT_STREQ("3rd", property_info_area->schema(match3->schema_index));
+    EXPECT_STREQ("3rd", property_info_area->type(match1->type_index));
+    EXPECT_STREQ("3rd", property_info_area->type(match2->type_index));
+    EXPECT_STREQ("3rd", property_info_area->type(match3->type_index));
   }
 
   // Check the long string node
@@ -120,7 +120,7 @@
   auto final_match = long_string_node.exact_match(0);
   EXPECT_STREQ("string", serialized_trie.data() + final_match->name_offset);
   EXPECT_STREQ("4th", property_info_area->context(final_match->context_index));
-  EXPECT_STREQ("4th", property_info_area->schema(final_match->schema_index));
+  EXPECT_STREQ("4th", property_info_area->type(final_match->type_index));
 }
 
 TEST(propertyinfoserializer, GetPropertyInfo) {
@@ -143,109 +143,109 @@
   auto root_node = property_info_area->root_node();
   EXPECT_STREQ("root", root_node.name());
   EXPECT_STREQ("default", property_info_area->context(root_node.context_index()));
-  EXPECT_STREQ("default", property_info_area->schema(root_node.schema_index()));
+  EXPECT_STREQ("default", property_info_area->type(root_node.type_index()));
 
   const char* context;
-  const char* schema;
-  property_info_area->GetPropertyInfo("abc", &context, &schema);
+  const char* type;
+  property_info_area->GetPropertyInfo("abc", &context, &type);
   EXPECT_STREQ("default", context);
-  EXPECT_STREQ("default", schema);
-  property_info_area->GetPropertyInfo("abc.abc", &context, &schema);
+  EXPECT_STREQ("default", type);
+  property_info_area->GetPropertyInfo("abc.abc", &context, &type);
   EXPECT_STREQ("default", context);
-  EXPECT_STREQ("default", schema);
-  property_info_area->GetPropertyInfo("123.abc", &context, &schema);
+  EXPECT_STREQ("default", type);
+  property_info_area->GetPropertyInfo("123.abc", &context, &type);
   EXPECT_STREQ("default", context);
-  EXPECT_STREQ("default", schema);
+  EXPECT_STREQ("default", type);
 
-  property_info_area->GetPropertyInfo("test.a", &context, &schema);
+  property_info_area->GetPropertyInfo("test.a", &context, &type);
   EXPECT_STREQ("1st", context);
-  EXPECT_STREQ("1st", schema);
-  property_info_area->GetPropertyInfo("test.b", &context, &schema);
+  EXPECT_STREQ("1st", type);
+  property_info_area->GetPropertyInfo("test.b", &context, &type);
   EXPECT_STREQ("1st", context);
-  EXPECT_STREQ("1st", schema);
-  property_info_area->GetPropertyInfo("test.c", &context, &schema);
+  EXPECT_STREQ("1st", type);
+  property_info_area->GetPropertyInfo("test.c", &context, &type);
   EXPECT_STREQ("1st", context);
-  EXPECT_STREQ("1st", schema);
+  EXPECT_STREQ("1st", type);
 
-  property_info_area->GetPropertyInfo("test.test", &context, &schema);
+  property_info_area->GetPropertyInfo("test.test", &context, &type);
   EXPECT_STREQ("5th", context);
-  EXPECT_STREQ("5th", schema);
-  property_info_area->GetPropertyInfo("test.testa", &context, &schema);
+  EXPECT_STREQ("5th", type);
+  property_info_area->GetPropertyInfo("test.testa", &context, &type);
   EXPECT_STREQ("2nd", context);
-  EXPECT_STREQ("2nd", schema);
-  property_info_area->GetPropertyInfo("test.testb", &context, &schema);
+  EXPECT_STREQ("2nd", type);
+  property_info_area->GetPropertyInfo("test.testb", &context, &type);
   EXPECT_STREQ("2nd", context);
-  EXPECT_STREQ("2nd", schema);
-  property_info_area->GetPropertyInfo("test.testc", &context, &schema);
+  EXPECT_STREQ("2nd", type);
+  property_info_area->GetPropertyInfo("test.testc", &context, &type);
   EXPECT_STREQ("2nd", context);
-  EXPECT_STREQ("2nd", schema);
+  EXPECT_STREQ("2nd", type);
 
-  property_info_area->GetPropertyInfo("test.test.a", &context, &schema);
+  property_info_area->GetPropertyInfo("test.test.a", &context, &type);
   EXPECT_STREQ("2nd", context);
-  EXPECT_STREQ("2nd", schema);
-  property_info_area->GetPropertyInfo("test.test.b", &context, &schema);
+  EXPECT_STREQ("2nd", type);
+  property_info_area->GetPropertyInfo("test.test.b", &context, &type);
   EXPECT_STREQ("2nd", context);
-  EXPECT_STREQ("2nd", schema);
-  property_info_area->GetPropertyInfo("test.test.c", &context, &schema);
+  EXPECT_STREQ("2nd", type);
+  property_info_area->GetPropertyInfo("test.test.c", &context, &type);
   EXPECT_STREQ("2nd", context);
-  EXPECT_STREQ("2nd", schema);
+  EXPECT_STREQ("2nd", type);
 
-  property_info_area->GetPropertyInfo("test.test1", &context, &schema);
+  property_info_area->GetPropertyInfo("test.test1", &context, &type);
   EXPECT_STREQ("3rd", context);
-  EXPECT_STREQ("3rd", schema);
-  property_info_area->GetPropertyInfo("test.test2", &context, &schema);
+  EXPECT_STREQ("3rd", type);
+  property_info_area->GetPropertyInfo("test.test2", &context, &type);
   EXPECT_STREQ("7th", context);
-  EXPECT_STREQ("7th", schema);
-  property_info_area->GetPropertyInfo("test.test3", &context, &schema);
+  EXPECT_STREQ("7th", type);
+  property_info_area->GetPropertyInfo("test.test3", &context, &type);
   EXPECT_STREQ("3rd", context);
-  EXPECT_STREQ("3rd", schema);
+  EXPECT_STREQ("3rd", type);
 
-  property_info_area->GetPropertyInfo("test.test11", &context, &schema);
+  property_info_area->GetPropertyInfo("test.test11", &context, &type);
   EXPECT_STREQ("2nd", context);
-  EXPECT_STREQ("2nd", schema);
-  property_info_area->GetPropertyInfo("test.test22", &context, &schema);
+  EXPECT_STREQ("2nd", type);
+  property_info_area->GetPropertyInfo("test.test22", &context, &type);
   EXPECT_STREQ("2nd", context);
-  EXPECT_STREQ("2nd", schema);
-  property_info_area->GetPropertyInfo("test.test33", &context, &schema);
+  EXPECT_STREQ("2nd", type);
+  property_info_area->GetPropertyInfo("test.test33", &context, &type);
   EXPECT_STREQ("2nd", context);
-  EXPECT_STREQ("2nd", schema);
+  EXPECT_STREQ("2nd", type);
 
-  property_info_area->GetPropertyInfo("this.is.a.long.string", &context, &schema);
+  property_info_area->GetPropertyInfo("this.is.a.long.string", &context, &type);
   EXPECT_STREQ("4th", context);
-  EXPECT_STREQ("4th", schema);
+  EXPECT_STREQ("4th", type);
 
-  property_info_area->GetPropertyInfo("this.is.a.long", &context, &schema);
+  property_info_area->GetPropertyInfo("this.is.a.long", &context, &type);
   EXPECT_STREQ("default", context);
-  EXPECT_STREQ("default", schema);
-  property_info_area->GetPropertyInfo("this.is.a", &context, &schema);
+  EXPECT_STREQ("default", type);
+  property_info_area->GetPropertyInfo("this.is.a", &context, &type);
   EXPECT_STREQ("default", context);
-  EXPECT_STREQ("default", schema);
-  property_info_area->GetPropertyInfo("this.is", &context, &schema);
+  EXPECT_STREQ("default", type);
+  property_info_area->GetPropertyInfo("this.is", &context, &type);
   EXPECT_STREQ("default", context);
-  EXPECT_STREQ("default", schema);
-  property_info_area->GetPropertyInfo("this", &context, &schema);
+  EXPECT_STREQ("default", type);
+  property_info_area->GetPropertyInfo("this", &context, &type);
   EXPECT_STREQ("default", context);
-  EXPECT_STREQ("default", schema);
+  EXPECT_STREQ("default", type);
 
-  property_info_area->GetPropertyInfo("test.test2.a", &context, &schema);
+  property_info_area->GetPropertyInfo("test.test2.a", &context, &type);
   EXPECT_STREQ("6th", context);
-  EXPECT_STREQ("6th", schema);
+  EXPECT_STREQ("6th", type);
 
-  property_info_area->GetPropertyInfo("testoneword", &context, &schema);
+  property_info_area->GetPropertyInfo("testoneword", &context, &type);
   EXPECT_STREQ("8th", context);
-  EXPECT_STREQ("8th", schema);
+  EXPECT_STREQ("8th", type);
 
-  property_info_area->GetPropertyInfo("testwordprefix", &context, &schema);
+  property_info_area->GetPropertyInfo("testwordprefix", &context, &type);
   EXPECT_STREQ("9th", context);
-  EXPECT_STREQ("9th", schema);
+  EXPECT_STREQ("9th", type);
 
-  property_info_area->GetPropertyInfo("testwordprefixblah", &context, &schema);
+  property_info_area->GetPropertyInfo("testwordprefixblah", &context, &type);
   EXPECT_STREQ("9th", context);
-  EXPECT_STREQ("9th", schema);
+  EXPECT_STREQ("9th", type);
 
-  property_info_area->GetPropertyInfo("testwordprefix.blah", &context, &schema);
+  property_info_area->GetPropertyInfo("testwordprefix.blah", &context, &type);
   EXPECT_STREQ("9th", context);
-  EXPECT_STREQ("9th", schema);
+  EXPECT_STREQ("9th", type);
 }
 
 TEST(propertyinfoserializer, RealProperties) {
@@ -777,35 +777,34 @@
   auto property_info_area = reinterpret_cast<const PropertyInfoArea*>(serialized_trie.data());
 
   const char* context;
-  const char* schema;
-  property_info_area->GetPropertyInfo("persist.radio", &context, &schema);
+  const char* type;
+  property_info_area->GetPropertyInfo("persist.radio", &context, &type);
   EXPECT_STREQ("1st", context);
-  EXPECT_STREQ("1st", schema);
-  property_info_area->GetPropertyInfo("persist.radio.subproperty", &context, &schema);
+  EXPECT_STREQ("1st", type);
+  property_info_area->GetPropertyInfo("persist.radio.subproperty", &context, &type);
   EXPECT_STREQ("1st", context);
-  EXPECT_STREQ("1st", schema);
-  property_info_area->GetPropertyInfo("persist.radiowords", &context, &schema);
+  EXPECT_STREQ("1st", type);
+  property_info_area->GetPropertyInfo("persist.radiowords", &context, &type);
   EXPECT_STREQ("1st", context);
-  EXPECT_STREQ("1st", schema);
-  property_info_area->GetPropertyInfo("persist.radio.long.long.long.sub.property", &context,
-                                      &schema);
+  EXPECT_STREQ("1st", type);
+  property_info_area->GetPropertyInfo("persist.radio.long.long.long.sub.property", &context, &type);
   EXPECT_STREQ("1st", context);
-  EXPECT_STREQ("1st", schema);
-  property_info_area->GetPropertyInfo("persist.radio.something.else.here", &context, &schema);
+  EXPECT_STREQ("1st", type);
+  property_info_area->GetPropertyInfo("persist.radio.something.else.here", &context, &type);
   EXPECT_STREQ("2nd", context);
-  EXPECT_STREQ("2nd", schema);
-  property_info_area->GetPropertyInfo("persist.radio.something.else.here2", &context, &schema);
+  EXPECT_STREQ("2nd", type);
+  property_info_area->GetPropertyInfo("persist.radio.something.else.here2", &context, &type);
   EXPECT_STREQ("2nd", context);
-  EXPECT_STREQ("2nd", schema);
-  property_info_area->GetPropertyInfo("persist.radio.something.else.here.after", &context, &schema);
+  EXPECT_STREQ("2nd", type);
+  property_info_area->GetPropertyInfo("persist.radio.something.else.here.after", &context, &type);
   EXPECT_STREQ("2nd", context);
-  EXPECT_STREQ("2nd", schema);
-  property_info_area->GetPropertyInfo("persist.radio.something.else.nothere", &context, &schema);
+  EXPECT_STREQ("2nd", type);
+  property_info_area->GetPropertyInfo("persist.radio.something.else.nothere", &context, &type);
   EXPECT_STREQ("1st", context);
-  EXPECT_STREQ("1st", schema);
-  property_info_area->GetPropertyInfo("persist.radio.something.else", &context, &schema);
+  EXPECT_STREQ("1st", type);
+  property_info_area->GetPropertyInfo("persist.radio.something.else", &context, &type);
   EXPECT_STREQ("1st", context);
-  EXPECT_STREQ("1st", schema);
+  EXPECT_STREQ("1st", type);
 }
 
 TEST(propertyinfoserializer, GetPropertyInfo_prefix_with_dot_vs_without) {
@@ -823,25 +822,67 @@
   auto property_info_area = reinterpret_cast<const PropertyInfoArea*>(serialized_trie.data());
 
   const char* context;
-  const char* schema;
-  property_info_area->GetPropertyInfo("persist.notradio", &context, &schema);
+  const char* type;
+  property_info_area->GetPropertyInfo("persist.notradio", &context, &type);
   EXPECT_STREQ("1st", context);
-  EXPECT_STREQ("1st", schema);
-  property_info_area->GetPropertyInfo("persist.radio", &context, &schema);
+  EXPECT_STREQ("1st", type);
+  property_info_area->GetPropertyInfo("persist.radio", &context, &type);
   EXPECT_STREQ("2nd", context);
-  EXPECT_STREQ("2nd", schema);
-  property_info_area->GetPropertyInfo("persist.radio.subproperty", &context, &schema);
+  EXPECT_STREQ("2nd", type);
+  property_info_area->GetPropertyInfo("persist.radio.subproperty", &context, &type);
   EXPECT_STREQ("2nd", context);
-  EXPECT_STREQ("2nd", schema);
-  property_info_area->GetPropertyInfo("persist.radiowords", &context, &schema);
+  EXPECT_STREQ("2nd", type);
+  property_info_area->GetPropertyInfo("persist.radiowords", &context, &type);
   EXPECT_STREQ("2nd", context);
-  EXPECT_STREQ("2nd", schema);
-  property_info_area->GetPropertyInfo("persist.radio.long.property.prefix.match", &context, &schema);
+  EXPECT_STREQ("2nd", type);
+  property_info_area->GetPropertyInfo("persist.radio.long.property.prefix.match", &context, &type);
   EXPECT_STREQ("2nd", context);
-  EXPECT_STREQ("2nd", schema);
-  property_info_area->GetPropertyInfo("persist.radio.long.property.exact.match", &context, &schema);
+  EXPECT_STREQ("2nd", type);
+  property_info_area->GetPropertyInfo("persist.radio.long.property.exact.match", &context, &type);
   EXPECT_STREQ("3rd", context);
-  EXPECT_STREQ("3rd", schema);
+  EXPECT_STREQ("3rd", type);
+}
+
+TEST(propertyinfoserializer, GetPropertyInfo_empty_context_and_type) {
+  auto property_info = std::vector<PropertyInfoEntry>{
+      {"persist.", "1st", "", false},
+      {"persist.dot_prefix.", "2nd", "", false},
+      {"persist.non_dot_prefix", "3rd", "", false},
+      {"persist.exact_match", "", "", true},
+      {"persist.dot_prefix2.", "", "4th", false},
+      {"persist.non_dot_prefix2", "", "5th", false},
+  };
+
+  auto serialized_trie = std::string();
+  auto build_trie_error = std::string();
+  ASSERT_TRUE(BuildTrie(property_info, "default", "default", &serialized_trie, &build_trie_error))
+      << build_trie_error;
+
+  auto property_info_area = reinterpret_cast<const PropertyInfoArea*>(serialized_trie.data());
+
+  const char* context;
+  const char* type;
+  property_info_area->GetPropertyInfo("notpersist.radio.something", &context, &type);
+  EXPECT_STREQ("default", context);
+  EXPECT_STREQ("default", type);
+  property_info_area->GetPropertyInfo("persist.nomatch", &context, &type);
+  EXPECT_STREQ("1st", context);
+  EXPECT_STREQ("default", type);
+  property_info_area->GetPropertyInfo("persist.dot_prefix.something", &context, &type);
+  EXPECT_STREQ("2nd", context);
+  EXPECT_STREQ("default", type);
+  property_info_area->GetPropertyInfo("persist.non_dot_prefix.something", &context, &type);
+  EXPECT_STREQ("3rd", context);
+  EXPECT_STREQ("default", type);
+  property_info_area->GetPropertyInfo("persist.exact_match", &context, &type);
+  EXPECT_STREQ("1st", context);
+  EXPECT_STREQ("default", type);
+  property_info_area->GetPropertyInfo("persist.dot_prefix2.something", &context, &type);
+  EXPECT_STREQ("1st", context);
+  EXPECT_STREQ("4th", type);
+  property_info_area->GetPropertyInfo("persist.non_dot_prefix2.something", &context, &type);
+  EXPECT_STREQ("1st", context);
+  EXPECT_STREQ("5th", type);
 }
 
 }  // namespace properties
diff --git a/property_service/libpropertyinfoserializer/space_tokenizer.h b/property_service/libpropertyinfoserializer/space_tokenizer.h
new file mode 100644
index 0000000..fba0c58
--- /dev/null
+++ b/property_service/libpropertyinfoserializer/space_tokenizer.h
@@ -0,0 +1,50 @@
+/*
+ * 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 PROPERTY_INFO_SERIALIZER_SPACE_TOKENIZER_H
+#define PROPERTY_INFO_SERIALIZER_SPACE_TOKENIZER_H
+
+namespace android {
+namespace properties {
+
+class SpaceTokenizer {
+ public:
+  SpaceTokenizer(const std::string& string)
+      : string_(string), it_(string_.begin()), end_(string_.end()) {}
+
+  std::string GetNext() {
+    auto next = std::string();
+    while (it_ != end_ && !isspace(*it_)) {
+      next.push_back(*it_++);
+    }
+    while (it_ != end_ && isspace(*it_)) {
+      it_++;
+    }
+    return next;
+  }
+
+  std::string GetRemaining() { return std::string(it_, end_); }
+
+ private:
+  std::string string_;
+  std::string::const_iterator it_;
+  std::string::const_iterator end_;
+};
+
+}  // namespace properties
+}  // namespace android
+
+#endif
diff --git a/property_service/libpropertyinfoserializer/trie_builder.cpp b/property_service/libpropertyinfoserializer/trie_builder.cpp
index feb753b..8c5ce84 100644
--- a/property_service/libpropertyinfoserializer/trie_builder.cpp
+++ b/property_service/libpropertyinfoserializer/trie_builder.cpp
@@ -23,23 +23,23 @@
 namespace android {
 namespace properties {
 
-TrieBuilder::TrieBuilder(const std::string& default_context, const std::string& default_schema)
+TrieBuilder::TrieBuilder(const std::string& default_context, const std::string& default_type)
     : builder_root_("root") {
   auto* context_pointer = StringPointerFromContainer(default_context, &contexts_);
   builder_root_.set_context(context_pointer);
-  auto* schema_pointer = StringPointerFromContainer(default_schema, &schemas_);
-  builder_root_.set_schema(schema_pointer);
+  auto* type_pointer = StringPointerFromContainer(default_type, &types_);
+  builder_root_.set_type(type_pointer);
 }
 
 bool TrieBuilder::AddToTrie(const std::string& name, const std::string& context,
-                            const std::string& schema, bool exact, std::string* error) {
+                            const std::string& type, bool exact, std::string* error) {
   auto* context_pointer = StringPointerFromContainer(context, &contexts_);
-  auto* schema_pointer = StringPointerFromContainer(schema, &schemas_);
-  return AddToTrie(name, context_pointer, schema_pointer, exact, error);
+  auto* type_pointer = StringPointerFromContainer(type, &types_);
+  return AddToTrie(name, context_pointer, type_pointer, exact, error);
 }
 
 bool TrieBuilder::AddToTrie(const std::string& name, const std::string* context,
-                            const std::string* schema, bool exact, std::string* error) {
+                            const std::string* type, bool exact, std::string* error) {
   TrieBuilderNode* current_node = &builder_root_;
 
   auto name_pieces = Split(name, ".");
@@ -66,12 +66,12 @@
 
   // Store our context based on what type of match it is.
   if (exact) {
-    if (!current_node->AddExactMatchContext(name_pieces.front(), context, schema)) {
+    if (!current_node->AddExactMatchContext(name_pieces.front(), context, type)) {
       *error = "Duplicate exact match detected for '" + name + "'";
       return false;
     }
   } else if (!ends_with_dot) {
-    if (!current_node->AddPrefixContext(name_pieces.front(), context, schema)) {
+    if (!current_node->AddPrefixContext(name_pieces.front(), context, type)) {
       *error = "Duplicate prefix match detected for '" + name + "'";
       return false;
     }
@@ -84,12 +84,12 @@
       *error = "Unable to allocate Trie node";
       return false;
     }
-    if (child->context() != nullptr || child->schema() != nullptr) {
+    if (child->context() != nullptr || child->type() != nullptr) {
       *error = "Duplicate prefix match detected for '" + name + "'";
       return false;
     }
     child->set_context(context);
-    child->set_schema(schema);
+    child->set_type(type);
   }
   return true;
 }
diff --git a/property_service/libpropertyinfoserializer/trie_builder.h b/property_service/libpropertyinfoserializer/trie_builder.h
index f928e76..b971589 100644
--- a/property_service/libpropertyinfoserializer/trie_builder.h
+++ b/property_service/libpropertyinfoserializer/trie_builder.h
@@ -26,13 +26,12 @@
 namespace properties {
 
 struct PropertyEntryBuilder {
-  PropertyEntryBuilder() : context(nullptr), schema(nullptr) {}
-  PropertyEntryBuilder(const std::string& name, const std::string* context,
-                       const std::string* schema)
-      : name(name), context(context), schema(schema) {}
+  PropertyEntryBuilder() : context(nullptr), type(nullptr) {}
+  PropertyEntryBuilder(const std::string& name, const std::string* context, const std::string* type)
+      : name(name), context(context), type(type) {}
   std::string name;
   const std::string* context;
-  const std::string* schema;
+  const std::string* type;
 };
 
 class TrieBuilderNode {
@@ -56,33 +55,33 @@
   TrieBuilderNode* AddChild(const std::string& name) { return &children_.emplace_back(name); }
 
   bool AddPrefixContext(const std::string& prefix, const std::string* context,
-                        const std::string* schema) {
+                        const std::string* type) {
     if (std::find_if(prefixes_.begin(), prefixes_.end(),
                      [&prefix](const auto& t) { return t.name == prefix; }) != prefixes_.end()) {
       return false;
     }
 
-    prefixes_.emplace_back(prefix, context, schema);
+    prefixes_.emplace_back(prefix, context, type);
     return true;
   }
 
   bool AddExactMatchContext(const std::string& exact_match, const std::string* context,
-                            const std::string* schema) {
+                            const std::string* type) {
     if (std::find_if(exact_matches_.begin(), exact_matches_.end(), [&exact_match](const auto& t) {
           return t.name == exact_match;
         }) != exact_matches_.end()) {
       return false;
     }
 
-    exact_matches_.emplace_back(exact_match, context, schema);
+    exact_matches_.emplace_back(exact_match, context, type);
     return true;
   }
 
   const std::string& name() const { return property_entry_.name; }
   const std::string* context() const { return property_entry_.context; }
   void set_context(const std::string* context) { property_entry_.context = context; }
-  const std::string* schema() const { return property_entry_.schema; }
-  void set_schema(const std::string* schema) { property_entry_.schema = schema; }
+  const std::string* type() const { return property_entry_.type; }
+  void set_type(const std::string* type) { property_entry_.type = type; }
 
   const PropertyEntryBuilder property_entry() const { return property_entry_; }
 
@@ -99,23 +98,23 @@
 
 class TrieBuilder {
  public:
-  TrieBuilder(const std::string& default_context, const std::string& default_schema);
-  bool AddToTrie(const std::string& name, const std::string& context, const std::string& schema,
+  TrieBuilder(const std::string& default_context, const std::string& default_type);
+  bool AddToTrie(const std::string& name, const std::string& context, const std::string& type,
                  bool exact, std::string* error);
 
   const TrieBuilderNode builder_root() const { return builder_root_; }
   const std::set<std::string>& contexts() const { return contexts_; }
-  const std::set<std::string>& schemas() const { return schemas_; }
+  const std::set<std::string>& types() const { return types_; }
 
  private:
-  bool AddToTrie(const std::string& name, const std::string* context, const std::string* schema,
+  bool AddToTrie(const std::string& name, const std::string* context, const std::string* type,
                  bool exact, std::string* error);
   const std::string* StringPointerFromContainer(const std::string& string,
                                                 std::set<std::string>* container);
 
   TrieBuilderNode builder_root_;
   std::set<std::string> contexts_;
-  std::set<std::string> schemas_;
+  std::set<std::string> types_;
 };
 
 }  // namespace properties
diff --git a/property_service/libpropertyinfoserializer/trie_builder_test.cpp b/property_service/libpropertyinfoserializer/trie_builder_test.cpp
index 2b948f3..5078810 100644
--- a/property_service/libpropertyinfoserializer/trie_builder_test.cpp
+++ b/property_service/libpropertyinfoserializer/trie_builder_test.cpp
@@ -22,19 +22,19 @@
 namespace properties {
 
 TEST(propertyinfoserializer, BuildTrie_Simple) {
-  auto trie_builder = TrieBuilder("default", "default_schema");
+  auto trie_builder = TrieBuilder("default", "default_type");
 
   // Add test data to tree
   auto error = std::string();
-  EXPECT_TRUE(trie_builder.AddToTrie("test.", "1st", "1st_schema", false, &error));
-  EXPECT_TRUE(trie_builder.AddToTrie("test.test", "2nd", "2nd_schema", false, &error));
-  EXPECT_TRUE(trie_builder.AddToTrie("test.test1", "3rd", "3rd_schema", true, &error));
-  EXPECT_TRUE(trie_builder.AddToTrie("test.test2", "3rd", "3rd_schema", true, &error));
-  EXPECT_TRUE(trie_builder.AddToTrie("test.test3", "3rd", "3rd_schema", true, &error));
-  EXPECT_TRUE(trie_builder.AddToTrie("this.is.a.long.string", "4th", "4th_schema", true, &error));
+  EXPECT_TRUE(trie_builder.AddToTrie("test.", "1st", "1st_type", false, &error));
+  EXPECT_TRUE(trie_builder.AddToTrie("test.test", "2nd", "2nd_type", false, &error));
+  EXPECT_TRUE(trie_builder.AddToTrie("test.test1", "3rd", "3rd_type", true, &error));
+  EXPECT_TRUE(trie_builder.AddToTrie("test.test2", "3rd", "3rd_type", true, &error));
+  EXPECT_TRUE(trie_builder.AddToTrie("test.test3", "3rd", "3rd_type", true, &error));
+  EXPECT_TRUE(trie_builder.AddToTrie("this.is.a.long.string", "4th", "4th_type", true, &error));
 
   ASSERT_EQ(5U, trie_builder.contexts().size());
-  ASSERT_EQ(5U, trie_builder.schemas().size());
+  ASSERT_EQ(5U, trie_builder.types().size());
 
   auto& builder_root = trie_builder.builder_root();
 
@@ -42,8 +42,8 @@
   EXPECT_EQ("root", builder_root.name());
   ASSERT_NE(nullptr, builder_root.context());
   EXPECT_EQ("default", *builder_root.context());
-  ASSERT_NE(nullptr, builder_root.schema());
-  EXPECT_EQ("default_schema", *builder_root.schema());
+  ASSERT_NE(nullptr, builder_root.type());
+  EXPECT_EQ("default_type", *builder_root.type());
 
   EXPECT_EQ(0U, builder_root.prefixes().size());
   EXPECT_EQ(0U, builder_root.exact_matches().size());
@@ -55,8 +55,8 @@
   EXPECT_EQ("test", test_node->name());
   ASSERT_NE(nullptr, test_node->context());
   EXPECT_EQ("1st", *test_node->context());
-  ASSERT_NE(nullptr, test_node->schema());
-  EXPECT_EQ("1st_schema", *test_node->schema());
+  ASSERT_NE(nullptr, test_node->type());
+  EXPECT_EQ("1st_type", *test_node->type());
 
   EXPECT_EQ(0U, test_node->children().size());
   EXPECT_EQ(1U, test_node->prefixes().size());
@@ -65,8 +65,8 @@
     EXPECT_EQ("test", property_entry.name);
     ASSERT_NE(nullptr, property_entry.context);
     EXPECT_EQ("2nd", *property_entry.context);
-    ASSERT_NE(nullptr, property_entry.schema);
-    EXPECT_EQ("2nd_schema", *property_entry.schema);
+    ASSERT_NE(nullptr, property_entry.type);
+    EXPECT_EQ("2nd_type", *property_entry.type);
   }
   EXPECT_EQ(3U, test_node->exact_matches().size());
   EXPECT_EQ("test1", test_node->exact_matches()[0].name);
@@ -80,18 +80,18 @@
   EXPECT_EQ("3rd", *test_node->exact_matches()[1].context);
   EXPECT_EQ("3rd", *test_node->exact_matches()[2].context);
 
-  ASSERT_NE(nullptr, test_node->exact_matches()[0].schema);
-  ASSERT_NE(nullptr, test_node->exact_matches()[1].schema);
-  ASSERT_NE(nullptr, test_node->exact_matches()[2].schema);
-  EXPECT_EQ("3rd_schema", *test_node->exact_matches()[0].schema);
-  EXPECT_EQ("3rd_schema", *test_node->exact_matches()[1].schema);
-  EXPECT_EQ("3rd_schema", *test_node->exact_matches()[2].schema);
+  ASSERT_NE(nullptr, test_node->exact_matches()[0].type);
+  ASSERT_NE(nullptr, test_node->exact_matches()[1].type);
+  ASSERT_NE(nullptr, test_node->exact_matches()[2].type);
+  EXPECT_EQ("3rd_type", *test_node->exact_matches()[0].type);
+  EXPECT_EQ("3rd_type", *test_node->exact_matches()[1].type);
+  EXPECT_EQ("3rd_type", *test_node->exact_matches()[2].type);
 
   // Check the long string node
   auto expect_empty_one_child = [](auto* node) {
     ASSERT_NE(nullptr, node);
     EXPECT_EQ(nullptr, node->context());
-    EXPECT_EQ(nullptr, node->schema());
+    EXPECT_EQ(nullptr, node->type());
     EXPECT_EQ(0U, node->prefixes().size());
     EXPECT_EQ(0U, node->exact_matches().size());
     EXPECT_EQ(1U, node->children().size());
@@ -120,8 +120,8 @@
     EXPECT_EQ("string", property_entry.name);
     ASSERT_NE(nullptr, property_entry.context);
     EXPECT_EQ("4th", *property_entry.context);
-    ASSERT_NE(nullptr, property_entry.schema);
-    EXPECT_EQ("4th_schema", *property_entry.schema);
+    ASSERT_NE(nullptr, property_entry.type);
+    EXPECT_EQ("4th_type", *property_entry.type);
   }
 }
 
diff --git a/property_service/libpropertyinfoserializer/trie_serializer.cpp b/property_service/libpropertyinfoserializer/trie_serializer.cpp
index 5326537..adeed1b 100644
--- a/property_service/libpropertyinfoserializer/trie_serializer.cpp
+++ b/property_service/libpropertyinfoserializer/trie_serializer.cpp
@@ -43,15 +43,15 @@
   uint32_t context_index = property_entry.context != nullptr && !property_entry.context->empty()
                                ? serialized_info()->FindContextIndex(property_entry.context->c_str())
                                : ~0u;
-  uint32_t schema_index = property_entry.schema != nullptr && !property_entry.schema->empty()
-                              ? serialized_info()->FindSchemaIndex(property_entry.schema->c_str())
-                              : ~0u;
+  uint32_t type_index = property_entry.type != nullptr && !property_entry.type->empty()
+                            ? serialized_info()->FindTypeIndex(property_entry.type->c_str())
+                            : ~0u;
   uint32_t offset;
   auto serialized_property_entry = arena_->AllocateObject<PropertyEntry>(&offset);
   serialized_property_entry->name_offset = arena_->AllocateAndWriteString(property_entry.name);
   serialized_property_entry->namelen = property_entry.name.size();
   serialized_property_entry->context_index = context_index;
-  serialized_property_entry->schema_index = schema_index;
+  serialized_property_entry->type_index = type_index;
   return offset;
 }
 
@@ -122,9 +122,9 @@
   header->contexts_offset = arena_->size();
   SerializeStrings(trie_builder.contexts());
 
-  // Store where we're about to write the schemas.
-  header->schemas_offset = arena_->size();
-  SerializeStrings(trie_builder.schemas());
+  // Store where we're about to write the types.
+  header->types_offset = arena_->size();
+  SerializeStrings(trie_builder.types());
 
   // We need to store size() up to this point now for Find*Offset() to work.
   header->size = arena_->size();
diff --git a/property_service/property_info_checker/Android.bp b/property_service/property_info_checker/Android.bp
new file mode 100644
index 0000000..6ee649a
--- /dev/null
+++ b/property_service/property_info_checker/Android.bp
@@ -0,0 +1,12 @@
+cc_binary {
+    name: "property_info_checker",
+    host_supported: true,
+    static_executable: true,
+    cpp_std: "experimental",
+    static_libs: [
+        "libpropertyinfoserializer",
+        "libpropertyinfoparser",
+        "libbase",
+    ],
+    srcs: ["property_info_checker.cpp"],
+}
diff --git a/property_service/property_info_checker/property_info_checker.cpp b/property_service/property_info_checker/property_info_checker.cpp
new file mode 100644
index 0000000..e4f8264
--- /dev/null
+++ b/property_service/property_info_checker/property_info_checker.cpp
@@ -0,0 +1,51 @@
+#include <iostream>
+#include <string>
+#include <vector>
+
+#include <android-base/file.h>
+
+#include <property_info_serializer/property_info_serializer.h>
+
+using android::base::ReadFileToString;
+using android::properties::BuildTrie;
+using android::properties::ParsePropertyInfoFile;
+using android::properties::PropertyInfoEntry;
+
+int main(int argc, char** argv) {
+  if (argc < 2) {
+    std::cerr << "A list of property info files to be checked is expected on the command line"
+              << std::endl;
+    return -1;
+  }
+
+  auto property_info_entries = std::vector<PropertyInfoEntry>{};
+
+  for (int i = 1; i < argc; ++i) {
+    auto filename = argv[i];
+    auto file_contents = std::string{};
+    if (!ReadFileToString(filename, &file_contents)) {
+      std::cerr << "Could not read properties from '" << filename << "'" << std::endl;
+      return -1;
+    }
+
+    auto errors = std::vector<std::string>{};
+    ParsePropertyInfoFile(file_contents, &property_info_entries, &errors);
+    if (!errors.empty()) {
+      for (const auto& error : errors) {
+        std::cerr << "Could not read line from '" << filename << "': " << error << std::endl;
+      }
+      return -1;
+    }
+  }
+
+  auto serialized_contexts = std::string{};
+  auto build_trie_error = std::string{};
+
+  if (!BuildTrie(property_info_entries, "u:object_r:default_prop:s0", "\\s*", &serialized_contexts,
+                 &build_trie_error)) {
+    std::cerr << "Unable to serialize property contexts: " << build_trie_error << std::endl;
+    return -1;
+  }
+
+  return 0;
+}
diff --git a/rootdir/Android.mk b/rootdir/Android.mk
index 492d63a..ca992d6 100644
--- a/rootdir/Android.mk
+++ b/rootdir/Android.mk
@@ -77,7 +77,7 @@
 #
 # create some directories (some are mount points) and symlinks
 LOCAL_POST_INSTALL_CMD := mkdir -p $(addprefix $(TARGET_ROOT_OUT)/, \
-    sbin dev proc sys system data oem acct config storage mnt $(BOARD_ROOT_EXTRA_FOLDERS)); \
+    sbin dev proc sys system data odm oem acct config storage mnt $(BOARD_ROOT_EXTRA_FOLDERS)); \
     ln -sf /system/bin $(TARGET_ROOT_OUT)/bin; \
     ln -sf /system/etc $(TARGET_ROOT_OUT)/etc; \
     ln -sf /data/user_de/0/com.android.shell/files/bugreports $(TARGET_ROOT_OUT)/bugreports; \
@@ -125,24 +125,81 @@
 bcp_md5 :=
 bcp_dep :=
 
-# If PLATFORM_VNDK_VERSION is defined and not "current", generate versioned
-# module names for ld.config.txt, llndk.libraries.txt and vndksp.libraries.txt
-# files.
-define versioned_module_name
+# If BOARD_VNDK_VERSION is defined, append PLATFORM_VNDK_VERSION to base name.
+define append_vndk_version
 $(strip \
-  $(if $(filter-out current,$(PLATFORM_VNDK_VERSION)), \
-    $(basename $(LOCAL_MODULE)).$(PLATFORM_VNDK_VERSION)$(suffix $(LOCAL_MODULE)), \
-    $(LOCAL_MODULE) \
+  $(if $(BOARD_VNDK_VERSION), \
+    $(basename $(1)).$(PLATFORM_VNDK_VERSION)$(suffix $(1)), \
+    $(1) \
   ) \
 )
 endef
 
+# Update namespace configuration file with library lists and VNDK version
+#
+# $(1): Input source file (ld.config.txt)
+# $(2): Output built module
+# $(3): VNDK version suffix
+define update_and_install_ld_config
+llndk_libraries := $(call normalize-path-list,$(addsuffix .so,\
+  $(filter-out $(VNDK_PRIVATE_LIBRARIES),$(LLNDK_LIBRARIES))))
+private_llndk_libraries := $(call normalize-path-list,$(addsuffix .so,\
+  $(filter $(VNDK_PRIVATE_LIBRARIES),$(LLNDK_LIBRARIES))))
+vndk_sameprocess_libraries := $(call normalize-path-list,$(addsuffix .so,\
+  $(filter-out $(VNDK_PRIVATE_LIBRARIES),$(VNDK_SAMEPROCESS_LIBRARIES))))
+vndk_core_libraries := $(call normalize-path-list,$(addsuffix .so,\
+  $(filter-out $(VNDK_PRIVATE_LIBRARIES),$(VNDK_CORE_LIBRARIES))))
+sanitizer_runtime_libraries := $(call normalize-path-list,$(addsuffix .so,\
+  $(ADDRESS_SANITIZER_RUNTIME_LIBRARY) \
+  $(UBSAN_RUNTIME_LIBRARY) \
+  $(TSAN_RUNTIME_LIBRARY) \
+  $(2ND_ADDRESS_SANITIZER_RUNTIME_LIBRARY) \
+  $(2ND_UBSAN_RUNTIME_LIBRARY) \
+  $(2ND_TSAN_RUNTIME_LIBRARY)))
+# If BOARD_VNDK_VERSION is not defined, VNDK version suffix will not be used.
+vndk_version_suffix := $(if $(strip $(3)),-$(strip $(3)))
+
+$(2): PRIVATE_LLNDK_LIBRARIES := $$(llndk_libraries)
+$(2): PRIVATE_PRIVATE_LLNDK_LIBRARIES := $$(private_llndk_libraries)
+$(2): PRIVATE_VNDK_SAMEPROCESS_LIBRARIES := $$(vndk_sameprocess_libraries)
+$(2): PRIVATE_VNDK_CORE_LIBRARIES := $$(vndk_core_libraries)
+$(2): PRIVATE_SANITIZER_RUNTIME_LIBRARIES := $$(sanitizer_runtime_libraries)
+$(2): PRIVATE_VNDK_VERSION := $$(vndk_version_suffix)
+$(2): $(1)
+	@echo "Generate: $$< -> $$@"
+	@mkdir -p $$(dir $$@)
+	$$(hide) sed -e 's?%LLNDK_LIBRARIES%?$$(PRIVATE_LLNDK_LIBRARIES)?g' $$< >$$@
+	$$(hide) sed -i -e 's?%PRIVATE_LLNDK_LIBRARIES%?$$(PRIVATE_PRIVATE_LLNDK_LIBRARIES)?g' $$@
+	$$(hide) sed -i -e 's?%VNDK_SAMEPROCESS_LIBRARIES%?$$(PRIVATE_VNDK_SAMEPROCESS_LIBRARIES)?g' $$@
+	$$(hide) sed -i -e 's?%VNDK_CORE_LIBRARIES%?$$(PRIVATE_VNDK_CORE_LIBRARIES)?g' $$@
+	$$(hide) sed -i -e 's?%SANITIZER_RUNTIME_LIBRARIES%?$$(PRIVATE_SANITIZER_RUNTIME_LIBRARIES)?g' $$@
+	$$(hide) sed -i -e 's?%VNDK_VER%?$$(PRIVATE_VNDK_VERSION)?g' $$@
+
+llndk_libraries :=
+private_llndk_libraries :=
+vndk_sameprocess_libraries :=
+vndk_core_libraries :=
+sanitizer_runtime_libraries :=
+vndk_version_suffix :=
+endef # update_and_install_ld_config
+
 #######################################
 # ld.config.txt
+#
+# For VNDK enforced devices that have defined BOARD_VNDK_VERSION, use
+# "ld.config.txt.in" as a source file. This configuration includes strict VNDK
+# run-time restrictions for vendor process.
+# Other treblized devices, that have not defined BOARD_VNDK_VERSION or that
+# have set BOARD_VNDK_RUNTIME_DISABLE to true, use "ld.config.txt" as a source
+# file. This configuration does not have strict VNDK run-time restrictions.
+# If the device is not treblized, use "ld.config.legacy.txt" for legacy
+# namespace configuration.
 include $(CLEAR_VARS)
+LOCAL_MODULE := ld.config.txt
+LOCAL_MODULE_CLASS := ETC
+LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)
 
 _enforce_vndk_at_runtime := false
-
 ifdef BOARD_VNDK_VERSION
 ifneq ($(BOARD_VNDK_RUNTIME_DISABLE),true)
   _enforce_vndk_at_runtime := true
@@ -150,65 +207,52 @@
 endif
 
 ifeq ($(_enforce_vndk_at_runtime),true)
-LOCAL_MODULE := ld.config.txt
-LOCAL_MODULE_CLASS := ETC
-LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)
-LOCAL_MODULE_STEM := $(call versioned_module_name)
+# for VNDK enforced devices
+LOCAL_MODULE_STEM := $(call append_vndk_version,$(LOCAL_MODULE))
 include $(BUILD_SYSTEM)/base_rules.mk
+$(eval $(call update_and_install_ld_config,\
+  $(LOCAL_PATH)/etc/ld.config.txt.in,\
+  $(LOCAL_BUILT_MODULE),\
+  $(PLATFORM_VNDK_VERSION)))
 
-llndk_libraries := $(call normalize-path-list,$(addsuffix .so,\
-$(filter-out $(VNDK_PRIVATE_LIBRARIES),$(LLNDK_LIBRARIES))))
+else ifeq ($(PRODUCT_TREBLE_LINKER_NAMESPACES)|$(SANITIZE_TARGET),true|)
+# for treblized but VNDK non-enforced devices
+LOCAL_MODULE_STEM := $(call append_vndk_version,$(LOCAL_MODULE))
+include $(BUILD_SYSTEM)/base_rules.mk
+$(eval $(call update_and_install_ld_config,\
+  $(LOCAL_PATH)/etc/ld.config.txt,\
+  $(LOCAL_BUILT_MODULE),\
+  $(if $(BOARD_VNDK_VERSION),$(PLATFORM_VNDK_VERSION))))
 
-private_llndk_libraries := $(call normalize-path-list,$(addsuffix .so,\
-$(filter $(VNDK_PRIVATE_LIBRARIES),$(LLNDK_LIBRARIES))))
-
-vndk_sameprocess_libraries := $(call normalize-path-list,$(addsuffix .so,\
-$(filter-out $(VNDK_PRIVATE_LIBRARIES),$(VNDK_SAMEPROCESS_LIBRARIES))))
-
-vndk_core_libraries := $(call normalize-path-list,$(addsuffix .so,\
-$(filter-out $(VNDK_PRIVATE_LIBRARIES),$(VNDK_CORE_LIBRARIES))))
-
-sanitizer_runtime_libraries := $(call normalize-path-list,$(addsuffix .so,\
-$(ADDRESS_SANITIZER_RUNTIME_LIBRARY) \
-$(UBSAN_RUNTIME_LIBRARY) \
-$(TSAN_RUNTIME_LIBRARY) \
-$(2ND_ADDRESS_SANITIZER_RUNTIME_LIBRARY) \
-$(2ND_UBSAN_RUNTIME_LIBRARY) \
-$(2ND_TSAN_RUNTIME_LIBRARY)))
-
-$(LOCAL_BUILT_MODULE): PRIVATE_LLNDK_LIBRARIES := $(llndk_libraries)
-$(LOCAL_BUILT_MODULE): PRIVATE_PRIVATE_LLNDK_LIBRARIES := $(private_llndk_libraries)
-$(LOCAL_BUILT_MODULE): PRIVATE_VNDK_SAMEPROCESS_LIBRARIES := $(vndk_sameprocess_libraries)
-$(LOCAL_BUILT_MODULE): PRIVATE_LLNDK_PRIVATE_LIBRARIES := $(llndk_private_libraries)
-$(LOCAL_BUILT_MODULE): PRIVATE_VNDK_CORE_LIBRARIES := $(vndk_core_libraries)
-$(LOCAL_BUILT_MODULE): PRIVATE_SANITIZER_RUNTIME_LIBRARIES := $(sanitizer_runtime_libraries)
-$(LOCAL_BUILT_MODULE): $(LOCAL_PATH)/etc/ld.config.txt.in
-	@echo "Generate: $< -> $@"
-	@mkdir -p $(dir $@)
-	$(hide) sed -e 's?%LLNDK_LIBRARIES%?$(PRIVATE_LLNDK_LIBRARIES)?g' $< >$@
-	$(hide) sed -i -e 's?%PRIVATE_LLNDK_LIBRARIES%?$(PRIVATE_PRIVATE_LLNDK_LIBRARIES)?g' $@
-	$(hide) sed -i -e 's?%VNDK_SAMEPROCESS_LIBRARIES%?$(PRIVATE_VNDK_SAMEPROCESS_LIBRARIES)?g' $@
-	$(hide) sed -i -e 's?%VNDK_CORE_LIBRARIES%?$(PRIVATE_VNDK_CORE_LIBRARIES)?g' $@
-	$(hide) sed -i -e 's?%SANITIZER_RUNTIME_LIBRARIES%?$(PRIVATE_SANITIZER_RUNTIME_LIBRARIES)?g' $@
-
-llndk_libraries :=
-vndk_sameprocess_libraries :=
-vndk_core_libraries :=
-sanitizer_runtime_libraries :=
-else # if _enforce_vndk_at_runtime is not true
-
-LOCAL_MODULE := ld.config.txt
-ifeq ($(PRODUCT_TREBLE_LINKER_NAMESPACES)|$(SANITIZE_TARGET),true|)
-  LOCAL_SRC_FILES := etc/ld.config.txt
-  LOCAL_MODULE_STEM := $(call versioned_module_name)
 else
-  LOCAL_SRC_FILES := etc/ld.config.legacy.txt
-  LOCAL_MODULE_STEM := $(LOCAL_MODULE)
-endif
+# for legacy non-treblized devices
+LOCAL_SRC_FILES := etc/ld.config.legacy.txt
+LOCAL_MODULE_STEM := $(LOCAL_MODULE)
+include $(BUILD_PREBUILT)
+
+endif # if _enforce_vndk_at_runtime is true
+
+_enforce_vndk_at_runtime :=
+
+#######################################
+# ld.config.noenforce.txt
+#
+# This file is a temporary configuration file only for GSI. Originally GSI has
+# BOARD_VNDK_VERSION defined and has strict VNDK enforcing rule based on
+# "ld.config.txt.in". However for the devices, that have not defined
+# BOARD_VNDK_VERSION, GSI provides this configuration file which is based on
+# "ld.config.txt".
+# Do not install this file for the devices other than GSI.
+include $(CLEAR_VARS)
+LOCAL_MODULE := ld.config.noenforce.txt
 LOCAL_MODULE_CLASS := ETC
 LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)
-include $(BUILD_PREBUILT)
-endif
+LOCAL_MODULE_STEM := $(LOCAL_MODULE)
+include $(BUILD_SYSTEM)/base_rules.mk
+$(eval $(call update_and_install_ld_config,\
+  $(LOCAL_PATH)/etc/ld.config.txt,\
+  $(LOCAL_BUILT_MODULE),\
+  $(PLATFORM_VNDK_VERSION)))
 
 #######################################
 # llndk.libraries.txt
@@ -216,7 +260,7 @@
 LOCAL_MODULE := llndk.libraries.txt
 LOCAL_MODULE_CLASS := ETC
 LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)
-LOCAL_MODULE_STEM := $(call versioned_module_name)
+LOCAL_MODULE_STEM := $(call append_vndk_version,$(LOCAL_MODULE))
 include $(BUILD_SYSTEM)/base_rules.mk
 $(LOCAL_BUILT_MODULE): PRIVATE_LLNDK_LIBRARIES := $(LLNDK_LIBRARIES)
 $(LOCAL_BUILT_MODULE):
@@ -232,7 +276,7 @@
 LOCAL_MODULE := vndksp.libraries.txt
 LOCAL_MODULE_CLASS := ETC
 LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)
-LOCAL_MODULE_STEM := $(call versioned_module_name)
+LOCAL_MODULE_STEM := $(call append_vndk_version,$(LOCAL_MODULE))
 include $(BUILD_SYSTEM)/base_rules.mk
 $(LOCAL_BUILT_MODULE): PRIVATE_VNDK_SAMEPROCESS_LIBRARIES := $(VNDK_SAMEPROCESS_LIBRARIES)
 $(LOCAL_BUILT_MODULE):
diff --git a/rootdir/OWNERS b/rootdir/OWNERS
index f335715..6029ae7 100644
--- a/rootdir/OWNERS
+++ b/rootdir/OWNERS
@@ -1,3 +1,4 @@
+jeffv@google.com
 jiyong@google.com
 smoreland@google.com
 tomcherry@google.com
diff --git a/rootdir/etc/ld.config.txt b/rootdir/etc/ld.config.txt
index 60afdd7..5d97a73 100644
--- a/rootdir/etc/ld.config.txt
+++ b/rootdir/etc/ld.config.txt
@@ -126,9 +126,9 @@
 namespace.rs.isolated = true
 namespace.rs.visible = true
 
-namespace.rs.search.paths  = /odm/${LIB}/vndk-sp${VNDK_VER}
-namespace.rs.search.paths += /vendor/${LIB}/vndk-sp${VNDK_VER}
-namespace.rs.search.paths += /system/${LIB}/vndk-sp${VNDK_VER}
+namespace.rs.search.paths  = /odm/${LIB}/vndk-sp
+namespace.rs.search.paths += /vendor/${LIB}/vndk-sp
+namespace.rs.search.paths += /system/${LIB}/vndk-sp%VNDK_VER%
 namespace.rs.search.paths += /odm/${LIB}
 namespace.rs.search.paths += /vendor/${LIB}
 
@@ -136,12 +136,12 @@
 namespace.rs.permitted.paths += /vendor/${LIB}
 namespace.rs.permitted.paths += /data
 
-namespace.rs.asan.search.paths  = /data/asan/odm/${LIB}/vndk-sp${VNDK_VER}
-namespace.rs.asan.search.paths +=           /odm/${LIB}/vndk-sp${VNDK_VER}
-namespace.rs.asan.search.paths += /data/asan/vendor/${LIB}/vndk-sp${VNDK_VER}
-namespace.rs.asan.search.paths +=           /vendor/${LIB}/vndk-sp${VNDK_VER}
-namespace.rs.asan.search.paths += /data/asan/system/${LIB}/vndk-sp${VNDK_VER}
-namespace.rs.asan.search.paths +=           /system/${LIB}/vndk-sp${VNDK_VER}
+namespace.rs.asan.search.paths  = /data/asan/odm/${LIB}/vndk-sp
+namespace.rs.asan.search.paths +=           /odm/${LIB}/vndk-sp
+namespace.rs.asan.search.paths += /data/asan/vendor/${LIB}/vndk-sp
+namespace.rs.asan.search.paths +=           /vendor/${LIB}/vndk-sp
+namespace.rs.asan.search.paths += /data/asan/system/${LIB}/vndk-sp%VNDK_VER%
+namespace.rs.asan.search.paths +=           /system/${LIB}/vndk-sp%VNDK_VER%
 namespace.rs.asan.search.paths += /data/asan/odm/${LIB}
 namespace.rs.asan.search.paths +=           /odm/${LIB}
 namespace.rs.asan.search.paths += /data/asan/vendor/${LIB}
@@ -196,21 +196,21 @@
 namespace.vndk.isolated = true
 namespace.vndk.visible = true
 
-namespace.vndk.search.paths  = /odm/${LIB}/vndk-sp${VNDK_VER}
-namespace.vndk.search.paths += /vendor/${LIB}/vndk-sp${VNDK_VER}
-namespace.vndk.search.paths += /system/${LIB}/vndk-sp${VNDK_VER}
+namespace.vndk.search.paths  = /odm/${LIB}/vndk-sp
+namespace.vndk.search.paths += /vendor/${LIB}/vndk-sp
+namespace.vndk.search.paths += /system/${LIB}/vndk-sp%VNDK_VER%
 
 namespace.vndk.permitted.paths  = /odm/${LIB}/hw
 namespace.vndk.permitted.paths += /odm/${LIB}/egl
 namespace.vndk.permitted.paths += /vendor/${LIB}/hw
 namespace.vndk.permitted.paths += /vendor/${LIB}/egl
 
-namespace.vndk.asan.search.paths  = /data/asan/odm/${LIB}/vndk-sp${VNDK_VER}
-namespace.vndk.asan.search.paths +=           /odm/${LIB}/vndk-sp${VNDK_VER}
-namespace.vndk.asan.search.paths += /data/asan/vendor/${LIB}/vndk-sp${VNDK_VER}
-namespace.vndk.asan.search.paths +=           /vendor/${LIB}/vndk-sp${VNDK_VER}
-namespace.vndk.asan.search.paths += /data/asan/system/${LIB}/vndk-sp${VNDK_VER}
-namespace.vndk.asan.search.paths +=           /system/${LIB}/vndk-sp${VNDK_VER}
+namespace.vndk.asan.search.paths  = /data/asan/odm/${LIB}/vndk-sp
+namespace.vndk.asan.search.paths +=           /odm/${LIB}/vndk-sp
+namespace.vndk.asan.search.paths += /data/asan/vendor/${LIB}/vndk-sp
+namespace.vndk.asan.search.paths +=           /vendor/${LIB}/vndk-sp
+namespace.vndk.asan.search.paths += /data/asan/system/${LIB}/vndk-sp%VNDK_VER%
+namespace.vndk.asan.search.paths +=           /system/${LIB}/vndk-sp%VNDK_VER%
 
 namespace.vndk.asan.permitted.paths  = /data/asan/odm/${LIB}/hw
 namespace.vndk.asan.permitted.paths +=           /odm/${LIB}/hw
@@ -247,43 +247,32 @@
 namespace.default.isolated = false
 
 namespace.default.search.paths  = /odm/${LIB}
-namespace.default.search.paths += /odm/${LIB}/vndk${VNDK_VER}
-namespace.default.search.paths += /odm/${LIB}/vndk-sp${VNDK_VER}
+namespace.default.search.paths += /odm/${LIB}/vndk
+namespace.default.search.paths += /odm/${LIB}/vndk-sp
 namespace.default.search.paths += /vendor/${LIB}
-namespace.default.search.paths += /vendor/${LIB}/vndk${VNDK_VER}
-namespace.default.search.paths += /vendor/${LIB}/vndk-sp${VNDK_VER}
+namespace.default.search.paths += /vendor/${LIB}/vndk
+namespace.default.search.paths += /vendor/${LIB}/vndk-sp
 
 # Access to system libraries are allowed
-namespace.default.search.paths += /system/${LIB}/vndk${VNDK_VER}
-namespace.default.search.paths += /system/${LIB}/vndk-sp${VNDK_VER}
+namespace.default.search.paths += /system/${LIB}/vndk%VNDK_VER%
+namespace.default.search.paths += /system/${LIB}/vndk-sp%VNDK_VER%
 namespace.default.search.paths += /system/${LIB}
 
-# TODO(b/70551668) Remove /vendor/${LIB}/hw from search paths.
-# Shared libraries in the directory should be dlopened with full file paths.
-# This is a workaround for some legacy prebuilt binaries.
-namespace.default.search.paths += /vendor/${LIB}/hw
-
-namespace.default.asan.search.paths += /data/asan/odm/${LIB}
+namespace.default.asan.search.paths  = /data/asan/odm/${LIB}
 namespace.default.asan.search.paths +=           /odm/${LIB}
-namespace.default.asan.search.paths += /data/asan/odm/${LIB}/vndk${VNDK_VER}
-namespace.default.asan.search.paths +=           /odm/${LIB}/vndk${VNDK_VER}
-namespace.default.asan.search.paths += /data/asan/odm/${LIB}/vndk-sp${VNDK_VER}
-namespace.default.asan.search.paths +=           /odm/${LIB}/vndk-sp${VNDK_VER}
+namespace.default.asan.search.paths += /data/asan/odm/${LIB}/vndk
+namespace.default.asan.search.paths +=           /odm/${LIB}/vndk
+namespace.default.asan.search.paths += /data/asan/odm/${LIB}/vndk-sp
+namespace.default.asan.search.paths +=           /odm/${LIB}/vndk-sp
 namespace.default.asan.search.paths += /data/asan/vendor/${LIB}
 namespace.default.asan.search.paths +=           /vendor/${LIB}
-namespace.default.asan.search.paths += /data/asan/vendor/${LIB}/vndk${VNDK_VER}
-namespace.default.asan.search.paths +=           /vendor/${LIB}/vndk${VNDK_VER}
-namespace.default.asan.search.paths += /data/asan/vendor/${LIB}/vndk-sp${VNDK_VER}
-namespace.default.asan.search.paths +=           /vendor/${LIB}/vndk-sp${VNDK_VER}
-namespace.default.asan.search.paths += /data/asan/system/${LIB}/vndk${VNDK_VER}
-namespace.default.asan.search.paths +=           /system/${LIB}/vndk${VNDK_VER}
-namespace.default.asan.search.paths += /data/asan/system/${LIB}/vndk-sp${VNDK_VER}
-namespace.default.asan.search.paths +=           /system/${LIB}/vndk-sp${VNDK_VER}
+namespace.default.asan.search.paths += /data/asan/vendor/${LIB}/vndk
+namespace.default.asan.search.paths +=           /vendor/${LIB}/vndk
+namespace.default.asan.search.paths += /data/asan/vendor/${LIB}/vndk-sp
+namespace.default.asan.search.paths +=           /vendor/${LIB}/vndk-sp
+namespace.default.asan.search.paths += /data/asan/system/${LIB}/vndk%VNDK_VER%
+namespace.default.asan.search.paths +=           /system/${LIB}/vndk%VNDK_VER%
+namespace.default.asan.search.paths += /data/asan/system/${LIB}/vndk-sp%VNDK_VER%
+namespace.default.asan.search.paths +=           /system/${LIB}/vndk-sp%VNDK_VER%
 namespace.default.asan.search.paths += /data/asan/system/${LIB}
 namespace.default.asan.search.paths +=           /system/${LIB}
-
-# TODO(b/70551668) Remove /vendor/${LIB}/hw from search paths.
-# Shared libraries in the directory should be dlopened with full file paths.
-# This is a workaround for some legacy prebuilt binaries.
-namespace.default.asan.search.paths += /data/asan/vendor/${LIB}/hw
-namespace.default.asan.search.paths +=           /vendor/${LIB}/hw
diff --git a/rootdir/etc/ld.config.txt.in b/rootdir/etc/ld.config.txt.in
index 0e43de7..cad09c3 100644
--- a/rootdir/etc/ld.config.txt.in
+++ b/rootdir/etc/ld.config.txt.in
@@ -129,9 +129,9 @@
 namespace.rs.isolated = true
 namespace.rs.visible = true
 
-namespace.rs.search.paths  = /odm/${LIB}/vndk-sp${VNDK_VER}
-namespace.rs.search.paths += /vendor/${LIB}/vndk-sp${VNDK_VER}
-namespace.rs.search.paths += /system/${LIB}/vndk-sp${VNDK_VER}
+namespace.rs.search.paths  = /odm/${LIB}/vndk-sp
+namespace.rs.search.paths += /vendor/${LIB}/vndk-sp
+namespace.rs.search.paths += /system/${LIB}/vndk-sp%VNDK_VER%
 namespace.rs.search.paths += /odm/${LIB}
 namespace.rs.search.paths += /vendor/${LIB}
 
@@ -139,12 +139,12 @@
 namespace.rs.permitted.paths += /vendor/${LIB}
 namespace.rs.permitted.paths += /data
 
-namespace.rs.asan.search.paths  = /data/asan/odm/${LIB}/vndk-sp${VNDK_VER}
-namespace.rs.asan.search.paths +=           /odm/${LIB}/vndk-sp${VNDK_VER}
-namespace.rs.asan.search.paths += /data/asan/vendor/${LIB}/vndk-sp${VNDK_VER}
-namespace.rs.asan.search.paths +=           /vendor/${LIB}/vndk-sp${VNDK_VER}
-namespace.rs.asan.search.paths += /data/asan/system/${LIB}/vndk-sp${VNDK_VER}
-namespace.rs.asan.search.paths +=           /system/${LIB}/vndk-sp${VNDK_VER}
+namespace.rs.asan.search.paths  = /data/asan/odm/${LIB}/vndk-sp
+namespace.rs.asan.search.paths +=           /odm/${LIB}/vndk-sp
+namespace.rs.asan.search.paths += /data/asan/vendor/${LIB}/vndk-sp
+namespace.rs.asan.search.paths +=           /vendor/${LIB}/vndk-sp
+namespace.rs.asan.search.paths += /data/asan/system/${LIB}/vndk-sp%VNDK_VER%
+namespace.rs.asan.search.paths +=           /system/${LIB}/vndk-sp%VNDK_VER%
 namespace.rs.asan.search.paths += /data/asan/odm/${LIB}
 namespace.rs.asan.search.paths +=           /odm/${LIB}
 namespace.rs.asan.search.paths += /data/asan/vendor/${LIB}
@@ -174,23 +174,23 @@
 namespace.vndk.isolated = true
 namespace.vndk.visible = true
 
-namespace.vndk.search.paths  = /odm/${LIB}/vndk-sp${VNDK_VER}
-namespace.vndk.search.paths += /vendor/${LIB}/vndk-sp${VNDK_VER}
-namespace.vndk.search.paths += /system/${LIB}/vndk-sp${VNDK_VER}
+namespace.vndk.search.paths  = /odm/${LIB}/vndk-sp
+namespace.vndk.search.paths += /vendor/${LIB}/vndk-sp
+namespace.vndk.search.paths += /system/${LIB}/vndk-sp%VNDK_VER%
 
 namespace.vndk.permitted.paths  = /odm/${LIB}/hw
 namespace.vndk.permitted.paths += /odm/${LIB}/egl
 namespace.vndk.permitted.paths += /vendor/${LIB}/hw
 namespace.vndk.permitted.paths += /vendor/${LIB}/egl
 # This is exceptionally required since android.hidl.memory@1.0-impl.so is here
-namespace.vndk.permitted.paths += /system/${LIB}/vndk-sp${VNDK_VER}/hw
+namespace.vndk.permitted.paths += /system/${LIB}/vndk-sp%VNDK_VER%/hw
 
-namespace.vndk.asan.search.paths  = /data/asan/odm/${LIB}/vndk-sp${VNDK_VER}
-namespace.vndk.asan.search.paths +=           /odm/${LIB}/vndk-sp${VNDK_VER}
-namespace.vndk.asan.search.paths += /data/asan/vendor/${LIB}/vndk-sp${VNDK_VER}
-namespace.vndk.asan.search.paths +=           /vendor/${LIB}/vndk-sp${VNDK_VER}
-namespace.vndk.asan.search.paths += /data/asan/system/${LIB}/vndk-sp${VNDK_VER}
-namespace.vndk.asan.search.paths +=           /system/${LIB}/vndk-sp${VNDK_VER}
+namespace.vndk.asan.search.paths  = /data/asan/odm/${LIB}/vndk-sp
+namespace.vndk.asan.search.paths +=           /odm/${LIB}/vndk-sp
+namespace.vndk.asan.search.paths += /data/asan/vendor/${LIB}/vndk-sp
+namespace.vndk.asan.search.paths +=           /vendor/${LIB}/vndk-sp
+namespace.vndk.asan.search.paths += /data/asan/system/${LIB}/vndk-sp%VNDK_VER%
+namespace.vndk.asan.search.paths +=           /system/${LIB}/vndk-sp%VNDK_VER%
 
 namespace.vndk.asan.permitted.paths  = /data/asan/odm/${LIB}/hw
 namespace.vndk.asan.permitted.paths +=           /odm/${LIB}/hw
@@ -201,8 +201,8 @@
 namespace.vndk.asan.permitted.paths += /data/asan/vendor/${LIB}/egl
 namespace.vndk.asan.permitted.paths +=           /vendor/${LIB}/egl
 
-namespace.vndk.asan.permitted.paths += /data/asan/system/${LIB}/vndk-sp${VNDK_VER}/hw
-namespace.vndk.asan.permitted.paths +=           /system/${LIB}/vndk-sp${VNDK_VER}/hw
+namespace.vndk.asan.permitted.paths += /data/asan/system/${LIB}/vndk-sp%VNDK_VER%/hw
+namespace.vndk.asan.permitted.paths +=           /system/${LIB}/vndk-sp%VNDK_VER%/hw
 
 # When these NDK libs are required inside this namespace, then it is redirected
 # to the default namespace. This is possible since their ABI is stable across
@@ -218,7 +218,7 @@
 # (LL-NDK only) access.
 ###############################################################################
 [vendor]
-additional.namespaces = system
+additional.namespaces = system,vndk
 
 ###############################################################################
 # "default" namespace
@@ -234,44 +234,60 @@
 namespace.default.visible = true
 
 namespace.default.search.paths  = /odm/${LIB}
-namespace.default.search.paths += /odm/${LIB}/vndk${VNDK_VER}
-namespace.default.search.paths += /odm/${LIB}/vndk-sp${VNDK_VER}
+namespace.default.search.paths += /odm/${LIB}/vndk
+namespace.default.search.paths += /odm/${LIB}/vndk-sp
 namespace.default.search.paths += /vendor/${LIB}
-namespace.default.search.paths += /vendor/${LIB}/vndk${VNDK_VER}
-namespace.default.search.paths += /vendor/${LIB}/vndk-sp${VNDK_VER}
-
-# TODO(b/70551668) remove this
-namespace.default.search.paths += /vendor/${LIB}/hw
+namespace.default.search.paths += /vendor/${LIB}/vndk
+namespace.default.search.paths += /vendor/${LIB}/vndk-sp
 
 namespace.default.permitted.paths  = /odm
 namespace.default.permitted.paths += /vendor
 
 namespace.default.asan.search.paths  = /data/asan/odm/${LIB}
 namespace.default.asan.search.paths +=           /odm/${LIB}
-namespace.default.asan.search.paths += /data/asan/odm/${LIB}/vndk${VNDK_VER}
-namespace.default.asan.search.paths +=           /odm/${LIB}/vndk${VNDK_VER}
-namespace.default.asan.search.paths += /data/asan/odm/${LIB}/vndk-sp${VNDK_VER}
-namespace.default.asan.search.paths +=           /odm/${LIB}/vndk-sp${VNDK_VER}
+namespace.default.asan.search.paths += /data/asan/odm/${LIB}/vndk
+namespace.default.asan.search.paths +=           /odm/${LIB}/vndk
+namespace.default.asan.search.paths += /data/asan/odm/${LIB}/vndk-sp
+namespace.default.asan.search.paths +=           /odm/${LIB}/vndk-sp
 namespace.default.asan.search.paths += /data/asan/vendor/${LIB}
 namespace.default.asan.search.paths +=           /vendor/${LIB}
-namespace.default.asan.search.paths += /data/asan/vendor/${LIB}/vndk${VNDK_VER}
-namespace.default.asan.search.paths +=           /vendor/${LIB}/vndk${VNDK_VER}
-namespace.default.asan.search.paths += /data/asan/vendor/${LIB}/vndk-sp${VNDK_VER}
-namespace.default.asan.search.paths +=           /vendor/${LIB}/vndk-sp${VNDK_VER}
-
-# TODO(b/70551668) remove this
-namespace.default.asan.search.paths += /data/asan/vendor/${LIB}/hw
-namespace.default.asan.search.paths +=           /vendor/${LIB}/hw
+namespace.default.asan.search.paths += /data/asan/vendor/${LIB}/vndk
+namespace.default.asan.search.paths +=           /vendor/${LIB}/vndk
+namespace.default.asan.search.paths += /data/asan/vendor/${LIB}/vndk-sp
+namespace.default.asan.search.paths +=           /vendor/${LIB}/vndk-sp
 
 namespace.default.asan.permitted.paths  = /data/asan/odm
 namespace.default.asan.permitted.paths +=           /odm
 namespace.default.asan.permitted.paths += /data/asan/vendor
 namespace.default.asan.permitted.paths +=           /vendor
 
-namespace.default.links = system
-namespace.default.link.system.shared_libs  = %LLNDK_LIBRARIES%
-namespace.default.link.system.shared_libs += %VNDK_SAMEPROCESS_LIBRARIES%
-namespace.default.link.system.shared_libs += %VNDK_CORE_LIBRARIES%
+namespace.default.links = system,vndk
+namespace.default.link.system.shared_libs = %LLNDK_LIBRARIES%
+namespace.default.link.vndk.shared_libs  = %VNDK_SAMEPROCESS_LIBRARIES%
+namespace.default.link.vndk.shared_libs += %VNDK_CORE_LIBRARIES%
+
+###############################################################################
+# "vndk" namespace
+#
+# This namespace is where VNDK and VNDK-SP libraries are loaded for
+# a vendor process.
+###############################################################################
+namespace.vndk.isolated = false
+
+namespace.vndk.search.paths  = /system/${LIB}/vndk-sp%VNDK_VER%
+namespace.vndk.search.paths += /system/${LIB}/vndk%VNDK_VER%
+
+namespace.vndk.asan.search.paths  = /data/asan/system/${LIB}/vndk-sp%VNDK_VER%
+namespace.vndk.asan.search.paths +=           /system/${LIB}/vndk-sp%VNDK_VER%
+namespace.vndk.asan.search.paths += /data/asan/system/${LIB}/vndk%VNDK_VER%
+namespace.vndk.asan.search.paths +=           /system/${LIB}/vndk%VNDK_VER%
+
+# When these NDK libs are required inside this namespace, then it is redirected
+# to the system namespace. This is possible since their ABI is stable across
+# Android releases.
+namespace.vndk.links = system
+namespace.vndk.link.system.shared_libs  = %LLNDK_LIBRARIES%
+namespace.vndk.link.system.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
 
 ###############################################################################
 # "system" namespace
@@ -281,13 +297,7 @@
 ###############################################################################
 namespace.system.isolated = false
 
-namespace.system.search.paths  = /system/${LIB}/vndk-sp${VNDK_VER}
-namespace.system.search.paths += /system/${LIB}/vndk${VNDK_VER}
-namespace.system.search.paths += /system/${LIB}
+namespace.system.search.paths = /system/${LIB}
 
-namespace.system.asan.search.paths  = /data/asan/system/${LIB}/vndk-sp${VNDK_VER}
-namespace.system.asan.search.paths +=           /system/${LIB}/vndk-sp${VNDK_VER}
-namespace.system.asan.search.paths += /data/asan/system/${LIB}/vndk${VNDK_VER}
-namespace.system.asan.search.paths +=           /system/${LIB}/vndk${VNDK_VER}
-namespace.system.asan.search.paths += /data/asan/system/${LIB}
+namespace.system.asan.search.paths  = /data/asan/system/${LIB}
 namespace.system.asan.search.paths +=           /system/${LIB}
diff --git a/rootdir/init.rc b/rootdir/init.rc
index bdd75af..d02cb9d 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -218,6 +218,12 @@
     # This is needed by any process that uses socket tagging.
     chmod 0644 /dev/xt_qtaguid
 
+    mkdir /dev/cg2_bpf
+    mount cgroup2 cg2_bpf /dev/cg2_bpf
+    chown root root /dev/cg2_bpf
+    chmod 0600 /dev/cg2_bpf
+    mount bpf bpf /sys/fs/bpf
+
     # Create location for fs_mgr to store abbreviated output from filesystem
     # checker programs.
     mkdir /dev/fscklogs 0770 root system
@@ -416,6 +422,7 @@
     mkdir /data/misc/sms 0770 system radio
     mkdir /data/misc/carrierid 0770 system radio
     mkdir /data/misc/zoneinfo 0775 system system
+    mkdir /data/misc/network_watchlist 0774 system system
     mkdir /data/misc/textclassifier 0771 system system
     mkdir /data/misc/vpn 0770 system vpn
     mkdir /data/misc/shared_relro 0771 shared_relro shared_relro
@@ -461,6 +468,8 @@
     mkdir /data/app 0771 system system
     mkdir /data/property 0700 root root
     mkdir /data/tombstones 0771 system system
+    mkdir /data/vendor/tombstones 0771 root root
+    mkdir /data/vendor/tombstones/wifi 0771 wifi wifi
 
     # create dalvik-cache, so as to enforce our permissions
     mkdir /data/dalvik-cache 0771 root root
diff --git a/rootdir/init.zygote32.rc b/rootdir/init.zygote32.rc
index d836c4e..ac87979 100644
--- a/rootdir/init.zygote32.rc
+++ b/rootdir/init.zygote32.rc
@@ -2,7 +2,7 @@
     class main
     priority -20
     user root
-    group root readproc
+    group root readproc reserved_disk
     socket zygote stream 660 root system
     onrestart write /sys/android_power/request_state wake
     onrestart write /sys/power/state on
diff --git a/rootdir/init.zygote32_64.rc b/rootdir/init.zygote32_64.rc
index 80bb673..a535846 100644
--- a/rootdir/init.zygote32_64.rc
+++ b/rootdir/init.zygote32_64.rc
@@ -2,7 +2,7 @@
     class main
     priority -20
     user root
-    group root readproc
+    group root readproc reserved_disk
     socket zygote stream 660 root system
     onrestart write /sys/android_power/request_state wake
     onrestart write /sys/power/state on
@@ -17,7 +17,7 @@
     class main
     priority -20
     user root
-    group root readproc
+    group root readproc reserved_disk
     socket zygote_secondary stream 660 root system
     onrestart restart zygote
     writepid /dev/cpuset/foreground/tasks
diff --git a/rootdir/init.zygote64.rc b/rootdir/init.zygote64.rc
index 05ec16f..6fc810b 100644
--- a/rootdir/init.zygote64.rc
+++ b/rootdir/init.zygote64.rc
@@ -2,7 +2,7 @@
     class main
     priority -20
     user root
-    group root readproc
+    group root readproc reserved_disk
     socket zygote stream 660 root system
     onrestart write /sys/android_power/request_state wake
     onrestart write /sys/power/state on
diff --git a/rootdir/init.zygote64_32.rc b/rootdir/init.zygote64_32.rc
index 09db7b0..7ddd52e 100644
--- a/rootdir/init.zygote64_32.rc
+++ b/rootdir/init.zygote64_32.rc
@@ -2,7 +2,7 @@
     class main
     priority -20
     user root
-    group root readproc
+    group root readproc reserved_disk
     socket zygote stream 660 root system
     onrestart write /sys/android_power/request_state wake
     onrestart write /sys/power/state on
@@ -17,7 +17,7 @@
     class main
     priority -20
     user root
-    group root readproc
+    group root readproc reserved_disk
     socket zygote_secondary stream 660 root system
     onrestart restart zygote
     writepid /dev/cpuset/foreground/tasks
diff --git a/rootdir/ueventd.rc b/rootdir/ueventd.rc
index eadf219..b03d83b 100644
--- a/rootdir/ueventd.rc
+++ b/rootdir/ueventd.rc
@@ -77,6 +77,7 @@
 /dev/graphics/*           0660   root       graphics
 /dev/msm_hw3dm            0660   system     graphics
 /dev/input/*              0660   root       input
+/dev/v4l-touch*           0660   root       input
 /dev/eac                  0660   root       audio
 /dev/cam                  0660   root       camera
 /dev/pmem                 0660   system     graphics
diff --git a/sdcard/Android.bp b/sdcard/Android.bp
new file mode 100644
index 0000000..c096587
--- /dev/null
+++ b/sdcard/Android.bp
@@ -0,0 +1,17 @@
+cc_binary {
+    srcs: ["sdcard.cpp"],
+    name: "sdcard",
+    cflags: [
+        "-Wall",
+        "-Wno-unused-parameter",
+        "-Werror",
+    ],
+    shared_libs: [
+        "libbase",
+        "libcutils",
+        "libminijail",
+    ],
+    sanitize: {
+        misc_undefined: ["integer"],
+    },
+}
diff --git a/sdcard/Android.mk b/sdcard/Android.mk
deleted file mode 100644
index 5b4dc58..0000000
--- a/sdcard/Android.mk
+++ /dev/null
@@ -1,12 +0,0 @@
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := sdcard.cpp fuse.cpp
-LOCAL_MODULE := sdcard
-LOCAL_CFLAGS := -Wall -Wno-unused-parameter -Werror
-LOCAL_SHARED_LIBRARIES := libbase libcutils libminijail libpackagelistparser
-
-LOCAL_SANITIZE := integer
-
-include $(BUILD_EXECUTABLE)
diff --git a/sdcard/fuse.cpp b/sdcard/fuse.cpp
deleted file mode 100644
index 10d0f04..0000000
--- a/sdcard/fuse.cpp
+++ /dev/null
@@ -1,1476 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <errno.h>
-#include <string.h>
-#include <unistd.h>
-
-#define LOG_TAG "sdcard"
-
-#include "fuse.h"
-
-#include <android-base/logging.h>
-
-/* FUSE_CANONICAL_PATH is not currently upstreamed */
-#define FUSE_CANONICAL_PATH 2016
-
-#define FUSE_UNKNOWN_INO 0xffffffff
-
-/* Pseudo-error constant used to indicate that no fuse status is needed
- * or that a reply has already been written. */
-#define NO_STATUS 1
-
-static inline void *id_to_ptr(__u64 nid)
-{
-    return (void *) (uintptr_t) nid;
-}
-
-static inline __u64 ptr_to_id(void *ptr)
-{
-    return (__u64) (uintptr_t) ptr;
-}
-
-static void acquire_node_locked(struct node* node)
-{
-    node->refcount++;
-    DLOG(INFO) << "ACQUIRE " << std::hex << node << std::dec
-               << " (" << node->name << ") rc=" << node->refcount;
-}
-
-static void remove_node_from_parent_locked(struct node* node);
-
-static void release_node_locked(struct node* node)
-{
-    DLOG(INFO) << "RELEASE " << std::hex << node << std::dec
-               << " (" << node->name << ") rc=" << node->refcount;
-    if (node->refcount > 0) {
-        node->refcount--;
-        if (!node->refcount) {
-            DLOG(INFO) << "DESTROY " << std::hex << node << std::dec << " (" << node->name << ")";
-            remove_node_from_parent_locked(node);
-
-            /* TODO: remove debugging - poison memory */
-            memset(node->name, 0xef, node->namelen);
-            free(node->name);
-            free(node->actual_name);
-            memset(node, 0xfc, sizeof(*node));
-            free(node);
-        }
-    } else {
-        LOG(ERROR) << std::hex << node << std::dec << " refcount=0";
-    }
-}
-
-static void add_node_to_parent_locked(struct node *node, struct node *parent) {
-    node->parent = parent;
-    node->next = parent->child;
-    parent->child = node;
-    acquire_node_locked(parent);
-}
-
-static void remove_node_from_parent_locked(struct node* node)
-{
-    if (node->parent) {
-        if (node->parent->child == node) {
-            node->parent->child = node->parent->child->next;
-        } else {
-            struct node *node2;
-            node2 = node->parent->child;
-            while (node2->next != node)
-                node2 = node2->next;
-            node2->next = node->next;
-        }
-        release_node_locked(node->parent);
-        node->parent = NULL;
-        node->next = NULL;
-    }
-}
-
-/* Gets the absolute path to a node into the provided buffer.
- *
- * Populates 'buf' with the path and returns the length of the path on success,
- * or returns -1 if the path is too long for the provided buffer.
- */
-static ssize_t get_node_path_locked(struct node* node, char* buf, size_t bufsize) {
-    const char* name;
-    size_t namelen;
-    if (node->graft_path) {
-        name = node->graft_path;
-        namelen = node->graft_pathlen;
-    } else if (node->actual_name) {
-        name = node->actual_name;
-        namelen = node->namelen;
-    } else {
-        name = node->name;
-        namelen = node->namelen;
-    }
-
-    if (bufsize < namelen + 1) {
-        return -1;
-    }
-
-    ssize_t pathlen = 0;
-    if (node->parent && node->graft_path == NULL) {
-        pathlen = get_node_path_locked(node->parent, buf, bufsize - namelen - 1);
-        if (pathlen < 0) {
-            return -1;
-        }
-        buf[pathlen++] = '/';
-    }
-
-    memcpy(buf + pathlen, name, namelen + 1); /* include trailing \0 */
-    return pathlen + namelen;
-}
-
-/* Finds the absolute path of a file within a given directory.
- * Performs a case-insensitive search for the file and sets the buffer to the path
- * of the first matching file.  If 'search' is zero or if no match is found, sets
- * the buffer to the path that the file would have, assuming the name were case-sensitive.
- *
- * Populates 'buf' with the path and returns the actual name (within 'buf') on success,
- * or returns NULL if the path is too long for the provided buffer.
- */
-static char* find_file_within(const char* path, const char* name,
-        char* buf, size_t bufsize, int search)
-{
-    size_t pathlen = strlen(path);
-    size_t namelen = strlen(name);
-    size_t childlen = pathlen + namelen + 1;
-    char* actual;
-
-    if (bufsize <= childlen) {
-        return NULL;
-    }
-
-    memcpy(buf, path, pathlen);
-    buf[pathlen] = '/';
-    actual = buf + pathlen + 1;
-    memcpy(actual, name, namelen + 1);
-
-    if (search && access(buf, F_OK)) {
-        struct dirent* entry;
-        DIR* dir = opendir(path);
-        if (!dir) {
-            PLOG(ERROR) << "opendir(" << path << ") failed";
-            return actual;
-        }
-        while ((entry = readdir(dir))) {
-            if (!strcasecmp(entry->d_name, name)) {
-                /* we have a match - replace the name, don't need to copy the null again */
-                memcpy(actual, entry->d_name, namelen);
-                break;
-            }
-        }
-        closedir(dir);
-    }
-    return actual;
-}
-
-static void attr_from_stat(struct fuse* fuse, struct fuse_attr *attr,
-        const struct stat *s, const struct node* node) {
-    attr->ino = node->ino;
-    attr->size = s->st_size;
-    attr->blocks = s->st_blocks;
-    attr->atime = s->st_atim.tv_sec;
-    attr->mtime = s->st_mtim.tv_sec;
-    attr->ctime = s->st_ctim.tv_sec;
-    attr->atimensec = s->st_atim.tv_nsec;
-    attr->mtimensec = s->st_mtim.tv_nsec;
-    attr->ctimensec = s->st_ctim.tv_nsec;
-    attr->mode = s->st_mode;
-    attr->nlink = s->st_nlink;
-
-    attr->uid = node->uid;
-
-    if (fuse->gid == AID_SDCARD_RW) {
-        /* As an optimization, certain trusted system components only run
-         * as owner but operate across all users. Since we're now handing
-         * out the sdcard_rw GID only to trusted apps, we're okay relaxing
-         * the user boundary enforcement for the default view. The UIDs
-         * assigned to app directories are still multiuser aware. */
-        attr->gid = AID_SDCARD_RW;
-    } else {
-        attr->gid = multiuser_get_uid(node->userid, fuse->gid);
-    }
-
-    int visible_mode = 0775 & ~fuse->mask;
-    if (node->perm == PERM_PRE_ROOT) {
-        /* Top of multi-user view should always be visible to ensure
-         * secondary users can traverse inside. */
-        visible_mode = 0711;
-    } else if (node->under_android) {
-        /* Block "other" access to Android directories, since only apps
-         * belonging to a specific user should be in there; we still
-         * leave +x open for the default view. */
-        if (fuse->gid == AID_SDCARD_RW) {
-            visible_mode = visible_mode & ~0006;
-        } else {
-            visible_mode = visible_mode & ~0007;
-        }
-    }
-    int owner_mode = s->st_mode & 0700;
-    int filtered_mode = visible_mode & (owner_mode | (owner_mode >> 3) | (owner_mode >> 6));
-    attr->mode = (attr->mode & S_IFMT) | filtered_mode;
-}
-
-static int touch(char* path, mode_t mode) {
-    int fd = TEMP_FAILURE_RETRY(open(path, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC,
-                                     mode));
-    if (fd == -1) {
-        if (errno == EEXIST) {
-            return 0;
-        } else {
-            PLOG(ERROR) << "open(" << path << ") failed";
-            return -1;
-        }
-    }
-    close(fd);
-    return 0;
-}
-
-static void derive_permissions_locked(struct fuse* fuse, struct node *parent,
-        struct node *node) {
-    appid_t appid;
-
-    /* By default, each node inherits from its parent */
-    node->perm = PERM_INHERIT;
-    node->userid = parent->userid;
-    node->uid = parent->uid;
-    node->under_android = parent->under_android;
-
-    /* Derive custom permissions based on parent and current node */
-    switch (parent->perm) {
-    case PERM_INHERIT:
-        /* Already inherited above */
-        break;
-    case PERM_PRE_ROOT:
-        /* Legacy internal layout places users at top level */
-        node->perm = PERM_ROOT;
-        node->userid = strtoul(node->name, NULL, 10);
-        break;
-    case PERM_ROOT:
-        /* Assume masked off by default. */
-        if (!strcasecmp(node->name, "Android")) {
-            /* App-specific directories inside; let anyone traverse */
-            node->perm = PERM_ANDROID;
-            node->under_android = true;
-        }
-        break;
-    case PERM_ANDROID:
-        if (!strcasecmp(node->name, "data")) {
-            /* App-specific directories inside; let anyone traverse */
-            node->perm = PERM_ANDROID_DATA;
-        } else if (!strcasecmp(node->name, "obb")) {
-            /* App-specific directories inside; let anyone traverse */
-            node->perm = PERM_ANDROID_OBB;
-            /* Single OBB directory is always shared */
-            node->graft_path = fuse->global->obb_path;
-            node->graft_pathlen = strlen(fuse->global->obb_path);
-        } else if (!strcasecmp(node->name, "media")) {
-            /* App-specific directories inside; let anyone traverse */
-            node->perm = PERM_ANDROID_MEDIA;
-        }
-        break;
-    case PERM_ANDROID_DATA:
-    case PERM_ANDROID_OBB:
-    case PERM_ANDROID_MEDIA:
-        const auto& iter = fuse->global->package_to_appid->find(node->name);
-        if (iter != fuse->global->package_to_appid->end()) {
-            appid = iter->second;
-            node->uid = multiuser_get_uid(parent->userid, appid);
-        }
-        break;
-    }
-}
-
-void derive_permissions_recursive_locked(struct fuse* fuse, struct node *parent) {
-    struct node *node;
-    for (node = parent->child; node; node = node->next) {
-        derive_permissions_locked(fuse, parent, node);
-        if (node->child) {
-            derive_permissions_recursive_locked(fuse, node);
-        }
-    }
-}
-
-/* Kernel has already enforced everything we returned through
- * derive_permissions_locked(), so this is used to lock down access
- * even further, such as enforcing that apps hold sdcard_rw. */
-static bool check_caller_access_to_name(struct fuse* fuse,
-        const struct fuse_in_header *hdr, const struct node* parent_node,
-        const char* name, int mode) {
-    /* Always block security-sensitive files at root */
-    if (parent_node && parent_node->perm == PERM_ROOT) {
-        if (!strcasecmp(name, "autorun.inf")
-                || !strcasecmp(name, ".android_secure")
-                || !strcasecmp(name, "android_secure")) {
-            return false;
-        }
-    }
-
-    /* Root always has access; access for any other UIDs should always
-     * be controlled through packages.list. */
-    if (hdr->uid == AID_ROOT) {
-        return true;
-    }
-
-    /* No extra permissions to enforce */
-    return true;
-}
-
-static bool check_caller_access_to_node(struct fuse* fuse,
-        const struct fuse_in_header *hdr, const struct node* node, int mode) {
-    return check_caller_access_to_name(fuse, hdr, node->parent, node->name, mode);
-}
-
-struct node *create_node_locked(struct fuse* fuse,
-        struct node *parent, const char *name, const char* actual_name)
-{
-    struct node *node;
-    size_t namelen = strlen(name);
-
-    // Detect overflows in the inode counter. "4 billion nodes should be enough
-    // for everybody".
-    if (fuse->global->inode_ctr == 0) {
-        LOG(ERROR) << "No more inode numbers available";
-        return NULL;
-    }
-
-    node = static_cast<struct node*>(calloc(1, sizeof(struct node)));
-    if (!node) {
-        return NULL;
-    }
-    node->name = static_cast<char*>(malloc(namelen + 1));
-    if (!node->name) {
-        free(node);
-        return NULL;
-    }
-    memcpy(node->name, name, namelen + 1);
-    if (strcmp(name, actual_name)) {
-        node->actual_name = static_cast<char*>(malloc(namelen + 1));
-        if (!node->actual_name) {
-            free(node->name);
-            free(node);
-            return NULL;
-        }
-        memcpy(node->actual_name, actual_name, namelen + 1);
-    }
-    node->namelen = namelen;
-    node->nid = ptr_to_id(node);
-    node->ino = fuse->global->inode_ctr++;
-    node->gen = fuse->global->next_generation++;
-
-    node->deleted = false;
-
-    derive_permissions_locked(fuse, parent, node);
-    acquire_node_locked(node);
-    add_node_to_parent_locked(node, parent);
-    return node;
-}
-
-static int rename_node_locked(struct node *node, const char *name,
-        const char* actual_name)
-{
-    size_t namelen = strlen(name);
-    int need_actual_name = strcmp(name, actual_name);
-
-    /* make the storage bigger without actually changing the name
-     * in case an error occurs part way */
-    if (namelen > node->namelen) {
-        char* new_name = static_cast<char*>(realloc(node->name, namelen + 1));
-        if (!new_name) {
-            return -ENOMEM;
-        }
-        node->name = new_name;
-        if (need_actual_name && node->actual_name) {
-            char* new_actual_name = static_cast<char*>(realloc(node->actual_name, namelen + 1));
-            if (!new_actual_name) {
-                return -ENOMEM;
-            }
-            node->actual_name = new_actual_name;
-        }
-    }
-
-    /* update the name, taking care to allocate storage before overwriting the old name */
-    if (need_actual_name) {
-        if (!node->actual_name) {
-            node->actual_name = static_cast<char*>(malloc(namelen + 1));
-            if (!node->actual_name) {
-                return -ENOMEM;
-            }
-        }
-        memcpy(node->actual_name, actual_name, namelen + 1);
-    } else {
-        free(node->actual_name);
-        node->actual_name = NULL;
-    }
-    memcpy(node->name, name, namelen + 1);
-    node->namelen = namelen;
-    return 0;
-}
-
-static struct node *lookup_node_by_id_locked(struct fuse *fuse, __u64 nid)
-{
-    if (nid == FUSE_ROOT_ID) {
-        return &fuse->global->root;
-    } else {
-        return static_cast<struct node*>(id_to_ptr(nid));
-    }
-}
-
-static struct node* lookup_node_and_path_by_id_locked(struct fuse* fuse, __u64 nid,
-        char* buf, size_t bufsize)
-{
-    struct node* node = lookup_node_by_id_locked(fuse, nid);
-    if (node && get_node_path_locked(node, buf, bufsize) < 0) {
-        node = NULL;
-    }
-    return node;
-}
-
-static struct node *lookup_child_by_name_locked(struct node *node, const char *name)
-{
-    for (node = node->child; node; node = node->next) {
-        /* use exact string comparison, nodes that differ by case
-         * must be considered distinct even if they refer to the same
-         * underlying file as otherwise operations such as "mv x x"
-         * will not work because the source and target nodes are the same. */
-        if (!strcmp(name, node->name) && !node->deleted) {
-            return node;
-        }
-    }
-    return 0;
-}
-
-static struct node* acquire_or_create_child_locked(
-        struct fuse* fuse, struct node* parent,
-        const char* name, const char* actual_name)
-{
-    struct node* child = lookup_child_by_name_locked(parent, name);
-    if (child) {
-        acquire_node_locked(child);
-    } else {
-        child = create_node_locked(fuse, parent, name, actual_name);
-    }
-    return child;
-}
-
-static void fuse_status(struct fuse *fuse, __u64 unique, int err)
-{
-    struct fuse_out_header hdr;
-    hdr.len = sizeof(hdr);
-    hdr.error = err;
-    hdr.unique = unique;
-    ssize_t ret = TEMP_FAILURE_RETRY(write(fuse->fd, &hdr, sizeof(hdr)));
-    if (ret == -1) {
-        PLOG(ERROR) << "*** STATUS FAILED ***";
-    } else if (static_cast<size_t>(ret) != sizeof(hdr)) {
-        LOG(ERROR) << "*** STATUS FAILED: written " << ret << " expected "
-                   << sizeof(hdr) << " ***";
-    }
-}
-
-static void fuse_reply(struct fuse *fuse, __u64 unique, void *data, int len)
-{
-    struct fuse_out_header hdr;
-    hdr.len = len + sizeof(hdr);
-    hdr.error = 0;
-    hdr.unique = unique;
-
-    struct iovec vec[2];
-    vec[0].iov_base = &hdr;
-    vec[0].iov_len = sizeof(hdr);
-    vec[1].iov_base = data;
-    vec[1].iov_len = len;
-
-    ssize_t ret = TEMP_FAILURE_RETRY(writev(fuse->fd, vec, 2));
-    if (ret == -1) {
-        PLOG(ERROR) << "*** REPLY FAILED ***";
-    } else if (static_cast<size_t>(ret) != sizeof(hdr) + len) {
-        LOG(ERROR) << "*** REPLY FAILED: written " << ret << " expected "
-                   << sizeof(hdr) + len << " ***";
-    }
-}
-
-static int fuse_reply_entry(struct fuse* fuse, __u64 unique,
-        struct node* parent, const char* name, const char* actual_name,
-        const char* path)
-{
-    struct node* node;
-    struct fuse_entry_out out;
-    struct stat s;
-
-    if (lstat(path, &s) == -1) {
-        return -errno;
-    }
-
-    pthread_mutex_lock(&fuse->global->lock);
-    node = acquire_or_create_child_locked(fuse, parent, name, actual_name);
-    if (!node) {
-        pthread_mutex_unlock(&fuse->global->lock);
-        return -ENOMEM;
-    }
-    memset(&out, 0, sizeof(out));
-    attr_from_stat(fuse, &out.attr, &s, node);
-    out.attr_valid = 10;
-    out.entry_valid = 10;
-    out.nodeid = node->nid;
-    out.generation = node->gen;
-    pthread_mutex_unlock(&fuse->global->lock);
-    fuse_reply(fuse, unique, &out, sizeof(out));
-    return NO_STATUS;
-}
-
-static int fuse_reply_attr(struct fuse* fuse, __u64 unique, const struct node* node,
-        const char* path)
-{
-    struct fuse_attr_out out;
-    struct stat s;
-
-    if (lstat(path, &s) == -1) {
-        return -errno;
-    }
-    memset(&out, 0, sizeof(out));
-    attr_from_stat(fuse, &out.attr, &s, node);
-    out.attr_valid = 10;
-    fuse_reply(fuse, unique, &out, sizeof(out));
-    return NO_STATUS;
-}
-
-static void fuse_notify_delete(struct fuse* fuse, const __u64 parent,
-        const __u64 child, const char* name) {
-    struct fuse_out_header hdr;
-    struct fuse_notify_delete_out data;
-    size_t namelen = strlen(name);
-    hdr.len = sizeof(hdr) + sizeof(data) + namelen + 1;
-    hdr.error = FUSE_NOTIFY_DELETE;
-    hdr.unique = 0;
-
-    data.parent = parent;
-    data.child = child;
-    data.namelen = namelen;
-    data.padding = 0;
-
-    struct iovec vec[3];
-    vec[0].iov_base = &hdr;
-    vec[0].iov_len = sizeof(hdr);
-    vec[1].iov_base = &data;
-    vec[1].iov_len = sizeof(data);
-    vec[2].iov_base = (void*) name;
-    vec[2].iov_len = namelen + 1;
-
-    ssize_t ret = TEMP_FAILURE_RETRY(writev(fuse->fd, vec, 3));
-    /* Ignore ENOENT, since other views may not have seen the entry */
-    if (ret == -1) {
-        if (errno != ENOENT) {
-            PLOG(ERROR) << "*** NOTIFY FAILED ***";
-        }
-    } else if (static_cast<size_t>(ret) != sizeof(hdr) + sizeof(data) + namelen + 1) {
-        LOG(ERROR) << "*** NOTIFY FAILED: written " << ret << " expected "
-                   << sizeof(hdr) + sizeof(data) + namelen + 1 << " ***";
-    }
-}
-
-static int handle_lookup(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header *hdr, const char* name)
-{
-    struct node* parent_node;
-    char parent_path[PATH_MAX];
-    char child_path[PATH_MAX];
-    const char* actual_name;
-
-    pthread_mutex_lock(&fuse->global->lock);
-    parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
-            parent_path, sizeof(parent_path));
-    DLOG(INFO) << "[" << handler->token << "] LOOKUP " << name << " @ " << hdr->nodeid
-               << " (" << (parent_node ? parent_node->name : "?") << ")";
-    pthread_mutex_unlock(&fuse->global->lock);
-
-    if (!parent_node || !(actual_name = find_file_within(parent_path, name,
-            child_path, sizeof(child_path), 1))) {
-        return -ENOENT;
-    }
-    if (!check_caller_access_to_name(fuse, hdr, parent_node, name, R_OK)) {
-        return -EACCES;
-    }
-
-    return fuse_reply_entry(fuse, hdr->unique, parent_node, name, actual_name, child_path);
-}
-
-static int handle_forget(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header *hdr, const struct fuse_forget_in *req)
-{
-    struct node* node;
-
-    pthread_mutex_lock(&fuse->global->lock);
-    node = lookup_node_by_id_locked(fuse, hdr->nodeid);
-    DLOG(INFO) << "[" << handler->token << "] FORGET #" << req->nlookup
-               << " @ " << std::hex << hdr->nodeid
-               << " (" << (node ? node->name : "?") << ")";
-    if (node) {
-        __u64 n = req->nlookup;
-        while (n) {
-            n--;
-            release_node_locked(node);
-        }
-    }
-    pthread_mutex_unlock(&fuse->global->lock);
-    return NO_STATUS; /* no reply */
-}
-
-static int handle_getattr(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header *hdr, const struct fuse_getattr_in *req)
-{
-    struct node* node;
-    char path[PATH_MAX];
-
-    pthread_mutex_lock(&fuse->global->lock);
-    node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid, path, sizeof(path));
-    DLOG(INFO) << "[" << handler->token << "] GETATTR flags=" << req->getattr_flags
-               << " fh=" << std::hex << req->fh << " @ " << hdr->nodeid << std::dec
-               << " (" << (node ? node->name : "?") << ")";
-    pthread_mutex_unlock(&fuse->global->lock);
-
-    if (!node) {
-        return -ENOENT;
-    }
-    if (!check_caller_access_to_node(fuse, hdr, node, R_OK)) {
-        return -EACCES;
-    }
-
-    return fuse_reply_attr(fuse, hdr->unique, node, path);
-}
-
-static int handle_setattr(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header *hdr, const struct fuse_setattr_in *req)
-{
-    struct node* node;
-    char path[PATH_MAX];
-    struct timespec times[2];
-
-    pthread_mutex_lock(&fuse->global->lock);
-    node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid, path, sizeof(path));
-    DLOG(INFO) << "[" << handler->token << "] SETATTR fh=" << std::hex << req->fh
-               << " valid=" << std::hex << req->valid << " @ " << hdr->nodeid << std::dec
-               << " (" << (node ? node->name : "?") << ")";
-    pthread_mutex_unlock(&fuse->global->lock);
-
-    if (!node) {
-        return -ENOENT;
-    }
-
-    if (!(req->valid & FATTR_FH) &&
-            !check_caller_access_to_node(fuse, hdr, node, W_OK)) {
-        return -EACCES;
-    }
-
-    /* XXX: incomplete implementation on purpose.
-     * chmod/chown should NEVER be implemented.*/
-
-    if ((req->valid & FATTR_SIZE) && TEMP_FAILURE_RETRY(truncate64(path, req->size)) == -1) {
-        return -errno;
-    }
-
-    /* Handle changing atime and mtime.  If FATTR_ATIME_and FATTR_ATIME_NOW
-     * are both set, then set it to the current time.  Else, set it to the
-     * time specified in the request.  Same goes for mtime.  Use utimensat(2)
-     * as it allows ATIME and MTIME to be changed independently, and has
-     * nanosecond resolution which fuse also has.
-     */
-    if (req->valid & (FATTR_ATIME | FATTR_MTIME)) {
-        times[0].tv_nsec = UTIME_OMIT;
-        times[1].tv_nsec = UTIME_OMIT;
-        if (req->valid & FATTR_ATIME) {
-            if (req->valid & FATTR_ATIME_NOW) {
-              times[0].tv_nsec = UTIME_NOW;
-            } else {
-              times[0].tv_sec = req->atime;
-              times[0].tv_nsec = req->atimensec;
-            }
-        }
-        if (req->valid & FATTR_MTIME) {
-            if (req->valid & FATTR_MTIME_NOW) {
-              times[1].tv_nsec = UTIME_NOW;
-            } else {
-              times[1].tv_sec = req->mtime;
-              times[1].tv_nsec = req->mtimensec;
-            }
-        }
-        DLOG(INFO) << "[" << handler->token << "] Calling utimensat on " << path
-                   << " with atime " << times[0].tv_sec << ", mtime=" << times[1].tv_sec;
-        if (utimensat(-1, path, times, 0) < 0) {
-            return -errno;
-        }
-    }
-    return fuse_reply_attr(fuse, hdr->unique, node, path);
-}
-
-static int handle_mknod(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const struct fuse_mknod_in* req, const char* name)
-{
-    struct node* parent_node;
-    char parent_path[PATH_MAX];
-    char child_path[PATH_MAX];
-    const char* actual_name;
-
-    pthread_mutex_lock(&fuse->global->lock);
-    parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
-            parent_path, sizeof(parent_path));
-    DLOG(INFO) << "[" << handler->token << "] MKNOD " << name << " 0" << std::oct << req->mode
-               << " @ " << std::hex << hdr->nodeid
-               << " (" << (parent_node ? parent_node->name : "?") << ")";
-    pthread_mutex_unlock(&fuse->global->lock);
-
-    if (!parent_node || !(actual_name = find_file_within(parent_path, name,
-            child_path, sizeof(child_path), 1))) {
-        return -ENOENT;
-    }
-    if (!check_caller_access_to_name(fuse, hdr, parent_node, name, W_OK)) {
-        return -EACCES;
-    }
-    __u32 mode = (req->mode & (~0777)) | 0664;
-    if (mknod(child_path, mode, req->rdev) == -1) {
-        return -errno;
-    }
-    return fuse_reply_entry(fuse, hdr->unique, parent_node, name, actual_name, child_path);
-}
-
-static int handle_mkdir(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const struct fuse_mkdir_in* req, const char* name)
-{
-    struct node* parent_node;
-    char parent_path[PATH_MAX];
-    char child_path[PATH_MAX];
-    const char* actual_name;
-
-    pthread_mutex_lock(&fuse->global->lock);
-    parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
-            parent_path, sizeof(parent_path));
-    DLOG(INFO) << "[" << handler->token << "] MKDIR " << name << " 0" << std::oct << req->mode
-               << " @ " << std::hex << hdr->nodeid
-               << " (" << (parent_node ? parent_node->name : "?") << ")";
-    pthread_mutex_unlock(&fuse->global->lock);
-
-    if (!parent_node || !(actual_name = find_file_within(parent_path, name,
-            child_path, sizeof(child_path), 1))) {
-        return -ENOENT;
-    }
-    if (!check_caller_access_to_name(fuse, hdr, parent_node, name, W_OK)) {
-        return -EACCES;
-    }
-    __u32 mode = (req->mode & (~0777)) | 0775;
-    if (mkdir(child_path, mode) == -1) {
-        return -errno;
-    }
-
-    /* When creating /Android/data and /Android/obb, mark them as .nomedia */
-    if (parent_node->perm == PERM_ANDROID && !strcasecmp(name, "data")) {
-        char nomedia[PATH_MAX];
-        snprintf(nomedia, PATH_MAX, "%s/.nomedia", child_path);
-        if (touch(nomedia, 0664) != 0) {
-            PLOG(ERROR) << "touch(" << nomedia << ") failed";
-            return -ENOENT;
-        }
-    }
-    if (parent_node->perm == PERM_ANDROID && !strcasecmp(name, "obb")) {
-        char nomedia[PATH_MAX];
-        snprintf(nomedia, PATH_MAX, "%s/.nomedia", fuse->global->obb_path);
-        if (touch(nomedia, 0664) != 0) {
-            PLOG(ERROR) << "touch(" << nomedia << ") failed";
-            return -ENOENT;
-        }
-    }
-
-    return fuse_reply_entry(fuse, hdr->unique, parent_node, name, actual_name, child_path);
-}
-
-static int handle_unlink(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const char* name)
-{
-    struct node* parent_node;
-    struct node* child_node;
-    char parent_path[PATH_MAX];
-    char child_path[PATH_MAX];
-
-    pthread_mutex_lock(&fuse->global->lock);
-    parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
-            parent_path, sizeof(parent_path));
-    DLOG(INFO) << "[" << handler->token << "] UNLINK " << name << " @ " << std::hex << hdr->nodeid
-               << " (" << (parent_node ? parent_node->name : "?") << ")";
-    pthread_mutex_unlock(&fuse->global->lock);
-
-    if (!parent_node || !find_file_within(parent_path, name,
-            child_path, sizeof(child_path), 1)) {
-        return -ENOENT;
-    }
-    if (!check_caller_access_to_name(fuse, hdr, parent_node, name, W_OK)) {
-        return -EACCES;
-    }
-    if (unlink(child_path) == -1) {
-        return -errno;
-    }
-    pthread_mutex_lock(&fuse->global->lock);
-    child_node = lookup_child_by_name_locked(parent_node, name);
-    if (child_node) {
-        child_node->deleted = true;
-    }
-    pthread_mutex_unlock(&fuse->global->lock);
-    if (parent_node && child_node) {
-        /* Tell all other views that node is gone */
-        DLOG(INFO) << "[" << handler->token << "] fuse_notify_delete"
-                   << " parent=" << std::hex << parent_node->nid
-                   << ", child=" << std::hex << child_node->nid << std::dec
-                   << ", name=" << name;
-        if (fuse != fuse->global->fuse_default) {
-            fuse_notify_delete(fuse->global->fuse_default, parent_node->nid, child_node->nid, name);
-        }
-        if (fuse != fuse->global->fuse_read) {
-            fuse_notify_delete(fuse->global->fuse_read, parent_node->nid, child_node->nid, name);
-        }
-        if (fuse != fuse->global->fuse_write) {
-            fuse_notify_delete(fuse->global->fuse_write, parent_node->nid, child_node->nid, name);
-        }
-    }
-    return 0;
-}
-
-static int handle_rmdir(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const char* name)
-{
-    struct node* child_node;
-    struct node* parent_node;
-    char parent_path[PATH_MAX];
-    char child_path[PATH_MAX];
-
-    pthread_mutex_lock(&fuse->global->lock);
-    parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
-            parent_path, sizeof(parent_path));
-    DLOG(INFO) << "[" << handler->token << "] UNLINK " << name << " @ " << std::hex << hdr->nodeid
-               << " (" << (parent_node ? parent_node->name : "?") << ")";
-    pthread_mutex_unlock(&fuse->global->lock);
-
-    if (!parent_node || !find_file_within(parent_path, name,
-            child_path, sizeof(child_path), 1)) {
-        return -ENOENT;
-    }
-    if (!check_caller_access_to_name(fuse, hdr, parent_node, name, W_OK)) {
-        return -EACCES;
-    }
-    if (rmdir(child_path) == -1) {
-        return -errno;
-    }
-    pthread_mutex_lock(&fuse->global->lock);
-    child_node = lookup_child_by_name_locked(parent_node, name);
-    if (child_node) {
-        child_node->deleted = true;
-    }
-    pthread_mutex_unlock(&fuse->global->lock);
-    if (parent_node && child_node) {
-        /* Tell all other views that node is gone */
-        DLOG(INFO) << "[" << handler->token << "] fuse_notify_delete"
-                   << " parent=" << std::hex << parent_node->nid
-                   << ", child=" << std::hex << child_node->nid << std::dec
-                   << ", name=" << name;
-        if (fuse != fuse->global->fuse_default) {
-            fuse_notify_delete(fuse->global->fuse_default, parent_node->nid, child_node->nid, name);
-        }
-        if (fuse != fuse->global->fuse_read) {
-            fuse_notify_delete(fuse->global->fuse_read, parent_node->nid, child_node->nid, name);
-        }
-        if (fuse != fuse->global->fuse_write) {
-            fuse_notify_delete(fuse->global->fuse_write, parent_node->nid, child_node->nid, name);
-        }
-    }
-    return 0;
-}
-
-static int handle_rename(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const struct fuse_rename_in* req,
-        const char* old_name, const char* new_name)
-{
-    struct node* old_parent_node;
-    struct node* new_parent_node;
-    struct node* child_node;
-    char old_parent_path[PATH_MAX];
-    char new_parent_path[PATH_MAX];
-    char old_child_path[PATH_MAX];
-    char new_child_path[PATH_MAX];
-    const char* new_actual_name;
-    int search;
-    int res;
-
-    pthread_mutex_lock(&fuse->global->lock);
-    old_parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
-            old_parent_path, sizeof(old_parent_path));
-    new_parent_node = lookup_node_and_path_by_id_locked(fuse, req->newdir,
-            new_parent_path, sizeof(new_parent_path));
-    DLOG(INFO) << "[" << handler->token << "] RENAME " << old_name << "->" << new_name
-               << " @ " << std::hex << hdr->nodeid
-               << " (" << (old_parent_node ? old_parent_node->name : "?") << ") -> "
-               << std::hex << req->newdir
-               << " (" << (new_parent_node ? new_parent_node->name : "?") << ")";
-    if (!old_parent_node || !new_parent_node) {
-        res = -ENOENT;
-        goto lookup_error;
-    }
-    if (!check_caller_access_to_name(fuse, hdr, old_parent_node, old_name, W_OK)) {
-        res = -EACCES;
-        goto lookup_error;
-    }
-    if (!check_caller_access_to_name(fuse, hdr, new_parent_node, new_name, W_OK)) {
-        res = -EACCES;
-        goto lookup_error;
-    }
-    child_node = lookup_child_by_name_locked(old_parent_node, old_name);
-    if (!child_node || get_node_path_locked(child_node,
-            old_child_path, sizeof(old_child_path)) < 0) {
-        res = -ENOENT;
-        goto lookup_error;
-    }
-    acquire_node_locked(child_node);
-    pthread_mutex_unlock(&fuse->global->lock);
-
-    /* Special case for renaming a file where destination is same path
-     * differing only by case.  In this case we don't want to look for a case
-     * insensitive match.  This allows commands like "mv foo FOO" to work as expected.
-     */
-    search = old_parent_node != new_parent_node
-            || strcasecmp(old_name, new_name);
-    if (!(new_actual_name = find_file_within(new_parent_path, new_name,
-            new_child_path, sizeof(new_child_path), search))) {
-        res = -ENOENT;
-        goto io_error;
-    }
-
-    DLOG(INFO) << "[" << handler->token << "] RENAME " << old_child_path << "->" << new_child_path;
-    res = rename(old_child_path, new_child_path);
-    if (res == -1) {
-        res = -errno;
-        goto io_error;
-    }
-
-    pthread_mutex_lock(&fuse->global->lock);
-    res = rename_node_locked(child_node, new_name, new_actual_name);
-    if (!res) {
-        remove_node_from_parent_locked(child_node);
-        derive_permissions_locked(fuse, new_parent_node, child_node);
-        derive_permissions_recursive_locked(fuse, child_node);
-        add_node_to_parent_locked(child_node, new_parent_node);
-    }
-    goto done;
-
-io_error:
-    pthread_mutex_lock(&fuse->global->lock);
-done:
-    release_node_locked(child_node);
-lookup_error:
-    pthread_mutex_unlock(&fuse->global->lock);
-    return res;
-}
-
-static int open_flags_to_access_mode(int open_flags) {
-    if ((open_flags & O_ACCMODE) == O_RDONLY) {
-        return R_OK;
-    } else if ((open_flags & O_ACCMODE) == O_WRONLY) {
-        return W_OK;
-    } else {
-        /* Probably O_RDRW, but treat as default to be safe */
-        return R_OK | W_OK;
-    }
-}
-
-static int handle_open(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const struct fuse_open_in* req)
-{
-    struct node* node;
-    char path[PATH_MAX];
-    struct fuse_open_out out = {};
-    struct handle *h;
-
-    pthread_mutex_lock(&fuse->global->lock);
-    node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid, path, sizeof(path));
-    DLOG(INFO) << "[" << handler->token << "] OPEN 0" << std::oct << req->flags
-               << " @ " << std::hex << hdr->nodeid << std::dec
-               << " (" << (node ? node->name : "?") << ")";
-    pthread_mutex_unlock(&fuse->global->lock);
-
-    if (!node) {
-        return -ENOENT;
-    }
-    if (!check_caller_access_to_node(fuse, hdr, node,
-            open_flags_to_access_mode(req->flags))) {
-        return -EACCES;
-    }
-    h = static_cast<struct handle*>(malloc(sizeof(*h)));
-    if (!h) {
-        return -ENOMEM;
-    }
-    DLOG(INFO) << "[" << handler->token << "] OPEN " << path;
-    h->fd = TEMP_FAILURE_RETRY(open(path, req->flags));
-    if (h->fd == -1) {
-        free(h);
-        return -errno;
-    }
-    out.fh = ptr_to_id(h);
-    out.open_flags = 0;
-    fuse_reply(fuse, hdr->unique, &out, sizeof(out));
-    return NO_STATUS;
-}
-
-static int handle_read(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const struct fuse_read_in* req)
-{
-    struct handle *h = static_cast<struct handle*>(id_to_ptr(req->fh));
-    __u64 unique = hdr->unique;
-    __u32 size = req->size;
-    __u64 offset = req->offset;
-    int res;
-    __u8 *read_buffer = (__u8 *) ((uintptr_t)(handler->read_buffer + PAGE_SIZE) & ~((uintptr_t)PAGE_SIZE-1));
-
-    /* Don't access any other fields of hdr or req beyond this point, the read buffer
-     * overlaps the request buffer and will clobber data in the request.  This
-     * saves us 128KB per request handler thread at the cost of this scary comment. */
-
-    DLOG(INFO) << "[" << handler->token << "] READ " << std::hex << h << std::dec
-               << "(" << h->fd << ") " << size << "@" << offset;
-    if (size > MAX_READ) {
-        return -EINVAL;
-    }
-    res = TEMP_FAILURE_RETRY(pread64(h->fd, read_buffer, size, offset));
-    if (res == -1) {
-        return -errno;
-    }
-    fuse_reply(fuse, unique, read_buffer, res);
-    return NO_STATUS;
-}
-
-static int handle_write(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const struct fuse_write_in* req,
-        const void* buffer)
-{
-    struct fuse_write_out out;
-    struct handle *h = static_cast<struct handle*>(id_to_ptr(req->fh));
-    int res;
-    __u8 aligned_buffer[req->size] __attribute__((__aligned__(PAGE_SIZE)));
-
-    if (req->flags & O_DIRECT) {
-        memcpy(aligned_buffer, buffer, req->size);
-        buffer = (const __u8*) aligned_buffer;
-    }
-
-    DLOG(INFO) << "[" << handler->token << "] WRITE " << std::hex << h << std::dec
-               << "(" << h->fd << ") " << req->size << "@" << req->offset;
-    res = TEMP_FAILURE_RETRY(pwrite64(h->fd, buffer, req->size, req->offset));
-    if (res == -1) {
-        return -errno;
-    }
-    out.size = res;
-    out.padding = 0;
-    fuse_reply(fuse, hdr->unique, &out, sizeof(out));
-    return NO_STATUS;
-}
-
-static int handle_statfs(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr)
-{
-    char path[PATH_MAX];
-    struct statfs stat;
-    struct fuse_statfs_out out;
-    int res;
-
-    pthread_mutex_lock(&fuse->global->lock);
-    DLOG(INFO) << "[" << handler->token << "] STATFS";
-    res = get_node_path_locked(&fuse->global->root, path, sizeof(path));
-    pthread_mutex_unlock(&fuse->global->lock);
-    if (res < 0) {
-        return -ENOENT;
-    }
-    if (TEMP_FAILURE_RETRY(statfs(fuse->global->root.name, &stat)) == -1) {
-        return -errno;
-    }
-    memset(&out, 0, sizeof(out));
-    out.st.blocks = stat.f_blocks;
-    out.st.bfree = stat.f_bfree;
-    out.st.bavail = stat.f_bavail;
-    out.st.files = stat.f_files;
-    out.st.ffree = stat.f_ffree;
-    out.st.bsize = stat.f_bsize;
-    out.st.namelen = stat.f_namelen;
-    out.st.frsize = stat.f_frsize;
-    fuse_reply(fuse, hdr->unique, &out, sizeof(out));
-    return NO_STATUS;
-}
-
-static int handle_release(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const struct fuse_release_in* req)
-{
-    struct handle *h = static_cast<struct handle*>(id_to_ptr(req->fh));
-
-    DLOG(INFO) << "[" << handler->token << "] RELEASE " << std::hex << h << std::dec
-               << "(" << h->fd << ")";
-    close(h->fd);
-    free(h);
-    return 0;
-}
-
-static int handle_fsync(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const struct fuse_fsync_in* req)
-{
-    bool is_dir = (hdr->opcode == FUSE_FSYNCDIR);
-    bool is_data_sync = req->fsync_flags & 1;
-
-    int fd = -1;
-    if (is_dir) {
-      struct dirhandle *dh = static_cast<struct dirhandle*>(id_to_ptr(req->fh));
-      fd = dirfd(dh->d);
-    } else {
-      struct handle *h = static_cast<struct handle*>(id_to_ptr(req->fh));
-      fd = h->fd;
-    }
-
-    DLOG(INFO) << "[" << handler->token << "] " << (is_dir ? "FSYNCDIR" : "FSYNC") << " "
-               << std::hex << req->fh << std::dec << "(" << fd << ") is_data_sync=" << is_data_sync;
-    int res = is_data_sync ? fdatasync(fd) : fsync(fd);
-    if (res == -1) {
-        return -errno;
-    }
-    return 0;
-}
-
-static int handle_flush(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr)
-{
-    DLOG(INFO) << "[" << handler->token << "] FLUSH";
-    return 0;
-}
-
-static int handle_opendir(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const struct fuse_open_in* req)
-{
-    struct node* node;
-    char path[PATH_MAX];
-    struct fuse_open_out out = {};
-    struct dirhandle *h;
-
-    pthread_mutex_lock(&fuse->global->lock);
-    node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid, path, sizeof(path));
-    DLOG(INFO) << "[" << handler->token << "] OPENDIR @ " << std::hex << hdr->nodeid
-               << " (" << (node ? node->name : "?") << ")";
-    pthread_mutex_unlock(&fuse->global->lock);
-
-    if (!node) {
-        return -ENOENT;
-    }
-    if (!check_caller_access_to_node(fuse, hdr, node, R_OK)) {
-        return -EACCES;
-    }
-    h = static_cast<struct dirhandle*>(malloc(sizeof(*h)));
-    if (!h) {
-        return -ENOMEM;
-    }
-    DLOG(INFO) << "[" << handler->token << "] OPENDIR " << path;
-    h->d = opendir(path);
-    if (!h->d) {
-        free(h);
-        return -errno;
-    }
-    out.fh = ptr_to_id(h);
-    out.open_flags = 0;
-    fuse_reply(fuse, hdr->unique, &out, sizeof(out));
-    return NO_STATUS;
-}
-
-static int handle_readdir(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const struct fuse_read_in* req)
-{
-    char buffer[8192];
-    struct fuse_dirent *fde = (struct fuse_dirent*) buffer;
-    struct dirent *de;
-    struct dirhandle *h = static_cast<struct dirhandle*>(id_to_ptr(req->fh));
-
-    DLOG(INFO) << "[" << handler->token << "] READDIR " << h;
-    if (req->offset == 0) {
-        /* rewinddir() might have been called above us, so rewind here too */
-        DLOG(INFO) << "[" << handler->token << "] calling rewinddir()";
-        rewinddir(h->d);
-    }
-    de = readdir(h->d);
-    if (!de) {
-        return 0;
-    }
-    fde->ino = FUSE_UNKNOWN_INO;
-    /* increment the offset so we can detect when rewinddir() seeks back to the beginning */
-    fde->off = req->offset + 1;
-    fde->type = de->d_type;
-    fde->namelen = strlen(de->d_name);
-    memcpy(fde->name, de->d_name, fde->namelen + 1);
-    fuse_reply(fuse, hdr->unique, fde,
-            FUSE_DIRENT_ALIGN(sizeof(struct fuse_dirent) + fde->namelen));
-    return NO_STATUS;
-}
-
-static int handle_releasedir(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const struct fuse_release_in* req)
-{
-    struct dirhandle *h = static_cast<struct dirhandle*>(id_to_ptr(req->fh));
-
-    DLOG(INFO) << "[" << handler->token << "] RELEASEDIR " << h;
-    closedir(h->d);
-    free(h);
-    return 0;
-}
-
-static int handle_init(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header* hdr, const struct fuse_init_in* req)
-{
-    struct fuse_init_out out;
-    size_t fuse_struct_size;
-
-    DLOG(INFO) << "[" << handler->token << "] INIT ver=" << req->major << "." << req->minor
-               << " maxread=" << req->max_readahead << " flags=" << std::hex << req->flags;
-
-    /* Kernel 2.6.16 is the first stable kernel with struct fuse_init_out
-     * defined (fuse version 7.6). The structure is the same from 7.6 through
-     * 7.22. Beginning with 7.23, the structure increased in size and added
-     * new parameters.
-     */
-    if (req->major != FUSE_KERNEL_VERSION || req->minor < 6) {
-        LOG(ERROR) << "Fuse kernel version mismatch: Kernel version "
-                   << req->major << "." << req->minor
-                   << ", Expected at least " << FUSE_KERNEL_VERSION << ".6";
-        return -1;
-    }
-
-    /* We limit ourselves to 15 because we don't handle BATCH_FORGET yet */
-    out.minor = MIN(req->minor, 15);
-    fuse_struct_size = sizeof(out);
-#if defined(FUSE_COMPAT_22_INIT_OUT_SIZE)
-    /* FUSE_KERNEL_VERSION >= 23. */
-
-    /* Since we return minor version 15, the kernel does not accept the latest
-     * fuse_init_out size. We need to use FUSE_COMPAT_22_INIT_OUT_SIZE always.*/
-    fuse_struct_size = FUSE_COMPAT_22_INIT_OUT_SIZE;
-#endif
-
-    out.major = FUSE_KERNEL_VERSION;
-    out.max_readahead = req->max_readahead;
-    out.flags = FUSE_ATOMIC_O_TRUNC | FUSE_BIG_WRITES;
-    out.max_background = 32;
-    out.congestion_threshold = 32;
-    out.max_write = MAX_WRITE;
-    fuse_reply(fuse, hdr->unique, &out, fuse_struct_size);
-    return NO_STATUS;
-}
-
-static int handle_canonical_path(struct fuse* fuse, struct fuse_handler* handler,
-        const struct fuse_in_header *hdr)
-{
-    struct node* node;
-    char path[PATH_MAX];
-    int len;
-
-    pthread_mutex_lock(&fuse->global->lock);
-    node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
-            path, sizeof(path));
-    DLOG(INFO) << "[" << handler->token << "] CANONICAL_PATH @ " << std::hex << hdr->nodeid
-               << std::dec << " (" << (node ? node->name : "?") << ")";
-    pthread_mutex_unlock(&fuse->global->lock);
-
-    if (!node) {
-        return -ENOENT;
-    }
-    if (!check_caller_access_to_node(fuse, hdr, node, R_OK)) {
-        return -EACCES;
-    }
-    len = strlen(path);
-    if (len + 1 > PATH_MAX)
-        len = PATH_MAX - 1;
-    path[PATH_MAX - 1] = 0;
-    fuse_reply(fuse, hdr->unique, path, len + 1);
-    return NO_STATUS;
-}
-
-static int handle_fuse_request(struct fuse *fuse, struct fuse_handler* handler,
-        const struct fuse_in_header *hdr, const void *data, size_t data_len)
-{
-    switch (hdr->opcode) {
-    case FUSE_LOOKUP: { /* bytez[] -> entry_out */
-        const char *name = static_cast<const char*>(data);
-        return handle_lookup(fuse, handler, hdr, name);
-    }
-
-    case FUSE_FORGET: {
-        const struct fuse_forget_in *req = static_cast<const struct fuse_forget_in*>(data);
-        return handle_forget(fuse, handler, hdr, req);
-    }
-
-    case FUSE_GETATTR: { /* getattr_in -> attr_out */
-        const struct fuse_getattr_in *req = static_cast<const struct fuse_getattr_in*>(data);
-        return handle_getattr(fuse, handler, hdr, req);
-    }
-
-    case FUSE_SETATTR: { /* setattr_in -> attr_out */
-        const struct fuse_setattr_in *req = static_cast<const struct fuse_setattr_in*>(data);
-        return handle_setattr(fuse, handler, hdr, req);
-    }
-
-//    case FUSE_READLINK:
-//    case FUSE_SYMLINK:
-    case FUSE_MKNOD: { /* mknod_in, bytez[] -> entry_out */
-        const struct fuse_mknod_in *req = static_cast<const struct fuse_mknod_in*>(data);
-        const char *name = ((const char*) data) + sizeof(*req);
-        return handle_mknod(fuse, handler, hdr, req, name);
-    }
-
-    case FUSE_MKDIR: { /* mkdir_in, bytez[] -> entry_out */
-        const struct fuse_mkdir_in *req = static_cast<const struct fuse_mkdir_in*>(data);
-        const char *name = ((const char*) data) + sizeof(*req);
-        return handle_mkdir(fuse, handler, hdr, req, name);
-    }
-
-    case FUSE_UNLINK: { /* bytez[] -> */
-        const char *name = static_cast<const char*>(data);
-        return handle_unlink(fuse, handler, hdr, name);
-    }
-
-    case FUSE_RMDIR: { /* bytez[] -> */
-        const char *name = static_cast<const char*>(data);
-        return handle_rmdir(fuse, handler, hdr, name);
-    }
-
-    case FUSE_RENAME: { /* rename_in, oldname, newname ->  */
-        const struct fuse_rename_in *req = static_cast<const struct fuse_rename_in*>(data);
-        const char *old_name = ((const char*) data) + sizeof(*req);
-        const char *new_name = old_name + strlen(old_name) + 1;
-        return handle_rename(fuse, handler, hdr, req, old_name, new_name);
-    }
-
-//    case FUSE_LINK:
-    case FUSE_OPEN: { /* open_in -> open_out */
-        const struct fuse_open_in *req = static_cast<const struct fuse_open_in*>(data);
-        return handle_open(fuse, handler, hdr, req);
-    }
-
-    case FUSE_READ: { /* read_in -> byte[] */
-        const struct fuse_read_in *req = static_cast<const struct fuse_read_in*>(data);
-        return handle_read(fuse, handler, hdr, req);
-    }
-
-    case FUSE_WRITE: { /* write_in, byte[write_in.size] -> write_out */
-        const struct fuse_write_in *req = static_cast<const struct fuse_write_in*>(data);
-        const void* buffer = (const __u8*)data + sizeof(*req);
-        return handle_write(fuse, handler, hdr, req, buffer);
-    }
-
-    case FUSE_STATFS: { /* getattr_in -> attr_out */
-        return handle_statfs(fuse, handler, hdr);
-    }
-
-    case FUSE_RELEASE: { /* release_in -> */
-        const struct fuse_release_in *req = static_cast<const struct fuse_release_in*>(data);
-        return handle_release(fuse, handler, hdr, req);
-    }
-
-    case FUSE_FSYNC:
-    case FUSE_FSYNCDIR: {
-        const struct fuse_fsync_in *req = static_cast<const struct fuse_fsync_in*>(data);
-        return handle_fsync(fuse, handler, hdr, req);
-    }
-
-//    case FUSE_SETXATTR:
-//    case FUSE_GETXATTR:
-//    case FUSE_LISTXATTR:
-//    case FUSE_REMOVEXATTR:
-    case FUSE_FLUSH: {
-        return handle_flush(fuse, handler, hdr);
-    }
-
-    case FUSE_OPENDIR: { /* open_in -> open_out */
-        const struct fuse_open_in *req = static_cast<const struct fuse_open_in*>(data);
-        return handle_opendir(fuse, handler, hdr, req);
-    }
-
-    case FUSE_READDIR: {
-        const struct fuse_read_in *req = static_cast<const struct fuse_read_in*>(data);
-        return handle_readdir(fuse, handler, hdr, req);
-    }
-
-    case FUSE_RELEASEDIR: { /* release_in -> */
-        const struct fuse_release_in *req = static_cast<const struct fuse_release_in*>(data);
-        return handle_releasedir(fuse, handler, hdr, req);
-    }
-
-    case FUSE_INIT: { /* init_in -> init_out */
-        const struct fuse_init_in *req = static_cast<const struct fuse_init_in*>(data);
-        return handle_init(fuse, handler, hdr, req);
-    }
-
-    case FUSE_CANONICAL_PATH: { /* nodeid -> bytez[] */
-        return handle_canonical_path(fuse, handler, hdr);
-    }
-
-    default: {
-        DLOG(INFO) << "[" << handler->token << "] NOTIMPL op=" << hdr->opcode
-                   << "uniq=" << std::hex << hdr->unique << "nid=" << hdr->nodeid << std::dec;
-        return -ENOSYS;
-    }
-    }
-}
-
-void handle_fuse_requests(struct fuse_handler* handler)
-{
-    struct fuse* fuse = handler->fuse;
-    for (;;) {
-        ssize_t len = TEMP_FAILURE_RETRY(read(fuse->fd,
-                handler->request_buffer, sizeof(handler->request_buffer)));
-        if (len == -1) {
-            if (errno == ENODEV) {
-                LOG(ERROR) << "[" << handler->token << "] someone stole our marbles!";
-                exit(2);
-            }
-            PLOG(ERROR) << "[" << handler->token << "] handle_fuse_requests";
-            continue;
-        }
-
-        if (static_cast<size_t>(len) < sizeof(struct fuse_in_header)) {
-            LOG(ERROR) << "[" << handler->token << "] request too short: len=" << len;
-            continue;
-        }
-
-        const struct fuse_in_header* hdr =
-            reinterpret_cast<const struct fuse_in_header*>(handler->request_buffer);
-        if (hdr->len != static_cast<size_t>(len)) {
-            LOG(ERROR) << "[" << handler->token << "] malformed header: len=" << len
-                       << ", hdr->len=" << hdr->len;
-            continue;
-        }
-
-        const void *data = handler->request_buffer + sizeof(struct fuse_in_header);
-        size_t data_len = len - sizeof(struct fuse_in_header);
-        __u64 unique = hdr->unique;
-        int res = handle_fuse_request(fuse, handler, hdr, data, data_len);
-
-        /* We do not access the request again after this point because the underlying
-         * buffer storage may have been reused while processing the request. */
-
-        if (res != NO_STATUS) {
-            if (res) {
-                DLOG(INFO) << "[" << handler->token << "] ERROR " << res;
-            }
-            fuse_status(fuse, unique, res);
-        }
-    }
-}
diff --git a/sdcard/fuse.h b/sdcard/fuse.h
deleted file mode 100644
index 9ccd21d..0000000
--- a/sdcard/fuse.h
+++ /dev/null
@@ -1,209 +0,0 @@
-/*
- * 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.
- */
-
-#ifndef FUSE_H_
-#define FUSE_H_
-
-#include <dirent.h>
-#include <fcntl.h>
-#include <linux/fuse.h>
-#include <pthread.h>
-#include <stdbool.h>
-#include <stdlib.h>
-#include <sys/param.h>
-#include <sys/stat.h>
-#include <sys/statfs.h>
-#include <sys/types.h>
-#include <sys/uio.h>
-#include <unistd.h>
-
-#include <map>
-#include <string>
-
-#include <android-base/logging.h>
-#include <cutils/fs.h>
-#include <cutils/multiuser.h>
-#include <packagelistparser/packagelistparser.h>
-
-#include <private/android_filesystem_config.h>
-
-#define FUSE_TRACE 0
-
-#if FUSE_TRACE
-static constexpr bool kEnableDLog = true;
-#else  // FUSE_TRACE == 0
-static constexpr bool kEnableDLog = false;
-#endif
-
-// Use same strategy as DCHECK().
-#define DLOG(x) \
-    if (kEnableDLog) LOG(x)
-
-/* Maximum number of bytes to write in one request. */
-#define MAX_WRITE (256 * 1024)
-
-/* Maximum number of bytes to read in one request. */
-#define MAX_READ (128 * 1024)
-
-/* Largest possible request.
- * The request size is bounded by the maximum size of a FUSE_WRITE request because it has
- * the largest possible data payload. */
-#define MAX_REQUEST_SIZE (sizeof(struct fuse_in_header) + sizeof(struct fuse_write_in) + MAX_WRITE)
-
-namespace {
-struct CaseInsensitiveCompare {
-    bool operator()(const std::string& lhs, const std::string& rhs) const {
-        return strcasecmp(lhs.c_str(), rhs.c_str()) < 0;
-    }
-};
-}
-
-using AppIdMap = std::map<std::string, appid_t, CaseInsensitiveCompare>;
-
-/* Permission mode for a specific node. Controls how file permissions
- * are derived for children nodes. */
-typedef enum {
-    /* Nothing special; this node should just inherit from its parent. */
-    PERM_INHERIT,
-    /* This node is one level above a normal root; used for legacy layouts
-     * which use the first level to represent user_id. */
-    PERM_PRE_ROOT,
-    /* This node is "/" */
-    PERM_ROOT,
-    /* This node is "/Android" */
-    PERM_ANDROID,
-    /* This node is "/Android/data" */
-    PERM_ANDROID_DATA,
-    /* This node is "/Android/obb" */
-    PERM_ANDROID_OBB,
-    /* This node is "/Android/media" */
-    PERM_ANDROID_MEDIA,
-} perm_t;
-
-struct handle {
-    int fd;
-};
-
-struct dirhandle {
-    DIR *d;
-};
-
-struct node {
-    __u32 refcount;
-    __u64 nid;
-    __u64 gen;
-    /*
-     * The inode number for this FUSE node. Note that this isn't stable across
-     * multiple invocations of the FUSE daemon.
-     */
-    __u32 ino;
-
-    /* State derived based on current position in hierarchy. */
-    perm_t perm;
-    userid_t userid;
-    uid_t uid;
-    bool under_android;
-
-    struct node *next;          /* per-dir sibling list */
-    struct node *child;         /* first contained file by this dir */
-    struct node *parent;        /* containing directory */
-
-    size_t namelen;
-    char *name;
-    /* If non-null, this is the real name of the file in the underlying storage.
-     * This may differ from the field "name" only by case.
-     * strlen(actual_name) will always equal strlen(name), so it is safe to use
-     * namelen for both fields.
-     */
-    char *actual_name;
-
-    /* If non-null, an exact underlying path that should be grafted into this
-     * position. Used to support things like OBB. */
-    char* graft_path;
-    size_t graft_pathlen;
-
-    bool deleted;
-};
-
-/* Global data for all FUSE mounts */
-struct fuse_global {
-    pthread_mutex_t lock;
-
-    uid_t uid;
-    gid_t gid;
-    bool multi_user;
-
-    char source_path[PATH_MAX];
-    char obb_path[PATH_MAX];
-
-    AppIdMap* package_to_appid;
-
-    __u64 next_generation;
-    struct node root;
-
-    /* Used to allocate unique inode numbers for fuse nodes. We use
-     * a simple counter based scheme where inode numbers from deleted
-     * nodes aren't reused. Note that inode allocations are not stable
-     * across multiple invocation of the sdcard daemon, but that shouldn't
-     * be a huge problem in practice.
-     *
-     * Note that we restrict inodes to 32 bit unsigned integers to prevent
-     * truncation on 32 bit processes when unsigned long long stat.st_ino is
-     * assigned to an unsigned long ino_t type in an LP32 process.
-     *
-     * Also note that fuse_attr and fuse_dirent inode values are 64 bits wide
-     * on both LP32 and LP64, but the fuse kernel code doesn't squash 64 bit
-     * inode numbers into 32 bit values on 64 bit kernels (see fuse_squash_ino
-     * in fs/fuse/inode.c).
-     *
-     * Accesses must be guarded by |lock|.
-     */
-    __u32 inode_ctr;
-
-    struct fuse* fuse_default;
-    struct fuse* fuse_read;
-    struct fuse* fuse_write;
-};
-
-/* Single FUSE mount */
-struct fuse {
-    struct fuse_global* global;
-
-    char dest_path[PATH_MAX];
-
-    int fd;
-
-    gid_t gid;
-    mode_t mask;
-};
-
-/* Private data used by a single FUSE handler */
-struct fuse_handler {
-    struct fuse* fuse;
-    int token;
-
-    /* To save memory, we never use the contents of the request buffer and the read
-     * buffer at the same time.  This allows us to share the underlying storage. */
-    union {
-        __u8 request_buffer[MAX_REQUEST_SIZE];
-        __u8 read_buffer[MAX_READ + PAGE_SIZE];
-    };
-};
-
-void handle_fuse_requests(struct fuse_handler* handler);
-void derive_permissions_recursive_locked(struct fuse* fuse, struct node *parent);
-
-#endif  /* FUSE_H_ */
diff --git a/sdcard/sdcard.cpp b/sdcard/sdcard.cpp
index 77d5a91..574bbfe 100644
--- a/sdcard/sdcard.cpp
+++ b/sdcard/sdcard.cpp
@@ -38,164 +38,18 @@
 #include <cutils/multiuser.h>
 #include <cutils/properties.h>
 
-#include <packagelistparser/packagelistparser.h>
-
 #include <libminijail.h>
 #include <scoped_minijail.h>
 
 #include <private/android_filesystem_config.h>
 
-// README
-//
-// What is this?
-//
-// sdcard is a program that uses FUSE to emulate FAT-on-sdcard style
-// directory permissions (all files are given fixed owner, group, and
-// permissions at creation, owner, group, and permissions are not
-// changeable, symlinks and hardlinks are not createable, etc.
-//
-// See usage() for command line options.
-//
-// It must be run as root, but will drop to requested UID/GID as soon as it
-// mounts a filesystem.  It will refuse to run if requested UID/GID are zero.
-//
-// Things I believe to be true:
-//
-// - ops that return a fuse_entry (LOOKUP, MKNOD, MKDIR, LINK, SYMLINK,
-// CREAT) must bump that node's refcount
-// - don't forget that FORGET can forget multiple references (req->nlookup)
-// - if an op that returns a fuse_entry fails writing the reply to the
-// kernel, you must rollback the refcount to reflect the reference the
-// kernel did not actually acquire
-//
-// This daemon can also derive custom filesystem permissions based on directory
-// structure when requested. These custom permissions support several features:
-//
-// - Apps can access their own files in /Android/data/com.example/ without
-// requiring any additional GIDs.
-// - Separate permissions for protecting directories like Pictures and Music.
-// - Multi-user separation on the same physical device.
-
-#include "fuse.h"
-
-#define PROP_SDCARDFS_DEVICE "ro.sys.sdcardfs"
-#define PROP_SDCARDFS_USER "persist.sys.sdcardfs"
+// NOTE: This is a vestigial program that simply exists to mount the in-kernel
+// sdcardfs filesystem.  The older FUSE-based design that used to live here has
+// been completely removed to avoid confusion.
 
 /* Supplementary groups to execute with. */
 static const gid_t kGroups[1] = { AID_PACKAGE_INFO };
 
-static bool package_parse_callback(pkg_info *info, void *userdata) {
-    struct fuse_global *global = (struct fuse_global *)userdata;
-    bool res = global->package_to_appid->emplace(info->name, info->uid).second;
-    packagelist_free(info);
-    return res;
-}
-
-static bool read_package_list(struct fuse_global* global) {
-    pthread_mutex_lock(&global->lock);
-
-    global->package_to_appid->clear();
-    bool rc = packagelist_parse(package_parse_callback, global);
-    DLOG(INFO) << "read_package_list: found " << global->package_to_appid->size() << " packages";
-
-    // Regenerate ownership details using newly loaded mapping.
-    derive_permissions_recursive_locked(global->fuse_default, &global->root);
-
-    pthread_mutex_unlock(&global->lock);
-
-    return rc;
-}
-
-static void watch_package_list(struct fuse_global* global) {
-    struct inotify_event *event;
-    char event_buf[512];
-
-    int nfd = inotify_init();
-    if (nfd == -1) {
-        PLOG(ERROR) << "inotify_init failed";
-        return;
-    }
-
-    bool active = false;
-    while (1) {
-        if (!active) {
-            int res = inotify_add_watch(nfd, PACKAGES_LIST_FILE, IN_DELETE_SELF);
-            if (res == -1) {
-                if (errno == ENOENT || errno == EACCES) {
-                    /* Framework may not have created the file yet, sleep and retry. */
-                    LOG(ERROR) << "missing \"" << PACKAGES_LIST_FILE << "\"; retrying...";
-                    sleep(3);
-                    continue;
-                } else {
-                    PLOG(ERROR) << "inotify_add_watch failed";
-                    return;
-                }
-            }
-
-            /* Watch above will tell us about any future changes, so
-             * read the current state. */
-            if (read_package_list(global) == false) {
-                LOG(ERROR) << "read_package_list failed";
-                return;
-            }
-            active = true;
-        }
-
-        int event_pos = 0;
-        ssize_t res = TEMP_FAILURE_RETRY(read(nfd, event_buf, sizeof(event_buf)));
-        if (res == -1) {
-            PLOG(ERROR) << "failed to read inotify event";
-            return;
-        } else if (static_cast<size_t>(res) < sizeof(*event)) {
-            LOG(ERROR) << "failed to read inotify event: read " << res << " expected "
-                       << sizeof(event_buf);
-            return;
-        }
-
-        while (res >= static_cast<ssize_t>(sizeof(*event))) {
-            int event_size;
-            event = reinterpret_cast<struct inotify_event*>(event_buf + event_pos);
-
-            DLOG(INFO) << "inotify event: " << std::hex << event->mask << std::dec;
-            if ((event->mask & IN_IGNORED) == IN_IGNORED) {
-                /* Previously watched file was deleted, probably due to move
-                 * that swapped in new data; re-arm the watch and read. */
-                active = false;
-            }
-
-            event_size = sizeof(*event) + event->len;
-            res -= event_size;
-            event_pos += event_size;
-        }
-    }
-}
-
-static int fuse_setup(struct fuse* fuse, gid_t gid, mode_t mask) {
-    char opts[256];
-
-    fuse->fd = TEMP_FAILURE_RETRY(open("/dev/fuse", O_RDWR | O_CLOEXEC));
-    if (fuse->fd == -1) {
-        PLOG(ERROR) << "failed to open fuse device";
-        return -1;
-    }
-
-    umount2(fuse->dest_path, MNT_DETACH);
-
-    snprintf(opts, sizeof(opts),
-            "fd=%i,rootmode=40000,default_permissions,allow_other,user_id=%d,group_id=%d",
-            fuse->fd, fuse->global->uid, fuse->global->gid);
-    if (mount("/dev/fuse", fuse->dest_path, "fuse", MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME,
-              opts) == -1) {
-        PLOG(ERROR) << "failed to mount fuse filesystem";
-        return -1;
-    }
-
-    fuse->gid = gid;
-    fuse->mask = mask;
-
-    return 0;
-}
-
 static void drop_privs(uid_t uid, gid_t gid) {
     ScopedMinijail j(minijail_new());
     minijail_set_supplementary_gids(j.get(), arraysize(kGroups), kGroups);
@@ -205,146 +59,28 @@
     minijail_enter(j.get());
 }
 
-static void* start_handler(void* data) {
-    struct fuse_handler* handler = static_cast<fuse_handler*>(data);
-    handle_fuse_requests(handler);
-    return NULL;
-}
-
-static void run(const char* source_path, const char* label, uid_t uid,
-        gid_t gid, userid_t userid, bool multi_user, bool full_write) {
-    struct fuse_global global;
-    struct fuse fuse_default;
-    struct fuse fuse_read;
-    struct fuse fuse_write;
-    struct fuse_handler handler_default;
-    struct fuse_handler handler_read;
-    struct fuse_handler handler_write;
-    pthread_t thread_default;
-    pthread_t thread_read;
-    pthread_t thread_write;
-
-    memset(&global, 0, sizeof(global));
-    memset(&fuse_default, 0, sizeof(fuse_default));
-    memset(&fuse_read, 0, sizeof(fuse_read));
-    memset(&fuse_write, 0, sizeof(fuse_write));
-    memset(&handler_default, 0, sizeof(handler_default));
-    memset(&handler_read, 0, sizeof(handler_read));
-    memset(&handler_write, 0, sizeof(handler_write));
-
-    pthread_mutex_init(&global.lock, NULL);
-    global.package_to_appid = new AppIdMap;
-    global.uid = uid;
-    global.gid = gid;
-    global.multi_user = multi_user;
-    global.next_generation = 0;
-    global.inode_ctr = 1;
-
-    memset(&global.root, 0, sizeof(global.root));
-    global.root.nid = FUSE_ROOT_ID; /* 1 */
-    global.root.refcount = 2;
-    global.root.namelen = strlen(source_path);
-    global.root.name = strdup(source_path);
-    global.root.userid = userid;
-    global.root.uid = AID_ROOT;
-    global.root.under_android = false;
-
-    // Clang static analyzer think strcpy potentially overwrites other fields
-    // in global. Use snprintf() to mute the false warning.
-    snprintf(global.source_path, sizeof(global.source_path), "%s", source_path);
-
-    if (multi_user) {
-        global.root.perm = PERM_PRE_ROOT;
-        snprintf(global.obb_path, sizeof(global.obb_path), "%s/obb", source_path);
-    } else {
-        global.root.perm = PERM_ROOT;
-        snprintf(global.obb_path, sizeof(global.obb_path), "%s/Android/obb", source_path);
-    }
-
-    fuse_default.global = &global;
-    fuse_read.global = &global;
-    fuse_write.global = &global;
-
-    global.fuse_default = &fuse_default;
-    global.fuse_read = &fuse_read;
-    global.fuse_write = &fuse_write;
-
-    snprintf(fuse_default.dest_path, PATH_MAX, "/mnt/runtime/default/%s", label);
-    snprintf(fuse_read.dest_path, PATH_MAX, "/mnt/runtime/read/%s", label);
-    snprintf(fuse_write.dest_path, PATH_MAX, "/mnt/runtime/write/%s", label);
-
-    handler_default.fuse = &fuse_default;
-    handler_read.fuse = &fuse_read;
-    handler_write.fuse = &fuse_write;
-
-    handler_default.token = 0;
-    handler_read.token = 1;
-    handler_write.token = 2;
-
-    umask(0);
-
-    if (multi_user) {
-        /* Multi-user storage is fully isolated per user, so "other"
-         * permissions are completely masked off. */
-        if (fuse_setup(&fuse_default, AID_SDCARD_RW, 0006)
-                || fuse_setup(&fuse_read, AID_EVERYBODY, 0027)
-                || fuse_setup(&fuse_write, AID_EVERYBODY, full_write ? 0007 : 0027)) {
-            PLOG(FATAL) << "failed to fuse_setup";
-        }
-    } else {
-        /* Physical storage is readable by all users on device, but
-         * the Android directories are masked off to a single user
-         * deep inside attr_from_stat(). */
-        if (fuse_setup(&fuse_default, AID_SDCARD_RW, 0006)
-                || fuse_setup(&fuse_read, AID_EVERYBODY, full_write ? 0027 : 0022)
-                || fuse_setup(&fuse_write, AID_EVERYBODY, full_write ? 0007 : 0022)) {
-            PLOG(FATAL) << "failed to fuse_setup";
-        }
-    }
-
-    // Will abort if priv-dropping fails.
-    drop_privs(uid, gid);
-
-    if (multi_user) {
-        fs_prepare_dir(global.obb_path, 0775, uid, gid);
-    }
-
-    if (pthread_create(&thread_default, NULL, start_handler, &handler_default)
-            || pthread_create(&thread_read, NULL, start_handler, &handler_read)
-            || pthread_create(&thread_write, NULL, start_handler, &handler_write)) {
-        LOG(FATAL) << "failed to pthread_create";
-    }
-
-    watch_package_list(&global);
-    LOG(FATAL) << "terminated prematurely";
-}
-
 static bool sdcardfs_setup(const std::string& source_path, const std::string& dest_path,
                            uid_t fsuid, gid_t fsgid, bool multi_user, userid_t userid, gid_t gid,
-                           mode_t mask, bool derive_gid) {
-    std::string opts = android::base::StringPrintf(
-        "fsuid=%d,fsgid=%d,%s%smask=%d,userid=%d,gid=%d", fsuid, fsgid,
-        multi_user ? "multiuser," : "", derive_gid ? "derive_gid," : "", mask, userid, gid);
+                           mode_t mask, bool derive_gid, bool default_normal) {
+    // Try several attempts, each time with one less option, to gracefully
+    // handle older kernels that aren't updated yet.
+    for (int i = 0; i < 4; i++) {
+        std::string new_opts;
+        if (multi_user && i < 3) new_opts += "multiuser,";
+        if (derive_gid && i < 2) new_opts += "derive_gid,";
+        if (default_normal && i < 1) new_opts += "default_normal,";
 
-    if (mount(source_path.c_str(), dest_path.c_str(), "sdcardfs",
-              MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME, opts.c_str()) == -1) {
-        if (derive_gid) {
-            PLOG(ERROR) << "trying to mount sdcardfs filesystem without derive_gid";
-            /* Maybe this isn't supported on this kernel. Try without. */
-            opts = android::base::StringPrintf("fsuid=%d,fsgid=%d,%smask=%d,userid=%d,gid=%d",
-                                               fsuid, fsgid, multi_user ? "multiuser," : "", mask,
-                                               userid, gid);
-            if (mount(source_path.c_str(), dest_path.c_str(), "sdcardfs",
-                      MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME, opts.c_str()) == -1) {
-                PLOG(ERROR) << "failed to mount sdcardfs filesystem";
-                return false;
-            }
+        auto opts = android::base::StringPrintf("fsuid=%d,fsgid=%d,%smask=%d,userid=%d,gid=%d",
+                                                fsuid, fsgid, new_opts.c_str(), mask, userid, gid);
+        if (mount(source_path.c_str(), dest_path.c_str(), "sdcardfs",
+                  MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME, opts.c_str()) == -1) {
+            PLOG(WARNING) << "Failed to mount sdcardfs with options " << opts;
         } else {
-            PLOG(ERROR) << "failed to mount sdcardfs filesystem";
-            return false;
+            return true;
         }
     }
-    return true;
+
+    return false;
 }
 
 static bool sdcardfs_setup_bind_remount(const std::string& source_path, const std::string& dest_path,
@@ -370,7 +106,7 @@
 
 static void run_sdcardfs(const std::string& source_path, const std::string& label, uid_t uid,
                          gid_t gid, userid_t userid, bool multi_user, bool full_write,
-                         bool derive_gid) {
+                         bool derive_gid, bool default_normal) {
     std::string dest_path_default = "/mnt/runtime/default/" + label;
     std::string dest_path_read = "/mnt/runtime/read/" + label;
     std::string dest_path_write = "/mnt/runtime/write/" + label;
@@ -380,7 +116,7 @@
         // Multi-user storage is fully isolated per user, so "other"
         // permissions are completely masked off.
         if (!sdcardfs_setup(source_path, dest_path_default, uid, gid, multi_user, userid,
-                            AID_SDCARD_RW, 0006, derive_gid) ||
+                            AID_SDCARD_RW, 0006, derive_gid, default_normal) ||
             !sdcardfs_setup_bind_remount(dest_path_default, dest_path_read, AID_EVERYBODY, 0027) ||
             !sdcardfs_setup_bind_remount(dest_path_default, dest_path_write, AID_EVERYBODY,
                                          full_write ? 0007 : 0027)) {
@@ -391,7 +127,7 @@
         // the Android directories are masked off to a single user
         // deep inside attr_from_stat().
         if (!sdcardfs_setup(source_path, dest_path_default, uid, gid, multi_user, userid,
-                            AID_SDCARD_RW, 0006, derive_gid) ||
+                            AID_SDCARD_RW, 0006, derive_gid, default_normal) ||
             !sdcardfs_setup_bind_remount(dest_path_default, dest_path_read, AID_EVERYBODY,
                                          full_write ? 0027 : 0022) ||
             !sdcardfs_setup_bind_remount(dest_path_default, dest_path_write, AID_EVERYBODY,
@@ -411,41 +147,6 @@
     exit(0);
 }
 
-static bool supports_sdcardfs(void) {
-    std::string filesystems;
-    if (!android::base::ReadFileToString("/proc/filesystems", &filesystems)) {
-        PLOG(ERROR) << "Could not read /proc/filesystems";
-        return false;
-    }
-    for (const auto& fs : android::base::Split(filesystems, "\n")) {
-        if (fs.find("sdcardfs") != std::string::npos) return true;
-    }
-    return false;
-}
-
-static bool should_use_sdcardfs(void) {
-    char property[PROPERTY_VALUE_MAX];
-
-    // Allow user to have a strong opinion about state
-    property_get(PROP_SDCARDFS_USER, property, "");
-    if (!strcmp(property, "force_on")) {
-        LOG(WARNING) << "User explicitly enabled sdcardfs";
-        return supports_sdcardfs();
-    } else if (!strcmp(property, "force_off")) {
-        LOG(WARNING) << "User explicitly disabled sdcardfs";
-        return false;
-    }
-
-    // Fall back to device opinion about state
-    if (property_get_bool(PROP_SDCARDFS_DEVICE, true)) {
-        LOG(WARNING) << "Device explicitly enabled sdcardfs";
-        return supports_sdcardfs();
-    } else {
-        LOG(WARNING) << "Device explicitly disabled sdcardfs";
-        return false;
-    }
-}
-
 static int usage() {
     LOG(ERROR) << "usage: sdcard [OPTIONS] <source_path> <label>"
                << "    -u: specify UID to run as"
@@ -466,12 +167,16 @@
     bool multi_user = false;
     bool full_write = false;
     bool derive_gid = false;
+    bool default_normal = false;
     int i;
     struct rlimit rlim;
     int fs_version;
 
+    setenv("ANDROID_LOG_TAGS", "*:v", 1);
+    android::base::InitLogging(argv, android::base::LogdLogger(android::base::SYSTEM));
+
     int opt;
-    while ((opt = getopt(argc, argv, "u:g:U:mwG")) != -1) {
+    while ((opt = getopt(argc, argv, "u:g:U:mwGi")) != -1) {
         switch (opt) {
             case 'u':
                 uid = strtoul(optarg, NULL, 10);
@@ -491,6 +196,9 @@
             case 'G':
                 derive_gid = true;
                 break;
+            case 'i':
+                default_normal = true;
+                break;
             case '?':
             default:
                 return usage();
@@ -533,10 +241,7 @@
         sleep(1);
     }
 
-    if (should_use_sdcardfs()) {
-        run_sdcardfs(source_path, label, uid, gid, userid, multi_user, full_write, derive_gid);
-    } else {
-        run(source_path, label, uid, gid, userid, multi_user, full_write);
-    }
+    run_sdcardfs(source_path, label, uid, gid, userid, multi_user, full_write, derive_gid,
+                 default_normal);
     return 1;
 }
diff --git a/shell_and_utilities/Android.bp b/shell_and_utilities/Android.bp
index 4203db4..3ccb92f 100644
--- a/shell_and_utilities/Android.bp
+++ b/shell_and_utilities/Android.bp
@@ -12,6 +12,7 @@
         "sh",
         "sh_vendor",
         "toolbox",
+        "toolbox_vendor",
         "toybox",
         "toybox_vendor",
     ],
diff --git a/shell_and_utilities/README.md b/shell_and_utilities/README.md
index 206204b..c423c69 100644
--- a/shell_and_utilities/README.md
+++ b/shell_and_utilities/README.md
@@ -175,18 +175,18 @@
 
 one-true-awk: awk
 
-toolbox: getevent newfs\_msdos
+toolbox: getevent getprop newfs\_msdos
 
 toybox: acpi base64 basename blockdev cal cat chcon chgrp chmod chown
 chroot chrt cksum clear cmp comm cp cpio cut date df diff dirname dmesg
 dos2unix du echo env expand expr fallocate false file find flock free
-getenforce getprop groups gunzip gzip head hostname hwclock id ifconfig
-inotifyd insmod ionice iorenice kill killall ln load\_policy log logname
-losetup ls lsmod lsof lspci lsusb md5sum microcom mkdir mkfifo mknod
-mkswap mktemp modinfo modprobe more mount mountpoint mv netstat nice
-nl nohup od paste patch pgrep pidof pkill pmap printenv printf ps pwd
-readlink realpath renice restorecon rm rmdir rmmod runcon sed sendevent
-seq setenforce setprop setsid sha1sum sha224sum sha256sum sha384sum
+getenforce groups gunzip gzip head hostname hwclock id ifconfig inotifyd
+insmod ionice iorenice kill killall ln load\_policy log logname losetup
+ls lsmod lsof lspci lsusb md5sum microcom mkdir mkfifo mknod mkswap
+mktemp modinfo modprobe more mount mountpoint mv netstat nice nl nohup
+od paste patch pgrep pidof pkill pmap printenv printf ps pwd readlink
+realpath renice restorecon rm rmdir rmmod runcon sed sendevent seq
+setenforce setprop setsid sha1sum sha224sum sha256sum sha384sum
 sha512sum sleep sort split start stat stop strings swapoff swapon sync
 sysctl tac tail tar taskset tee time timeout top touch tr true truncate
 tty ulimit umount uname uniq unix2dos uptime usleep uudecode uuencode
diff --git a/storaged/Android.bp b/storaged/Android.bp
index 2c7dea1..b478f4a 100644
--- a/storaged/Android.bp
+++ b/storaged/Android.bp
@@ -65,6 +65,8 @@
         "binder/android/os/storaged/IStoragedPrivate.aidl",
     ],
 
+    static_libs: ["libhealthhalutils"],
+
     logtags: ["EventLogTags.logtags"],
 
     proto: {
@@ -84,7 +86,10 @@
 
     srcs: ["main.cpp"],
 
-    static_libs: ["libstoraged"],
+    static_libs: [
+        "libhealthhalutils",
+        "libstoraged",
+    ],
 }
 
 /*
@@ -98,7 +103,10 @@
 
     srcs: ["tests/storaged_test.cpp"],
 
-    static_libs: ["libstoraged"],
+    static_libs: [
+        "libhealthhalutils",
+        "libstoraged",
+    ],
 }
 
 // AIDL interface between storaged and framework.jar
diff --git a/storaged/include/storaged.h b/storaged/include/storaged.h
index 2e31e26..7b27988 100644
--- a/storaged/include/storaged.h
+++ b/storaged/include/storaged.h
@@ -81,7 +81,7 @@
   private:
     time_t mTimer;
     storaged_config mConfig;
-    disk_stats_monitor mDsm;
+    unique_ptr<disk_stats_monitor> mDsm;
     uid_monitor mUidm;
     time_t mStarttime;
     sp<android::hardware::health::V2_0::IHealth> health;
@@ -96,8 +96,11 @@
         return string("/data/misc_ce/") + to_string(user_id) +
                "/storaged/storaged.proto";
     }
-public:
+    void init_health_service();
+
+  public:
     storaged_t(void);
+    void init(void);
     void event(void);
     void event_checked(void);
     void pause(void) {
@@ -132,7 +135,6 @@
     void add_user_ce(userid_t user_id);
     void remove_user_ce(userid_t user_id);
 
-    void init_health_service();
     virtual ::android::hardware::Return<void> healthInfoChanged(
         const ::android::hardware::health::V1_0::HealthInfo& info);
     void serviceDied(uint64_t cookie, const wp<::android::hidl::base::V1_0::IBase>& who);
diff --git a/storaged/include/storaged_diskstats.h b/storaged/include/storaged_diskstats.h
index ff030f6..0b93ba6 100644
--- a/storaged/include/storaged_diskstats.h
+++ b/storaged/include/storaged_diskstats.h
@@ -19,6 +19,8 @@
 
 #include <stdint.h>
 
+#include <android/hardware/health/2.0/IHealth.h>
+
 // number of attributes diskstats has
 #define DISK_STATS_SIZE ( 11 )
 
@@ -160,6 +162,7 @@
     const double mSigma;
     struct disk_perf mMean;
     struct disk_perf mStd;
+    android::sp<android::hardware::health::V2_0::IHealth> mHealth;
 
     void update_mean();
     void update_std();
@@ -170,21 +173,27 @@
     void update(struct disk_stats* stats);
 
 public:
-    disk_stats_monitor(uint32_t window_size = 5, double sigma = 1.0) :
-        DISK_STATS_PATH(access(MMC_DISK_STATS_PATH, R_OK) ?
-                            (access(SDA_DISK_STATS_PATH, R_OK) ?
-                                nullptr :
-                                SDA_DISK_STATS_PATH) :
-                            MMC_DISK_STATS_PATH),
-        mPrevious(), mAccumulate(), mAccumulate_pub(),
-        mStall(false), mValid(false),
-        mWindow(window_size), mSigma(sigma),
-        mMean(), mStd() {}
-    bool enabled() {
-        return DISK_STATS_PATH != nullptr;
-    }
-    void update(void);
-    void publish(void);
+  disk_stats_monitor(const android::sp<android::hardware::health::V2_0::IHealth>& healthService,
+                     uint32_t window_size = 5, double sigma = 1.0)
+      : DISK_STATS_PATH(
+            healthService != nullptr
+                ? nullptr
+                : (access(MMC_DISK_STATS_PATH, R_OK) == 0
+                       ? MMC_DISK_STATS_PATH
+                       : (access(SDA_DISK_STATS_PATH, R_OK) == 0 ? SDA_DISK_STATS_PATH : nullptr))),
+        mPrevious(),
+        mAccumulate(),
+        mAccumulate_pub(),
+        mStall(false),
+        mValid(false),
+        mWindow(window_size),
+        mSigma(sigma),
+        mMean(),
+        mStd(),
+        mHealth(healthService) {}
+  bool enabled() { return mHealth != nullptr || DISK_STATS_PATH != nullptr; }
+  void update(void);
+  void publish(void);
 };
 
-#endif /* _STORAGED_DISKSTATS_H_ */
\ No newline at end of file
+#endif /* _STORAGED_DISKSTATS_H_ */
diff --git a/storaged/include/storaged_info.h b/storaged/include/storaged_info.h
index 85ce074..88a53de 100644
--- a/storaged/include/storaged_info.h
+++ b/storaged/include/storaged_info.h
@@ -21,6 +21,7 @@
 
 #include <chrono>
 
+#include <android/hardware/health/2.0/IHealth.h>
 #include <utils/Mutex.h>
 
 #include "storaged.h"
@@ -35,7 +36,7 @@
 using namespace storaged_proto;
 
 class storage_info_t {
-protected:
+  protected:
     FRIEND_TEST(storaged_test, storage_info_t);
     // emmc lifetime
     uint16_t eol;                   // pre-eol (end of life) information
@@ -66,8 +67,10 @@
     }
     void publish();
     storage_info_t* s_info;
-public:
-    static storage_info_t* get_storage_info();
+
+  public:
+    static storage_info_t* get_storage_info(
+        const sp<android::hardware::health::V2_0::IHealth>& healthService);
     virtual ~storage_info_t() {};
     virtual void report() {};
     void load_perf_history_proto(const IOPerfHistory& perf_history);
@@ -99,4 +102,18 @@
     virtual void report();
 };
 
+class health_storage_info_t : public storage_info_t {
+  private:
+    using IHealth = hardware::health::V2_0::IHealth;
+    using StorageInfo = hardware::health::V2_0::StorageInfo;
+
+    sp<IHealth> mHealth;
+    void set_values_from_hal_storage_info(const StorageInfo& halInfo);
+
+  public:
+    health_storage_info_t(const sp<IHealth>& service) : mHealth(service){};
+    virtual ~health_storage_info_t() {}
+    virtual void report();
+};
+
 #endif /* _STORAGED_INFO_H_ */
diff --git a/storaged/main.cpp b/storaged/main.cpp
index c1b1329..b3f1281 100644
--- a/storaged/main.cpp
+++ b/storaged/main.cpp
@@ -51,7 +51,7 @@
 void* storaged_main(void* /* unused */) {
     storaged_sp = new storaged_t();
 
-    storaged_sp->init_health_service();
+    storaged_sp->init();
     storaged_sp->report_storage_info();
 
     LOG_TO(SYSTEM, INFO) << "storaged: Start";
diff --git a/storaged/storaged.cpp b/storaged/storaged.cpp
index ff0de29..6807cd9 100644
--- a/storaged/storaged.cpp
+++ b/storaged/storaged.cpp
@@ -28,11 +28,12 @@
 #include <sstream>
 #include <string>
 
-#include <android/hidl/manager/1.0/IServiceManager.h>
 #include <android-base/file.h>
 #include <android-base/logging.h>
+#include <android/hidl/manager/1.0/IServiceManager.h>
 #include <batteryservice/BatteryServiceConstants.h>
 #include <cutils/properties.h>
+#include <healthhalutils/HealthHalUtils.h>
 #include <hidl/HidlTransportSupport.h>
 #include <hwbinder/IPCThreadState.h>
 #include <log/log.h>
@@ -62,25 +63,16 @@
 
 const uint32_t storaged_t::current_version = 4;
 
-using android::hardware::health::V1_0::BatteryStatus;
-using android::hardware::health::V1_0::toString;
-using android::hardware::health::V1_0::HealthInfo;
-using android::hardware::health::V2_0::IHealth;
-using android::hardware::health::V2_0::Result;
 using android::hardware::interfacesEqual;
 using android::hardware::Return;
+using android::hardware::health::V1_0::BatteryStatus;
+using android::hardware::health::V1_0::HealthInfo;
+using android::hardware::health::V1_0::toString;
+using android::hardware::health::V2_0::get_health_service;
+using android::hardware::health::V2_0::IHealth;
+using android::hardware::health::V2_0::Result;
 using android::hidl::manager::V1_0::IServiceManager;
 
-static sp<IHealth> get_health_service() {
-    for (auto&& instanceName : {"default", "backup"}) {
-        auto ret = IHealth::getService(instanceName);
-        if (ret != nullptr) {
-            return ret;
-        }
-        LOG_TO(SYSTEM, INFO) << "health: storaged: cannot get " << instanceName << " service";
-    }
-    return nullptr;
-}
 
 inline charger_stat_t is_charger_on(BatteryStatus prop) {
     return (prop == BatteryStatus::CHARGING || prop == BatteryStatus::FULL) ?
@@ -92,6 +84,12 @@
     return android::hardware::Void();
 }
 
+void storaged_t::init() {
+    init_health_service();
+    mDsm = std::make_unique<disk_stats_monitor>(health);
+    storage_info.reset(storage_info_t::get_storage_info(health));
+}
+
 void storaged_t::init_health_service() {
     if (!mUidm.enabled())
         return;
@@ -160,8 +158,6 @@
         property_get_int32("ro.storaged.flush_proto.interval",
                            DEFAULT_PERIODIC_CHORES_INTERVAL_FLUSH_PROTO);
 
-    storage_info.reset(storage_info_t::get_storage_info());
-
     mStarttime = time(NULL);
     mTimer = 0;
 }
@@ -315,10 +311,10 @@
 void storaged_t::event(void) {
     unordered_map<int, StoragedProto> protos;
 
-    if (mDsm.enabled()) {
-        mDsm.update();
+    if (mDsm->enabled()) {
+        mDsm->update();
         if (!(mTimer % mConfig.periodic_chores_interval_disk_stats_publish)) {
-            mDsm.publish();
+            mDsm->publish();
         }
     }
 
diff --git a/storaged/storaged_diskstats.cpp b/storaged/storaged_diskstats.cpp
index 0604e0a..1050033 100644
--- a/storaged/storaged_diskstats.cpp
+++ b/storaged/storaged_diskstats.cpp
@@ -30,6 +30,12 @@
 
 namespace {
 
+using android::sp;
+using android::hardware::health::V2_0::DiskStats;
+using android::hardware::health::V2_0::IHealth;
+using android::hardware::health::V2_0::Result;
+using android::hardware::health::V2_0::toString;
+
 #ifdef DEBUG
 void log_debug_disk_perf(struct disk_perf* perf, const char* type) {
     // skip if the input structure are all zeros
@@ -60,17 +66,30 @@
 
 } // namespace
 
-bool parse_disk_stats(const char* disk_stats_path, struct disk_stats* stats)
-{
-    // Get time
-    struct timespec ts;
+bool get_time(struct timespec* ts) {
     // Use monotonic to exclude suspend time so that we measure IO bytes/sec
     // when system is running.
-    int ret = clock_gettime(CLOCK_MONOTONIC, &ts);
+    int ret = clock_gettime(CLOCK_MONOTONIC, ts);
     if (ret < 0) {
         PLOG_TO(SYSTEM, ERROR) << "clock_gettime() failed";
         return false;
     }
+    return true;
+}
+
+void init_disk_stats_other(const struct timespec& ts, struct disk_stats* stats) {
+    stats->start_time = 0;
+    stats->end_time = (uint64_t)ts.tv_sec * SEC_TO_MSEC + ts.tv_nsec / (MSEC_TO_USEC * USEC_TO_NSEC);
+    stats->counter = 1;
+    stats->io_avg = (double)stats->io_in_flight;
+}
+
+bool parse_disk_stats(const char* disk_stats_path, struct disk_stats* stats) {
+    // Get time
+    struct timespec ts;
+    if (!get_time(&ts)) {
+        return false;
+    }
 
     std::string buffer;
     if (!android::base::ReadFileToString(disk_stats_path, &buffer)) {
@@ -84,11 +103,52 @@
         ss >> *((uint64_t*)stats + i);
     }
     // Other entries
-    stats->start_time = 0;
-    stats->end_time = (uint64_t)ts.tv_sec * SEC_TO_MSEC +
-        ts.tv_nsec / (MSEC_TO_USEC * USEC_TO_NSEC);
-    stats->counter = 1;
-    stats->io_avg = (double)stats->io_in_flight;
+    init_disk_stats_other(ts, stats);
+    return true;
+}
+
+void convert_hal_disk_stats(struct disk_stats* dst, const DiskStats& src) {
+    dst->read_ios = src.reads;
+    dst->read_merges = src.readMerges;
+    dst->read_sectors = src.readSectors;
+    dst->read_ticks = src.readTicks;
+    dst->write_ios = src.writes;
+    dst->write_merges = src.writeMerges;
+    dst->write_sectors = src.writeSectors;
+    dst->write_ticks = src.writeTicks;
+    dst->io_in_flight = src.ioInFlight;
+    dst->io_ticks = src.ioTicks;
+    dst->io_in_queue = src.ioInQueue;
+}
+
+bool get_disk_stats_from_health_hal(const sp<IHealth>& service, struct disk_stats* stats) {
+    struct timespec ts;
+    if (!get_time(&ts)) {
+        return false;
+    }
+
+    bool success = false;
+    auto ret = service->getDiskStats([&success, stats](auto result, const auto& halStats) {
+        if (result != Result::SUCCESS || halStats.size() == 0) {
+            LOG_TO(SYSTEM, ERROR) << "getDiskStats failed with result " << toString(result)
+                                  << " and size " << halStats.size();
+            return;
+        }
+
+        convert_hal_disk_stats(stats, halStats[0]);
+        success = true;
+    });
+
+    if (!ret.isOk()) {
+        LOG_TO(SYSTEM, ERROR) << "getDiskStats failed with " << ret.description();
+        return false;
+    }
+
+    if (!success) {
+        return false;
+    }
+
+    init_disk_stats_other(ts, stats);
     return true;
 }
 
@@ -243,8 +303,14 @@
 
 void disk_stats_monitor::update() {
     disk_stats curr;
-    if (!parse_disk_stats(DISK_STATS_PATH, &curr)) {
-        return;
+    if (mHealth != nullptr) {
+        if (!get_disk_stats_from_health_hal(mHealth, &curr)) {
+            return;
+        }
+    } else {
+        if (!parse_disk_stats(DISK_STATS_PATH, &curr)) {
+            return;
+        }
     }
 
     update(&curr);
diff --git a/storaged/storaged_info.cpp b/storaged/storaged_info.cpp
index b39804d..055f375 100644
--- a/storaged/storaged_info.cpp
+++ b/storaged/storaged_info.cpp
@@ -36,6 +36,10 @@
 using namespace android::base;
 using namespace storaged_proto;
 
+using android::hardware::health::V2_0::IHealth;
+using android::hardware::health::V2_0::Result;
+using android::hardware::health::V2_0::StorageInfo;
+
 const string emmc_info_t::emmc_sysfs = "/sys/bus/mmc/devices/mmc0:0001/";
 const string emmc_info_t::emmc_debugfs = "/d/mmc0/mmc0:0001/ext_csd";
 const char* emmc_info_t::emmc_ver_str[9] = {
@@ -54,8 +58,10 @@
 
 } // namespace
 
-storage_info_t* storage_info_t::get_storage_info()
-{
+storage_info_t* storage_info_t::get_storage_info(const sp<IHealth>& healthService) {
+    if (healthService != nullptr) {
+        return new health_storage_info_t(healthService);
+    }
     if (FileExists(emmc_info_t::emmc_sysfs) ||
         FileExists(emmc_info_t::emmc_debugfs)) {
         return new emmc_info_t;
@@ -358,3 +364,25 @@
     publish();
 }
 
+void health_storage_info_t::report() {
+    auto ret = mHealth->getStorageInfo([this](auto result, const auto& halInfos) {
+        if (result != Result::SUCCESS || halInfos.size() == 0) {
+            LOG_TO(SYSTEM, DEBUG) << "getStorageInfo failed with result " << toString(result)
+                                  << " and size " << halInfos.size();
+            return;
+        }
+        set_values_from_hal_storage_info(halInfos[0]);
+        publish();
+    });
+
+    if (!ret.isOk()) {
+        LOG_TO(SYSTEM, DEBUG) << "getStorageInfo failed with " << ret.description();
+    }
+}
+
+void health_storage_info_t::set_values_from_hal_storage_info(const StorageInfo& halInfo) {
+    eol = halInfo.eol;
+    lifetime_a = halInfo.lifetimeA;
+    lifetime_b = halInfo.lifetimeB;
+    version = halInfo.version;
+}
diff --git a/storaged/tests/storaged_test.cpp b/storaged/tests/storaged_test.cpp
index 6a5fc61..d1fa9ed 100644
--- a/storaged/tests/storaged_test.cpp
+++ b/storaged/tests/storaged_test.cpp
@@ -25,6 +25,7 @@
 
 #include <gtest/gtest.h>
 
+#include <healthhalutils/HealthHalUtils.h>
 #include <storaged.h>               // data structures
 #include <storaged_utils.h>         // functions to test
 
@@ -234,10 +235,17 @@
 }
 
 TEST(storaged_test, disk_stats_monitor) {
+    using android::hardware::health::V2_0::get_health_service;
+
+    auto healthService = get_health_service();
+
     // asserting that there is one file for diskstats
-    ASSERT_TRUE(access(MMC_DISK_STATS_PATH, R_OK) >= 0 || access(SDA_DISK_STATS_PATH, R_OK) >= 0);
+    ASSERT_TRUE(healthService != nullptr || access(MMC_DISK_STATS_PATH, R_OK) >= 0 ||
+                access(SDA_DISK_STATS_PATH, R_OK) >= 0);
+
     // testing if detect() will return the right value
-    disk_stats_monitor dsm_detect;
+    disk_stats_monitor dsm_detect{healthService};
+    ASSERT_TRUE(dsm_detect.enabled());
     // feed monitor with constant perf data for io perf baseline
     // using constant perf is reasonable since the functionality of stream_stats
     // has already been tested
@@ -280,7 +288,7 @@
     }
 
     // testing if stalled disk_stats can be correctly accumulated in the monitor
-    disk_stats_monitor dsm_acc;
+    disk_stats_monitor dsm_acc{healthService};
     struct disk_stats norm_inc = {
         .read_ios = 200,
         .read_merges = 0,
diff --git a/toolbox/Android.bp b/toolbox/Android.bp
index 9c2cafa..9f7fc3b 100644
--- a/toolbox/Android.bp
+++ b/toolbox/Android.bp
@@ -1,11 +1,19 @@
-common_cflags = [
-    "-Werror",
-    "-Wno-unused-parameter",
-    "-Wno-unused-const-variable",
-    "-include bsd-compatibility.h"
-]
+cc_defaults {
+    name: "toolbox_defaults",
+
+    cflags: [
+        "-Werror",
+        "-Wno-unused-parameter",
+        "-Wno-unused-const-variable",
+        "-include bsd-compatibility.h",
+    ],
+    local_include_dirs: ["upstream-netbsd/include/"],
+}
 
 cc_library_static {
+    name: "libtoolbox_dd",
+    defaults: ["toolbox_defaults"],
+    vendor_available: true,
     srcs: [
         "upstream-netbsd/bin/dd/args.c",
         "upstream-netbsd/bin/dd/conv.c",
@@ -19,17 +27,71 @@
         "upstream-netbsd/lib/libc/string/swab.c",
         "upstream-netbsd/lib/libutil/raise_default_signal.c",
     ],
-    cflags: common_cflags + [
+    cflags: [
         "-Dmain=dd_main",
         "-DNO_CONV",
     ],
-    local_include_dirs: ["upstream-netbsd/include/"],
-    name: "libtoolbox_dd",
+}
+
+genrule {
+    name: "toolbox_input_labels",
+    tool_files: ["generate-input.h-labels.py"],
+    cmd: "$(location) $(in) >$(out)",
+    srcs: [":kernel_input_headers"],
+    out: ["input.h-labels.h"],
+}
+
+cc_defaults {
+    name: "toolbox_binary_defaults",
+    defaults: ["toolbox_defaults"],
+    cpp_std: "experimental",
+    srcs: [
+        "toolbox.c",
+        "getevent.c",
+        "getprop.cpp",
+        "newfs_msdos.c",
+    ],
+    generated_headers: [
+        "toolbox_input_labels",
+    ],
+    whole_static_libs: ["libtoolbox_dd"],
+    shared_libs: [
+        "libbase",
+        "libcutils",
+    ],
+    static_libs: ["libpropertyinfoparser"],
+
+    symlinks: [
+        "dd",
+        "getevent",
+        "getprop",
+        "newfs_msdos",
+    ],
+}
+
+cc_binary {
+    name: "toolbox",
+    defaults: ["toolbox_binary_defaults"],
+}
+
+cc_binary {
+    name: "toolbox_vendor",
+    stem: "toolbox",
+    vendor: true,
+    defaults: ["toolbox_binary_defaults"],
+}
+
+// We only want 'r' on userdebug and eng builds.
+cc_binary {
+    name: "r",
+    defaults: ["toolbox_defaults"],
+    srcs: ["r.c"],
 }
 
 // We build BSD grep separately, so it can provide egrep and fgrep too.
 cc_defaults {
     name: "grep_common",
+    defaults: ["toolbox_defaults"],
     srcs: [
         "upstream-netbsd/usr.bin/grep/fastgrep.c",
         "upstream-netbsd/usr.bin/grep/file.c",
@@ -37,9 +99,10 @@
         "upstream-netbsd/usr.bin/grep/queue.c",
         "upstream-netbsd/usr.bin/grep/util.c",
     ],
-    cflags: common_cflags,
-    local_include_dirs: ["upstream-netbsd/include/"],
-    symlinks: ["egrep", "fgrep"],
+    symlinks: [
+        "egrep",
+        "fgrep",
+    ],
 
     sanitize: {
         integer_overflow: false,
diff --git a/toolbox/Android.mk b/toolbox/Android.mk
deleted file mode 100644
index c4795a7..0000000
--- a/toolbox/Android.mk
+++ /dev/null
@@ -1,70 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-
-common_cflags := \
-    -Werror -Wno-unused-parameter -Wno-unused-const-variable \
-    -include bsd-compatibility.h \
-
-include $(CLEAR_VARS)
-
-BSD_TOOLS := \
-    dd \
-
-OUR_TOOLS := \
-    getevent \
-    newfs_msdos \
-
-ALL_TOOLS = $(BSD_TOOLS) $(OUR_TOOLS)
-
-LOCAL_SRC_FILES := \
-    toolbox.c \
-    $(patsubst %,%.c,$(OUR_TOOLS)) \
-
-LOCAL_CFLAGS += $(common_cflags)
-LOCAL_C_INCLUDES += $(LOCAL_PATH)/upstream-netbsd/include/
-
-LOCAL_SHARED_LIBRARIES := \
-    libcutils \
-
-LOCAL_WHOLE_STATIC_LIBRARIES := $(patsubst %,libtoolbox_%,$(BSD_TOOLS))
-
-LOCAL_MODULE := toolbox
-
-# Install the symlinks.
-LOCAL_POST_INSTALL_CMD := $(hide) $(foreach t,$(ALL_TOOLS),ln -sf toolbox $(TARGET_OUT)/bin/$(t);)
-
-# Including this will define $(intermediates).
-#
-include $(BUILD_EXECUTABLE)
-
-$(LOCAL_PATH)/toolbox.c: $(intermediates)/tools.h
-
-TOOLS_H := $(intermediates)/tools.h
-$(TOOLS_H): PRIVATE_TOOLS := toolbox $(ALL_TOOLS)
-$(TOOLS_H): PRIVATE_CUSTOM_TOOL = echo "/* file generated automatically */" > $@ ; for t in $(PRIVATE_TOOLS) ; do echo "TOOL($$t)" >> $@ ; done
-$(TOOLS_H): $(LOCAL_PATH)/Android.mk
-$(TOOLS_H):
-	$(transform-generated-source)
-
-$(LOCAL_PATH)/getevent.c: $(intermediates)/input.h-labels.h
-
-UAPI_INPUT_EVENT_CODES_H := bionic/libc/kernel/uapi/linux/input.h bionic/libc/kernel/uapi/linux/input-event-codes.h
-INPUT_H_LABELS_H := $(intermediates)/input.h-labels.h
-$(INPUT_H_LABELS_H): PRIVATE_LOCAL_PATH := $(LOCAL_PATH)
-# The PRIVATE_CUSTOM_TOOL line uses = to evaluate the output path late.
-# We copy the input path so it can't be accidentally modified later.
-$(INPUT_H_LABELS_H): PRIVATE_UAPI_INPUT_EVENT_CODES_H := $(UAPI_INPUT_EVENT_CODES_H)
-$(INPUT_H_LABELS_H): PRIVATE_CUSTOM_TOOL = $(PRIVATE_LOCAL_PATH)/generate-input.h-labels.py $(PRIVATE_UAPI_INPUT_EVENT_CODES_H) > $@
-# The dependency line though gets evaluated now, so the PRIVATE_ copy doesn't exist yet,
-# and the original can't yet have been modified, so this is both sufficient and necessary.
-$(INPUT_H_LABELS_H): $(LOCAL_PATH)/Android.mk $(LOCAL_PATH)/generate-input.h-labels.py $(UAPI_INPUT_EVENT_CODES_H)
-$(INPUT_H_LABELS_H):
-	$(transform-generated-source)
-
-# We only want 'r' on userdebug and eng builds.
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := r.c
-LOCAL_CFLAGS += $(common_cflags)
-LOCAL_C_INCLUDES += $(LOCAL_PATH)/upstream-netbsd/include/
-LOCAL_MODULE := r
-LOCAL_MODULE_TAGS := debug
-include $(BUILD_EXECUTABLE)
diff --git a/toolbox/getprop.cpp b/toolbox/getprop.cpp
new file mode 100644
index 0000000..9e324a0
--- /dev/null
+++ b/toolbox/getprop.cpp
@@ -0,0 +1,161 @@
+//
+// 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 <sys/system_properties.h>
+
+#include <iostream>
+#include <string>
+#include <vector>
+
+#include <android-base/properties.h>
+#include <property_info_parser/property_info_parser.h>
+
+using android::base::GetProperty;
+using android::properties::PropertyInfoAreaFile;
+
+PropertyInfoAreaFile property_info_file;
+
+enum class ResultType {
+    Value,
+    Context,
+    Type,
+};
+
+void PrintAllProperties(ResultType result_type) {
+    std::vector<std::pair<std::string, std::string>> properties;
+    __system_property_foreach(
+        [](const prop_info* pi, void* cookie) {
+            __system_property_read_callback(
+                pi,
+                [](void* cookie, const char* name, const char* value, unsigned) {
+                    auto properties =
+                        reinterpret_cast<std::vector<std::pair<std::string, std::string>>*>(cookie);
+                    properties->emplace_back(name, value);
+                },
+                cookie);
+        },
+        &properties);
+
+    std::sort(properties.begin(), properties.end());
+
+    if (result_type != ResultType::Value) {
+        for (auto& [name, value] : properties) {
+            const char* context = nullptr;
+            const char* type = nullptr;
+            property_info_file->GetPropertyInfo(name.c_str(), &context, &type);
+            if (result_type == ResultType::Context) {
+                value = context;
+            } else {
+                value = type;
+            }
+        }
+    }
+
+    for (const auto& [name, value] : properties) {
+        std::cout << "[" << name << "]: [" << value << "]" << std::endl;
+    }
+}
+
+void PrintProperty(const char* name, const char* default_value, ResultType result_type) {
+    switch (result_type) {
+        case ResultType::Value:
+            std::cout << GetProperty(name, default_value) << std::endl;
+            break;
+        case ResultType::Context: {
+            const char* context = nullptr;
+            property_info_file->GetPropertyInfo(name, &context, nullptr);
+            std::cout << context << std::endl;
+            break;
+        }
+        case ResultType::Type: {
+            const char* type = nullptr;
+            property_info_file->GetPropertyInfo(name, nullptr, &type);
+            std::cout << type << std::endl;
+            break;
+        }
+    }
+}
+
+extern "C" int getprop_main(int argc, char** argv) {
+    auto result_type = ResultType::Value;
+
+    while (true) {
+        static const struct option long_options[] = {
+            {"help", no_argument, nullptr, 'h'},
+            {nullptr, 0, nullptr, 0},
+        };
+
+        int arg = getopt_long(argc, argv, "TZ", long_options, nullptr);
+
+        if (arg == -1) {
+            break;
+        }
+
+        switch (arg) {
+            case 'h':
+                std::cout << "usage: getprop [-TZ] [NAME [DEFAULT]]\n"
+                             "\n"
+                             "Gets an Android system property, or lists them all.\n"
+                             "\n"
+                             "-T\tShow property types instead of values\n"
+                             "-Z\tShow property contexts instead of values\n"
+                          << std::endl;
+                return 0;
+            case 'T':
+                if (result_type != ResultType::Value) {
+                    std::cerr << "Only one of -T or -Z may be specified" << std::endl;
+                    return -1;
+                }
+                result_type = ResultType::Type;
+                break;
+            case 'Z':
+                if (result_type != ResultType::Value) {
+                    std::cerr << "Only one of -T or -Z may be specified" << std::endl;
+                    return -1;
+                }
+                result_type = ResultType::Context;
+                break;
+            case '?':
+                return -1;
+            default:
+                std::cerr << "getprop: getopt returned invalid result: " << arg << std::endl;
+                return -1;
+        }
+    }
+
+    if (result_type != ResultType::Value) {
+        property_info_file.LoadDefaultPath();
+        if (!property_info_file) {
+            std::cerr << "Unable to load property info file" << std::endl;
+            return -1;
+        }
+    }
+
+    if (optind >= argc) {
+        PrintAllProperties(result_type);
+        return 0;
+    }
+
+    if (optind < argc - 2) {
+        std::cerr << "getprop: Max 2 arguments (see \"getprop --help\")" << std::endl;
+        return -1;
+    }
+
+    PrintProperty(argv[optind], (optind == argc - 1) ? "" : argv[optind + 1], result_type);
+
+    return 0;
+}
diff --git a/toolbox/tools.h b/toolbox/tools.h
new file mode 100644
index 0000000..505f528
--- /dev/null
+++ b/toolbox/tools.h
@@ -0,0 +1,5 @@
+TOOL(dd)
+TOOL(getevent)
+TOOL(getprop)
+TOOL(newfs_msdos)
+TOOL(toolbox)
diff --git a/trusty/OWNERS b/trusty/OWNERS
index 25291fd..357b4f4 100644
--- a/trusty/OWNERS
+++ b/trusty/OWNERS
@@ -1 +1,3 @@
 bohr@google.com
+swillden@google.com
+dkrahn@google.com
diff --git a/trusty/keymaster/Android.bp b/trusty/keymaster/Android.bp
index 322a63d..479a7e0 100644
--- a/trusty/keymaster/Android.bp
+++ b/trusty/keymaster/Android.bp
@@ -36,7 +36,6 @@
         "libcrypto",
         "libcutils",
         "libkeymaster_portable",
-        "libkeymaster_staging",
         "libtrusty",
         "libkeymaster_messages",
         "libsoftkeymasterdevice",
diff --git a/trusty/storage/proxy/storage.c b/trusty/storage/proxy/storage.c
index c61e89d..5b83e21 100644
--- a/trusty/storage/proxy/storage.c
+++ b/trusty/storage/proxy/storage.c
@@ -379,7 +379,7 @@
     }
 
     if (req->size > MAX_READ_SIZE) {
-        ALOGW("%s: request is too large (%zd > %zd) - refusing\n",
+        ALOGW("%s: request is too large (%u > %d) - refusing\n",
               __func__, req->size, MAX_READ_SIZE);
         msg->result = STORAGE_ERR_NOT_VALID;
         goto err_response;