Merge "Don't display bugreport progress when it recedes, for real..."
diff --git a/.clang-format-2 b/.clang-format-2
index aab4665..41591ce 100644
--- a/.clang-format-2
+++ b/.clang-format-2
@@ -1,4 +1,5 @@
 BasedOnStyle: Google
+AllowShortFunctionsOnASingleLine: Inline
 ColumnLimit: 100
 CommentPragmas: NOLINT:.*
 DerivePointerAlignment: false
diff --git a/.clang-format-4 b/.clang-format-4
index 1497447..ae4a451 100644
--- a/.clang-format-4
+++ b/.clang-format-4
@@ -1,5 +1,6 @@
 BasedOnStyle: Google
 AccessModifierOffset: -2
+AllowShortFunctionsOnASingleLine: Inline
 ColumnLimit: 100
 CommentPragmas: NOLINT:.*
 DerivePointerAlignment: false
diff --git a/adb/Android.mk b/adb/Android.mk
index 8a43e37..112bc80 100644
--- a/adb/Android.mk
+++ b/adb/Android.mk
@@ -81,12 +81,14 @@
 
 LIBADB_darwin_SRC_FILES := \
     sysdeps_unix.cpp \
+    sysdeps/posix/network.cpp \
     client/usb_dispatch.cpp \
     client/usb_libusb.cpp \
     client/usb_osx.cpp \
 
 LIBADB_linux_SRC_FILES := \
     sysdeps_unix.cpp \
+    sysdeps/posix/network.cpp \
     client/usb_dispatch.cpp \
     client/usb_libusb.cpp \
     client/usb_linux.cpp \
@@ -123,13 +125,13 @@
     $(LIBADB_SRC_FILES) \
     adbd_auth.cpp \
     jdwp_service.cpp \
+    sysdeps/posix/network.cpp \
 
-LOCAL_C_INCLUDES := system/core/qemu_pipe/include
 LOCAL_SANITIZE := $(adb_target_sanitize)
 
 # Even though we're building a static library (and thus there's no link step for
 # this to take effect), this adds the includes to our path.
-LOCAL_STATIC_LIBRARIES := libcrypto_utils libcrypto libqemu_pipe libbase
+LOCAL_STATIC_LIBRARIES := libcrypto_utils libcrypto libbase
 
 LOCAL_WHOLE_STATIC_LIBRARIES := libadbd_usb
 
@@ -218,9 +220,9 @@
 LOCAL_SRC_FILES_darwin := $(LIBADB_TEST_darwin_SRCS)
 LOCAL_SRC_FILES_windows := $(LIBADB_TEST_windows_SRCS)
 LOCAL_SANITIZE := $(adb_host_sanitize)
-LOCAL_SHARED_LIBRARIES := libbase
 LOCAL_STATIC_LIBRARIES := \
     libadb \
+    libbase \
     libcrypto_utils \
     libcrypto \
     libcutils \
@@ -361,8 +363,8 @@
 LOCAL_STRIP_MODULE := keep_symbols
 LOCAL_STATIC_LIBRARIES := \
     libadbd \
+    libavb_user \
     libbase \
-    libqemu_pipe \
     libbootloader_message \
     libfs_mgr \
     libfec \
diff --git a/adb/adb.cpp b/adb/adb.cpp
index 577e9b9..39e71e5 100644
--- a/adb/adb.cpp
+++ b/adb/adb.cpp
@@ -59,10 +59,12 @@
 
 std::string adb_version() {
     // Don't change the format of this --- it's parsed by ddmlib.
-    return android::base::StringPrintf("Android Debug Bridge version %d.%d.%d\n"
-                                       "Revision %s\n",
-                                       ADB_VERSION_MAJOR, ADB_VERSION_MINOR, ADB_SERVER_VERSION,
-                                       ADB_REVISION);
+    return android::base::StringPrintf(
+        "Android Debug Bridge version %d.%d.%d\n"
+        "Revision %s\n"
+        "Installed as %s\n",
+        ADB_VERSION_MAJOR, ADB_VERSION_MINOR, ADB_SERVER_VERSION, ADB_REVISION,
+        android::base::GetExecutablePath().c_str());
 }
 
 void fatal(const char *fmt, ...) {
@@ -251,6 +253,19 @@
     send_packet(cp, t);
 }
 
+#if ADB_HOST
+
+void SendConnectOnHost(atransport* t) {
+    // Send an empty message before A_CNXN message. This is because the data toggle of the ep_out on
+    // host and ep_in on device may not be the same.
+    apacket* p = get_apacket();
+    CHECK(p);
+    send_packet(p, t);
+    send_connect(t);
+}
+
+#endif
+
 // qual_overwrite is used to overwrite a qualifier string.  dst is a
 // pointer to a char pointer.  It is assumed that if *dst is non-NULL, it
 // was malloc'ed and needs to freed.  *dst will be set to a dup of src.
@@ -297,29 +312,29 @@
     const std::string& type = pieces[0];
     if (type == "bootloader") {
         D("setting connection_state to kCsBootloader");
-        t->connection_state = kCsBootloader;
+        t->SetConnectionState(kCsBootloader);
         update_transports();
     } else if (type == "device") {
         D("setting connection_state to kCsDevice");
-        t->connection_state = kCsDevice;
+        t->SetConnectionState(kCsDevice);
         update_transports();
     } else if (type == "recovery") {
         D("setting connection_state to kCsRecovery");
-        t->connection_state = kCsRecovery;
+        t->SetConnectionState(kCsRecovery);
         update_transports();
     } else if (type == "sideload") {
         D("setting connection_state to kCsSideload");
-        t->connection_state = kCsSideload;
+        t->SetConnectionState(kCsSideload);
         update_transports();
     } else {
         D("setting connection_state to kCsHost");
-        t->connection_state = kCsHost;
+        t->SetConnectionState(kCsHost);
     }
 }
 
 static void handle_new_connection(atransport* t, apacket* p) {
-    if (t->connection_state != kCsOffline) {
-        t->connection_state = kCsOffline;
+    if (t->GetConnectionState() != kCsOffline) {
+        t->SetConnectionState(kCsOffline);
         handle_offline(t);
     }
 
@@ -353,10 +368,10 @@
         if (p->msg.arg0){
             send_packet(p, t);
 #if ADB_HOST
-            send_connect(t);
+            SendConnectOnHost(t);
 #endif
         } else {
-            t->connection_state = kCsOffline;
+            t->SetConnectionState(kCsOffline);
             handle_offline(t);
             send_packet(p, t);
         }
@@ -370,7 +385,9 @@
         switch (p->msg.arg0) {
 #if ADB_HOST
             case ADB_AUTH_TOKEN:
-                t->connection_state = kCsUnauthorized;
+                if (t->GetConnectionState() == kCsOffline) {
+                    t->SetConnectionState(kCsUnauthorized);
+                }
                 send_auth_response(p->data, p->msg.data_length, t);
                 break;
 #else
@@ -389,7 +406,7 @@
                 break;
 #endif
             default:
-                t->connection_state = kCsOffline;
+                t->SetConnectionState(kCsOffline);
                 handle_offline(t);
                 break;
         }
@@ -505,8 +522,8 @@
     if (!_try_make_handle_noninheritable(h)) {
         // Show the handle value to give us a clue in case we have problems
         // with pseudo-handle values.
-        fprintf(stderr, "Cannot make handle 0x%p non-inheritable: %s\n",
-                h, android::base::SystemErrorCodeToString(GetLastError()).c_str());
+        fprintf(stderr, "adb: cannot make handle 0x%p non-inheritable: %s\n", h,
+                android::base::SystemErrorCodeToString(GetLastError()).c_str());
         return false;
     }
 
@@ -521,7 +538,7 @@
     HANDLE pipe_read_raw = NULL;
     HANDLE pipe_write_raw = NULL;
     if (!CreatePipe(&pipe_read_raw, &pipe_write_raw, sa, 0)) {
-        fprintf(stderr, "Cannot create pipe: %s\n",
+        fprintf(stderr, "adb: CreatePipe failed: %s\n",
                 android::base::SystemErrorCodeToString(GetLastError()).c_str());
         return false;
     }
@@ -552,7 +569,8 @@
     std::unique_ptr<FILE, decltype(&fclose)> stream(nullptr, fclose);
 
     if (original_fd == -1) {
-        fprintf(stderr, "Failed to get file descriptor for %s: %s\n", output_name, strerror(errno));
+        fprintf(stderr, "adb: failed to get file descriptor for %s: %s\n", output_name,
+                strerror(errno));
         return EXIT_FAILURE;
     }
 
@@ -564,7 +582,7 @@
         // call this function if subprocesses may be started concurrently.
         const int fd = dup(original_fd);
         if (fd == -1) {
-            fprintf(stderr, "Failed to duplicate file descriptor for %s: %s\n", output_name,
+            fprintf(stderr, "adb: failed to duplicate file descriptor for %s: %s\n", output_name,
                     strerror(errno));
             return EXIT_FAILURE;
         }
@@ -572,7 +590,7 @@
         // Note that although we call fdopen() below with a binary flag, it may not adhere to that
         // flag, so we have to set the mode manually.
         if (_setmode(fd, _O_BINARY) == -1) {
-            fprintf(stderr, "Failed to set binary mode for duplicate of %s: %s\n", output_name,
+            fprintf(stderr, "adb: failed to set binary mode for duplicate of %s: %s\n", output_name,
                     strerror(errno));
             unix_close(fd);
             return EXIT_FAILURE;
@@ -580,7 +598,7 @@
 
         stream.reset(fdopen(fd, "wb"));
         if (stream.get() == nullptr) {
-            fprintf(stderr, "Failed to open duplicate stream for %s: %s\n", output_name,
+            fprintf(stderr, "adb: failed to open duplicate stream for %s: %s\n", output_name,
                     strerror(errno));
             unix_close(fd);
             return EXIT_FAILURE;
@@ -589,7 +607,7 @@
         // Unbuffer the stream because it will be buffered by default and we want subprocess output
         // to be shown immediately.
         if (setvbuf(stream.get(), NULL, _IONBF, 0) == -1) {
-            fprintf(stderr, "Failed to unbuffer %s: %s\n", output_name, strerror(errno));
+            fprintf(stderr, "adb: failed to unbuffer %s: %s\n", output_name, strerror(errno));
             return EXIT_FAILURE;
         }
 
@@ -606,7 +624,7 @@
             if (err == ERROR_BROKEN_PIPE) {
                 return EXIT_SUCCESS;
             } else {
-                fprintf(stderr, "Failed to read from %s: %s\n", output_name,
+                fprintf(stderr, "adb: failed to read from %s: %s\n", output_name,
                         android::base::SystemErrorCodeToString(err).c_str());
                 return EXIT_FAILURE;
             }
@@ -617,8 +635,8 @@
             // fwrite() actually calls adb_fwrite() which can write UTF-8 to the console.
             const size_t bytes_written = fwrite(buf, 1, bytes_read, stream.get());
             if (bytes_written != bytes_read) {
-                fprintf(stderr, "Only wrote %zu of %lu bytes to %s\n", bytes_written, bytes_read,
-                        output_name);
+                fprintf(stderr, "adb: error: only wrote %zu of %lu bytes to %s\n", bytes_written,
+                        bytes_read, output_name);
                 return EXIT_FAILURE;
             }
         }
@@ -661,7 +679,7 @@
             FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING,
             FILE_ATTRIBUTE_NORMAL, NULL));
     if (nul_read.get() == INVALID_HANDLE_VALUE) {
-        fprintf(stderr, "Cannot open 'nul': %s\n",
+        fprintf(stderr, "adb: CreateFileW 'nul' failed: %s\n",
                 android::base::SystemErrorCodeToString(GetLastError()).c_str());
         return -1;
     }
@@ -723,8 +741,7 @@
         // If this fires, either handle values are larger than 32-bits or else
         // there is a bug in our casting.
         // https://msdn.microsoft.com/en-us/library/windows/desktop/aa384203%28v=vs.85%29.aspx
-        fprintf(stderr, "Cannot fit pipe handle value into 32-bits: 0x%p\n",
-                ack_write.get());
+        fprintf(stderr, "adb: cannot fit pipe handle value into 32-bits: 0x%p\n", ack_write.get());
         return -1;
     }
 
@@ -734,7 +751,7 @@
                                                    arraysize(program_path));
     if ((module_result >= arraysize(program_path)) || (module_result == 0)) {
         // String truncation or some other error.
-        fprintf(stderr, "Cannot get executable path: %s\n",
+        fprintf(stderr, "adb: cannot get executable path: %s\n",
                 android::base::SystemErrorCodeToString(GetLastError()).c_str());
         return -1;
     }
@@ -759,7 +776,7 @@
             NULL,                    /* use parent's starting directory */
             &startup,                 /* startup info, i.e. std handles */
             &pinfo )) {
-        fprintf(stderr, "Cannot create process: %s\n",
+        fprintf(stderr, "adb: CreateProcessW failed: %s\n",
                 android::base::SystemErrorCodeToString(GetLastError()).c_str());
         return -1;
     }
@@ -789,7 +806,7 @@
             _beginthreadex(NULL, 0, _redirect_stdout_thread, stdout_read.get(),
                            0, NULL)));
     if (stdout_thread.get() == nullptr) {
-        fprintf(stderr, "Cannot create thread: %s\n", strerror(errno));
+        fprintf(stderr, "adb: cannot create thread: %s\n", strerror(errno));
         return -1;
     }
     stdout_read.release();  // Transfer ownership to new thread
@@ -798,7 +815,7 @@
             _beginthreadex(NULL, 0, _redirect_stderr_thread, stderr_read.get(),
                            0, NULL)));
     if (stderr_thread.get() == nullptr) {
-        fprintf(stderr, "Cannot create thread: %s\n", strerror(errno));
+        fprintf(stderr, "adb: cannot create thread: %s\n", strerror(errno));
         return -1;
     }
     stderr_read.release();  // Transfer ownership to new thread
@@ -843,22 +860,20 @@
     if (wait_result == WAIT_TIMEOUT) {
         // Threads did not finish after waiting a little while. Perhaps the
         // server didn't close pipes, or it is hung.
-        fprintf(stderr, "Timed-out waiting for threads to finish reading from "
-                "ADB Server\n");
+        fprintf(stderr, "adb: timed out waiting for threads to finish reading from ADB server\n");
         // Process handles are signaled when the process exits, so if we wait
         // on the handle for 0 seconds and it returns 'timeout', that means that
         // the process is still running.
         if (WaitForSingleObject(process_handle.get(), 0) == WAIT_TIMEOUT) {
             // We could TerminateProcess(), but that seems somewhat presumptive.
-            fprintf(stderr, "ADB Server is running: process id %lu\n",
-                    pinfo.dwProcessId);
+            fprintf(stderr, "adb: server is running with process id %lu\n", pinfo.dwProcessId);
         }
         return -1;
     }
 
     if (wait_result != WAIT_OBJECT_0) {
-        fprintf(stderr, "Unexpected result waiting for threads: %lu: %s\n",
-                wait_result, android::base::SystemErrorCodeToString(GetLastError()).c_str());
+        fprintf(stderr, "adb: unexpected result waiting for threads: %lu: %s\n", wait_result,
+                android::base::SystemErrorCodeToString(GetLastError()).c_str());
         return -1;
     }
 
@@ -892,7 +907,7 @@
         int result = execl(path.c_str(), "adb", "-L", socket_spec.c_str(), "fork-server", "server",
                            "--reply-fd", reply_fd, NULL);
         // this should not return
-        fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
+        fprintf(stderr, "adb: execl returned %d: %s\n", result, strerror(errno));
     } else  {
         // parent side of the fork
 
@@ -1032,7 +1047,6 @@
     SendProtocolString(fd, s);
     return 0;
 }
-#endif
 
 int handle_host_request(const char* service, TransportType type,
                         const char* serial, int reply_fd, asocket* s) {
@@ -1051,7 +1065,6 @@
         android::base::quick_exit(0);
     }
 
-#if ADB_HOST
     // "transport:" is used for switching transport with a specified serial number
     // "transport-usb:" is used for switching transport to the only USB transport
     // "transport-local:" is used for switching transport to the only local transport
@@ -1096,16 +1109,10 @@
     if (!strcmp(service, "reconnect-offline")) {
         std::string response;
         close_usb_devices([&response](const atransport* transport) {
-            switch (transport->connection_state) {
+            switch (transport->GetConnectionState()) {
                 case kCsOffline:
                 case kCsUnauthorized:
-                    response += "reconnecting ";
-                    if (transport->serial) {
-                        response += transport->serial;
-                    } else {
-                        response += "<unknown>";
-                    }
-                    response += "\n";
+                    response += "reconnecting " + transport->serial_name() + "\n";
                     return true;
                 default:
                     return false;
@@ -1129,7 +1136,6 @@
         return 0;
     }
 
-#if ADB_HOST
     if (!strcmp(service, "host-features")) {
         FeatureSet features = supported_features();
         // Abuse features to report libusb status.
@@ -1139,7 +1145,6 @@
         SendOkay(reply_fd, FeatureSetToString(features));
         return 0;
     }
-#endif
 
     // remove TCP transport
     if (!strncmp(service, "disconnect:", 11)) {
@@ -1209,15 +1214,19 @@
     }
 
     if (!strcmp(service, "reconnect")) {
-        if (s->transport != nullptr) {
-            kick_transport(s->transport);
+        std::string response;
+        atransport* t = acquire_one_transport(type, serial, nullptr, &response, true);
+        if (t != nullptr) {
+            kick_transport(t);
+            response =
+                "reconnecting " + t->serial_name() + " [" + t->connection_state_name() + "]\n";
         }
-        return SendOkay(reply_fd, "done");
+        return SendOkay(reply_fd, response);
     }
-#endif // ADB_HOST
 
     int ret = handle_forward_request(service, type, serial, reply_fd);
     if (ret >= 0)
       return ret - 1;
     return -1;
 }
+#endif  // ADB_HOST
diff --git a/adb/adb.h b/adb/adb.h
index aea5fb8..e3675d8 100644
--- a/adb/adb.h
+++ b/adb/adb.h
@@ -139,7 +139,7 @@
 int get_available_local_transport_index();
 #endif
 int  init_socket_transport(atransport *t, int s, int port, int local);
-void init_usb_transport(atransport *t, usb_handle *usb, ConnectionState state);
+void init_usb_transport(atransport* t, usb_handle* usb);
 
 std::string getEmulatorSerialString(int console_port);
 #if ADB_HOST
@@ -222,6 +222,9 @@
 void handle_offline(atransport *t);
 
 void send_connect(atransport *t);
+#if ADB_HOST
+void SendConnectOnHost(atransport* t);
+#endif
 
 void parse_banner(const std::string&, atransport* t);
 
diff --git a/adb/adb_auth_host.cpp b/adb/adb_auth_host.cpp
index c3f1fe0..365bf77 100644
--- a/adb/adb_auth_host.cpp
+++ b/adb/adb_auth_host.cpp
@@ -82,16 +82,17 @@
         return false;
     }
 
-    size_t base64_key_length;
-    if (!EVP_EncodedLength(&base64_key_length, sizeof(binary_key_data))) {
+    size_t expected_length;
+    if (!EVP_EncodedLength(&expected_length, sizeof(binary_key_data))) {
         LOG(ERROR) << "Public key too large to base64 encode";
         return false;
     }
 
     std::string content;
-    content.resize(base64_key_length);
-    base64_key_length = EVP_EncodeBlock(reinterpret_cast<uint8_t*>(&content[0]), binary_key_data,
-                                        sizeof(binary_key_data));
+    content.resize(expected_length);
+    size_t actual_length = EVP_EncodeBlock(reinterpret_cast<uint8_t*>(&content[0]), binary_key_data,
+                                           sizeof(binary_key_data));
+    content.resize(actual_length);
 
     content += get_user_info();
 
diff --git a/adb/adb_client.cpp b/adb/adb_client.cpp
index ef52189..b656887 100644
--- a/adb/adb_client.cpp
+++ b/adb/adb_client.cpp
@@ -136,8 +136,7 @@
         return -2;
     }
 
-    if ((memcmp(&service[0],"host",4) != 0 || service == "host:reconnect") &&
-        switch_socket_transport(fd, error)) {
+    if (memcmp(&service[0], "host", 4) != 0 && switch_socket_transport(fd, error)) {
         return -1;
     }
 
@@ -147,11 +146,9 @@
         return -1;
     }
 
-    if (service != "reconnect") {
-        if (!adb_status(fd, error)) {
-            adb_close(fd);
-            return -1;
-        }
+    if (!adb_status(fd, error)) {
+        adb_close(fd);
+        return -1;
     }
 
     D("_adb_connect: return fd %d", fd);
@@ -164,21 +161,21 @@
 
     D("adb_connect: service %s", service.c_str());
     if (fd == -2 && !is_local_socket_spec(__adb_server_socket_spec)) {
-        fprintf(stderr,"** Cannot start server on remote host\n");
+        fprintf(stderr, "* cannot start server on remote host\n");
         // error is the original network connection error
         return fd;
     } else if (fd == -2) {
-        fprintf(stdout, "* daemon not running. starting it now at %s *\n", __adb_server_socket_spec);
+        fprintf(stderr, "* daemon not running; starting now at %s\n", __adb_server_socket_spec);
     start_server:
         if (launch_server(__adb_server_socket_spec)) {
-            fprintf(stderr,"* failed to start daemon *\n");
+            fprintf(stderr, "* failed to start daemon\n");
             // launch_server() has already printed detailed error info, so just
             // return a generic error string about the overall adb_connect()
             // that the caller requested.
             *error = "cannot connect to daemon";
             return -1;
         } else {
-            fprintf(stdout,"* daemon started successfully *\n");
+            fprintf(stderr, "* daemon started successfully\n");
         }
         // Give the server some time to start properly and detect devices.
         std::this_thread::sleep_for(3s);
@@ -213,8 +210,8 @@
         }
 
         if (version != ADB_SERVER_VERSION) {
-            printf("adb server version (%d) doesn't match this client (%d); killing...\n",
-                   version, ADB_SERVER_VERSION);
+            fprintf(stderr, "adb server version (%d) doesn't match this client (%d); killing...\n",
+                    version, ADB_SERVER_VERSION);
             fd = _adb_connect("host:kill", error);
             if (fd >= 0) {
                 ReadOrderlyShutdown(fd);
@@ -240,7 +237,7 @@
     if (fd == -1) {
         D("_adb_connect error: %s", error->c_str());
     } else if(fd == -2) {
-        fprintf(stderr,"** daemon still not running\n");
+        fprintf(stderr, "* daemon still not running\n");
     }
     D("adb_connect: return fd %d", fd);
 
diff --git a/adb/adb_trace.cpp b/adb/adb_trace.cpp
index c369d60..eac923d 100644
--- a/adb/adb_trace.cpp
+++ b/adb/adb_trace.cpp
@@ -155,7 +155,7 @@
     }
 #endif
 
-#if !defined(_WIN32)
+#if ADB_HOST && !defined(_WIN32)
     // adb historically ignored $ANDROID_LOG_TAGS but passed it through to logcat.
     // If set, move it out of the way so that libbase logging doesn't try to parse it.
     std::string log_tags;
@@ -168,7 +168,7 @@
 
     android::base::InitLogging(argv, &AdbLogger);
 
-#if !defined(_WIN32)
+#if ADB_HOST && !defined(_WIN32)
     // Put $ANDROID_LOG_TAGS back so we can pass it to logcat.
     if (!log_tags.empty()) setenv("ANDROID_LOG_TAGS", log_tags.c_str(), 1);
 #endif
diff --git a/adb/adb_trace.h b/adb/adb_trace.h
index aaffa29..fc6560c 100644
--- a/adb/adb_trace.h
+++ b/adb/adb_trace.h
@@ -58,6 +58,9 @@
 void adb_trace_init(char**);
 void adb_trace_enable(AdbTrace trace_tag);
 
+// Include <atomic> before stdatomic.h (introduced in cutils/trace.h) to avoid compile error.
+#include <atomic>
+
 #define ATRACE_TAG ATRACE_TAG_ADB
 #include <cutils/trace.h>
 #include <utils/Trace.h>
diff --git a/adb/adb_utils.cpp b/adb/adb_utils.cpp
index 7058acb..6f2403d 100644
--- a/adb/adb_utils.cpp
+++ b/adb/adb_utils.cpp
@@ -75,7 +75,7 @@
 
 bool directory_exists(const std::string& path) {
   struct stat sb;
-  return lstat(path.c_str(), &sb) != -1 && S_ISDIR(sb.st_mode);
+  return stat(path.c_str(), &sb) != -1 && S_ISDIR(sb.st_mode);
 }
 
 std::string escape_arg(const std::string& s) {
@@ -267,8 +267,8 @@
     adb_close(fd);
 }
 
-int usage(const char* fmt, ...) {
-    fprintf(stderr, "adb: ");
+int syntax_error(const char* fmt, ...) {
+    fprintf(stderr, "adb: usage: ");
 
     va_list ap;
     va_start(ap, fmt);
diff --git a/adb/adb_utils.h b/adb/adb_utils.h
index e0ad103..c1d5549 100644
--- a/adb/adb_utils.h
+++ b/adb/adb_utils.h
@@ -21,7 +21,7 @@
 
 #include <android-base/macros.h>
 
-int usage(const char*, ...);
+int syntax_error(const char*, ...);
 
 void close_stdin();
 
diff --git a/adb/adb_utils_test.cpp b/adb/adb_utils_test.cpp
index a3bc445..e1b6287 100644
--- a/adb/adb_utils_test.cpp
+++ b/adb/adb_utils_test.cpp
@@ -55,7 +55,6 @@
   ASSERT_FALSE(directory_exists(subdir(profiles_dir, "does-not-exist")));
 #else
   ASSERT_TRUE(directory_exists("/proc"));
-  ASSERT_FALSE(directory_exists("/proc/self")); // Symbolic link.
   ASSERT_FALSE(directory_exists("/proc/does-not-exist"));
 #endif
 }
diff --git a/adb/bugreport.cpp b/adb/bugreport.cpp
index d159d6a..d0cc072 100644
--- a/adb/bugreport.cpp
+++ b/adb/bugreport.cpp
@@ -137,7 +137,7 @@
             SetSrcFile(&line[strlen(BUGZ_OK_PREFIX)]);
         } else if (android::base::StartsWith(line, BUGZ_FAIL_PREFIX)) {
             const char* error_message = &line[strlen(BUGZ_FAIL_PREFIX)];
-            fprintf(stderr, "Device failed to take a zipped bugreport: %s\n", error_message);
+            fprintf(stderr, "adb: device failed to take a zipped bugreport: %s\n", error_message);
             status_ = -1;
         } else if (show_progress_ && android::base::StartsWith(line, BUGZ_PROGRESS_PREFIX)) {
             // progress_line should have the following format:
@@ -196,7 +196,7 @@
 };
 
 int Bugreport::DoIt(TransportType transport_type, const char* serial, int argc, const char** argv) {
-    if (argc > 2) return usage("usage: adb bugreport [PATH]");
+    if (argc > 2) return syntax_error("adb bugreport [PATH]");
 
     // Gets bugreportz version.
     std::string bugz_stdout, bugz_stderr;
diff --git a/adb/client/usb_libusb.cpp b/adb/client/usb_libusb.cpp
index 7adb262..fec4742 100644
--- a/adb/client/usb_libusb.cpp
+++ b/adb/client/usb_libusb.cpp
@@ -62,12 +62,11 @@
 using unique_device_handle = std::unique_ptr<libusb_device_handle, DeviceHandleDeleter>;
 
 struct transfer_info {
-    transfer_info(const char* name, uint16_t zero_mask) :
-        name(name),
-        transfer(libusb_alloc_transfer(0)),
-        zero_mask(zero_mask)
-    {
-    }
+    transfer_info(const char* name, uint16_t zero_mask, bool is_bulk_out)
+        : name(name),
+          transfer(libusb_alloc_transfer(0)),
+          is_bulk_out(is_bulk_out),
+          zero_mask(zero_mask) {}
 
     ~transfer_info() {
         libusb_free_transfer(transfer);
@@ -75,6 +74,7 @@
 
     const char* name;
     libusb_transfer* transfer;
+    bool is_bulk_out;
     bool transfer_complete;
     std::condition_variable cv;
     std::mutex mutex;
@@ -96,12 +96,11 @@
           serial(serial),
           closing(false),
           device_handle(device_handle.release()),
-          read("read", zero_mask),
-          write("write", zero_mask),
+          read("read", zero_mask, false),
+          write("write", zero_mask, true),
           interface(interface),
           bulk_in(bulk_in),
-          bulk_out(bulk_out) {
-    }
+          bulk_out(bulk_out) {}
 
     ~usb_handle() {
         Close();
@@ -306,14 +305,6 @@
             }
             device_serial.resize(rc);
 
-            // Try to reset the device.
-            rc = libusb_reset_device(handle_raw);
-            if (rc != 0) {
-                LOG(WARNING) << "failed to reset opened device '" << device_serial
-                             << "': " << libusb_error_name(rc);
-                continue;
-            }
-
             // WARNING: this isn't released via RAII.
             rc = libusb_claim_interface(handle.get(), interface_num);
             if (rc != 0) {
@@ -373,11 +364,6 @@
     device_poll_thread = new std::thread(poll_for_devices);
     android::base::at_quick_exit([]() {
         terminate_device_poll_thread = true;
-        std::unique_lock<std::mutex> lock(usb_handles_mutex);
-        for (auto& it : usb_handles) {
-            it.second->Close();
-        }
-        lock.unlock();
         device_poll_thread->join();
     });
 }
@@ -405,7 +391,8 @@
             return;
         }
 
-        if (transfer->actual_length != transfer->length) {
+        // usb_read() can return when receiving some data.
+        if (info->is_bulk_out && transfer->actual_length != transfer->length) {
             LOG(DEBUG) << info->name << " transfer incomplete, resubmitting";
             transfer->length -= transfer->actual_length;
             transfer->buffer += transfer->actual_length;
@@ -499,8 +486,12 @@
     info->transfer->num_iso_packets = 0;
 
     int rc = perform_usb_transfer(h, info, std::move(lock));
-    LOG(DEBUG) << "usb_read(" << len << ") = " << rc;
-    return rc;
+    LOG(DEBUG) << "usb_read(" << len << ") = " << rc << ", actual_length "
+               << info->transfer->actual_length;
+    if (rc < 0) {
+        return rc;
+    }
+    return info->transfer->actual_length;
 }
 
 int usb_close(usb_handle* h) {
diff --git a/adb/client/usb_linux.cpp b/adb/client/usb_linux.cpp
index 13b7674..6efed27 100644
--- a/adb/client/usb_linux.cpp
+++ b/adb/client/usb_linux.cpp
@@ -401,7 +401,6 @@
     }
 }
 
-
 int usb_write(usb_handle *h, const void *_data, int len)
 {
     D("++ usb_write ++");
@@ -429,19 +428,16 @@
     int n;
 
     D("++ usb_read ++");
-    while(len > 0) {
+    int orig_len = len;
+    while (len == orig_len) {
         int xfer = len;
 
         D("[ usb read %d fd = %d], path=%s", xfer, h->fd, h->path.c_str());
         n = usb_bulk_read(h, data, xfer);
         D("[ usb read %d ] = %d, path=%s", xfer, n, h->path.c_str());
-        if(n != xfer) {
+        if (n <= 0) {
             if((errno == ETIMEDOUT) && (h->fd != -1)) {
                 D("[ timeout ]");
-                if(n > 0){
-                    data += n;
-                    len -= n;
-                }
                 continue;
             }
             D("ERROR: n = %d, errno = %d (%s)",
@@ -449,12 +445,12 @@
             return -1;
         }
 
-        len -= xfer;
-        data += xfer;
+        len -= n;
+        data += n;
     }
 
     D("-- usb_read --");
-    return 0;
+    return orig_len - len;
 }
 
 void usb_kick(usb_handle* h) {
@@ -574,7 +570,7 @@
     register_usb_transport(done_usb, serial.c_str(), dev_path, done_usb->writeable);
 }
 
-static void device_poll_thread(void*) {
+static void device_poll_thread() {
     adb_thread_setname("device poll");
     D("Created device thread");
     while (true) {
@@ -593,8 +589,6 @@
     actions.sa_handler = [](int) {};
     sigaction(SIGALRM, &actions, nullptr);
 
-    if (!adb_thread_create(device_poll_thread, nullptr)) {
-        fatal_errno("cannot create device_poll thread");
-    }
+    std::thread(device_poll_thread).detach();
 }
 } // namespace native
diff --git a/adb/client/usb_osx.cpp b/adb/client/usb_osx.cpp
index d4fc7c0..fcd0bc0 100644
--- a/adb/client/usb_osx.cpp
+++ b/adb/client/usb_osx.cpp
@@ -405,7 +405,7 @@
 
 std::mutex& operate_device_lock = *new std::mutex();
 
-static void RunLoopThread(void* unused) {
+static void RunLoopThread() {
     adb_thread_setname("RunLoop");
 
     VLOG(USB) << "RunLoopThread started";
@@ -436,9 +436,7 @@
 
         usb_inited_flag = false;
 
-        if (!adb_thread_create(RunLoopThread, nullptr)) {
-            fatal_errno("cannot create RunLoop thread");
-        }
+        std::thread(RunLoopThread).detach();
 
         // Wait for initialization to finish
         while (!usb_inited_flag) {
@@ -520,7 +518,7 @@
     }
 
     if (kIOReturnSuccess == result)
-        return 0;
+        return numBytes;
     else {
         LOG(ERROR) << "usb_read failed with status: " << std::hex << result;
     }
diff --git a/adb/client/usb_windows.cpp b/adb/client/usb_windows.cpp
index 640e91e..ee7f802 100644
--- a/adb/client/usb_windows.cpp
+++ b/adb/client/usb_windows.cpp
@@ -103,7 +103,7 @@
 
 /// Entry point for thread that polls (every second) for new usb interfaces.
 /// This routine calls find_devices in infinite loop.
-static void device_poll_thread(void*);
+static void device_poll_thread();
 
 /// Initializes this module
 void usb_init();
@@ -174,7 +174,7 @@
   return 1;
 }
 
-void device_poll_thread(void*) {
+void device_poll_thread() {
   adb_thread_setname("Device Poll");
   D("Created device thread");
 
@@ -203,7 +203,7 @@
   return DefWindowProcW(hwnd, uMsg, wParam, lParam);
 }
 
-static void _power_notification_thread(void*) {
+static void _power_notification_thread() {
   // This uses a thread with its own window message pump to get power
   // notifications. If adb runs from a non-interactive service account, this
   // might not work (not sure). If that happens to not work, we could use
@@ -258,12 +258,8 @@
 }
 
 void usb_init() {
-  if (!adb_thread_create(device_poll_thread, nullptr)) {
-    fatal_errno("cannot create device poll thread");
-  }
-  if (!adb_thread_create(_power_notification_thread, nullptr)) {
-    fatal_errno("cannot create power notification thread");
-  }
+  std::thread(device_poll_thread).detach();
+  std::thread(_power_notification_thread).detach();
 }
 
 usb_handle* do_usb_open(const wchar_t* interface_name) {
@@ -419,6 +415,7 @@
   unsigned long time_out = 0;
   unsigned long read = 0;
   int err = 0;
+  int orig_len = len;
 
   D("usb_read %d", len);
   if (NULL == handle) {
@@ -427,9 +424,8 @@
     goto fail;
   }
 
-  while (len > 0) {
-    if (!AdbReadEndpointSync(handle->adb_read_pipe, data, len, &read,
-                             time_out)) {
+  while (len == orig_len) {
+    if (!AdbReadEndpointSync(handle->adb_read_pipe, data, len, &read, time_out)) {
       D("AdbReadEndpointSync failed: %s",
         android::base::SystemErrorCodeToString(GetLastError()).c_str());
       err = EIO;
@@ -437,11 +433,11 @@
     }
     D("usb_read got: %ld, expected: %d", read, len);
 
-    data = (char *)data + read;
+    data = (char*)data + read;
     len -= read;
   }
 
-  return 0;
+  return orig_len - len;
 
 fail:
   // Any failure should cause us to kick the device instead of leaving it a
diff --git a/adb/commandline.cpp b/adb/commandline.cpp
index 3de7be6..a9b1540 100644
--- a/adb/commandline.cpp
+++ b/adb/commandline.cpp
@@ -68,20 +68,17 @@
 static int install_app_legacy(TransportType t, const char* serial, int argc, const char** argv);
 static int uninstall_app_legacy(TransportType t, const char* serial, int argc, const char** argv);
 
-static auto& gProductOutPath = *new std::string();
 extern int gListenAll;
 
 DefaultStandardStreamsCallback DEFAULT_STANDARD_STREAMS_CALLBACK(nullptr, nullptr);
 
-static std::string product_file(const char *extra) {
-    if (gProductOutPath.empty()) {
-        fprintf(stderr, "adb: Product directory not specified; "
-                "use -p or define ANDROID_PRODUCT_OUT\n");
+static std::string product_file(const char* file) {
+    const char* ANDROID_PRODUCT_OUT = getenv("ANDROID_PRODUCT_OUT");
+    if (ANDROID_PRODUCT_OUT == nullptr) {
+        fprintf(stderr, "adb: product directory not specified; set $ANDROID_PRODUCT_OUT\n");
         exit(1);
     }
-
-    return android::base::StringPrintf("%s%s%s",
-                                       gProductOutPath.c_str(), OS_PATH_SEPARATOR_STR, extra);
+    return android::base::StringPrintf("%s%s%s", ANDROID_PRODUCT_OUT, OS_PATH_SEPARATOR_STR, file);
 }
 
 static void help() {
@@ -92,11 +89,7 @@
         " -a         listen on all network interfaces, not just localhost\n"
         " -d         use USB device (error if multiple devices connected)\n"
         " -e         use TCP/IP device (error if multiple TCP/IP devices available)\n"
-        " -s SERIAL\n"
-        "     use device with given serial number (overrides $ANDROID_SERIAL)\n"
-        " -p PRODUCT\n"
-        "     name or path ('angler'/'out/target/product/angler');\n"
-        "     default $ANDROID_PRODUCT_OUT\n"
+        " -s SERIAL  use device with given serial (overrides $ANDROID_SERIAL)\n"
         " -H         name of adb server host [default=localhost]\n"
         " -P         port of adb server [default=5037]\n"
         " -L SOCKET  listen on given socket for adb server [default=tcp:localhost:5037]\n"
@@ -138,9 +131,8 @@
         " pull [-a] REMOTE... LOCAL\n"
         "     copy files/dirs from device\n"
         "     -a: preserve file timestamp and mode\n"
-        " sync [DIR]\n"
-        "     copy all changed files to device; if DIR is \"system\", \"vendor\", \"oem\",\n"
-        "     or \"data\", only sync that partition (default all)\n"
+        " sync [system|vendor|oem|data|all]\n"
+        "     sync a local build from $ANDROID_PRODUCT_OUT to the device (default all)\n"
         "     -l: list but don't copy\n"
         "\n"
         "shell:\n"
@@ -169,15 +161,7 @@
         "     '-k': keep the data and cache directories\n"
         "\n"
         "backup/restore:\n"
-        " backup [-f FILE] [-apk|-noapk] [-obb|-noobb] [-shared|-noshared] [-all] [-system|-nosystem] [PACKAGE...]\n"
-        "     write an archive of the device's data to FILE [default=backup.adb]\n"
-        "     package list optional if -all/-shared are supplied\n"
-        "     -apk/-noapk: do/don't back up .apk files (default -noapk)\n"
-        "     -obb/-noobb: do/don't back up .obb files (default -noobb)\n"
-        "     -shared|-noshared: do/don't back up shared storage (default -noshared)\n"
-        "     -all: back up all installed applications\n"
-        "     -system|-nosystem: include system apps in -all (default -system)\n"
-        " restore FILE             restore device contents from FILE\n"
+        "   to show usage run \"adb shell bu help\"\n"
         "\n"
         "debugging:\n"
         " bugreport [PATH]\n"
@@ -220,6 +204,7 @@
         " kill-server              kill the server if it is running\n"
         " reconnect                kick connection from host side to force reconnect\n"
         " reconnect device         kick connection from device side to force reconnect\n"
+        " reconnect offline        reset offline/unauthorized devices to force reconnect\n"
         "\n"
         "environment variables:\n"
         " $ADB_TRACE\n"
@@ -663,13 +648,8 @@
 #endif
 
     // TODO: combine read_and_dump with stdin_read_thread to make life simpler?
-    int exit_code = 1;
-    if (!adb_thread_create(stdin_read_thread_loop, args)) {
-        PLOG(ERROR) << "error starting stdin read thread";
-        delete args;
-    } else {
-        exit_code = read_and_dump(fd, use_shell_protocol);
-    }
+    std::thread(stdin_read_thread_loop, args).detach();
+    int exit_code = read_and_dump(fd, use_shell_protocol);
 
     // TODO: properly exit stdin_read_thread_loop and close |fd|.
 
@@ -703,8 +683,7 @@
         switch (opt) {
             case 'e':
                 if (!(strlen(optarg) == 1 || strcmp(optarg, "none") == 0)) {
-                    fprintf(stderr, "error: -e requires a single-character argument or 'none'\n");
-                    return 1;
+                    return syntax_error("-e requires a single-character argument or 'none'");
                 }
                 escape_char = (strcmp(optarg, "none") == 0) ? 0 : optarg[0];
                 break;
@@ -782,54 +761,46 @@
     return RemoteShell(use_shell_protocol, shell_type_arg, escape_char, command);
 }
 
-static int adb_download_buffer(const char *service, const char *fn, const void* data, unsigned sz,
-                               bool show_progress)
-{
+static int adb_sideload_legacy(const char* filename, int in_fd, int size) {
     std::string error;
-    int fd = adb_connect(android::base::StringPrintf("%s:%d", service, sz), &error);
-    if (fd < 0) {
-        fprintf(stderr,"error: %s\n", error.c_str());
+    int out_fd = adb_connect(android::base::StringPrintf("sideload:%d", size), &error);
+    if (out_fd < 0) {
+        fprintf(stderr, "adb: pre-KitKat sideload connection failed: %s\n", error.c_str());
         return -1;
     }
 
     int opt = CHUNK_SIZE;
-    opt = adb_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const void *) &opt, sizeof(opt));
+    opt = adb_setsockopt(out_fd, SOL_SOCKET, SO_SNDBUF, &opt, sizeof(opt));
 
-    unsigned total = sz;
-    const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data);
-
-    if (show_progress) {
-        const char* x = strrchr(service, ':');
-        if (x) service = x + 1;
-    }
-
-    while (sz > 0) {
-        unsigned xfer = (sz > CHUNK_SIZE) ? CHUNK_SIZE : sz;
-        if (!WriteFdExactly(fd, ptr, xfer)) {
-            std::string error;
-            adb_status(fd, &error);
-            fprintf(stderr,"* failed to write data '%s' *\n", error.c_str());
-            adb_close(fd);
+    char buf[CHUNK_SIZE];
+    int total = size;
+    while (size > 0) {
+        unsigned xfer = (size > CHUNK_SIZE) ? CHUNK_SIZE : size;
+        if (!ReadFdExactly(in_fd, buf, xfer)) {
+            fprintf(stderr, "adb: failed to read data from %s: %s\n", filename, strerror(errno));
+            adb_close(out_fd);
             return -1;
         }
-        sz -= xfer;
-        ptr += xfer;
-        if (show_progress) {
-            printf("sending: '%s' %4d%%    \r", fn, (int)(100LL - ((100LL * sz) / (total))));
-            fflush(stdout);
+        if (!WriteFdExactly(out_fd, buf, xfer)) {
+            std::string error;
+            adb_status(out_fd, &error);
+            fprintf(stderr, "adb: failed to write data: %s\n", error.c_str());
+            adb_close(out_fd);
+            return -1;
         }
+        size -= xfer;
+        printf("sending: '%s' %4d%%    \r", filename, (int)(100LL - ((100LL * size) / (total))));
+        fflush(stdout);
     }
-    if (show_progress) {
-        printf("\n");
-    }
+    printf("\n");
 
-    if (!adb_status(fd, &error)) {
-        fprintf(stderr,"* error response '%s' *\n", error.c_str());
-        adb_close(fd);
+    if (!adb_status(out_fd, &error)) {
+        fprintf(stderr, "adb: error response: %s\n", error.c_str());
+        adb_close(out_fd);
         return -1;
     }
 
-    adb_close(fd);
+    adb_close(out_fd);
     return 0;
 }
 
@@ -854,66 +825,77 @@
  * - When the other side sends "DONEDONE" instead of a block number,
  *   we hang up.
  */
-static int adb_sideload_host(const char* fn) {
-    fprintf(stderr, "loading: '%s'...\n", fn);
-
-    std::string content;
-    if (!android::base::ReadFileToString(fn, &content)) {
-        fprintf(stderr, "failed: %s\n", strerror(errno));
+static int adb_sideload_host(const char* filename) {
+    // TODO: use a LinePrinter instead...
+    struct stat sb;
+    if (stat(filename, &sb) == -1) {
+        fprintf(stderr, "adb: failed to stat file %s: %s\n", filename, strerror(errno));
+        return -1;
+    }
+    unique_fd package_fd(adb_open(filename, O_RDONLY));
+    if (package_fd == -1) {
+        fprintf(stderr, "adb: failed to open file %s: %s\n", filename, strerror(errno));
         return -1;
     }
 
-    const uint8_t* data = reinterpret_cast<const uint8_t*>(content.data());
-    unsigned sz = content.size();
-
-    fprintf(stderr, "connecting...\n");
-    std::string service =
-            android::base::StringPrintf("sideload-host:%d:%d", sz, SIDELOAD_HOST_BLOCK_SIZE);
+    std::string service = android::base::StringPrintf(
+        "sideload-host:%d:%d", static_cast<int>(sb.st_size), SIDELOAD_HOST_BLOCK_SIZE);
     std::string error;
-    unique_fd fd(adb_connect(service, &error));
-    if (fd < 0) {
-        // Try falling back to the older sideload method.  Maybe this
+    unique_fd device_fd(adb_connect(service, &error));
+    if (device_fd < 0) {
+        // Try falling back to the older (<= K) sideload method. Maybe this
         // is an older device that doesn't support sideload-host.
-        fprintf(stderr, "falling back to older sideload method...\n");
-        return adb_download_buffer("sideload", fn, data, sz, true);
+        fprintf(stderr, "adb: sideload connection failed: %s\n", error.c_str());
+        fprintf(stderr, "adb: trying pre-KitKat sideload method...\n");
+        return adb_sideload_legacy(filename, package_fd, static_cast<int>(sb.st_size));
     }
 
     int opt = SIDELOAD_HOST_BLOCK_SIZE;
-    adb_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &opt, sizeof(opt));
+    adb_setsockopt(device_fd, SOL_SOCKET, SO_SNDBUF, &opt, sizeof(opt));
+
+    char buf[SIDELOAD_HOST_BLOCK_SIZE];
 
     size_t xfer = 0;
     int last_percent = -1;
     while (true) {
-        char buf[9];
-        if (!ReadFdExactly(fd, buf, 8)) {
-            fprintf(stderr, "* failed to read command: %s\n", strerror(errno));
+        if (!ReadFdExactly(device_fd, buf, 8)) {
+            fprintf(stderr, "adb: failed to read command: %s\n", strerror(errno));
             return -1;
         }
         buf[8] = '\0';
 
         if (strcmp("DONEDONE", buf) == 0) {
             printf("\rTotal xfer: %.2fx%*s\n",
-                   (double)xfer / (sz ? sz : 1), (int)strlen(fn)+10, "");
+                   static_cast<double>(xfer) / (sb.st_size ? sb.st_size : 1),
+                   static_cast<int>(strlen(filename) + 10), "");
             return 0;
         }
 
         int block = strtol(buf, NULL, 10);
 
         size_t offset = block * SIDELOAD_HOST_BLOCK_SIZE;
-        if (offset >= sz) {
-            fprintf(stderr, "* attempt to read block %d past end\n", block);
+        if (offset >= static_cast<size_t>(sb.st_size)) {
+            fprintf(stderr, "adb: failed to read block %d past end\n", block);
             return -1;
         }
-        const uint8_t* start = data + offset;
-        size_t offset_end = offset + SIDELOAD_HOST_BLOCK_SIZE;
+
         size_t to_write = SIDELOAD_HOST_BLOCK_SIZE;
-        if (offset_end > sz) {
-            to_write = sz - offset;
+        if ((offset + SIDELOAD_HOST_BLOCK_SIZE) > static_cast<size_t>(sb.st_size)) {
+            to_write = sb.st_size - offset;
         }
 
-        if (!WriteFdExactly(fd, start, to_write)) {
-            adb_status(fd, &error);
-            fprintf(stderr,"* failed to write data '%s' *\n", error.c_str());
+        if (adb_lseek(package_fd, offset, SEEK_SET) != static_cast<int>(offset)) {
+            fprintf(stderr, "adb: failed to seek to package block: %s\n", strerror(errno));
+            return -1;
+        }
+        if (!ReadFdExactly(package_fd, buf, to_write)) {
+            fprintf(stderr, "adb: failed to read package block: %s\n", strerror(errno));
+            return -1;
+        }
+
+        if (!WriteFdExactly(device_fd, buf, to_write)) {
+            adb_status(device_fd, &error);
+            fprintf(stderr, "adb: failed to write data '%s' *\n", error.c_str());
             return -1;
         }
         xfer += to_write;
@@ -924,9 +906,9 @@
         // extra access to things like the zip central directory).
         // This estimate of the completion becomes 100% when we've
         // transferred ~2.13 (=100/47) times the package size.
-        int percent = (int)(xfer * 47LL / (sz ? sz : 1));
+        int percent = static_cast<int>(xfer * 47LL / (sb.st_size ? sb.st_size : 1));
         if (percent != last_percent) {
-            printf("\rserving: '%s'  (~%d%%)    ", fn, percent);
+            printf("\rserving: '%s'  (~%d%%)    ", filename, percent);
             fflush(stdout);
             last_percent = percent;
         }
@@ -945,19 +927,13 @@
     fprintf(stderr, "error: adb %s not implemented on Win32\n", argv[0]);
     return -1;
 #else
-    if (argc < 2) {
-        fprintf(stderr, "usage: adb %s <adb service name> [ppp opts]\n",
-                argv[0]);
-
-        return 1;
-    }
+    if (argc < 2) return syntax_error("adb %s <adb service name> [ppp opts]", argv[0]);
 
     const char* adb_service_name = argv[1];
     std::string error;
     int fd = adb_connect(adb_service_name, &error);
     if (fd < 0) {
-        fprintf(stderr,"Error: Could not open adb service: %s. Error: %s\n",
-                adb_service_name, error.c_str());
+        fprintf(stderr, "adb: could not open adb service %s: %s\n", adb_service_name, error.c_str());
         return 1;
     }
 
@@ -1176,10 +1152,7 @@
     /* find, extract, and use any -f argument */
     for (int i = 1; i < argc; i++) {
         if (!strcmp("-f", argv[i])) {
-            if (i == argc-1) {
-                fprintf(stderr, "adb: backup -f passed with no filename.\n");
-                return EXIT_FAILURE;
-            }
+            if (i == argc - 1) return syntax_error("backup -f passed with no filename");
             filename = argv[i+1];
             for (int j = i+2; j <= argc; ) {
                 argv[i++] = argv[j++];
@@ -1191,10 +1164,7 @@
 
     // Bare "adb backup" or "adb backup -f filename" are not valid invocations ---
     // a list of packages is required.
-    if (argc < 2) {
-        fprintf(stderr, "adb: backup either needs a list of packages or -all/-shared.\n");
-        return EXIT_FAILURE;
-    }
+    if (argc < 2) return syntax_error("backup either needs a list of packages or -all/-shared");
 
     adb_unlink(filename);
     int outFd = adb_creat(filename, 0640);
@@ -1219,7 +1189,7 @@
         return EXIT_FAILURE;
     }
 
-    printf("Now unlock your device and confirm the backup operation...\n");
+    fprintf(stdout, "Now unlock your device and confirm the backup operation...\n");
     fflush(stdout);
 
     copy_to_file(fd, outFd);
@@ -1230,7 +1200,7 @@
 }
 
 static int restore(int argc, const char** argv) {
-    if (argc != 2) return usage("restore requires an argument");
+    if (argc != 2) return syntax_error("restore requires an argument");
 
     const char* filename = argv[1];
     int tarFd = adb_open(filename, O_RDONLY);
@@ -1247,7 +1217,9 @@
         return -1;
     }
 
-    printf("Now unlock your device and confirm the restore operation.\n");
+    fprintf(stdout, "Now unlock your device and confirm the restore operation.\n");
+    fflush(stdout);
+
     copy_to_file(tarFd, fd);
 
     // Provide an in-band EOD marker in case the archive file is malformed
@@ -1261,66 +1233,6 @@
     return 0;
 }
 
-/* <hint> may be:
- * - A simple product name
- *   e.g., "sooner"
- * - A relative path from the CWD to the ANDROID_PRODUCT_OUT dir
- *   e.g., "out/target/product/sooner"
- * - An absolute path to the PRODUCT_OUT dir
- *   e.g., "/src/device/out/target/product/sooner"
- *
- * Given <hint>, try to construct an absolute path to the
- * ANDROID_PRODUCT_OUT dir.
- */
-static std::string find_product_out_path(const std::string& hint) {
-    if (hint.empty()) {
-        return "";
-    }
-
-    // If it's already absolute, don't bother doing any work.
-    if (adb_is_absolute_host_path(hint.c_str())) {
-        return hint;
-    }
-
-    // If any of the OS_PATH_SEPARATORS is found, assume it's a relative path;
-    // make it absolute.
-    // NOLINT: Do not complain if OS_PATH_SEPARATORS has only one character.
-    if (hint.find_first_of(OS_PATH_SEPARATORS) != std::string::npos) {  // NOLINT
-        std::string cwd;
-        if (!getcwd(&cwd)) {
-            perror("adb: getcwd failed");
-            return "";
-        }
-        return android::base::StringPrintf("%s%c%s", cwd.c_str(), OS_PATH_SEPARATOR, hint.c_str());
-    }
-
-    // It's a string without any slashes.  Try to do something with it.
-    //
-    // Try to find the root of the build tree, and build a PRODUCT_OUT
-    // path from there.
-    char* top = getenv("ANDROID_BUILD_TOP");
-    if (top == nullptr) {
-        fprintf(stderr, "adb: ANDROID_BUILD_TOP not set!\n");
-        return "";
-    }
-
-    std::string path = top;
-    path += OS_PATH_SEPARATOR_STR;
-    path += "out";
-    path += OS_PATH_SEPARATOR_STR;
-    path += "target";
-    path += OS_PATH_SEPARATOR_STR;
-    path += "product";
-    path += OS_PATH_SEPARATOR_STR;
-    path += hint;
-    if (!directory_exists(path)) {
-        fprintf(stderr, "adb: Couldn't find a product dir based on -p %s; "
-                        "\"%s\" doesn't exist\n", hint.c_str(), path.c_str());
-        return "";
-    }
-    return path;
-}
-
 static void parse_push_pull_args(const char** arg, int narg,
                                  std::vector<const char*>* srcs,
                                  const char** dst, bool* copy_attrs) {
@@ -1339,7 +1251,7 @@
             } else if (!strcmp(*arg, "--")) {
                 ignore_flags = true;
             } else {
-                fprintf(stderr, "adb: unrecognized option '%s'\n", *arg);
+                syntax_error("unrecognized option '%s'", *arg);
                 exit(1);
             }
         }
@@ -1411,17 +1323,6 @@
     signal(SIGPIPE, SIG_IGN);
 #endif
 
-    // If defined, this should be an absolute path to
-    // the directory containing all of the various system images
-    // for a particular product.  If not defined, and the adb
-    // command requires this information, then the user must
-    // specify the path using "-p".
-    char* ANDROID_PRODUCT_OUT = getenv("ANDROID_PRODUCT_OUT");
-    if (ANDROID_PRODUCT_OUT != nullptr) {
-        gProductOutPath = ANDROID_PRODUCT_OUT;
-    }
-    // TODO: also try TARGET_PRODUCT/TARGET_DEVICE as a hint
-
     const char* server_host_str = nullptr;
     const char* server_port_str = nullptr;
     const char* server_socket_str = nullptr;
@@ -1438,7 +1339,7 @@
             /* this is a special flag used only when the ADB client launches the ADB Server */
             is_daemon = 1;
         } else if (!strcmp(argv[0], "--reply-fd")) {
-            if (argc < 2) return usage("--reply-fd requires an argument");
+            if (argc < 2) return syntax_error("--reply-fd requires an argument");
             const char* reply_fd_str = argv[1];
             argc--;
             argv++;
@@ -1447,26 +1348,11 @@
                 fprintf(stderr, "adb: invalid reply fd \"%s\"\n", reply_fd_str);
                 return 1;
             }
-        } else if (!strncmp(argv[0], "-p", 2)) {
-            const char* product = nullptr;
-            if (argv[0][2] == '\0') {
-                if (argc < 2) return usage("-p requires an argument");
-                product = argv[1];
-                argc--;
-                argv++;
-            } else {
-                product = argv[0] + 2;
-            }
-            gProductOutPath = find_product_out_path(product);
-            if (gProductOutPath.empty()) {
-                fprintf(stderr, "adb: could not resolve \"-p %s\"\n", product);
-                return 1;
-            }
         } else if (argv[0][0]=='-' && argv[0][1]=='s') {
             if (isdigit(argv[0][2])) {
                 serial = argv[0] + 2;
             } else {
-                if (argc < 2 || argv[0][2] != '\0') return usage("-s requires an argument");
+                if (argc < 2 || argv[0][2] != '\0') return syntax_error("-s requires an argument");
                 serial = argv[1];
                 argc--;
                 argv++;
@@ -1479,7 +1365,7 @@
             gListenAll = 1;
         } else if (!strncmp(argv[0], "-H", 2)) {
             if (argv[0][2] == '\0') {
-                if (argc < 2) return usage("-H requires an argument");
+                if (argc < 2) return syntax_error("-H requires an argument");
                 server_host_str = argv[1];
                 argc--;
                 argv++;
@@ -1488,7 +1374,7 @@
             }
         } else if (!strncmp(argv[0], "-P", 2)) {
             if (argv[0][2] == '\0') {
-                if (argc < 2) return usage("-P requires an argument");
+                if (argc < 2) return syntax_error("-P requires an argument");
                 server_port_str = argv[1];
                 argc--;
                 argv++;
@@ -1496,7 +1382,7 @@
                 server_port_str = argv[0] + 2;
             }
         } else if (!strcmp(argv[0], "-L")) {
-            if (argc < 2) return usage("-L requires an argument");
+            if (argc < 2) return syntax_error("-L requires an argument");
             server_socket_str = argv[1];
             argc--;
             argv++;
@@ -1509,8 +1395,7 @@
     }
 
     if ((server_host_str || server_port_str) && server_socket_str) {
-        fprintf(stderr, "adb: -L is incompatible with -H or -P\n");
-        exit(1);
+        return syntax_error("-L is incompatible with -H or -P");
     }
 
     // If -L, -H, or -P are specified, ignore environment variables.
@@ -1605,8 +1490,7 @@
         } else if (argc == 2 && !strcmp(argv[1], "-l")) {
             listopt = argv[1];
         } else {
-            fprintf(stderr, "Usage: adb devices [-l]\n");
-            return 1;
+            return syntax_error("adb devices [-l]");
         }
 
         std::string query = android::base::StringPrintf("host:%s%s", argv[0], listopt);
@@ -1614,19 +1498,13 @@
         return adb_query_command(query);
     }
     else if (!strcmp(argv[0], "connect")) {
-        if (argc != 2) {
-            fprintf(stderr, "Usage: adb connect <host>[:<port>]\n");
-            return 1;
-        }
+        if (argc != 2) return syntax_error("adb connect <host>[:<port>]");
 
         std::string query = android::base::StringPrintf("host:connect:%s", argv[1]);
         return adb_query_command(query);
     }
     else if (!strcmp(argv[0], "disconnect")) {
-        if (argc > 2) {
-            fprintf(stderr, "Usage: adb disconnect [<host>[:<port>]]\n");
-            return 1;
-        }
+        if (argc > 2) return syntax_error("adb disconnect [<host>[:<port>]]");
 
         std::string query = android::base::StringPrintf("host:disconnect:%s",
                                                         (argc == 2) ? argv[1] : "");
@@ -1641,10 +1519,7 @@
     else if (!strcmp(argv[0], "exec-in") || !strcmp(argv[0], "exec-out")) {
         int exec_in = !strcmp(argv[0], "exec-in");
 
-        if (argc < 2) {
-            fprintf(stderr, "Usage: adb %s command\n", argv[0]);
-            return 1;
-        }
+        if (argc < 2) return syntax_error("adb %s command", argv[0]);
 
         std::string cmd = "exec:";
         cmd += argv[1];
@@ -1692,7 +1567,7 @@
         }
     }
     else if (!strcmp(argv[0], "sideload")) {
-        if (argc != 2) return usage("sideload requires an argument");
+        if (argc != 2) return syntax_error("sideload requires an argument");
         if (adb_sideload_host(argv[1])) {
             return 1;
         } else {
@@ -1726,7 +1601,7 @@
         bool reverse = !strcmp(argv[0], "reverse");
         ++argv;
         --argc;
-        if (argc < 1) return usage("%s requires an argument", argv[0]);
+        if (argc < 1) return syntax_error("%s requires an argument", argv[0]);
 
         // Determine the <host-prefix> for this command.
         std::string host_prefix;
@@ -1746,24 +1621,24 @@
 
         std::string cmd, error;
         if (strcmp(argv[0], "--list") == 0) {
-            if (argc != 1) return usage("--list doesn't take any arguments");
+            if (argc != 1) return syntax_error("--list doesn't take any arguments");
             return adb_query_command(host_prefix + ":list-forward");
         } else if (strcmp(argv[0], "--remove-all") == 0) {
-            if (argc != 1) return usage("--remove-all doesn't take any arguments");
+            if (argc != 1) return syntax_error("--remove-all doesn't take any arguments");
             cmd = host_prefix + ":killforward-all";
         } else if (strcmp(argv[0], "--remove") == 0) {
             // forward --remove <local>
-            if (argc != 2) return usage("--remove requires an argument");
+            if (argc != 2) return syntax_error("--remove requires an argument");
             cmd = host_prefix + ":killforward:" + argv[1];
         } else if (strcmp(argv[0], "--no-rebind") == 0) {
             // forward --no-rebind <local> <remote>
-            if (argc != 3) return usage("--no-rebind takes two arguments");
+            if (argc != 3) return syntax_error("--no-rebind takes two arguments");
             if (forward_targets_are_valid(argv[1], argv[2], &error)) {
                 cmd = host_prefix + ":forward:norebind:" + argv[1] + ";" + argv[2];
             }
         } else {
             // forward <local> <remote>
-            if (argc != 2) return usage("forward takes two arguments");
+            if (argc != 2) return syntax_error("forward takes two arguments");
             if (forward_targets_are_valid(argv[0], argv[1], &error)) {
                 cmd = host_prefix + ":forward:" + argv[0] + ";" + argv[1];
             }
@@ -1792,7 +1667,7 @@
     }
     /* do_sync_*() commands */
     else if (!strcmp(argv[0], "ls")) {
-        if (argc != 2) return usage("ls requires an argument");
+        if (argc != 2) return syntax_error("ls requires an argument");
         return do_sync_ls(argv[1]) ? 0 : 1;
     }
     else if (!strcmp(argv[0], "push")) {
@@ -1801,7 +1676,7 @@
         const char* dst = nullptr;
 
         parse_push_pull_args(&argv[1], argc - 1, &srcs, &dst, &copy_attrs);
-        if (srcs.empty() || !dst) return usage("push requires an argument");
+        if (srcs.empty() || !dst) return syntax_error("push requires an argument");
         return do_sync_push(srcs, dst) ? 0 : 1;
     }
     else if (!strcmp(argv[0], "pull")) {
@@ -1810,22 +1685,22 @@
         const char* dst = ".";
 
         parse_push_pull_args(&argv[1], argc - 1, &srcs, &dst, &copy_attrs);
-        if (srcs.empty()) return usage("pull requires an argument");
+        if (srcs.empty()) return syntax_error("pull requires an argument");
         return do_sync_pull(srcs, dst, copy_attrs) ? 0 : 1;
     }
     else if (!strcmp(argv[0], "install")) {
-        if (argc < 2) return usage("install requires an argument");
+        if (argc < 2) return syntax_error("install requires an argument");
         if (_use_legacy_install()) {
             return install_app_legacy(transport_type, serial, argc, argv);
         }
         return install_app(transport_type, serial, argc, argv);
     }
     else if (!strcmp(argv[0], "install-multiple")) {
-        if (argc < 2) return usage("install-multiple requires an argument");
+        if (argc < 2) return syntax_error("install-multiple requires an argument");
         return install_multiple_app(transport_type, serial, argc, argv);
     }
     else if (!strcmp(argv[0], "uninstall")) {
-        if (argc < 2) return usage("uninstall requires an argument");
+        if (argc < 2) return syntax_error("uninstall requires an argument");
         if (_use_legacy_install()) {
             return uninstall_app_legacy(transport_type, serial, argc, argv);
         }
@@ -1848,12 +1723,14 @@
             // A local path or "android"/"data" arg was specified.
             src = argv[1];
         } else {
-            return usage("usage: adb sync [-l] [PARTITION]");
+            return syntax_error("adb sync [-l] [PARTITION]");
         }
 
+        if (src == "all") src = "";
+
         if (src != "" &&
             src != "system" && src != "data" && src != "vendor" && src != "oem") {
-            return usage("don't know how to sync %s partition", src.c_str());
+            return syntax_error("don't know how to sync %s partition", src.c_str());
         }
 
         std::string system_src_path = product_file("system");
@@ -1905,7 +1782,7 @@
         return restore(argc, argv);
     }
     else if (!strcmp(argv[0], "keygen")) {
-        if (argc != 2) return usage("keygen requires an argument");
+        if (argc != 2) return syntax_error("keygen requires an argument");
         // Always print key generation information for keygen command.
         adb_trace_enable(AUTH);
         return adb_auth_keygen(argv[1]);
@@ -1948,7 +1825,7 @@
         return adb_query_command("host:host-features");
     } else if (!strcmp(argv[0], "reconnect")) {
         if (argc == 1) {
-            return adb_query_command("host:reconnect");
+            return adb_query_command(format_host_command(argv[0], transport_type, serial));
         } else if (argc == 2) {
             if (!strcmp(argv[1], "device")) {
                 std::string err;
@@ -1958,12 +1835,12 @@
                 std::string err;
                 return adb_query_command("host:reconnect-offline");
             } else {
-                return usage("usage: adb reconnect [device|offline]");
+                return syntax_error("adb reconnect [device|offline]");
             }
         }
     }
 
-    usage("unknown command %s", argv[0]);
+    syntax_error("unknown command %s", argv[0]);
     return 1;
 }
 
@@ -1990,19 +1867,18 @@
     // The last argument must be the APK file
     const char* file = argv[argc - 1];
     if (!android::base::EndsWithIgnoreCase(file, ".apk")) {
-        fprintf(stderr, "Filename doesn't end .apk: %s\n", file);
-        return EXIT_FAILURE;
+        return syntax_error("filename doesn't end .apk: %s", file);
     }
 
     struct stat sb;
     if (stat(file, &sb) == -1) {
-        fprintf(stderr, "Failed to stat %s: %s\n", file, strerror(errno));
+        fprintf(stderr, "adb: failed to stat %s: %s\n", file, strerror(errno));
         return 1;
     }
 
     int localFd = adb_open(file, O_RDONLY);
     if (localFd < 0) {
-        fprintf(stderr, "Failed to open %s: %s\n", file, strerror(errno));
+        fprintf(stderr, "adb: failed to open %s: %s\n", file, strerror(errno));
         return 1;
     }
 
@@ -2020,7 +1896,7 @@
 
     int remoteFd = adb_connect(cmd, &error);
     if (remoteFd < 0) {
-        fprintf(stderr, "Connect error for write: %s\n", error.c_str());
+        fprintf(stderr, "adb: connect error for write: %s\n", error.c_str());
         adb_close(localFd);
         return 1;
     }
@@ -2032,12 +1908,12 @@
     adb_close(localFd);
     adb_close(remoteFd);
 
-    if (strncmp("Success", buf, 7)) {
-        fprintf(stderr, "Failed to install %s: %s", file, buf);
-        return 1;
+    if (!strncmp("Success", buf, 7)) {
+        fputs(buf, stdout);
+        return 0;
     }
-    fputs(buf, stderr);
-    return 0;
+    fprintf(stderr, "adb: failed to install %s: %s", file, buf);
+    return 1;
 }
 
 static int install_multiple_app(TransportType transport, const char* serial, int argc,
@@ -2059,10 +1935,7 @@
         }
     }
 
-    if (first_apk == -1) {
-        fprintf(stderr, "No APK file on command line\n");
-        return 1;
-    }
+    if (first_apk == -1) return syntax_error("need APK file on command line");
 
     std::string install_cmd;
     if (_use_legacy_install()) {
@@ -2080,7 +1953,7 @@
     std::string error;
     int fd = adb_connect(cmd, &error);
     if (fd < 0) {
-        fprintf(stderr, "Connect error for create: %s\n", error.c_str());
+        fprintf(stderr, "adb: connect error for create: %s\n", error.c_str());
         return EXIT_FAILURE;
     }
     char buf[BUFSIZ];
@@ -2097,7 +1970,7 @@
         }
     }
     if (session_id < 0) {
-        fprintf(stderr, "Failed to create session\n");
+        fprintf(stderr, "adb: failed to create session\n");
         fputs(buf, stderr);
         return EXIT_FAILURE;
     }
@@ -2108,7 +1981,7 @@
         const char* file = argv[i];
         struct stat sb;
         if (stat(file, &sb) == -1) {
-            fprintf(stderr, "Failed to stat %s: %s\n", file, strerror(errno));
+            fprintf(stderr, "adb: failed to stat %s: %s\n", file, strerror(errno));
             success = 0;
             goto finalize_session;
         }
@@ -2120,7 +1993,7 @@
 
         int localFd = adb_open(file, O_RDONLY);
         if (localFd < 0) {
-            fprintf(stderr, "Failed to open %s: %s\n", file, strerror(errno));
+            fprintf(stderr, "adb: failed to open %s: %s\n", file, strerror(errno));
             success = 0;
             goto finalize_session;
         }
@@ -2128,7 +2001,7 @@
         std::string error;
         int remoteFd = adb_connect(cmd, &error);
         if (remoteFd < 0) {
-            fprintf(stderr, "Connect error for write: %s\n", error.c_str());
+            fprintf(stderr, "adb: connect error for write: %s\n", error.c_str());
             adb_close(localFd);
             success = 0;
             goto finalize_session;
@@ -2141,7 +2014,7 @@
         adb_close(remoteFd);
 
         if (strncmp("Success", buf, 7)) {
-            fprintf(stderr, "Failed to write %s\n", file);
+            fprintf(stderr, "adb: failed to write %s\n", file);
             fputs(buf, stderr);
             success = 0;
             goto finalize_session;
@@ -2155,20 +2028,19 @@
                                         install_cmd.c_str(), success ? "commit" : "abandon", session_id);
     fd = adb_connect(service, &error);
     if (fd < 0) {
-        fprintf(stderr, "Connect error for finalize: %s\n", error.c_str());
+        fprintf(stderr, "adb: connect error for finalize: %s\n", error.c_str());
         return EXIT_FAILURE;
     }
     read_status_line(fd, buf, sizeof(buf));
     adb_close(fd);
 
     if (!strncmp("Success", buf, 7)) {
-        fputs(buf, stderr);
+        fputs(buf, stdout);
         return 0;
-    } else {
-        fprintf(stderr, "Failed to finalize session\n");
-        fputs(buf, stderr);
-        return EXIT_FAILURE;
     }
+    fprintf(stderr, "adb: failed to finalize session\n");
+    fputs(buf, stderr);
+    return EXIT_FAILURE;
 }
 
 static int pm_command(TransportType transport, const char* serial, int argc, const char** argv) {
@@ -2226,10 +2098,7 @@
         }
     }
 
-    if (last_apk == -1) {
-        fprintf(stderr, "No APK file on command line\n");
-        return EXIT_FAILURE;
-    }
+    if (last_apk == -1) return syntax_error("need APK file on command line");
 
     int result = -1;
     std::vector<const char*> apk_file = {argv[last_apk]};
diff --git a/adb/commandline.h b/adb/commandline.h
index 0cf655c..9ba69a3 100644
--- a/adb/commandline.h
+++ b/adb/commandline.h
@@ -87,7 +87,6 @@
 extern DefaultStandardStreamsCallback DEFAULT_STANDARD_STREAMS_CALLBACK;
 
 int adb_commandline(int argc, const char** argv);
-int usage();
 
 // Connects to the device "shell" service with |command| and prints the
 // resulting output.
diff --git a/adb/daemon/main.cpp b/adb/daemon/main.cpp
index 7da94ce..7a87df4 100644
--- a/adb/daemon/main.cpp
+++ b/adb/daemon/main.cpp
@@ -32,10 +32,10 @@
 #include <android-base/properties.h>
 #include <android-base/stringprintf.h>
 #include <libminijail.h>
+#include <log/log_properties.h>
 #include <scoped_minijail.h>
 
 #include <private/android_filesystem_config.h>
-#include <private/android_logger.h>
 #include "debuggerd/handler.h"
 #include "selinux/android.h"
 
diff --git a/adb/daemon/mdns.cpp b/adb/daemon/mdns.cpp
index 7811143..849378f 100644
--- a/adb/daemon/mdns.cpp
+++ b/adb/daemon/mdns.cpp
@@ -17,12 +17,14 @@
 #include "adb_mdns.h"
 #include "sysdeps.h"
 
-#include <chrono>
 #include <dns_sd.h>
 #include <endian.h>
-#include <mutex>
 #include <unistd.h>
 
+#include <chrono>
+#include <mutex>
+#include <thread>
+
 #include <android-base/logging.h>
 #include <android-base/properties.h>
 
@@ -58,7 +60,7 @@
     }
 }
 
-static void setup_mdns_thread(void* /* unused */) {
+static void setup_mdns_thread() {
     start_mdns();
     std::lock_guard<std::mutex> lock(mdns_lock);
 
@@ -88,7 +90,7 @@
 
 void setup_mdns(int port_in) {
     port = port_in;
-    adb_thread_create(setup_mdns_thread, nullptr, nullptr);
+    std::thread(setup_mdns_thread).detach();
 
     // TODO: Make this more robust against a hard kill.
     atexit(teardown_mdns);
diff --git a/adb/daemon/usb.cpp b/adb/daemon/usb.cpp
index 92e9039..d3b2f3d 100644
--- a/adb/daemon/usb.cpp
+++ b/adb/daemon/usb.cpp
@@ -64,7 +64,7 @@
 
 #define FUNCTIONFS_ENDPOINT_ALLOC       _IOR('g', 231, __u32)
 
-static constexpr size_t ENDPOINT_ALLOC_RETRIES = 2;
+static constexpr size_t ENDPOINT_ALLOC_RETRIES = 10;
 
 static int dummy_fd = -1;
 
@@ -451,9 +451,7 @@
     h->close = usb_ffs_close;
 
     D("[ usb_init - starting thread ]");
-    if (!adb_thread_create(usb_ffs_open_thread, h)) {
-        fatal_errno("[ cannot create usb thread ]\n");
-    }
+    std::thread(usb_ffs_open_thread, h).detach();
 }
 
 void usb_init() {
diff --git a/adb/fdevent.cpp b/adb/fdevent.cpp
index 04cd865..72c9eef 100644
--- a/adb/fdevent.cpp
+++ b/adb/fdevent.cpp
@@ -75,13 +75,13 @@
 static bool main_thread_valid;
 static unsigned long main_thread_id;
 
-static void check_main_thread() {
+void check_main_thread() {
     if (main_thread_valid) {
         CHECK_EQ(main_thread_id, adb_thread_id());
     }
 }
 
-static void set_main_thread() {
+void set_main_thread() {
     main_thread_valid = true;
     main_thread_id = adb_thread_id();
 }
diff --git a/adb/fdevent.h b/adb/fdevent.h
index 207f9b7..e32845a 100644
--- a/adb/fdevent.h
+++ b/adb/fdevent.h
@@ -76,9 +76,12 @@
 */
 void fdevent_loop();
 
+void check_main_thread();
+
 // The following functions are used only for tests.
 void fdevent_terminate_loop();
 size_t fdevent_installed_count();
 void fdevent_reset();
+void set_main_thread();
 
 #endif
diff --git a/adb/fdevent_test.cpp b/adb/fdevent_test.cpp
index c933ed5..bdb973a 100644
--- a/adb/fdevent_test.cpp
+++ b/adb/fdevent_test.cpp
@@ -21,6 +21,7 @@
 #include <limits>
 #include <queue>
 #include <string>
+#include <thread>
 #include <vector>
 
 #include "adb_io.h"
@@ -77,9 +78,9 @@
 };
 
 TEST_F(FdeventTest, fdevent_terminate) {
-    adb_thread_t thread;
     PrepareThread();
-    ASSERT_TRUE(adb_thread_create([](void*) { fdevent_loop(); }, nullptr, &thread));
+
+    std::thread thread(fdevent_loop);
     TerminateThread(thread);
 }
 
@@ -112,7 +113,6 @@
     int fd_pair2[2];
     ASSERT_EQ(0, adb_socketpair(fd_pair1));
     ASSERT_EQ(0, adb_socketpair(fd_pair2));
-    adb_thread_t thread;
     ThreadArg thread_arg;
     thread_arg.first_read_fd = fd_pair1[0];
     thread_arg.last_write_fd = fd_pair2[1];
@@ -121,8 +121,7 @@
     int reader = fd_pair2[0];
 
     PrepareThread();
-    ASSERT_TRUE(adb_thread_create(reinterpret_cast<void (*)(void*)>(FdEventThreadFunc), &thread_arg,
-                                  &thread));
+    std::thread thread(FdEventThreadFunc, &thread_arg);
 
     for (size_t i = 0; i < MESSAGE_LOOP_COUNT; ++i) {
         std::string read_buffer = MESSAGE;
@@ -152,7 +151,7 @@
     }
 }
 
-static void InvalidFdThreadFunc(void*) {
+static void InvalidFdThreadFunc() {
     const int INVALID_READ_FD = std::numeric_limits<int>::max() - 1;
     size_t happened_event_count = 0;
     InvalidFdArg read_arg;
@@ -171,7 +170,6 @@
 }
 
 TEST_F(FdeventTest, invalid_fd) {
-    adb_thread_t thread;
-    ASSERT_TRUE(adb_thread_create(InvalidFdThreadFunc, nullptr, &thread));
-    ASSERT_TRUE(adb_thread_join(thread));
+    std::thread thread(InvalidFdThreadFunc);
+    thread.join();
 }
diff --git a/adb/fdevent_test.h b/adb/fdevent_test.h
index ef65b74..f4215ae 100644
--- a/adb/fdevent_test.h
+++ b/adb/fdevent_test.h
@@ -16,6 +16,8 @@
 
 #include <gtest/gtest.h>
 
+#include <thread>
+
 #include "socket.h"
 #include "sysdeps.h"
 
@@ -59,10 +61,10 @@
 #endif
     }
 
-    void TerminateThread(adb_thread_t thread) {
+    void TerminateThread(std::thread& thread) {
         fdevent_terminate_loop();
         ASSERT_TRUE(WriteFdExactly(dummy, "", 1));
-        ASSERT_TRUE(adb_thread_join(thread));
+        thread.join();
         ASSERT_EQ(0, adb_close(dummy));
     }
 };
diff --git a/adb/jdwp_service.cpp b/adb/jdwp_service.cpp
index 9589d88..f0dff06 100644
--- a/adb/jdwp_service.cpp
+++ b/adb/jdwp_service.cpp
@@ -179,8 +179,6 @@
     fdevent* fde = nullptr;
 
     std::vector<unique_fd> out_fds;
-    char in_buf[PID_LEN + 1];
-    ssize_t in_len = 0;
 };
 
 static size_t jdwp_process_list(char* buffer, size_t bufferlen) {
@@ -224,33 +222,16 @@
     if (events & FDE_READ) {
         if (proc->pid < 0) {
             /* read the PID as a 4-hexchar string */
-            if (proc->in_len < 0) {
-                fatal("attempting to read JDWP pid again?");
-            }
-
-            char* p = proc->in_buf + proc->in_len;
-            size_t size = PID_LEN - proc->in_len;
-
-            ssize_t rc = TEMP_FAILURE_RETRY(recv(socket, p, size, 0));
-            if (rc < 0) {
-                if (errno == EAGAIN) {
-                    return;
-                }
-
+            char buf[PID_LEN + 1];
+            ssize_t rc = TEMP_FAILURE_RETRY(recv(socket, buf, PID_LEN, 0));
+            if (rc != PID_LEN) {
                 D("failed to read jdwp pid: %s", strerror(errno));
                 goto CloseProcess;
             }
+            buf[PID_LEN] = '\0';
 
-            proc->in_len += rc;
-            if (proc->in_len != PID_LEN) {
-                return;
-            }
-
-            proc->in_buf[PID_LEN] = '\0';
-            proc->in_len = -1;
-
-            if (sscanf(proc->in_buf, "%04x", &proc->pid) != 1) {
-                D("could not decode JDWP %p PID number: '%s'", proc, p);
+            if (sscanf(buf, "%04x", &proc->pid) != 1) {
+                D("could not decode JDWP %p PID number: '%s'", proc, buf);
                 goto CloseProcess;
             }
 
@@ -405,7 +386,7 @@
     addr.sun_family = AF_UNIX;
     memcpy(addr.sun_path, sockname, socknamelen);
 
-    s = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
+    s = socket(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0);
     if (s < 0) {
         D("could not create vm debug control socket. %d: %s", errno, strerror(errno));
         return -1;
diff --git a/adb/services.cpp b/adb/services.cpp
index 47f0a03..9605e6e 100644
--- a/adb/services.cpp
+++ b/adb/services.cpp
@@ -31,6 +31,8 @@
 #include <unistd.h>
 #endif
 
+#include <thread>
+
 #include <android-base/file.h>
 #include <android-base/parsenetaddress.h>
 #include <android-base/stringprintf.h>
@@ -41,7 +43,7 @@
 #include <android-base/properties.h>
 #include <bootloader_message/bootloader_message.h>
 #include <cutils/android_reboot.h>
-#include <private/android_logger.h>
+#include <log/log_properties.h>
 #endif
 
 #include "adb.h"
@@ -259,13 +261,7 @@
     sti->cookie = cookie;
     sti->fd = s[1];
 
-    if (!adb_thread_create(service_bootstrap_func, sti)) {
-        free(sti);
-        adb_close(s[0]);
-        adb_close(s[1]);
-        printf("cannot create service thread\n");
-        return -1;
-    }
+    std::thread(service_bootstrap_func, sti).detach();
 
     D("service thread started, %d:%d",s[0], s[1]);
     return s[0];
@@ -351,7 +347,7 @@
         std::string error = "unknown error";
         const char* serial = sinfo->serial.length() ? sinfo->serial.c_str() : NULL;
         atransport* t = acquire_one_transport(sinfo->transport_type, serial, &is_ambiguous, &error);
-        if (t != nullptr && (sinfo->state == kCsAny || sinfo->state == t->connection_state)) {
+        if (t != nullptr && (sinfo->state == kCsAny || sinfo->state == t->GetConnectionState())) {
             SendOkay(fd);
             break;
         } else if (!is_ambiguous) {
diff --git a/adb/set_verity_enable_state_service.cpp b/adb/set_verity_enable_state_service.cpp
index 76b156d..b2b1c18 100644
--- a/adb/set_verity_enable_state_service.cpp
+++ b/adb/set_verity_enable_state_service.cpp
@@ -20,13 +20,14 @@
 
 #include <fcntl.h>
 #include <inttypes.h>
+#include <libavb_user/libavb_user.h>
 #include <stdarg.h>
 #include <stdio.h>
 #include <sys/stat.h>
 
 #include "android-base/properties.h"
 #include "android-base/stringprintf.h"
-#include <private/android_logger.h>
+#include <log/log_properties.h>
 
 #include "adb.h"
 #include "adb_io.h"
@@ -45,13 +46,12 @@
 #endif
 
 /* Turn verity on/off */
-static int set_verity_enabled_state(int fd, const char *block_device,
-                                    const char* mount_point, bool enable)
-{
+static bool set_verity_enabled_state(int fd, const char* block_device, const char* mount_point,
+                                     bool enable) {
     if (!make_block_device_writable(block_device)) {
         WriteFdFmt(fd, "Could not make block device %s writable (%s).\n",
                    block_device, strerror(errno));
-        return -1;
+        return false;
     }
 
     fec::io fh(block_device, O_RDWR);
@@ -59,39 +59,84 @@
     if (!fh) {
         WriteFdFmt(fd, "Could not open block device %s (%s).\n", block_device, strerror(errno));
         WriteFdFmt(fd, "Maybe run adb root?\n");
-        return -1;
+        return false;
     }
 
     fec_verity_metadata metadata;
 
     if (!fh.get_verity_metadata(metadata)) {
         WriteFdFmt(fd, "Couldn't find verity metadata!\n");
-        return -1;
+        return false;
     }
 
     if (!enable && metadata.disabled) {
         WriteFdFmt(fd, "Verity already disabled on %s\n", mount_point);
-        return -1;
+        return false;
     }
 
     if (enable && !metadata.disabled) {
         WriteFdFmt(fd, "Verity already enabled on %s\n", mount_point);
-        return -1;
+        return false;
     }
 
     if (!fh.set_verity_status(enable)) {
         WriteFdFmt(fd, "Could not set verity %s flag on device %s with error %s\n",
                    enable ? "enabled" : "disabled",
                    block_device, strerror(errno));
-        return -1;
+        return false;
     }
 
     WriteFdFmt(fd, "Verity %s on %s\n", enable ? "enabled" : "disabled", mount_point);
-    return 0;
+    return true;
+}
+
+/* Helper function to get A/B suffix, if any. If the device isn't
+ * using A/B the empty string is returned. Otherwise either "_a",
+ * "_b", ... is returned.
+ *
+ * Note that since sometime in O androidboot.slot_suffix is deprecated
+ * and androidboot.slot should be used instead. Since bootloaders may
+ * be out of sync with the OS, we check both and for extra safety
+ * prepend a leading underscore if there isn't one already.
+ */
+static std::string get_ab_suffix() {
+    std::string ab_suffix = android::base::GetProperty("ro.boot.slot_suffix", "");
+    if (ab_suffix == "") {
+        ab_suffix = android::base::GetProperty("ro.boot.slot", "");
+    }
+    if (ab_suffix.size() > 0 && ab_suffix[0] != '_') {
+        ab_suffix = std::string("_") + ab_suffix;
+    }
+    return ab_suffix;
+}
+
+/* Use AVB to turn verity on/off */
+static bool set_avb_verity_enabled_state(int fd, AvbOps* ops, bool enable_verity) {
+    std::string ab_suffix = get_ab_suffix();
+
+    bool verity_enabled;
+    if (!avb_user_verity_get(ops, ab_suffix.c_str(), &verity_enabled)) {
+        WriteFdFmt(fd, "Error getting verity state\n");
+        return false;
+    }
+
+    if ((verity_enabled && enable_verity) || (!verity_enabled && !enable_verity)) {
+        WriteFdFmt(fd, "verity is already %s\n", verity_enabled ? "enabled" : "disabled");
+        return false;
+    }
+
+    if (!avb_user_verity_set(ops, ab_suffix.c_str(), enable_verity)) {
+        WriteFdFmt(fd, "Error setting verity\n");
+        return false;
+    }
+
+    WriteFdFmt(fd, "Successfully %s verity\n", enable_verity ? "enabled" : "disabled");
+    return true;
 }
 
 void set_verity_enabled_state_service(int fd, void* cookie) {
     unique_fd closer(fd);
+    bool any_changed = false;
 
     bool enable = (cookie != NULL);
     if (!kAllowDisableVerity) {
@@ -108,21 +153,37 @@
         return;
     }
 
-    // read all fstab entries at once from all sources
-    fstab = fs_mgr_read_fstab_default();
-    if (!fstab) {
-        WriteFdFmt(fd, "Failed to read fstab\nMaybe run adb root?\n");
-        return;
-    }
+    // Figure out if we're using VB1.0 or VB2.0 (aka AVB).
+    std::string vbmeta_hash = android::base::GetProperty("ro.boot.vbmeta.digest", "");
+    if (vbmeta_hash != "") {
+        // Yep, the system is using AVB (by contract, androidboot.vbmeta.hash is
+        // set by the bootloader when using AVB).
+        AvbOps* ops = avb_ops_user_new();
+        if (ops == nullptr) {
+            WriteFdFmt(fd, "Error getting AVB ops\n");
+            return;
+        }
+        if (set_avb_verity_enabled_state(fd, ops, enable)) {
+            any_changed = true;
+        }
+        avb_ops_user_free(ops);
+    } else {
+        // Not using AVB - assume VB1.0.
 
-    // Loop through entries looking for ones that vold manages.
-    bool any_changed = false;
-    for (int i = 0; i < fstab->num_entries; i++) {
-        if (fs_mgr_is_verified(&fstab->recs[i])) {
-            if (!set_verity_enabled_state(fd, fstab->recs[i].blk_device,
-                                          fstab->recs[i].mount_point,
-                                          enable)) {
-                any_changed = true;
+        // read all fstab entries at once from all sources
+        fstab = fs_mgr_read_fstab_default();
+        if (!fstab) {
+            WriteFdFmt(fd, "Failed to read fstab\nMaybe run adb root?\n");
+            return;
+        }
+
+        // Loop through entries looking for ones that vold manages.
+        for (int i = 0; i < fstab->num_entries; i++) {
+            if (fs_mgr_is_verified(&fstab->recs[i])) {
+                if (set_verity_enabled_state(fd, fstab->recs[i].blk_device,
+                                             fstab->recs[i].mount_point, enable)) {
+                    any_changed = true;
+                }
             }
         }
     }
diff --git a/adb/shell_service.cpp b/adb/shell_service.cpp
index d4f334b..ee821f8 100644
--- a/adb/shell_service.cpp
+++ b/adb/shell_service.cpp
@@ -90,6 +90,7 @@
 
 #include <memory>
 #include <string>
+#include <thread>
 #include <unordered_map>
 #include <vector>
 
@@ -392,12 +393,7 @@
 
 bool Subprocess::StartThread(std::unique_ptr<Subprocess> subprocess, std::string* error) {
     Subprocess* raw = subprocess.release();
-    if (!adb_thread_create(ThreadHandler, raw)) {
-        *error =
-            android::base::StringPrintf("failed to create subprocess thread: %s", strerror(errno));
-        kill(raw->pid_, SIGKILL);
-        return false;
-    }
+    std::thread(ThreadHandler, raw).detach();
 
     return true;
 }
diff --git a/adb/socket_test.cpp b/adb/socket_test.cpp
index f56f7f7..f7c66db 100644
--- a/adb/socket_test.cpp
+++ b/adb/socket_test.cpp
@@ -42,10 +42,6 @@
 
 class LocalSocketTest : public FdeventTest {};
 
-static void FdEventThreadFunc(void*) {
-    fdevent_loop();
-}
-
 constexpr auto SLEEP_FOR_FDEVENT = 100ms;
 
 TEST_F(LocalSocketTest, smoke) {
@@ -88,8 +84,7 @@
     connect(prev_tail, end);
 
     PrepareThread();
-    adb_thread_t thread;
-    ASSERT_TRUE(adb_thread_create(FdEventThreadFunc, nullptr, &thread));
+    std::thread thread(fdevent_loop);
 
     for (size_t i = 0; i < MESSAGE_LOOP_COUNT; ++i) {
         std::string read_buffer = MESSAGE;
@@ -152,9 +147,7 @@
     arg.cause_close_fd = cause_close_fd[1];
 
     PrepareThread();
-    adb_thread_t thread;
-    ASSERT_TRUE(adb_thread_create(reinterpret_cast<void (*)(void*)>(CloseWithPacketThreadFunc),
-                                  &arg, &thread));
+    std::thread thread(CloseWithPacketThreadFunc, &arg);
     // Wait until the fdevent_loop() starts.
     std::this_thread::sleep_for(SLEEP_FOR_FDEVENT);
     ASSERT_EQ(0, adb_close(cause_close_fd[0]));
@@ -177,9 +170,7 @@
     arg.cause_close_fd = cause_close_fd[1];
 
     PrepareThread();
-    adb_thread_t thread;
-    ASSERT_TRUE(adb_thread_create(reinterpret_cast<void (*)(void*)>(CloseWithPacketThreadFunc),
-                                  &arg, &thread));
+    std::thread thread(CloseWithPacketThreadFunc, &arg);
     // Wait until the fdevent_loop() starts.
     std::this_thread::sleep_for(SLEEP_FOR_FDEVENT);
     ASSERT_EQ(0, adb_close(cause_close_fd[0]));
@@ -211,10 +202,7 @@
     arg.cause_close_fd = cause_close_fd[1];
 
     PrepareThread();
-    adb_thread_t thread;
-    ASSERT_TRUE(adb_thread_create(reinterpret_cast<void (*)(void*)>(CloseWithPacketThreadFunc),
-                                  &arg, &thread));
-
+    std::thread thread(CloseWithPacketThreadFunc, &arg);
     // Wait until the fdevent_loop() starts.
     std::this_thread::sleep_for(SLEEP_FOR_FDEVENT);
     EXPECT_EQ(2u + GetAdditionalLocalSocketCount(), fdevent_installed_count());
@@ -252,9 +240,7 @@
     int listen_fd = network_inaddr_any_server(5038, SOCK_STREAM, &error);
     ASSERT_GE(listen_fd, 0);
 
-    adb_thread_t client_thread;
-    ASSERT_TRUE(adb_thread_create(reinterpret_cast<void (*)(void*)>(ClientThreadFunc), nullptr,
-                                  &client_thread));
+    std::thread client_thread(ClientThreadFunc);
 
     int accept_fd = adb_socket_accept(listen_fd, nullptr, nullptr);
     ASSERT_GE(accept_fd, 0);
@@ -262,16 +248,14 @@
     arg.socket_fd = accept_fd;
 
     PrepareThread();
-    adb_thread_t thread;
-    ASSERT_TRUE(adb_thread_create(reinterpret_cast<void (*)(void*)>(CloseRdHupSocketThreadFunc),
-                                  &arg, &thread));
+    std::thread thread(CloseRdHupSocketThreadFunc, &arg);
 
     // Wait until the fdevent_loop() starts.
     std::this_thread::sleep_for(SLEEP_FOR_FDEVENT);
     EXPECT_EQ(1u + GetAdditionalLocalSocketCount(), fdevent_installed_count());
 
     // Wait until the client closes its socket.
-    ASSERT_TRUE(adb_thread_join(client_thread));
+    client_thread.join();
 
     std::this_thread::sleep_for(SLEEP_FOR_FDEVENT);
     ASSERT_EQ(GetAdditionalLocalSocketCount(), fdevent_installed_count());
diff --git a/adb/sockets.cpp b/adb/sockets.cpp
index c05903f..14ad1ff 100644
--- a/adb/sockets.cpp
+++ b/adb/sockets.cpp
@@ -32,7 +32,7 @@
 
 #if !ADB_HOST
 #include <android-base/properties.h>
-#include <private/android_logger.h>
+#include <log/log_properties.h>
 #endif
 
 #include "adb.h"
@@ -794,7 +794,7 @@
     if (!s->transport) {
         SendFail(s->peer->fd, "device offline (no transport)");
         goto fail;
-    } else if (s->transport->connection_state == kCsOffline) {
+    } else if (s->transport->GetConnectionState() == kCsOffline) {
         /* if there's no remote we fail the connection
          ** right here and terminate it
          */
diff --git a/adb/sysdeps.h b/adb/sysdeps.h
index f195b4e..49c7847 100644
--- a/adb/sysdeps.h
+++ b/adb/sysdeps.h
@@ -35,6 +35,7 @@
 #include <android-base/utf8.h>
 
 #include "sysdeps/errno.h"
+#include "sysdeps/network.h"
 #include "sysdeps/stat.h"
 
 /*
@@ -98,64 +99,6 @@
     return c == '\\' || c == '/';
 }
 
-typedef void (*adb_thread_func_t)(void* arg);
-typedef HANDLE adb_thread_t;
-
-struct adb_winthread_args {
-    adb_thread_func_t func;
-    void* arg;
-};
-
-static unsigned __stdcall adb_winthread_wrapper(void* heap_args) {
-    // Move the arguments from the heap onto the thread's stack.
-    adb_winthread_args thread_args = *static_cast<adb_winthread_args*>(heap_args);
-    delete static_cast<adb_winthread_args*>(heap_args);
-    thread_args.func(thread_args.arg);
-    return 0;
-}
-
-static __inline__ bool adb_thread_create(adb_thread_func_t func, void* arg,
-                                         adb_thread_t* thread = nullptr) {
-    adb_winthread_args* args = new adb_winthread_args{.func = func, .arg = arg};
-    uintptr_t handle = _beginthreadex(nullptr, 0, adb_winthread_wrapper, args, 0, nullptr);
-    if (handle != static_cast<uintptr_t>(0)) {
-        if (thread) {
-            *thread = reinterpret_cast<HANDLE>(handle);
-        } else {
-            CloseHandle(thread);
-        }
-        return true;
-    }
-    return false;
-}
-
-static __inline__ bool adb_thread_join(adb_thread_t thread) {
-    switch (WaitForSingleObject(thread, INFINITE)) {
-        case WAIT_OBJECT_0:
-            CloseHandle(thread);
-            return true;
-
-        case WAIT_FAILED:
-            fprintf(stderr, "adb_thread_join failed: %s\n",
-                    android::base::SystemErrorCodeToString(GetLastError()).c_str());
-            break;
-
-        default:
-            abort();
-    }
-
-    return false;
-}
-
-static __inline__ bool adb_thread_detach(adb_thread_t thread) {
-    CloseHandle(thread);
-    return true;
-}
-
-static __inline__ void __attribute__((noreturn)) adb_thread_exit() {
-    _endthreadex(0);
-}
-
 static __inline__ int adb_thread_setname(const std::string& name) {
     // TODO: See https://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx for how to set
     // the thread name in Windows. Unfortunately, it only works during debugging, but
@@ -163,14 +106,6 @@
     return 0;
 }
 
-static __inline__ adb_thread_t adb_thread_self() {
-    return GetCurrentThread();
-}
-
-static __inline__ bool adb_thread_equal(adb_thread_t lhs, adb_thread_t rhs) {
-    return GetThreadId(lhs) == GetThreadId(rhs);
-}
-
 static __inline__  unsigned long adb_thread_id()
 {
     return GetCurrentThreadId();
@@ -248,8 +183,6 @@
 int unix_isatty(int fd);
 #define  isatty  ___xxx_isatty
 
-int network_loopback_client(int port, int type, std::string* error);
-int network_loopback_server(int port, int type, std::string* error);
 int network_inaddr_any_server(int port, int type, std::string* error);
 
 inline int network_local_client(const char* name, int namespace_id, int type, std::string* error) {
@@ -268,10 +201,6 @@
 #undef   accept
 #define  accept  ___xxx_accept
 
-int adb_getsockname(int fd, struct sockaddr* sockaddr, socklen_t* optlen);
-#undef getsockname
-#define getsockname(...) ___xxx_getsockname(__VA__ARGS__)
-
 // Returns the local port number of a bound socket, or -1 on failure.
 int adb_socket_get_local_port(int fd);
 
@@ -591,17 +520,6 @@
   return fd;
 }
 
-inline int network_loopback_client(int port, int type, std::string* error) {
-  return _fd_set_error_str(socket_network_client("localhost", port, type), error);
-}
-
-inline int network_loopback_server(int port, int type, std::string* error) {
-  int fd = socket_loopback_server(port, type);
-  if (fd < 0 && errno == EAFNOSUPPORT)
-      return _fd_set_error_str(socket_loopback_server6(port, type), error);
-  return _fd_set_error_str(fd, error);
-}
-
 inline int network_inaddr_any_server(int port, int type, std::string* error) {
   return _fd_set_error_str(socket_inaddr_any_server(port, type), error);
 }
@@ -660,55 +578,6 @@
 #define  unix_write  adb_write
 #define  unix_close  adb_close
 
-// Win32 is limited to DWORDs for thread return values; limit the POSIX systems to this as well to
-// ensure compatibility.
-typedef void (*adb_thread_func_t)(void* arg);
-typedef pthread_t adb_thread_t;
-
-struct adb_pthread_args {
-    adb_thread_func_t func;
-    void* arg;
-};
-
-static void* adb_pthread_wrapper(void* heap_args) {
-    // Move the arguments from the heap onto the thread's stack.
-    adb_pthread_args thread_args = *reinterpret_cast<adb_pthread_args*>(heap_args);
-    delete static_cast<adb_pthread_args*>(heap_args);
-    thread_args.func(thread_args.arg);
-    return nullptr;
-}
-
-static __inline__ bool adb_thread_create(adb_thread_func_t start, void* arg,
-                                         adb_thread_t* thread = nullptr) {
-    pthread_t temp;
-    pthread_attr_t attr;
-    pthread_attr_init(&attr);
-    pthread_attr_setdetachstate(&attr, thread ? PTHREAD_CREATE_JOINABLE : PTHREAD_CREATE_DETACHED);
-    auto* pthread_args = new adb_pthread_args{.func = start, .arg = arg};
-    errno = pthread_create(&temp, &attr, adb_pthread_wrapper, pthread_args);
-    if (errno == 0) {
-        if (thread) {
-            *thread = temp;
-        }
-        return true;
-    }
-    return false;
-}
-
-static __inline__ bool adb_thread_join(adb_thread_t thread) {
-    errno = pthread_join(thread, nullptr);
-    return errno == 0;
-}
-
-static __inline__ bool adb_thread_detach(adb_thread_t thread) {
-    errno = pthread_detach(thread);
-    return errno == 0;
-}
-
-static __inline__ void __attribute__((noreturn)) adb_thread_exit() {
-    pthread_exit(nullptr);
-}
-
 static __inline__ int adb_thread_setname(const std::string& name) {
 #ifdef __APPLE__
     return pthread_setname_np(name.c_str());
diff --git a/bootstat/uptime_parser.h b/adb/sysdeps/network.h
similarity index 65%
copy from bootstat/uptime_parser.h
copy to adb/sysdeps/network.h
index 756ae9b..83ce371 100644
--- a/bootstat/uptime_parser.h
+++ b/adb/sysdeps/network.h
@@ -1,5 +1,7 @@
+#pragma once
+
 /*
- * Copyright (C) 2016 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,16 +16,7 @@
  * limitations under the License.
  */
 
-#ifndef UPTIME_PARSER_H_
-#define UPTIME_PARSER_H_
+#include <string>
 
-#include <time.h>
-
-namespace bootstat {
-
-// Returns the number of seconds the system has been on since reboot.
-time_t ParseUptime();
-
-}  // namespace bootstat
-
-#endif  // UPTIME_PARSER_H_
\ No newline at end of file
+int network_loopback_client(int port, int type, std::string* error);
+int network_loopback_server(int port, int type, std::string* error);
diff --git a/adb/sysdeps/posix/network.cpp b/adb/sysdeps/posix/network.cpp
new file mode 100644
index 0000000..45da5af
--- /dev/null
+++ b/adb/sysdeps/posix/network.cpp
@@ -0,0 +1,127 @@
+/*
+ * 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 "sysdeps/network.h"
+
+#include <errno.h>
+#include <netinet/in.h>
+#include <sys/socket.h>
+
+#include <string>
+
+#include "adb_unique_fd.h"
+
+static void set_error(std::string* error) {
+    if (error) {
+        *error = strerror(errno);
+    }
+}
+
+static sockaddr* loopback_addr4(sockaddr_storage* addr, socklen_t* addrlen, int port) {
+    struct sockaddr_in* addr4 = reinterpret_cast<sockaddr_in*>(addr);
+    *addrlen = sizeof(*addr4);
+
+    addr4->sin_family = AF_INET;
+    addr4->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+    addr4->sin_port = htons(port);
+    return reinterpret_cast<sockaddr*>(addr);
+}
+
+static sockaddr* loopback_addr6(sockaddr_storage* addr, socklen_t* addrlen, int port) {
+    struct sockaddr_in6* addr6 = reinterpret_cast<sockaddr_in6*>(addr);
+    *addrlen = sizeof(*addr6);
+
+    addr6->sin6_family = AF_INET6;
+    addr6->sin6_addr = in6addr_loopback;
+    addr6->sin6_port = htons(port);
+    return reinterpret_cast<sockaddr*>(addr);
+}
+
+static int _network_loopback_client(bool ipv6, int port, int type, std::string* error) {
+    unique_fd s(socket(ipv6 ? AF_INET6 : AF_INET, type, 0));
+    if (s == -1) {
+        set_error(error);
+        return -1;
+    }
+
+    struct sockaddr_storage addr_storage = {};
+    socklen_t addrlen = sizeof(addr_storage);
+    sockaddr* addr = (ipv6 ? loopback_addr6 : loopback_addr4)(&addr_storage, &addrlen, 0);
+
+    if (bind(s.get(), addr, addrlen) != 0) {
+        set_error(error);
+        return -1;
+    }
+
+    addr = (ipv6 ? loopback_addr6 : loopback_addr4)(&addr_storage, &addrlen, port);
+
+    if (connect(s.get(), addr, addrlen) != 0) {
+        set_error(error);
+        return -1;
+    }
+
+    return s.release();
+}
+
+int network_loopback_client(int port, int type, std::string* error) {
+    // Try IPv4 first, use IPv6 as a fallback.
+    int rc = _network_loopback_client(false, port, type, error);
+    if (rc == -1) {
+        return _network_loopback_client(true, port, type, error);
+    }
+    return rc;
+}
+
+static int _network_loopback_server(bool ipv6, int port, int type, std::string* error) {
+    unique_fd s(socket(ipv6 ? AF_INET6 : AF_INET, type, 0));
+    if (s == -1) {
+        set_error(error);
+        return -1;
+    }
+
+    int n = 1;
+    setsockopt(s.get(), SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n));
+
+    struct sockaddr_storage addr_storage = {};
+    socklen_t addrlen = sizeof(addr_storage);
+    sockaddr* addr = (ipv6 ? loopback_addr6 : loopback_addr4)(&addr_storage, &addrlen, port);
+
+    if (bind(s, addr, addrlen) != 0) {
+        set_error(error);
+        return -1;
+    }
+
+    if (type == SOCK_STREAM || type == SOCK_SEQPACKET) {
+        // Arbitrarily selected value, ported from libcutils.
+        if (listen(s, 4) != 0) {
+            set_error(error);
+            return -1;
+        }
+    }
+
+    return s.release();
+}
+
+int network_loopback_server(int port, int type, std::string* error) {
+    int rc = _network_loopback_server(false, port, type, error);
+
+    // Only attempt to listen on IPv6 if IPv4 is unavailable.
+    // We don't want to start an IPv6 server if there's already an IPv4 one running.
+    if (rc == -1 && (errno == EADDRNOTAVAIL || errno == EAFNOSUPPORT)) {
+        return _network_loopback_server(true, port, type, error);
+    }
+    return rc;
+}
diff --git a/adb/sysdeps_test.cpp b/adb/sysdeps_test.cpp
index 9007e75..edb0fb3 100644
--- a/adb/sysdeps_test.cpp
+++ b/adb/sysdeps_test.cpp
@@ -25,54 +25,6 @@
 #include "sysdeps.h"
 #include "sysdeps/chrono.h"
 
-static void increment_atomic_int(void* c) {
-    std::this_thread::sleep_for(1s);
-    reinterpret_cast<std::atomic<int>*>(c)->fetch_add(1);
-}
-
-TEST(sysdeps_thread, smoke) {
-    std::atomic<int> counter(0);
-
-    for (int i = 0; i < 100; ++i) {
-        ASSERT_TRUE(adb_thread_create(increment_atomic_int, &counter));
-    }
-
-    std::this_thread::sleep_for(2s);
-    ASSERT_EQ(100, counter.load());
-}
-
-TEST(sysdeps_thread, join) {
-    std::atomic<int> counter(0);
-    std::vector<adb_thread_t> threads(500);
-    for (size_t i = 0; i < threads.size(); ++i) {
-        ASSERT_TRUE(adb_thread_create(increment_atomic_int, &counter, &threads[i]));
-    }
-
-    int current = counter.load();
-    ASSERT_GE(current, 0);
-    // Make sure that adb_thread_create actually creates threads, and doesn't do something silly
-    // like synchronously run the function passed in. The sleep in increment_atomic_int should be
-    // enough to keep this from being flakey.
-    ASSERT_LT(current, 500);
-
-    for (const auto& thread : threads) {
-        ASSERT_TRUE(adb_thread_join(thread));
-    }
-
-    ASSERT_EQ(500, counter.load());
-}
-
-TEST(sysdeps_thread, exit) {
-    adb_thread_t thread;
-    ASSERT_TRUE(adb_thread_create(
-        [](void*) {
-            adb_thread_exit();
-            for (;;) continue;
-        },
-        nullptr, &thread));
-    ASSERT_TRUE(adb_thread_join(thread));
-}
-
 TEST(sysdeps_socketpair, smoke) {
     int fds[2];
     ASSERT_EQ(0, adb_socketpair(fds)) << strerror(errno);
@@ -254,13 +206,13 @@
     static std::mutex &m = *new std::mutex();
     m.lock();
     ASSERT_FALSE(m.try_lock());
-    adb_thread_create([](void*) {
+    std::thread thread([]() {
         ASSERT_FALSE(m.try_lock());
         m.lock();
         finished.store(true);
         std::this_thread::sleep_for(200ms);
         m.unlock();
-    }, nullptr);
+    });
 
     ASSERT_FALSE(finished.load());
     std::this_thread::sleep_for(100ms);
@@ -270,6 +222,8 @@
     m.lock();
     ASSERT_TRUE(finished.load());
     m.unlock();
+
+    thread.join();
 }
 
 TEST(sysdeps_mutex, recursive_mutex_smoke) {
@@ -279,12 +233,12 @@
     ASSERT_TRUE(m.try_lock());
     m.unlock();
 
-    adb_thread_create([](void*) {
+    std::thread thread([]() {
         ASSERT_FALSE(m.try_lock());
         m.lock();
         std::this_thread::sleep_for(500ms);
         m.unlock();
-    }, nullptr);
+    });
 
     std::this_thread::sleep_for(100ms);
     m.unlock();
@@ -292,6 +246,8 @@
     ASSERT_FALSE(m.try_lock());
     m.lock();
     m.unlock();
+
+    thread.join();
 }
 
 TEST(sysdeps_condition_variable, smoke) {
@@ -300,14 +256,16 @@
     static volatile bool flag = false;
 
     std::unique_lock<std::mutex> lock(m);
-    adb_thread_create([](void*) {
+    std::thread thread([]() {
         m.lock();
         flag = true;
         cond.notify_one();
         m.unlock();
-    }, nullptr);
+    });
 
     while (!flag) {
         cond.wait(lock);
     }
+
+    thread.join();
 }
diff --git a/adb/sysdeps_win32.cpp b/adb/sysdeps_win32.cpp
index f997e6b..5873b2b 100644
--- a/adb/sysdeps_win32.cpp
+++ b/adb/sysdeps_win32.cpp
@@ -984,7 +984,7 @@
         return -1;
     }
 
-    int result = (getsockname)(fh->fh_socket, sockaddr, optlen);
+    int result = getsockname(fh->fh_socket, sockaddr, optlen);
     if (result == SOCKET_ERROR) {
         const DWORD err = WSAGetLastError();
         D("adb_getsockname: setsockopt on fd %d failed: %s\n", fd,
@@ -1042,11 +1042,6 @@
     int local_port = -1;
     std::string error;
 
-    struct sockaddr_storage peer_addr = {};
-    struct sockaddr_storage client_addr = {};
-    socklen_t peer_socklen = sizeof(peer_addr);
-    socklen_t client_socklen = sizeof(client_addr);
-
     server = network_loopback_server(0, SOCK_STREAM, &error);
     if (server < 0) {
         D("adb_socketpair: failed to create server: %s", error.c_str());
@@ -1066,32 +1061,12 @@
         goto fail;
     }
 
-    // Make sure that the peer that connected to us and the client are the same.
-    accepted = adb_socket_accept(server, reinterpret_cast<sockaddr*>(&peer_addr), &peer_socklen);
+    accepted = adb_socket_accept(server, nullptr, nullptr);
     if (accepted < 0) {
         D("adb_socketpair: failed to accept: %s", strerror(errno));
         goto fail;
     }
-
-    if (adb_getsockname(client, reinterpret_cast<sockaddr*>(&client_addr), &client_socklen) != 0) {
-        D("adb_socketpair: failed to getpeername: %s", strerror(errno));
-        goto fail;
-    }
-
-    if (peer_socklen != client_socklen) {
-        D("adb_socketpair: client and peer sockaddrs have different lengths");
-        errno = EIO;
-        goto fail;
-    }
-
-    if (memcmp(&peer_addr, &client_addr, peer_socklen) != 0) {
-        D("adb_socketpair: client and peer sockaddrs don't match");
-        errno = EIO;
-        goto fail;
-    }
-
     adb_close(server);
-
     sv[0] = client;
     sv[1] = accepted;
     return 0;
diff --git a/adb/test_device.py b/adb/test_device.py
index e76aaed..a30972e 100644
--- a/adb/test_device.py
+++ b/adb/test_device.py
@@ -1188,6 +1188,77 @@
         self.device.shell(['rm', '-f', '/data/local/tmp/adb-test-*'])
 
 
+class DeviceOfflineTest(DeviceTest):
+    def _get_device_state(self, serialno):
+        output = subprocess.check_output(self.device.adb_cmd + ['devices'])
+        for line in output.split('\n'):
+            m = re.match('(\S+)\s+(\S+)', line)
+            if m and m.group(1) == serialno:
+                return m.group(2)
+        return None
+
+    def test_killed_when_pushing_a_large_file(self):
+        """
+           While running adb push with a large file, kill adb server.
+           Occasionally the device becomes offline. Because the device is still
+           reading data without realizing that the adb server has been restarted.
+           Test if we can bring the device online automatically now.
+           http://b/32952319
+        """
+        serialno = subprocess.check_output(self.device.adb_cmd + ['get-serialno']).strip()
+        # 1. Push a large file
+        file_path = 'tmp_large_file'
+        try:
+            fh = open(file_path, 'w')
+            fh.write('\0' * (100 * 1024 * 1024))
+            fh.close()
+            subproc = subprocess.Popen(self.device.adb_cmd + ['push', file_path, '/data/local/tmp'])
+            time.sleep(0.1)
+            # 2. Kill the adb server
+            subprocess.check_call(self.device.adb_cmd + ['kill-server'])
+            subproc.terminate()
+        finally:
+            try:
+                os.unlink(file_path)
+            except:
+                pass
+        # 3. See if the device still exist.
+        # Sleep to wait for the adb server exit.
+        time.sleep(0.5)
+        # 4. The device should be online
+        self.assertEqual(self._get_device_state(serialno), 'device')
+
+    def test_killed_when_pulling_a_large_file(self):
+        """
+           While running adb pull with a large file, kill adb server.
+           Occasionally the device can't be connected. Because the device is trying to
+           send a message larger than what is expected by the adb server.
+           Test if we can bring the device online automatically now.
+        """
+        serialno = subprocess.check_output(self.device.adb_cmd + ['get-serialno']).strip()
+        file_path = 'tmp_large_file'
+        try:
+            # 1. Create a large file on device.
+            self.device.shell(['dd', 'if=/dev/zero', 'of=/data/local/tmp/tmp_large_file',
+                               'bs=1000000', 'count=100'])
+            # 2. Pull the large file on host.
+            subproc = subprocess.Popen(self.device.adb_cmd +
+                                       ['pull','/data/local/tmp/tmp_large_file', file_path])
+            time.sleep(0.1)
+            # 3. Kill the adb server
+            subprocess.check_call(self.device.adb_cmd + ['kill-server'])
+            subproc.terminate()
+        finally:
+            try:
+                os.unlink(file_path)
+            except:
+                pass
+        # 4. See if the device still exist.
+        # Sleep to wait for the adb server exit.
+        time.sleep(0.5)
+        self.assertEqual(self._get_device_state(serialno), 'device')
+
+
 def main():
     random.seed(0)
     if len(adb.get_devices()) > 0:
diff --git a/adb/transport.cpp b/adb/transport.cpp
index c951f5b..cc8c162 100644
--- a/adb/transport.cpp
+++ b/adb/transport.cpp
@@ -29,9 +29,11 @@
 #include <algorithm>
 #include <list>
 #include <mutex>
+#include <thread>
 
 #include <android-base/logging.h>
 #include <android-base/parsenetaddress.h>
+#include <android-base/quick_exit.h>
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
 
@@ -40,6 +42,7 @@
 #include "adb_trace.h"
 #include "adb_utils.h"
 #include "diagnose_usb.h"
+#include "fdevent.h"
 
 static void transport_unref(atransport *t);
 
@@ -208,6 +211,11 @@
                 put_apacket(p);
                 break;
             }
+#if ADB_HOST
+            if (p->msg.command == 0) {
+                continue;
+            }
+#endif
         }
 
         D("%s: received remote packet, sending to transport", t->serial);
@@ -270,7 +278,11 @@
             if (active) {
                 D("%s: transport got packet, sending to remote", t->serial);
                 ATRACE_NAME("write_transport write_remote");
-                t->write_to_remote(p, t);
+                if (t->Write(p) != 0) {
+                    D("%s: remote write failed for transport", t->serial);
+                    put_apacket(p);
+                    break;
+                }
             } else {
                 D("%s: transport ignoring packet while offline", t->serial);
             }
@@ -492,7 +504,7 @@
     }
 
     /* don't create transport threads for inaccessible devices */
-    if (t->connection_state != kCsNoPerm) {
+    if (t->GetConnectionState() != kCsNoPerm) {
         /* initial references are the two threads */
         t->ref_count = 2;
 
@@ -509,13 +521,8 @@
 
         fdevent_set(&(t->transport_fde), FDE_READ);
 
-        if (!adb_thread_create(write_transport_thread, t)) {
-            fatal_errno("cannot create write_transport thread");
-        }
-
-        if (!adb_thread_create(read_transport_thread, t)) {
-            fatal_errno("cannot create read_transport thread");
-        }
+        std::thread(write_transport_thread, t).detach();
+        std::thread(read_transport_thread, t).detach();
     }
 
     {
@@ -542,6 +549,15 @@
                     transport_registration_func, 0);
 
     fdevent_set(&transport_registration_fde, FDE_READ);
+#if ADB_HOST
+    android::base::at_quick_exit([]() {
+        // To avoid only writing part of a packet to a transport after exit, kick all transports.
+        std::lock_guard<std::mutex> lock(transport_lock);
+        for (auto t : transport_list) {
+            t->Kick();
+        }
+    });
+#endif
 }
 
 /* the fdevent select pump is single threaded */
@@ -604,7 +620,7 @@
 }
 
 atransport* acquire_one_transport(TransportType type, const char* serial, bool* is_ambiguous,
-                                  std::string* error_out) {
+                                  std::string* error_out, bool accept_any_state) {
     atransport* result = nullptr;
 
     if (serial) {
@@ -619,7 +635,7 @@
 
     std::unique_lock<std::mutex> lock(transport_lock);
     for (const auto& t : transport_list) {
-        if (t->connection_state == kCsNoPerm) {
+        if (t->GetConnectionState() == kCsNoPerm) {
 #if ADB_HOST
             *error_out = UsbNoPermissionsLongHelpText();
 #endif
@@ -668,7 +684,7 @@
     lock.unlock();
 
     // Don't return unauthorized devices; the caller can't do anything with them.
-    if (result && result->connection_state == kCsUnauthorized) {
+    if (result && result->GetConnectionState() == kCsUnauthorized && !accept_any_state) {
         *error_out = "device unauthorized.\n";
         char* ADB_VENDOR_KEYS = getenv("ADB_VENDOR_KEYS");
         *error_out += "This adb server's $ADB_VENDOR_KEYS is ";
@@ -680,7 +696,7 @@
     }
 
     // Don't return offline devices; the caller can't do anything with them.
-    if (result && result->connection_state == kCsOffline) {
+    if (result && result->GetConnectionState() == kCsOffline && !accept_any_state) {
         *error_out = "device offline";
         result = nullptr;
     }
@@ -692,16 +708,38 @@
     return result;
 }
 
+int atransport::Write(apacket* p) {
+#if ADB_HOST
+    std::lock_guard<std::mutex> lock(write_msg_lock_);
+#endif
+    return write_func_(p, this);
+}
+
 void atransport::Kick() {
     if (!kicked_) {
         kicked_ = true;
         CHECK(kick_func_ != nullptr);
+#if ADB_HOST
+        // On host, adb server should avoid writing part of a packet, so don't
+        // kick a transport whiling writing a packet.
+        std::lock_guard<std::mutex> lock(write_msg_lock_);
+#endif
         kick_func_(this);
     }
 }
 
+ConnectionState atransport::GetConnectionState() const {
+    return connection_state_;
+}
+
+void atransport::SetConnectionState(ConnectionState state) {
+    check_main_thread();
+    connection_state_ = state;
+}
+
 const std::string atransport::connection_state_name() const {
-    switch (connection_state) {
+    ConnectionState state = GetConnectionState();
+    switch (state) {
         case kCsOffline:
             return "offline";
         case kCsBootloader:
@@ -967,10 +1005,10 @@
 
 void register_usb_transport(usb_handle* usb, const char* serial, const char* devpath,
                             unsigned writeable) {
-    atransport* t = new atransport();
+    atransport* t = new atransport((writeable ? kCsOffline : kCsNoPerm));
 
     D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb, serial ? serial : "");
-    init_usb_transport(t, usb, (writeable ? kCsOffline : kCsNoPerm));
+    init_usb_transport(t, usb);
     if (serial) {
         t->serial = strdup(serial);
     }
@@ -991,12 +1029,13 @@
 void unregister_usb_transport(usb_handle* usb) {
     std::lock_guard<std::mutex> lock(transport_lock);
     transport_list.remove_if(
-        [usb](atransport* t) { return t->usb == usb && t->connection_state == kCsNoPerm; });
+        [usb](atransport* t) { return t->usb == usb && t->GetConnectionState() == kCsNoPerm; });
 }
 
 int check_header(apacket* p, atransport* t) {
     if (p->msg.magic != (p->msg.command ^ 0xffffffff)) {
-        VLOG(RWX) << "check_header(): invalid magic";
+        VLOG(RWX) << "check_header(): invalid magic command = " << std::hex << p->msg.command
+                  << ", magic = " << p->msg.magic;
         return -1;
     }
 
@@ -1024,4 +1063,11 @@
     keys_.pop_front();
     return result;
 }
+bool atransport::SetSendConnectOnError() {
+    if (has_send_connect_on_error_) {
+        return false;
+    }
+    has_send_connect_on_error_ = true;
+    return true;
+}
 #endif
diff --git a/adb/transport.h b/adb/transport.h
index 4d97fc7..8c15d66 100644
--- a/adb/transport.h
+++ b/adb/transport.h
@@ -19,10 +19,12 @@
 
 #include <sys/types.h>
 
+#include <atomic>
 #include <deque>
 #include <functional>
 #include <list>
 #include <memory>
+#include <mutex>
 #include <string>
 #include <unordered_set>
 
@@ -57,31 +59,35 @@
     // class in one go is a very large change. Given how bad our testing is,
     // it's better to do this piece by piece.
 
-    atransport() {
+    atransport(ConnectionState state = kCsOffline) : connection_state_(state) {
         transport_fde = {};
         protocol_version = A_VERSION;
         max_payload = MAX_PAYLOAD;
     }
-
     virtual ~atransport() {}
 
     int (*read_from_remote)(apacket* p, atransport* t) = nullptr;
-    int (*write_to_remote)(apacket* p, atransport* t) = nullptr;
     void (*close)(atransport* t) = nullptr;
+
+    void SetWriteFunction(int (*write_func)(apacket*, atransport*)) { write_func_ = write_func; }
     void SetKickFunction(void (*kick_func)(atransport*)) {
         kick_func_ = kick_func;
     }
     bool IsKicked() {
         return kicked_;
     }
+    int Write(apacket* p);
     void Kick();
 
+    // ConnectionState can be read by all threads, but can only be written in the main thread.
+    ConnectionState GetConnectionState() const;
+    void SetConnectionState(ConnectionState state);
+
     int fd = -1;
     int transport_socket = -1;
     fdevent transport_fde;
     size_t ref_count = 0;
     uint32_t sync_token = 0;
-    ConnectionState connection_state = kCsOffline;
     bool online = false;
     TransportType type = kTransportAny;
 
@@ -114,11 +120,13 @@
 
 #if ADB_HOST
     std::shared_ptr<RSA> NextKey();
+    bool SetSendConnectOnError();
 #endif
 
     char token[TOKEN_SIZE] = {};
     size_t failed_auth_attempts = 0;
 
+    const std::string serial_name() const { return serial ? serial : "<unknown>"; }
     const std::string connection_state_name() const;
 
     void update_version(int version, size_t payload);
@@ -157,6 +165,7 @@
     int local_port_for_emulator_ = -1;
     bool kicked_ = false;
     void (*kick_func_)(atransport*) = nullptr;
+    int (*write_func_)(apacket*, atransport*) = nullptr;
 
     // A set of features transmitted in the banner with the initial connection.
     // This is stored in the banner as 'features=feature0,feature1,etc'.
@@ -167,8 +176,11 @@
     // A list of adisconnect callbacks called when the transport is kicked.
     std::list<adisconnect*> disconnects_;
 
+    std::atomic<ConnectionState> connection_state_;
 #if ADB_HOST
     std::deque<std::shared_ptr<RSA>> keys_;
+    std::mutex write_msg_lock_;
+    bool has_send_connect_on_error_ = false;
 #endif
 
     DISALLOW_COPY_AND_ASSIGN(atransport);
@@ -181,8 +193,8 @@
  * is set to true and nullptr returned.
  * If no suitable transport is found, error is set and nullptr returned.
  */
-atransport* acquire_one_transport(TransportType type, const char* serial,
-                                  bool* is_ambiguous, std::string* error_out);
+atransport* acquire_one_transport(TransportType type, const char* serial, bool* is_ambiguous,
+                                  std::string* error_out, bool accept_any_state = false);
 void kick_transport(atransport* t);
 void update_transports(void);
 
diff --git a/adb/transport_local.cpp b/adb/transport_local.cpp
index 12b98ba..3ee286a 100644
--- a/adb/transport_local.cpp
+++ b/adb/transport_local.cpp
@@ -199,7 +199,7 @@
 std::mutex &retry_ports_lock = *new std::mutex;
 std::condition_variable &retry_ports_cond = *new std::condition_variable;
 
-static void client_socket_thread(void* x) {
+static void client_socket_thread(int) {
     adb_thread_setname("client_socket_thread");
     D("transport: client_socket_thread() starting");
     PollAllLocalPortsForEmulator();
@@ -244,9 +244,8 @@
 
 #else // ADB_HOST
 
-static void server_socket_thread(void* arg) {
+static void server_socket_thread(int port) {
     int serverfd, fd;
-    int port = (int) (uintptr_t) arg;
 
     adb_thread_setname("server socket");
     D("transport: server_socket_thread() starting");
@@ -289,7 +288,7 @@
 #define open    adb_open
 #define read    adb_read
 #define write   adb_write
-#include <qemu_pipe.h>
+#include <system/qemu_pipe.h>
 #undef open
 #undef read
 #undef write
@@ -325,7 +324,7 @@
  *   the transport registration is completed. That's why we need to send the
  *   'start' request after the transport is registered.
  */
-static void qemu_socket_thread(void* arg) {
+static void qemu_socket_thread(int port) {
     /* 'accept' request to the adb QEMUD service. */
     static const char _accept_req[] = "accept";
     /* 'start' request to the adb QEMUD service. */
@@ -333,7 +332,6 @@
     /* 'ok' reply from the adb QEMUD service. */
     static const char _ok_resp[] = "ok";
 
-    const int port = (int) (uintptr_t) arg;
     int fd;
     char tmp[256];
     char con_name[32];
@@ -350,7 +348,7 @@
         /* This could be an older version of the emulator, that doesn't
          * implement adb QEMUD service. Fall back to the old TCP way. */
         D("adb service is not available. Falling back to TCP socket.");
-        adb_thread_create(server_socket_thread, arg);
+        std::thread(server_socket_thread, port).detach();
         return;
     }
 
@@ -394,7 +392,7 @@
 
 void local_init(int port)
 {
-    adb_thread_func_t func;
+    void (*func)(int);
     const char* debug_name = "";
 
 #if ADB_HOST
@@ -414,9 +412,7 @@
 #endif // !ADB_HOST
 
     D("transport: local %s init", debug_name);
-    if (!adb_thread_create(func, (void *) (uintptr_t) port)) {
-        fatal_errno("cannot create local socket %s thread", debug_name);
-    }
+    std::thread(func, port).detach();
 }
 
 static void remote_kick(atransport *t)
@@ -519,12 +515,11 @@
     int  fail = 0;
 
     t->SetKickFunction(remote_kick);
+    t->SetWriteFunction(remote_write);
     t->close = remote_close;
     t->read_from_remote = remote_read;
-    t->write_to_remote = remote_write;
     t->sfd = s;
     t->sync_token = 1;
-    t->connection_state = kCsOffline;
     t->type = kTransportLocal;
 
 #if ADB_HOST
diff --git a/adb/transport_test.cpp b/adb/transport_test.cpp
index 8b38e03..68689d4 100644
--- a/adb/transport_test.cpp
+++ b/adb/transport_test.cpp
@@ -94,12 +94,13 @@
 }
 
 TEST(transport, parse_banner_no_features) {
+    set_main_thread();
     atransport t;
 
     parse_banner("host::", &t);
 
     ASSERT_EQ(0U, t.features().size());
-    ASSERT_EQ(kCsHost, t.connection_state);
+    ASSERT_EQ(kCsHost, t.GetConnectionState());
 
     ASSERT_EQ(nullptr, t.product);
     ASSERT_EQ(nullptr, t.model);
@@ -113,7 +114,7 @@
         "host::ro.product.name=foo;ro.product.model=bar;ro.product.device=baz;";
     parse_banner(banner, &t);
 
-    ASSERT_EQ(kCsHost, t.connection_state);
+    ASSERT_EQ(kCsHost, t.GetConnectionState());
 
     ASSERT_EQ(0U, t.features().size());
 
@@ -130,7 +131,7 @@
         "features=woodly,doodly";
     parse_banner(banner, &t);
 
-    ASSERT_EQ(kCsHost, t.connection_state);
+    ASSERT_EQ(kCsHost, t.GetConnectionState());
 
     ASSERT_EQ(2U, t.features().size());
     ASSERT_TRUE(t.has_feature("woodly"));
diff --git a/adb/transport_usb.cpp b/adb/transport_usb.cpp
index 516b4f2..ce419b8 100644
--- a/adb/transport_usb.cpp
+++ b/adb/transport_usb.cpp
@@ -25,9 +25,115 @@
 
 #include "adb.h"
 
+#if ADB_HOST
+
+static constexpr size_t MAX_USB_BULK_PACKET_SIZE = 1024u;
+
+// Call usb_read using a buffer having a multiple of MAX_USB_BULK_PACKET_SIZE bytes
+// to avoid overflow. See http://libusb.sourceforge.net/api-1.0/packetoverflow.html.
+static int UsbReadMessage(usb_handle* h, amessage* msg) {
+    D("UsbReadMessage");
+    char buffer[MAX_USB_BULK_PACKET_SIZE];
+    int n = usb_read(h, buffer, sizeof(buffer));
+    if (n == sizeof(*msg)) {
+        memcpy(msg, buffer, sizeof(*msg));
+    }
+    return n;
+}
+
+// Call usb_read using a buffer having a multiple of MAX_USB_BULK_PACKET_SIZE bytes
+// to avoid overflow. See http://libusb.sourceforge.net/api-1.0/packetoverflow.html.
+static int UsbReadPayload(usb_handle* h, apacket* p) {
+    D("UsbReadPayload");
+    size_t need_size = p->msg.data_length;
+    size_t data_pos = 0u;
+    while (need_size > 0u) {
+        int n = 0;
+        if (data_pos + MAX_USB_BULK_PACKET_SIZE <= sizeof(p->data)) {
+            // Read directly to p->data.
+            size_t rem_size = need_size % MAX_USB_BULK_PACKET_SIZE;
+            size_t direct_read_size = need_size - rem_size;
+            if (rem_size &&
+                data_pos + direct_read_size + MAX_USB_BULK_PACKET_SIZE <= sizeof(p->data)) {
+                direct_read_size += MAX_USB_BULK_PACKET_SIZE;
+            }
+            n = usb_read(h, &p->data[data_pos], direct_read_size);
+            if (n < 0) {
+                D("usb_read(size %zu) failed", direct_read_size);
+                return n;
+            }
+        } else {
+            // Read indirectly using a buffer.
+            char buffer[MAX_USB_BULK_PACKET_SIZE];
+            n = usb_read(h, buffer, sizeof(buffer));
+            if (n < 0) {
+                D("usb_read(size %zu) failed", sizeof(buffer));
+                return -1;
+            }
+            size_t copy_size = std::min(static_cast<size_t>(n), need_size);
+            D("usb read %d bytes, need %zu bytes, copy %zu bytes", n, need_size, copy_size);
+            memcpy(&p->data[data_pos], buffer, copy_size);
+        }
+        data_pos += n;
+        need_size -= std::min(static_cast<size_t>(n), need_size);
+    }
+    return static_cast<int>(data_pos);
+}
+
+static int remote_read(apacket* p, atransport* t) {
+    int n = UsbReadMessage(t->usb, &p->msg);
+    if (n < 0) {
+        D("remote usb: read terminated (message)");
+        return -1;
+    }
+    if (static_cast<size_t>(n) != sizeof(p->msg) || check_header(p, t)) {
+        D("remote usb: check_header failed, skip it");
+        goto err_msg;
+    }
+    if (t->GetConnectionState() == kCsOffline) {
+        // If we read a wrong msg header declaring a large message payload, don't read its payload.
+        // Otherwise we may miss true messages from the device.
+        if (p->msg.command != A_CNXN && p->msg.command != A_AUTH) {
+            goto err_msg;
+        }
+    }
+    if (p->msg.data_length) {
+        n = UsbReadPayload(t->usb, p);
+        if (n < 0) {
+            D("remote usb: terminated (data)");
+            return -1;
+        }
+        if (static_cast<uint32_t>(n) != p->msg.data_length) {
+            D("remote usb: read payload failed (need %u bytes, give %d bytes), skip it",
+              p->msg.data_length, n);
+            goto err_msg;
+        }
+    }
+    if (check_data(p)) {
+        D("remote usb: check_data failed, skip it");
+        goto err_msg;
+    }
+    return 0;
+
+err_msg:
+    p->msg.command = 0;
+    if (t->GetConnectionState() == kCsOffline) {
+        // If the data toggle of ep_out on device and ep_in on host are not the same, we may receive
+        // an error message. In this case, resend one A_CNXN message to connect the device.
+        if (t->SetSendConnectOnError()) {
+            SendConnectOnHost(t);
+        }
+    }
+    return 0;
+}
+
+#else
+
+// On Android devices, we rely on the kernel to provide buffered read.
+// So we can recover automatically from EOVERFLOW.
 static int remote_read(apacket *p, atransport *t)
 {
-    if(usb_read(t->usb, &p->msg, sizeof(amessage))){
+    if (usb_read(t->usb, &p->msg, sizeof(amessage))) {
         D("remote usb: read terminated (message)");
         return -1;
     }
@@ -38,7 +144,7 @@
     }
 
     if(p->msg.data_length) {
-        if(usb_read(t->usb, p->data, p->msg.data_length)){
+        if (usb_read(t->usb, p->data, p->msg.data_length)) {
             D("remote usb: terminated (data)");
             return -1;
         }
@@ -51,17 +157,18 @@
 
     return 0;
 }
+#endif
 
 static int remote_write(apacket *p, atransport *t)
 {
     unsigned size = p->msg.data_length;
 
-    if(usb_write(t->usb, &p->msg, sizeof(amessage))) {
+    if (usb_write(t->usb, &p->msg, sizeof(amessage))) {
         D("remote usb: 1 - write terminated");
         return -1;
     }
     if(p->msg.data_length == 0) return 0;
-    if(usb_write(t->usb, &p->data, size)) {
+    if (usb_write(t->usb, &p->data, size)) {
         D("remote usb: 2 - write terminated");
         return -1;
     }
@@ -75,20 +182,17 @@
     t->usb = 0;
 }
 
-static void remote_kick(atransport *t)
-{
+static void remote_kick(atransport* t) {
     usb_kick(t->usb);
 }
 
-void init_usb_transport(atransport *t, usb_handle *h, ConnectionState state)
-{
+void init_usb_transport(atransport* t, usb_handle* h) {
     D("transport: usb");
     t->close = remote_close;
     t->SetKickFunction(remote_kick);
+    t->SetWriteFunction(remote_write);
     t->read_from_remote = remote_read;
-    t->write_to_remote = remote_write;
     t->sync_token = 1;
-    t->connection_state = state;
     t->type = kTransportUsb;
     t->usb = h;
 }
diff --git a/base/Android.bp b/base/Android.bp
index 7b1dc8e..81b96db 100644
--- a/base/Android.bp
+++ b/base/Android.bp
@@ -20,8 +20,25 @@
     "-Werror",
 ]
 
+cc_library_headers {
+    name: "libbase_headers",
+    vendor_available: true,
+    host_supported: true,
+    export_include_dirs: ["include"],
+
+    target: {
+        linux_bionic: {
+            enabled: true,
+        },
+        windows: {
+            enabled: true,
+        },
+    },
+}
+
 cc_library {
     name: "libbase",
+    vendor_available: true,
     clang: true,
     host_supported: true,
     srcs: [
@@ -33,33 +50,50 @@
         "strings.cpp",
         "test_utils.cpp",
     ],
-    local_include_dirs: ["include"],
+
+    header_libs: [
+        "libbase_headers",
+        "libutils_headers",
+    ],
+    export_header_lib_headers: ["libbase_headers"],
+
     cppflags: libbase_cppflags,
-    export_include_dirs: ["include"],
     shared_libs: ["liblog"],
     target: {
         android: {
             srcs: [
                 "errors_unix.cpp",
                 "properties.cpp",
+                "chrono_utils.cpp",
             ],
             cppflags: ["-Wexit-time-destructors"],
             sanitize: {
                 misc_undefined: ["integer"],
             },
+
         },
         darwin: {
-            srcs: ["errors_unix.cpp"],
+            srcs: [
+                "chrono_utils.cpp",
+                "errors_unix.cpp",
+            ],
             cppflags: ["-Wexit-time-destructors"],
         },
         linux_bionic: {
-            srcs: ["errors_unix.cpp"],
+            srcs: [
+                "chrono_utils.cpp",
+                "errors_unix.cpp",
+            ],
             cppflags: ["-Wexit-time-destructors"],
             enabled: true,
         },
         linux: {
-            srcs: ["errors_unix.cpp"],
+            srcs: [
+                "chrono_utils.cpp",
+                "errors_unix.cpp",
+            ],
             cppflags: ["-Wexit-time-destructors"],
+            host_ldlibs: ["-lrt"],
         },
         windows: {
             srcs: [
@@ -86,17 +120,25 @@
         "parseint_test.cpp",
         "parsenetaddress_test.cpp",
         "quick_exit_test.cpp",
+        "scopeguard_test.cpp",
         "stringprintf_test.cpp",
         "strings_test.cpp",
         "test_main.cpp",
     ],
     target: {
         android: {
-            srcs: ["properties_test.cpp"],
+            srcs: [
+                "chrono_utils_test.cpp",
+                "properties_test.cpp"
+            ],
             sanitize: {
                 misc_undefined: ["integer"],
             },
         },
+        linux: {
+            srcs: ["chrono_utils_test.cpp"],
+            host_ldlibs: ["-lrt"],
+        },
         windows: {
             srcs: ["utf8_test.cpp"],
             enabled: true,
diff --git a/base/chrono_utils.cpp b/base/chrono_utils.cpp
new file mode 100644
index 0000000..5eedf3b
--- /dev/null
+++ b/base/chrono_utils.cpp
@@ -0,0 +1,37 @@
+/*
+ * 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/chrono_utils.h"
+
+#include <time.h>
+
+namespace android {
+namespace base {
+
+boot_clock::time_point boot_clock::now() {
+#ifdef __ANDROID__
+  timespec ts;
+  clock_gettime(CLOCK_BOOTTIME, &ts);
+  return boot_clock::time_point(std::chrono::seconds(ts.tv_sec) +
+                                std::chrono::nanoseconds(ts.tv_nsec));
+#else
+  // Darwin does not support clock_gettime.
+  return boot_clock::time_point();
+#endif  // __ANDROID__
+}
+
+}  // namespace base
+}  // namespace android
diff --git a/base/chrono_utils_test.cpp b/base/chrono_utils_test.cpp
new file mode 100644
index 0000000..057132d
--- /dev/null
+++ b/base/chrono_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/chrono_utils.h"
+
+#include <time.h>
+
+#include <chrono>
+
+#include <gtest/gtest.h>
+
+namespace android {
+namespace base {
+
+std::chrono::seconds GetBootTimeSeconds() {
+  struct timespec now;
+  clock_gettime(CLOCK_BOOTTIME, &now);
+
+  auto now_tp = boot_clock::time_point(std::chrono::seconds(now.tv_sec) +
+                                       std::chrono::nanoseconds(now.tv_nsec));
+  return std::chrono::duration_cast<std::chrono::seconds>(now_tp.time_since_epoch());
+}
+
+// Tests (at least) the seconds accuracy of the boot_clock::now() method.
+TEST(ChronoUtilsTest, BootClockNowSeconds) {
+  auto now = GetBootTimeSeconds();
+  auto boot_seconds =
+      std::chrono::duration_cast<std::chrono::seconds>(boot_clock::now().time_since_epoch());
+  EXPECT_EQ(now, boot_seconds);
+}
+
+}  // namespace base
+}  // namespace android
\ No newline at end of file
diff --git a/base/file.cpp b/base/file.cpp
index 378a405..7fbebc5 100644
--- a/base/file.cpp
+++ b/base/file.cpp
@@ -28,8 +28,9 @@
 #include <string>
 #include <vector>
 
-#include "android-base/macros.h"  // For TEMP_FAILURE_RETRY on Darwin.
 #include "android-base/logging.h"
+#include "android-base/macros.h"  // For TEMP_FAILURE_RETRY on Darwin.
+#include "android-base/unique_fd.h"
 #include "android-base/utf8.h"
 #include "utils/Compat.h"
 
@@ -49,6 +50,14 @@
 bool ReadFdToString(int fd, std::string* content) {
   content->clear();
 
+  // Although original we had small files in mind, this code gets used for
+  // very large files too, where the std::string growth heuristics might not
+  // be suitable. https://code.google.com/p/android/issues/detail?id=258500.
+  struct stat sb;
+  if (fstat(fd, &sb) != -1 && sb.st_size > 0) {
+    content->reserve(sb.st_size);
+  }
+
   char buf[BUFSIZ];
   ssize_t n;
   while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], sizeof(buf)))) > 0) {
@@ -61,13 +70,11 @@
   content->clear();
 
   int flags = O_RDONLY | O_CLOEXEC | O_BINARY | (follow_symlinks ? 0 : O_NOFOLLOW);
-  int fd = TEMP_FAILURE_RETRY(open(path.c_str(), flags));
+  android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags)));
   if (fd == -1) {
     return false;
   }
-  bool result = ReadFdToString(fd, content);
-  close(fd);
-  return result;
+  return ReadFdToString(fd, content);
 }
 
 bool WriteStringToFd(const std::string& content, int fd) {
@@ -98,7 +105,7 @@
                        bool follow_symlinks) {
   int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY |
               (follow_symlinks ? 0 : O_NOFOLLOW);
-  int fd = TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode));
+  android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode)));
   if (fd == -1) {
     PLOG(ERROR) << "android::WriteStringToFile open failed";
     return false;
@@ -118,7 +125,6 @@
     PLOG(ERROR) << "android::WriteStringToFile write failed";
     return CleanUpAfterFailedWrite(path);
   }
-  close(fd);
   return true;
 }
 #endif
@@ -127,14 +133,11 @@
                        bool follow_symlinks) {
   int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY |
               (follow_symlinks ? 0 : O_NOFOLLOW);
-  int fd = TEMP_FAILURE_RETRY(open(path.c_str(), flags, DEFFILEMODE));
+  android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags, DEFFILEMODE)));
   if (fd == -1) {
     return false;
   }
-
-  bool result = WriteStringToFd(content, fd);
-  close(fd);
-  return result || CleanUpAfterFailedWrite(path);
+  return WriteStringToFd(content, fd) || CleanUpAfterFailedWrite(path);
 }
 
 bool ReadFully(int fd, void* data, size_t byte_count) {
diff --git a/base/file_test.cpp b/base/file_test.cpp
index 266131e..02b431d 100644
--- a/base/file_test.cpp
+++ b/base/file_test.cpp
@@ -214,3 +214,46 @@
   EXPECT_EQ(".", android::base::Dirname("sh"));
   EXPECT_EQ("/system/bin", android::base::Dirname("/system/bin/sh/"));
 }
+
+TEST(file, ReadFileToString_capacity) {
+  TemporaryFile tf;
+  ASSERT_TRUE(tf.fd != -1);
+
+  // For a huge file, the overhead should still be small.
+  std::string s;
+  size_t size = 16 * 1024 * 1024;
+  ASSERT_TRUE(android::base::WriteStringToFile(std::string(size, 'x'), tf.path));
+  ASSERT_TRUE(android::base::ReadFileToString(tf.path, &s));
+  EXPECT_EQ(size, s.size());
+  EXPECT_LT(s.capacity(), size + 16);
+
+  // Even for weird badly-aligned sizes.
+  size += 12345;
+  ASSERT_TRUE(android::base::WriteStringToFile(std::string(size, 'x'), tf.path));
+  ASSERT_TRUE(android::base::ReadFileToString(tf.path, &s));
+  EXPECT_EQ(size, s.size());
+  EXPECT_LT(s.capacity(), size + 16);
+
+  // We'll shrink an enormous string if you read a small file into it.
+  size = 64;
+  ASSERT_TRUE(android::base::WriteStringToFile(std::string(size, 'x'), tf.path));
+  ASSERT_TRUE(android::base::ReadFileToString(tf.path, &s));
+  EXPECT_EQ(size, s.size());
+  EXPECT_LT(s.capacity(), size + 16);
+}
+
+TEST(file, ReadFileToString_capacity_0) {
+  TemporaryFile tf;
+  ASSERT_TRUE(tf.fd != -1);
+
+  // Because /proc reports its files as zero-length, we don't actually trust
+  // any file that claims to be zero-length. Rather than add increasingly
+  // complex heuristics for shrinking the passed-in string in that case, we
+  // currently leave it alone.
+  std::string s;
+  size_t initial_capacity = s.capacity();
+  ASSERT_TRUE(android::base::WriteStringToFile("", tf.path));
+  ASSERT_TRUE(android::base::ReadFileToString(tf.path, &s));
+  EXPECT_EQ(0U, s.size());
+  EXPECT_EQ(initial_capacity, s.capacity());
+}
diff --git a/base/include/android-base/chrono_utils.h b/base/include/android-base/chrono_utils.h
new file mode 100644
index 0000000..0086425
--- /dev/null
+++ b/base/include/android-base/chrono_utils.h
@@ -0,0 +1,37 @@
+/*
+ * 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 ANDROID_BASE_CHRONO_UTILS_H
+#define ANDROID_BASE_CHRONO_UTILS_H
+
+#include <chrono>
+
+namespace android {
+namespace base {
+
+// A std::chrono clock based on CLOCK_BOOTTIME.
+class boot_clock {
+ public:
+  typedef std::chrono::nanoseconds duration;
+  typedef std::chrono::time_point<boot_clock, duration> time_point;
+
+  static time_point now();
+};
+
+}  // namespace base
+}  // namespace android
+
+#endif  // ANDROID_BASE_CHRONO_UTILS_H
diff --git a/base/include/android-base/properties.h b/base/include/android-base/properties.h
index 4de5e57..041586c 100644
--- a/base/include/android-base/properties.h
+++ b/base/include/android-base/properties.h
@@ -62,15 +62,14 @@
 // Waits for the system property `key` to have the value `expected_value`.
 // Times out after `relative_timeout`.
 // Returns true on success, false on timeout.
-bool WaitForProperty(const std::string& key,
-                     const std::string& expected_value,
-                     std::chrono::milliseconds relative_timeout);
+bool WaitForProperty(const std::string& key, const std::string& expected_value,
+                     std::chrono::milliseconds relative_timeout = std::chrono::milliseconds::max());
 
 // Waits for the system property `key` to be created.
 // Times out after `relative_timeout`.
 // Returns true on success, false on timeout.
-bool WaitForPropertyCreation(const std::string& key,
-                             std::chrono::milliseconds relative_timeout);
+bool WaitForPropertyCreation(const std::string& key, std::chrono::milliseconds relative_timeout =
+                                                         std::chrono::milliseconds::max());
 
 } // namespace base
 } // namespace android
diff --git a/base/include/android-base/scopeguard.h b/base/include/android-base/scopeguard.h
new file mode 100644
index 0000000..abcf4bc
--- /dev/null
+++ b/base/include/android-base/scopeguard.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 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.
+ */
+
+#ifndef ANDROID_BASE_SCOPEGUARD_H
+#define ANDROID_BASE_SCOPEGUARD_H
+
+#include <utility>  // for std::move
+
+namespace android {
+namespace base {
+
+template <typename F>
+class ScopeGuard {
+ public:
+  ScopeGuard(F f) : f_(f), active_(true) {}
+
+  ScopeGuard(ScopeGuard&& that) : f_(std::move(that.f_)), active_(that.active_) {
+    that.active_ = false;
+  }
+
+  ~ScopeGuard() {
+    if (active_) f_();
+  }
+
+  ScopeGuard() = delete;
+  ScopeGuard(const ScopeGuard&) = delete;
+  void operator=(const ScopeGuard&) = delete;
+  void operator=(ScopeGuard&& that) = delete;
+
+  void Disable() { active_ = false; }
+
+  bool active() const { return active_; }
+
+ private:
+  F f_;
+  bool active_;
+};
+
+template <typename T>
+ScopeGuard<T> make_scope_guard(T f) {
+  return ScopeGuard<T>(f);
+}
+
+}  // namespace base
+}  // namespace android
+
+#endif  // ANDROID_BASE_SCOPEGUARD_H
diff --git a/base/properties.cpp b/base/properties.cpp
index 32c0128..816bca0 100644
--- a/base/properties.cpp
+++ b/base/properties.cpp
@@ -101,22 +101,24 @@
 }
 
 // TODO: chrono_utils?
-static void DurationToTimeSpec(timespec& ts, std::chrono::nanoseconds d) {
+static void DurationToTimeSpec(timespec& ts, const std::chrono::milliseconds d) {
   auto s = std::chrono::duration_cast<std::chrono::seconds>(d);
   auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(d - s);
   ts.tv_sec = s.count();
   ts.tv_nsec = ns.count();
 }
 
+// TODO: boot_clock?
 using AbsTime = std::chrono::time_point<std::chrono::steady_clock>;
 
-static void UpdateTimeSpec(timespec& ts,
-                           const AbsTime& timeout) {
+static void UpdateTimeSpec(timespec& ts, std::chrono::milliseconds relative_timeout,
+                           const AbsTime& start_time) {
   auto now = std::chrono::steady_clock::now();
-  auto remaining_timeout = std::chrono::duration_cast<std::chrono::nanoseconds>(timeout - now);
-  if (remaining_timeout < 0ns) {
+  auto time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - start_time);
+  if (time_elapsed >= relative_timeout) {
     ts = { 0, 0 };
   } else {
+    auto remaining_timeout = relative_timeout - time_elapsed;
     DurationToTimeSpec(ts, remaining_timeout);
   }
 }
@@ -127,11 +129,7 @@
 // Returns nullptr on timeout.
 static const prop_info* WaitForPropertyCreation(const std::string& key,
                                                 const std::chrono::milliseconds& relative_timeout,
-                                                AbsTime& absolute_timeout) {
-  // TODO: boot_clock?
-  auto now = std::chrono::steady_clock::now();
-  absolute_timeout = now + relative_timeout;
-
+                                                const AbsTime& start_time) {
   // Find the property's prop_info*.
   const prop_info* pi;
   unsigned global_serial = 0;
@@ -139,17 +137,16 @@
     // The property doesn't even exist yet.
     // Wait for a global change and then look again.
     timespec ts;
-    UpdateTimeSpec(ts, absolute_timeout);
+    UpdateTimeSpec(ts, relative_timeout, start_time);
     if (!__system_property_wait(nullptr, global_serial, &global_serial, &ts)) return nullptr;
   }
   return pi;
 }
 
-bool WaitForProperty(const std::string& key,
-                     const std::string& expected_value,
+bool WaitForProperty(const std::string& key, const std::string& expected_value,
                      std::chrono::milliseconds relative_timeout) {
-  AbsTime absolute_timeout;
-  const prop_info* pi = WaitForPropertyCreation(key, relative_timeout, absolute_timeout);
+  auto start_time = std::chrono::steady_clock::now();
+  const prop_info* pi = WaitForPropertyCreation(key, relative_timeout, start_time);
   if (pi == nullptr) return false;
 
   WaitForPropertyData data;
@@ -162,7 +159,7 @@
     if (data.done) return true;
 
     // It didn't, so wait for the property to change before checking again.
-    UpdateTimeSpec(ts, absolute_timeout);
+    UpdateTimeSpec(ts, relative_timeout, start_time);
     uint32_t unused;
     if (!__system_property_wait(pi, data.last_read_serial, &unused, &ts)) return false;
   }
@@ -170,8 +167,8 @@
 
 bool WaitForPropertyCreation(const std::string& key,
                              std::chrono::milliseconds relative_timeout) {
-  AbsTime absolute_timeout;
-  return (WaitForPropertyCreation(key, relative_timeout, absolute_timeout) != nullptr);
+  auto start_time = std::chrono::steady_clock::now();
+  return (WaitForPropertyCreation(key, relative_timeout, start_time) != nullptr);
 }
 
 }  // namespace base
diff --git a/base/properties_test.cpp b/base/properties_test.cpp
index 1bbe482..de5f3dc 100644
--- a/base/properties_test.cpp
+++ b/base/properties_test.cpp
@@ -151,6 +151,38 @@
   ASSERT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0), 600ms);
 }
 
+TEST(properties, WaitForProperty_MaxTimeout) {
+  std::atomic<bool> flag{false};
+  std::thread thread([&]() {
+    android::base::SetProperty("debug.libbase.WaitForProperty_test", "a");
+    while (!flag) std::this_thread::yield();
+    std::this_thread::sleep_for(500ms);
+    android::base::SetProperty("debug.libbase.WaitForProperty_test", "b");
+  });
+
+  ASSERT_TRUE(android::base::WaitForProperty("debug.libbase.WaitForProperty_test", "a", 1s));
+  flag = true;
+  // Test that this does not immediately return false due to overflow issues with the timeout.
+  ASSERT_TRUE(android::base::WaitForProperty("debug.libbase.WaitForProperty_test", "b"));
+  thread.join();
+}
+
+TEST(properties, WaitForProperty_NegativeTimeout) {
+  std::atomic<bool> flag{false};
+  std::thread thread([&]() {
+    android::base::SetProperty("debug.libbase.WaitForProperty_test", "a");
+    while (!flag) std::this_thread::yield();
+    std::this_thread::sleep_for(500ms);
+    android::base::SetProperty("debug.libbase.WaitForProperty_test", "b");
+  });
+
+  ASSERT_TRUE(android::base::WaitForProperty("debug.libbase.WaitForProperty_test", "a", 1s));
+  flag = true;
+  // Assert that this immediately returns with a negative timeout
+  ASSERT_FALSE(android::base::WaitForProperty("debug.libbase.WaitForProperty_test", "b", -100ms));
+  thread.join();
+}
+
 TEST(properties, WaitForPropertyCreation) {
   std::thread thread([&]() {
     std::this_thread::sleep_for(100ms);
diff --git a/base/scopeguard_test.cpp b/base/scopeguard_test.cpp
new file mode 100644
index 0000000..e11154a
--- /dev/null
+++ b/base/scopeguard_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/scopeguard.h"
+
+#include <utility>
+
+#include <gtest/gtest.h>
+
+TEST(scopeguard, normal) {
+  bool guarded_var = true;
+  {
+    auto scopeguard = android::base::make_scope_guard([&guarded_var] { guarded_var = false; });
+  }
+  ASSERT_FALSE(guarded_var);
+}
+
+TEST(scopeguard, disabled) {
+  bool guarded_var = true;
+  {
+    auto scopeguard = android::base::make_scope_guard([&guarded_var] { guarded_var = false; });
+    scopeguard.Disable();
+  }
+  ASSERT_TRUE(guarded_var);
+}
+
+TEST(scopeguard, moved) {
+  int guarded_var = true;
+  auto scopeguard = android::base::make_scope_guard([&guarded_var] { guarded_var = false; });
+  { decltype(scopeguard) new_guard(std::move(scopeguard)); }
+  EXPECT_FALSE(scopeguard.active());
+  ASSERT_FALSE(guarded_var);
+}
diff --git a/base/utf8.cpp b/base/utf8.cpp
old mode 100755
new mode 100644
diff --git a/base/utf8_test.cpp b/base/utf8_test.cpp
old mode 100755
new mode 100644
diff --git a/bootstat/Android.bp b/bootstat/Android.bp
index f744ad1..bc90a6e 100644
--- a/bootstat/Android.bp
+++ b/bootstat/Android.bp
@@ -16,7 +16,6 @@
 
 bootstat_lib_src_files = [
     "boot_event_record_store.cpp",
-    "uptime_parser.cpp",
 ]
 
 cc_defaults {
@@ -75,6 +74,7 @@
 // -----------------------------------------------------------------------------
 cc_test {
     name: "bootstat_tests",
+    test_suites: ["device-tests"],
     defaults: ["bootstat_defaults"],
     host_supported: true,
     static_libs: [
diff --git a/bootstat/AndroidTest.xml b/bootstat/AndroidTest.xml
new file mode 100644
index 0000000..f3783fa
--- /dev/null
+++ b/bootstat/AndroidTest.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 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.
+-->
+<configuration description="Config for bootstat_tests">
+    <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
+        <option name="cleanup" value="true" />
+        <option name="push" value="bootstat_tests->/data/local/tmp/bootstat_tests" />
+    </target_preparer>
+    <option name="test-suite-tag" value="apct" />
+    <test class="com.android.tradefed.testtype.GTest" >
+        <option name="native-test-device-path" value="/data/local/tmp" />
+        <option name="module-name" value="bootstat_tests" />
+    </test>
+</configuration>
\ No newline at end of file
diff --git a/bootstat/boot_event_record_store.cpp b/bootstat/boot_event_record_store.cpp
index 2648594..99d9405 100644
--- a/bootstat/boot_event_record_store.cpp
+++ b/bootstat/boot_event_record_store.cpp
@@ -20,13 +20,16 @@
 #include <fcntl.h>
 #include <sys/stat.h>
 #include <utime.h>
+
+#include <chrono>
 #include <cstdlib>
 #include <string>
 #include <utility>
+
+#include <android-base/chrono_utils.h>
 #include <android-base/file.h>
 #include <android-base/logging.h>
 #include <android-base/parseint.h>
-#include "uptime_parser.h"
 
 namespace {
 
@@ -55,7 +58,9 @@
 }
 
 void BootEventRecordStore::AddBootEvent(const std::string& event) {
-  AddBootEventWithValue(event, bootstat::ParseUptime());
+    auto uptime = std::chrono::duration_cast<std::chrono::seconds>(
+        android::base::boot_clock::now().time_since_epoch());
+    AddBootEventWithValue(event, uptime.count());
 }
 
 // The implementation of AddBootEventValue makes use of the mtime file
diff --git a/bootstat/boot_event_record_store_test.cpp b/bootstat/boot_event_record_store_test.cpp
index 90f6513..d98169b 100644
--- a/bootstat/boot_event_record_store_test.cpp
+++ b/bootstat/boot_event_record_store_test.cpp
@@ -21,15 +21,18 @@
 #include <sys/stat.h>
 #include <sys/time.h>
 #include <unistd.h>
+
+#include <chrono>
 #include <cstdint>
 #include <cstdlib>
+
+#include <android-base/chrono_utils.h>
 #include <android-base/file.h>
 #include <android-base/logging.h>
 #include <android-base/test_utils.h>
 #include <android-base/unique_fd.h>
-#include <gtest/gtest.h>
 #include <gmock/gmock.h>
-#include "uptime_parser.h"
+#include <gtest/gtest.h>
 
 using testing::UnorderedElementsAreArray;
 
@@ -89,6 +92,13 @@
   rmdir(path.c_str());
 }
 
+// Returns the time in seconds since boot.
+time_t GetUptimeSeconds() {
+    return std::chrono::duration_cast<std::chrono::seconds>(
+               android::base::boot_clock::now().time_since_epoch())
+        .count();
+}
+
 class BootEventRecordStoreTest : public ::testing::Test {
  public:
   BootEventRecordStoreTest() {
@@ -126,7 +136,7 @@
   BootEventRecordStore store;
   store.SetStorePath(GetStorePathForTesting());
 
-  time_t uptime = bootstat::ParseUptime();
+  time_t uptime = GetUptimeSeconds();
   ASSERT_NE(-1, uptime);
 
   store.AddBootEvent("cenozoic");
@@ -141,7 +151,7 @@
   BootEventRecordStore store;
   store.SetStorePath(GetStorePathForTesting());
 
-  time_t uptime = bootstat::ParseUptime();
+  time_t uptime = GetUptimeSeconds();
   ASSERT_NE(-1, uptime);
 
   store.AddBootEvent("cretaceous");
diff --git a/bootstat/bootstat.cpp b/bootstat/bootstat.cpp
index a4cc5f2..6f25d96 100644
--- a/bootstat/bootstat.cpp
+++ b/bootstat/bootstat.cpp
@@ -21,6 +21,7 @@
 #include <getopt.h>
 #include <unistd.h>
 
+#include <chrono>
 #include <cmath>
 #include <cstddef>
 #include <cstdio>
@@ -30,15 +31,15 @@
 #include <string>
 #include <vector>
 
-#include <android/log.h>
+#include <android-base/chrono_utils.h>
 #include <android-base/logging.h>
 #include <android-base/parseint.h>
 #include <android-base/strings.h>
+#include <android/log.h>
 #include <cutils/properties.h>
 #include <metricslogger/metrics_logger.h>
 
 #include "boot_event_record_store.h"
-#include "uptime_parser.h"
 
 namespace {
 
@@ -255,7 +256,8 @@
   BootEventRecordStore boot_event_store;
   BootEventRecordStore::BootEventRecord record;
 
-  time_t uptime = bootstat::ParseUptime();
+  auto uptime = std::chrono::duration_cast<std::chrono::seconds>(
+      android::base::boot_clock::now().time_since_epoch());
   time_t current_time_utc = time(nullptr);
 
   if (boot_event_store.GetBootEvent("last_boot_time_utc", &record)) {
@@ -282,22 +284,21 @@
     // Log the amount of time elapsed until the device is decrypted, which
     // includes the variable amount of time the user takes to enter the
     // decryption password.
-    boot_event_store.AddBootEventWithValue("boot_decryption_complete", uptime);
+    boot_event_store.AddBootEventWithValue("boot_decryption_complete", uptime.count());
 
     // Subtract the decryption time to normalize the boot cycle timing.
-    time_t boot_complete = uptime - record.second;
+    std::chrono::seconds boot_complete = std::chrono::seconds(uptime.count() - record.second);
     boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_post_decrypt",
-                                           boot_complete);
-
+                                           boot_complete.count());
 
   } else {
-    boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_no_encryption",
-                                           uptime);
+      boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_no_encryption",
+                                             uptime.count());
   }
 
   // Record the total time from device startup to boot complete, regardless of
   // encryption state.
-  boot_event_store.AddBootEventWithValue(boot_complete_prefix, uptime);
+  boot_event_store.AddBootEventWithValue(boot_complete_prefix, uptime.count());
 
   RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init");
   RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.selinux");
diff --git a/bootstat/uptime_parser.cpp b/bootstat/uptime_parser.cpp
deleted file mode 100644
index 7c2034c..0000000
--- a/bootstat/uptime_parser.cpp
+++ /dev/null
@@ -1,38 +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.
- */
-
-#include "uptime_parser.h"
-
-#include <time.h>
-#include <cstdlib>
-#include <string>
-#include <android-base/file.h>
-#include <android-base/logging.h>
-
-namespace bootstat {
-
-time_t ParseUptime() {
-  std::string uptime_str;
-  if (!android::base::ReadFileToString("/proc/uptime", &uptime_str)) {
-    PLOG(ERROR) << "Failed to read /proc/uptime";
-    return -1;
-  }
-
-  // Cast intentionally rounds down.
-  return static_cast<time_t>(strtod(uptime_str.c_str(), NULL));
-}
-
-}  // namespace bootstat
\ No newline at end of file
diff --git a/cpio/mkbootfs.c b/cpio/mkbootfs.c
index b89c395..e52762e 100644
--- a/cpio/mkbootfs.c
+++ b/cpio/mkbootfs.c
@@ -301,6 +301,7 @@
             allocated *= 2;
             canned_config = (struct fs_config_entry*)realloc(
                 canned_config, allocated * sizeof(struct fs_config_entry));
+            if (canned_config == NULL) die("failed to reallocate memory");
         }
 
         struct fs_config_entry* cc = canned_config + used;
@@ -320,6 +321,7 @@
         ++allocated;
         canned_config = (struct fs_config_entry*)realloc(
             canned_config, allocated * sizeof(struct fs_config_entry));
+        if (canned_config == NULL) die("failed to reallocate memory");
     }
     canned_config[used].name = NULL;
 
diff --git a/debuggerd/Android.bp b/debuggerd/Android.bp
index 2d6c7f5..4783d6e 100644
--- a/debuggerd/Android.bp
+++ b/debuggerd/Android.bp
@@ -161,7 +161,9 @@
     target: {
         android: {
             srcs: [
+                "client/debuggerd_client_test.cpp",
                 "debuggerd_test.cpp",
+                "tombstoned_client.cpp",
                 "util.cpp"
             ],
         },
@@ -171,10 +173,12 @@
         "libbacktrace",
         "libbase",
         "libcutils",
+        "libdebuggerd_client",
     ],
 
     static_libs: [
-        "libdebuggerd"
+        "libdebuggerd",
+        "libc_logging",
     ],
 
     local_include_dirs: [
diff --git a/debuggerd/client/debuggerd_client.cpp b/debuggerd/client/debuggerd_client.cpp
index f2975d1..2be13c6 100644
--- a/debuggerd/client/debuggerd_client.cpp
+++ b/debuggerd/client/debuggerd_client.cpp
@@ -19,12 +19,14 @@
 #include <fcntl.h>
 #include <signal.h>
 #include <stdlib.h>
+#include <sys/poll.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
 
 #include <chrono>
 
+#include <android-base/file.h>
 #include <android-base/logging.h>
 #include <android-base/stringprintf.h>
 #include <android-base/unique_fd.h>
@@ -33,6 +35,8 @@
 #include <debuggerd/protocol.h>
 #include <debuggerd/util.h>
 
+using namespace std::chrono_literals;
+
 using android::base::unique_fd;
 
 static bool send_signal(pid_t pid, bool backtrace) {
@@ -45,37 +49,44 @@
   return true;
 }
 
+template <typename Duration>
+static void populate_timeval(struct timeval* tv, const Duration& duration) {
+  auto seconds = std::chrono::duration_cast<std::chrono::seconds>(duration);
+  auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(duration - seconds);
+  tv->tv_sec = static_cast<long>(seconds.count());
+  tv->tv_usec = static_cast<long>(microseconds.count());
+}
+
 bool debuggerd_trigger_dump(pid_t pid, unique_fd output_fd, DebuggerdDumpType dump_type,
-                            int timeout_ms) {
+                            unsigned int timeout_ms) {
   LOG(INFO) << "libdebuggerd_client: started dumping process " << pid;
   unique_fd sockfd;
   const auto end = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms);
-  auto set_timeout = [timeout_ms, &sockfd, &end]() {
+  auto time_left = [&end]() { return end - std::chrono::steady_clock::now(); };
+  auto set_timeout = [timeout_ms, &time_left](int sockfd) {
     if (timeout_ms <= 0) {
-      return true;
+      return sockfd;
     }
 
-    auto now = std::chrono::steady_clock::now();
-    if (now > end) {
-      return false;
+    auto remaining = time_left();
+    if (remaining < decltype(remaining)::zero()) {
+      LOG(ERROR) << "libdebuggerd_client: timeout expired";
+      return -1;
     }
 
-    auto time_left = std::chrono::duration_cast<std::chrono::microseconds>(end - now);
-    auto seconds = std::chrono::duration_cast<std::chrono::seconds>(time_left);
-    auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(time_left - seconds);
-    struct timeval timeout = {
-      .tv_sec = static_cast<long>(seconds.count()),
-      .tv_usec = static_cast<long>(microseconds.count()),
-    };
+    struct timeval timeout;
+    populate_timeval(&timeout, remaining);
 
     if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) != 0) {
-      return false;
+      PLOG(ERROR) << "libdebuggerd_client: failed to set receive timeout";
+      return -1;
     }
     if (setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)) != 0) {
-      return false;
+      PLOG(ERROR) << "libdebuggerd_client: failed to set send timeout";
+      return -1;
     }
 
-    return true;
+    return sockfd;
   };
 
   sockfd.reset(socket(AF_LOCAL, SOCK_SEQPACKET, 0));
@@ -84,36 +95,56 @@
     return false;
   }
 
-  if (!set_timeout()) {
-    PLOG(ERROR) << "libdebugger_client: failed to set timeout";
-    return false;
-  }
-
-  if (socket_local_client_connect(sockfd.get(), kTombstonedInterceptSocketName,
+  if (socket_local_client_connect(set_timeout(sockfd.get()), kTombstonedInterceptSocketName,
                                   ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET) == -1) {
     PLOG(ERROR) << "libdebuggerd_client: failed to connect to tombstoned";
     return false;
   }
 
   InterceptRequest req = {.pid = pid };
-  if (!set_timeout()) {
+  if (!set_timeout(sockfd)) {
     PLOG(ERROR) << "libdebugger_client: failed to set timeout";
+    return false;
   }
 
-  if (send_fd(sockfd.get(), &req, sizeof(req), std::move(output_fd)) != sizeof(req)) {
+  // Create an intermediate pipe to pass to the other end.
+  unique_fd pipe_read, pipe_write;
+  if (!Pipe(&pipe_read, &pipe_write)) {
+    PLOG(ERROR) << "libdebuggerd_client: failed to create pipe";
+    return false;
+  }
+
+  if (send_fd(set_timeout(sockfd), &req, sizeof(req), std::move(pipe_write)) != sizeof(req)) {
     PLOG(ERROR) << "libdebuggerd_client: failed to send output fd to tombstoned";
     return false;
   }
 
-  bool backtrace = dump_type == kDebuggerdBacktrace;
-  send_signal(pid, backtrace);
-
-  if (!set_timeout()) {
-    PLOG(ERROR) << "libdebugger_client: failed to set timeout";
+  // Check to make sure we've successfully registered.
+  InterceptResponse response;
+  ssize_t rc =
+      TEMP_FAILURE_RETRY(recv(set_timeout(sockfd.get()), &response, sizeof(response), MSG_TRUNC));
+  if (rc == 0) {
+    LOG(ERROR) << "libdebuggerd_client: failed to read response from tombstoned: timeout reached?";
+    return false;
+  } else if (rc != sizeof(response)) {
+    LOG(ERROR)
+        << "libdebuggerd_client: received packet of unexpected length from tombstoned: expected "
+        << sizeof(response) << ", received " << rc;
+    return false;
   }
 
-  InterceptResponse response;
-  ssize_t rc = TEMP_FAILURE_RETRY(recv(sockfd.get(), &response, sizeof(response), MSG_TRUNC));
+  if (response.status != InterceptStatus::kRegistered) {
+    LOG(ERROR) << "libdebuggerd_client: unexpected registration response: "
+               << static_cast<int>(response.status);
+    return false;
+  }
+
+  bool backtrace = dump_type == kDebuggerdBacktrace;
+  if (!send_signal(pid, backtrace)) {
+    return false;
+  }
+
+  rc = TEMP_FAILURE_RETRY(recv(set_timeout(sockfd.get()), &response, sizeof(response), MSG_TRUNC));
   if (rc == 0) {
     LOG(ERROR) << "libdebuggerd_client: failed to read response from tombstoned: timeout reached?";
     return false;
@@ -124,9 +155,53 @@
     return false;
   }
 
-  if (response.success != 1) {
+  if (response.status != InterceptStatus::kStarted) {
     response.error_message[sizeof(response.error_message) - 1] = '\0';
     LOG(ERROR) << "libdebuggerd_client: tombstoned reported failure: " << response.error_message;
+    return false;
+  }
+
+  // Forward output from the pipe to the output fd.
+  while (true) {
+    auto remaining_ms = std::chrono::duration_cast<std::chrono::milliseconds>(time_left()).count();
+    if (timeout_ms <= 0) {
+      remaining_ms = -1;
+    } else if (remaining_ms < 0) {
+      LOG(ERROR) << "libdebuggerd_client: timeout expired";
+      return false;
+    }
+
+    struct pollfd pfd = {
+        .fd = pipe_read.get(), .events = POLLIN, .revents = 0,
+    };
+
+    rc = poll(&pfd, 1, remaining_ms);
+    if (rc == -1) {
+      if (errno == EINTR) {
+        continue;
+      } else {
+        PLOG(ERROR) << "libdebuggerd_client: error while polling";
+        return false;
+      }
+    } else if (rc == 0) {
+      LOG(ERROR) << "libdebuggerd_client: timeout expired";
+      return false;
+    }
+
+    char buf[1024];
+    rc = TEMP_FAILURE_RETRY(read(pipe_read.get(), buf, sizeof(buf)));
+    if (rc == 0) {
+      // Done.
+      break;
+    } else if (rc == -1) {
+      PLOG(ERROR) << "libdebuggerd_client: error while reading";
+      return false;
+    }
+
+    if (!android::base::WriteFully(output_fd.get(), buf, rc)) {
+      PLOG(ERROR) << "libdebuggerd_client: error while writing";
+      return false;
+    }
   }
 
   LOG(INFO) << "libdebuggerd_client: done dumping process " << pid;
diff --git a/debuggerd/client/debuggerd_client_test.cpp b/debuggerd/client/debuggerd_client_test.cpp
new file mode 100644
index 0000000..aff03e5
--- /dev/null
+++ b/debuggerd/client/debuggerd_client_test.cpp
@@ -0,0 +1,111 @@
+/*
+ * 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 <debuggerd/client.h>
+
+#include <fcntl.h>
+#include <stdio.h>
+#include <unistd.h>
+
+#include <chrono>
+#include <thread>
+#include <vector>
+
+#include <gtest/gtest.h>
+
+#include <android-base/file.h>
+#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
+#include <android-base/unique_fd.h>
+
+#include <debuggerd/util.h>
+
+using namespace std::chrono_literals;
+using android::base::unique_fd;
+
+TEST(debuggerd_client, race) {
+  static constexpr int THREAD_COUNT = 1024;
+  pid_t forkpid = fork();
+
+  ASSERT_NE(-1, forkpid);
+
+  if (forkpid == 0) {
+    // Spawn a bunch of threads, to make crash_dump take longer.
+    std::vector<std::thread> threads;
+    for (int i = 0; i < THREAD_COUNT; ++i) {
+      threads.emplace_back([]() {
+        while (true) {
+          std::this_thread::sleep_for(60s);
+        }
+      });
+    }
+
+    std::this_thread::sleep_for(60s);
+    exit(0);
+  }
+
+  unique_fd pipe_read, pipe_write;
+  ASSERT_TRUE(Pipe(&pipe_read, &pipe_write));
+
+  // 64 kB should be enough for everyone.
+  constexpr int PIPE_SIZE = 64 * 1024 * 1024;
+  ASSERT_EQ(PIPE_SIZE, fcntl(pipe_read.get(), F_SETPIPE_SZ, PIPE_SIZE));
+
+  // Wait for a bit to let the child spawn all of its threads.
+  std::this_thread::sleep_for(250ms);
+
+  ASSERT_TRUE(debuggerd_trigger_dump(forkpid, std::move(pipe_write), kDebuggerdBacktrace, 10000));
+  // Immediately kill the forked child, to make sure that the dump didn't return early.
+  ASSERT_EQ(0, kill(forkpid, SIGKILL)) << strerror(errno);
+
+  // Check the output.
+  std::string result;
+  ASSERT_TRUE(android::base::ReadFdToString(pipe_read.get(), &result));
+
+  // Look for "----- end <PID> -----"
+  int found_end = 0;
+
+  std::string expected_end = android::base::StringPrintf("----- end %d -----", forkpid);
+
+  std::vector<std::string> lines = android::base::Split(result, "\n");
+  for (const std::string& line : lines) {
+    if (line == expected_end) {
+      ++found_end;
+    }
+  }
+
+  EXPECT_EQ(1, found_end) << "\nOutput: \n" << result;
+}
+
+TEST(debuggerd_client, no_timeout) {
+  unique_fd pipe_read, pipe_write;
+  ASSERT_TRUE(Pipe(&pipe_read, &pipe_write));
+
+  pid_t forkpid = fork();
+  ASSERT_NE(-1, forkpid);
+  if (forkpid == 0) {
+    pipe_write.reset();
+    char dummy;
+    TEMP_FAILURE_RETRY(read(pipe_read.get(), &dummy, sizeof(dummy)));
+    exit(0);
+  }
+
+  pipe_read.reset();
+
+  unique_fd output_read, output_write;
+  ASSERT_TRUE(Pipe(&output_read, &output_write));
+  ASSERT_TRUE(debuggerd_trigger_dump(forkpid, std::move(output_write), kDebuggerdBacktrace, 0));
+}
diff --git a/debuggerd/debuggerd_test.cpp b/debuggerd/debuggerd_test.cpp
index 1a27f3f..568879e 100644
--- a/debuggerd/debuggerd_test.cpp
+++ b/debuggerd/debuggerd_test.cpp
@@ -36,6 +36,7 @@
 #include <cutils/sockets.h>
 #include <debuggerd/handler.h>
 #include <debuggerd/protocol.h>
+#include <debuggerd/tombstoned.h>
 #include <debuggerd/util.h>
 #include <gtest/gtest.h>
 
@@ -77,6 +78,62 @@
     }                                                                           \
   } 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)
+
+static void tombstoned_intercept(pid_t target_pid, unique_fd* intercept_fd, unique_fd* output_fd) {
+  intercept_fd->reset(socket_local_client(kTombstonedInterceptSocketName,
+                                          ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
+  if (intercept_fd->get() == -1) {
+    FAIL() << "failed to contact tombstoned: " << strerror(errno);
+  }
+
+  InterceptRequest req = {.pid = target_pid};
+
+  unique_fd output_pipe_write;
+  if (!Pipe(output_fd, &output_pipe_write)) {
+    FAIL() << "failed to create output pipe: " << strerror(errno);
+  }
+
+  std::string pipe_size_str;
+  int pipe_buffer_size;
+  if (!android::base::ReadFileToString("/proc/sys/fs/pipe-max-size", &pipe_size_str)) {
+    FAIL() << "failed to read /proc/sys/fs/pipe-max-size: " << strerror(errno);
+  }
+
+  pipe_size_str = android::base::Trim(pipe_size_str);
+
+  if (!android::base::ParseInt(pipe_size_str.c_str(), &pipe_buffer_size, 0)) {
+    FAIL() << "failed to parse pipe max size";
+  }
+
+  if (fcntl(output_fd->get(), F_SETPIPE_SZ, pipe_buffer_size) != pipe_buffer_size) {
+    FAIL() << "failed to set pipe size: " << strerror(errno);
+  }
+
+  if (send_fd(intercept_fd->get(), &req, sizeof(req), std::move(output_pipe_write)) != sizeof(req)) {
+    FAIL() << "failed to send output fd to tombstoned: " << strerror(errno);
+  }
+
+  InterceptResponse response;
+  ssize_t rc = TEMP_FAILURE_RETRY(read(intercept_fd->get(), &response, sizeof(response)));
+  if (rc == -1) {
+    FAIL() << "failed to read response from tombstoned: " << strerror(errno);
+  } else if (rc == 0) {
+    FAIL() << "failed to read response from tombstoned (EOF)";
+  } else if (rc != sizeof(response)) {
+    FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(response)
+           << ", received " << rc;
+  }
+
+  ASSERT_EQ(InterceptStatus::kRegistered, response.status);
+}
+
 class CrasherTest : public ::testing::Test {
  public:
   pid_t crasher_pid = -1;
@@ -118,38 +175,7 @@
     FAIL() << "crasher hasn't been started";
   }
 
-  intercept_fd.reset(socket_local_client(kTombstonedInterceptSocketName,
-                                         ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
-  if (intercept_fd == -1) {
-    FAIL() << "failed to contact tombstoned: " << strerror(errno);
-  }
-
-  InterceptRequest req = {.pid = crasher_pid };
-
-  unique_fd output_pipe_write;
-  if (!Pipe(output_fd, &output_pipe_write)) {
-    FAIL() << "failed to create output pipe: " << strerror(errno);
-  }
-
-  std::string pipe_size_str;
-  int pipe_buffer_size;
-  if (!android::base::ReadFileToString("/proc/sys/fs/pipe-max-size", &pipe_size_str)) {
-    FAIL() << "failed to read /proc/sys/fs/pipe-max-size: " << strerror(errno);
-  }
-
-  pipe_size_str = android::base::Trim(pipe_size_str);
-
-  if (!android::base::ParseInt(pipe_size_str.c_str(), &pipe_buffer_size, 0)) {
-    FAIL() << "failed to parse pipe max size";
-  }
-
-  if (fcntl(output_fd->get(), F_SETPIPE_SZ, pipe_buffer_size) != pipe_buffer_size) {
-    FAIL() << "failed to set pipe size: " << strerror(errno);
-  }
-
-  if (send_fd(intercept_fd.get(), &req, sizeof(req), std::move(output_pipe_write)) != sizeof(req)) {
-    FAIL() << "failed to send output fd to tombstoned: " << strerror(errno);
-  }
+  tombstoned_intercept(crasher_pid, &this->intercept_fd, output_fd);
 }
 
 void CrasherTest::FinishIntercept(int* result) {
@@ -165,7 +191,7 @@
     FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(response)
            << ", received " << rc;
   } else {
-    *result = response.success;
+    *result = response.status == InterceptStatus::kStarted ? 1 : 0;
   }
 }
 
@@ -208,12 +234,14 @@
     FAIL() << "failed to wait for crasher: " << strerror(errno);
   }
 
-  if (WIFEXITED(status)) {
-    FAIL() << "crasher failed to exec: " << strerror(WEXITSTATUS(status));
-  } else if (!WIFSIGNALED(status)) {
-    FAIL() << "crasher didn't terminate via a signal";
+  if (signo == 0) {
+    ASSERT_TRUE(WIFEXITED(status));
+    ASSERT_EQ(0, WEXITSTATUS(signo));
+  } else {
+    ASSERT_FALSE(WIFEXITED(status));
+    ASSERT_TRUE(WIFSIGNALED(status)) << "crasher didn't terminate via a signal";
+    ASSERT_EQ(signo, WTERMSIG(status));
   }
-  ASSERT_EQ(signo, WTERMSIG(status));
   crasher_pid = -1;
 }
 
@@ -318,6 +346,26 @@
   ASSERT_MATCH(result, R"(Abort message: 'abort message goes here')");
 }
 
+TEST_F(CrasherTest, abort_message_backtrace) {
+  int intercept_result;
+  unique_fd output_fd;
+  StartProcess([]() {
+    android_set_abort_message("not actually aborting");
+    raise(DEBUGGER_SIGNAL);
+    exit(0);
+  });
+  StartIntercept(&output_fd);
+  FinishCrasher();
+  AssertDeath(0);
+  FinishIntercept(&intercept_result);
+
+  ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
+
+  std::string result;
+  ConsumeFd(std::move(output_fd), &result);
+  ASSERT_NOT_MATCH(result, R"(Abort message:)");
+}
+
 TEST_F(CrasherTest, intercept_timeout) {
   int intercept_result;
   unique_fd output_fd;
@@ -461,6 +509,7 @@
       err(1, "failed to drop ambient capabilities");
     }
 
+    pthread_setname_np(pthread_self(), "thread_name");
     raise(SIGSYS);
   });
 
@@ -474,15 +523,13 @@
   FinishIntercept(&intercept_result);
   ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
   ConsumeFd(std::move(output_fd), &result);
+  ASSERT_MATCH(result, R"(name: thread_name\s+>>> .+debuggerd_test(32|64) <<<)");
   ASSERT_MATCH(result, R"(#00 pc [0-9a-f]+\s+ /system/lib)" ARCH_SUFFIX R"(/libc.so \(tgkill)");
 }
 
 TEST(crash_dump, zombie) {
   pid_t forkpid = fork();
 
-  int pipefd[2];
-  ASSERT_EQ(0, pipe2(pipefd, O_CLOEXEC));
-
   pid_t rc;
   int status;
 
@@ -508,3 +555,97 @@
     ASSERT_EQ(0, WEXITSTATUS(status));
   }
 }
+
+TEST(tombstoned, no_notify) {
+  // Do this a few times.
+  for (int i = 0; i < 3; ++i) {
+    pid_t pid = 123'456'789 + i;
+
+    unique_fd intercept_fd, output_fd;
+    tombstoned_intercept(pid, &intercept_fd, &output_fd);
+
+    {
+      unique_fd tombstoned_socket, input_fd;
+      ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd));
+      ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
+    }
+
+    pid_t read_pid;
+    ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
+    ASSERT_EQ(read_pid, pid);
+  }
+}
+
+TEST(tombstoned, stress) {
+  // Spawn threads to simultaneously do a bunch of failing dumps and a bunch of successful dumps.
+  static constexpr int kDumpCount = 100;
+
+  std::atomic<bool> start(false);
+  std::vector<std::thread> threads;
+  threads.emplace_back([&start]() {
+    while (!start) {
+      continue;
+    }
+
+    // Use a way out of range pid, to avoid stomping on an actual process.
+    pid_t pid_base = 1'000'000;
+
+    for (int dump = 0; dump < kDumpCount; ++dump) {
+      pid_t pid = pid_base + dump;
+
+      unique_fd intercept_fd, output_fd;
+      tombstoned_intercept(pid, &intercept_fd, &output_fd);
+
+      // Pretend to crash, and then immediately close the socket.
+      unique_fd sockfd(socket_local_client(kTombstonedCrashSocketName,
+                                           ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
+      if (sockfd == -1) {
+        FAIL() << "failed to connect to tombstoned: " << strerror(errno);
+      }
+      TombstonedCrashPacket packet = {};
+      packet.packet_type = CrashPacketType::kDumpRequest;
+      packet.packet.dump_request.pid = pid;
+      if (TEMP_FAILURE_RETRY(write(sockfd, &packet, sizeof(packet))) != sizeof(packet)) {
+        FAIL() << "failed to write to tombstoned: " << strerror(errno);
+      }
+
+      continue;
+    }
+  });
+
+  threads.emplace_back([&start]() {
+    while (!start) {
+      continue;
+    }
+
+    // Use a way out of range pid, to avoid stomping on an actual process.
+    pid_t pid_base = 2'000'000;
+
+    for (int dump = 0; dump < kDumpCount; ++dump) {
+      pid_t pid = pid_base + dump;
+
+      unique_fd intercept_fd, output_fd;
+      tombstoned_intercept(pid, &intercept_fd, &output_fd);
+
+      {
+        unique_fd tombstoned_socket, input_fd;
+        ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd));
+        ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
+        tombstoned_notify_completion(tombstoned_socket.get());
+      }
+
+      // TODO: Fix the race that requires this sleep.
+      std::this_thread::sleep_for(50ms);
+
+      pid_t read_pid;
+      ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
+      ASSERT_EQ(read_pid, pid);
+    }
+  });
+
+  start = true;
+
+  for (std::thread& thread : threads) {
+    thread.join();
+  }
+}
diff --git a/debuggerd/handler/debuggerd_handler.cpp b/debuggerd/handler/debuggerd_handler.cpp
index cf24d57..b70554f 100644
--- a/debuggerd/handler/debuggerd_handler.cpp
+++ b/debuggerd/handler/debuggerd_handler.cpp
@@ -120,7 +120,7 @@
   }
 
   if (signum == DEBUGGER_SIGNAL) {
-    __libc_format_log(ANDROID_LOG_FATAL, "libc", "Requested dump for tid %d (%s)", gettid(),
+    __libc_format_log(ANDROID_LOG_INFO, "libc", "Requested dump for tid %d (%s)", gettid(),
                       thread_name);
     return;
   }
@@ -389,8 +389,9 @@
 
   log_signal_summary(signal_number, info);
 
-  // Populate si_value with the abort message address, if found.
-  if (abort_message) {
+  // 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;
   }
 
diff --git a/debuggerd/include/debuggerd/client.h b/debuggerd/include/debuggerd/client.h
index 91f143b..01de57b 100644
--- a/debuggerd/include/debuggerd/client.h
+++ b/debuggerd/include/debuggerd/client.h
@@ -28,9 +28,9 @@
 };
 
 // Trigger a dump of specified process to output_fd.
-// output_fd is *not* consumed, timeouts <= 0 will wait forever.
+// output_fd is consumed, timeout of 0 will wait forever.
 bool debuggerd_trigger_dump(pid_t pid, android::base::unique_fd output_fd,
-                            enum DebuggerdDumpType dump_type, int timeout_ms);
+                            enum DebuggerdDumpType dump_type, unsigned int timeout_ms);
 
 int dump_backtrace_to_file(pid_t tid, int fd);
 int dump_backtrace_to_file_timeout(pid_t tid, int fd, int timeout_secs);
diff --git a/debuggerd/include/debuggerd/protocol.h b/debuggerd/include/debuggerd/protocol.h
index bb2ab0d..0756876 100644
--- a/debuggerd/include/debuggerd/protocol.h
+++ b/debuggerd/include/debuggerd/protocol.h
@@ -56,8 +56,14 @@
   int32_t pid;
 };
 
+enum class InterceptStatus : uint8_t {
+  kFailed,
+  kStarted,
+  kRegistered,
+};
+
 // Sent either immediately upon failure, or when the intercept has been used.
 struct InterceptResponse {
-  uint8_t success;          // 0 or 1
+  InterceptStatus status;
   char error_message[127];  // always null-terminated
 };
diff --git a/debuggerd/libdebuggerd/test/tombstone_test.cpp b/debuggerd/libdebuggerd/test/tombstone_test.cpp
index 5ee07cd..325210d 100644
--- a/debuggerd/libdebuggerd/test/tombstone_test.cpp
+++ b/debuggerd/libdebuggerd/test/tombstone_test.cpp
@@ -77,7 +77,9 @@
     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);
   }
 
@@ -292,7 +294,9 @@
   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);
@@ -348,7 +352,9 @@
   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);
@@ -404,7 +410,9 @@
   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);
@@ -458,7 +466,9 @@
   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);
 #else
@@ -503,7 +513,7 @@
   map_mock_->AddMap(map);
 
   siginfo_t si;
-  si.si_signo = 0;
+  memset(&si, 0, sizeof(si));
   ptrace_set_fake_getsiginfo(si);
   dump_all_maps(backtrace_mock_.get(), map_mock_.get(), &log_, 100);
 
@@ -539,7 +549,9 @@
     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);
@@ -592,7 +604,7 @@
 
 TEST_F(TombstoneTest, dump_signal_info_error) {
   siginfo_t si;
-  si.si_signo = 0;
+  memset(&si, 0, sizeof(si));
   ptrace_set_fake_getsiginfo(si);
 
   dump_signal_info(&log_, 123);
diff --git a/debuggerd/libdebuggerd/tombstone.cpp b/debuggerd/libdebuggerd/tombstone.cpp
index c23da44..0c38449 100644
--- a/debuggerd/libdebuggerd/tombstone.cpp
+++ b/debuggerd/libdebuggerd/tombstone.cpp
@@ -283,7 +283,7 @@
     if (BacktraceMap::IsValid(map) && !map.name.empty()) {
       line += "  " + map.name;
       uintptr_t offset = 0;
-      std::string func_name(backtrace->GetFunctionName(stack_data[i], &offset));
+      std::string func_name(backtrace->GetFunctionName(stack_data[i], &offset, &map));
       if (!func_name.empty()) {
         line += " (" + func_name;
         if (offset) {
diff --git a/debuggerd/libdebuggerd/utility.cpp b/debuggerd/libdebuggerd/utility.cpp
index 22fde5e..7f450e6 100644
--- a/debuggerd/libdebuggerd/utility.cpp
+++ b/debuggerd/libdebuggerd/utility.cpp
@@ -22,16 +22,22 @@
 #include <signal.h>
 #include <string.h>
 #include <sys/ptrace.h>
+#include <sys/uio.h>
 #include <sys/wait.h>
 #include <unistd.h>
 
 #include <string>
 
+#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 <backtrace/Backtrace.h>
 #include <log/log.h>
 
+using android::base::unique_fd;
+
 // Whitelist output desired in the logcat output.
 bool is_allowed_in_logcat(enum logtype ltype) {
   if ((ltype == HEADER)
@@ -42,6 +48,19 @@
   return false;
 }
 
+static bool should_write_to_kmsg() {
+  // Write to kmsg if tombstoned isn't up, and we're able to do so.
+  if (!android::base::GetBoolProperty("ro.debuggable", false)) {
+    return false;
+  }
+
+  if (android::base::GetProperty("init.svc.tombstoned", "") == "running") {
+    return false;
+  }
+
+  return true;
+}
+
 __attribute__((__weak__, visibility("default")))
 void _LOG(log_t* log, enum logtype ltype, const char* fmt, ...) {
   bool write_to_tombstone = (log->tfd != -1);
@@ -49,6 +68,7 @@
                       && log->crashed_tid != -1
                       && log->current_tid != -1
                       && (log->crashed_tid == log->current_tid);
+  static bool write_to_kmsg = should_write_to_kmsg();
 
   char buf[512];
   va_list ap;
@@ -70,6 +90,30 @@
     if (log->amfd_data != nullptr) {
       *log->amfd_data += buf;
     }
+
+    if (write_to_kmsg) {
+      unique_fd kmsg_fd(open("/dev/kmsg_debug", O_WRONLY | O_APPEND | O_CLOEXEC));
+      if (kmsg_fd.get() >= 0) {
+        // Our output might contain newlines which would otherwise be handled by the android logger.
+        // Split the lines up ourselves before sending to the kernel logger.
+        if (buf[len - 1] == '\n') {
+          buf[len - 1] = '\0';
+        }
+
+        std::vector<std::string> fragments = android::base::Split(buf, "\n");
+        for (const std::string& fragment : fragments) {
+          static constexpr char prefix[] = "<3>DEBUG: ";
+          struct iovec iov[3];
+          iov[0].iov_base = const_cast<char*>(prefix);
+          iov[0].iov_len = strlen(prefix);
+          iov[1].iov_base = const_cast<char*>(fragment.c_str());
+          iov[1].iov_len = fragment.length();
+          iov[2].iov_base = const_cast<char*>("\n");
+          iov[2].iov_len = 1;
+          TEMP_FAILURE_RETRY(writev(kmsg_fd.get(), iov, 3));
+        }
+      }
+    }
   }
 }
 
@@ -205,7 +249,7 @@
 }
 
 void read_with_default(const char* path, char* buf, size_t len, const char* default_value) {
-  android::base::unique_fd fd(open(path, O_RDONLY));
+  unique_fd fd(open(path, O_RDONLY | O_CLOEXEC));
   if (fd != -1) {
     int rc = TEMP_FAILURE_RETRY(read(fd.get(), buf, len - 1));
     if (rc != -1) {
diff --git a/debuggerd/tombstoned/intercept_manager.cpp b/debuggerd/tombstoned/intercept_manager.cpp
index 789260d..dff942c 100644
--- a/debuggerd/tombstoned/intercept_manager.cpp
+++ b/debuggerd/tombstoned/intercept_manager.cpp
@@ -105,6 +105,7 @@
     // We trust the other side, so only do minimal validity checking.
     if (intercept_request.pid <= 0 || intercept_request.pid > std::numeric_limits<pid_t>::max()) {
       InterceptResponse response = {};
+      response.status = InterceptStatus::kFailed;
       snprintf(response.error_message, sizeof(response.error_message), "invalid pid %" PRId32,
                intercept_request.pid);
       TEMP_FAILURE_RETRY(write(sockfd, &response, sizeof(response)));
@@ -113,9 +114,10 @@
 
     intercept->intercept_pid = intercept_request.pid;
 
-    // Register the intercept with the InterceptManager.
+    // Check if it's already registered.
     if (intercept_manager->intercepts.count(intercept_request.pid) > 0) {
       InterceptResponse response = {};
+      response.status = InterceptStatus::kFailed;
       snprintf(response.error_message, sizeof(response.error_message),
                "pid %" PRId32 " already intercepted", intercept_request.pid);
       TEMP_FAILURE_RETRY(write(sockfd, &response, sizeof(response)));
@@ -123,6 +125,15 @@
       goto fail;
     }
 
+    // Let the other side know that the intercept has been registered, now that we know we can't
+    // fail. tombstoned is single threaded, so this isn't racy.
+    InterceptResponse response = {};
+    response.status = InterceptStatus::kRegistered;
+    if (TEMP_FAILURE_RETRY(write(sockfd, &response, sizeof(response))) == -1) {
+      PLOG(WARNING) << "failed to notify interceptor of registration";
+      goto fail;
+    }
+
     intercept->output_fd = std::move(rcv_fd);
     intercept_manager->intercepts[intercept_request.pid] = std::unique_ptr<Intercept>(intercept);
     intercept->registered = true;
@@ -174,7 +185,7 @@
 
   LOG(INFO) << "found intercept fd " << intercept->output_fd.get() << " for pid " << pid;
   InterceptResponse response = {};
-  response.success = 1;
+  response.status = InterceptStatus::kStarted;
   TEMP_FAILURE_RETRY(write(intercept->sockfd, &response, sizeof(response)));
   *out_fd = std::move(intercept->output_fd);
 
diff --git a/debuggerd/tombstoned/tombstoned.cpp b/debuggerd/tombstoned/tombstoned.cpp
index 6754508..2248a21 100644
--- a/debuggerd/tombstoned/tombstoned.cpp
+++ b/debuggerd/tombstoned/tombstoned.cpp
@@ -126,9 +126,7 @@
   return result;
 }
 
-static void dequeue_request(Crash* crash) {
-  ++num_concurrent_dumps;
-
+static void perform_request(Crash* crash) {
   unique_fd output_fd;
   if (!intercept_manager->GetIntercept(crash->crash_pid, &output_fd)) {
     output_fd = get_tombstone_fd();
@@ -153,12 +151,22 @@
                  crash_completed_cb, crash);
     event_add(crash->crash_event, &timeout);
   }
+
+  ++num_concurrent_dumps;
   return;
 
 fail:
   delete crash;
 }
 
+static void dequeue_requests() {
+  while (!queued_requests.empty() && num_concurrent_dumps < kMaxConcurrentDumps) {
+    Crash* next_crash = queued_requests.front();
+    queued_requests.pop_front();
+    perform_request(next_crash);
+  }
+}
+
 static void crash_accept_cb(evconnlistener* listener, evutil_socket_t sockfd, sockaddr*, int,
                             void*) {
   event_base* base = evconnlistener_get_base(listener);
@@ -207,7 +215,7 @@
     LOG(INFO) << "enqueueing crash request for pid " << crash->crash_pid;
     queued_requests.push_back(crash);
   } else {
-    dequeue_request(crash);
+    perform_request(crash);
   }
 
   return;
@@ -247,11 +255,7 @@
   delete crash;
 
   // If there's something queued up, let them proceed.
-  if (!queued_requests.empty()) {
-    Crash* next_crash = queued_requests.front();
-    queued_requests.pop_front();
-    dequeue_request(next_crash);
-  }
+  dequeue_requests();
 }
 
 int main(int, char* []) {
diff --git a/demangle/demangle.cpp b/demangle/demangle.cpp
index be4d2dd..66e5e58 100644
--- a/demangle/demangle.cpp
+++ b/demangle/demangle.cpp
@@ -20,22 +20,25 @@
 #include <string.h>
 #include <unistd.h>
 
+#include <cctype>
 #include <string>
 
 #include <demangle.h>
 
 extern "C" char* __cxa_demangle(const char*, char*, size_t*, int*);
 
-void usage(const char* prog_name) {
-  printf("Usage: %s [-c] <NAME_TO_DEMANGLE>\n", prog_name);
-  printf("  -c\n");
-  printf("    Compare the results of __cxa_demangle against the current\n");
-  printf("    demangler.\n");
+static void Usage(const char* prog_name) {
+  printf("usage: %s [-c] [NAME_TO_DEMANGLE...]\n", prog_name);
+  printf("\n");
+  printf("Demangles C++ mangled names if supplied on the command-line, or found\n");
+  printf("reading from stdin otherwise.\n");
+  printf("\n");
+  printf("-c\tCompare against __cxa_demangle\n");
+  printf("\n");
 }
 
-std::string DemangleWithCxa(const char* name) {
+static std::string DemangleWithCxa(const char* name) {
   const char* cxa_demangle = __cxa_demangle(name, nullptr, nullptr, nullptr);
-
   if (cxa_demangle == nullptr) {
     return name;
   }
@@ -54,6 +57,49 @@
   return demangled_str;
 }
 
+static void Compare(const char* name, const std::string& demangled_name) {
+  std::string cxa_demangled_name(DemangleWithCxa(name));
+  if (cxa_demangled_name != demangled_name) {
+    printf("\nMismatch!\n");
+    printf("\tmangled name: %s\n", name);
+    printf("\tour demangle: %s\n", demangled_name.c_str());
+    printf("\tcxa demangle: %s\n", cxa_demangled_name.c_str());
+    exit(1);
+  }
+}
+
+static int Filter(bool compare) {
+  char* line = nullptr;
+  size_t line_length = 0;
+
+  while ((getline(&line, &line_length, stdin)) != -1) {
+    char* p = line;
+    char* name;
+    while ((name = strstr(p, "_Z")) != nullptr) {
+      // Output anything before the identifier.
+      *name = 0;
+      printf("%s", p);
+      *name = '_';
+
+      // Extract the identifier.
+      p = name;
+      while (*p && (std::isalnum(*p) || *p == '_' || *p == '.' || *p == '$')) ++p;
+
+      // Demangle and output.
+      std::string identifier(name, p);
+      std::string demangled_name = demangle(identifier.c_str());
+      printf("%s", demangled_name.c_str());
+
+      if (compare) Compare(identifier.c_str(), demangled_name);
+    }
+    // Output anything after the last identifier.
+    printf("%s", p);
+  }
+
+  free(line);
+  return 0;
+}
+
 int main(int argc, char** argv) {
 #ifdef __BIONIC__
   const char* prog_name = getprogname();
@@ -67,31 +113,21 @@
     if (opt_char == 'c') {
       compare = true;
     } else {
-      usage(prog_name);
+      Usage(prog_name);
       return 1;
     }
   }
-  if (optind >= argc || argc - optind != 1) {
-    printf("Must supply a single argument.\n\n");
-    usage(prog_name);
-    return 1;
-  }
-  const char* name = argv[optind];
 
-  std::string demangled_name = demangle(name);
+  // With no arguments, act as a filter.
+  if (optind == argc) return Filter(compare);
 
-  printf("%s\n", demangled_name.c_str());
+  // Otherwise demangle each argument.
+  while (optind < argc) {
+    const char* name = argv[optind++];
+    std::string demangled_name = demangle(name);
+    printf("%s\n", demangled_name.c_str());
 
-  if (compare) {
-    std::string cxa_demangle_str(DemangleWithCxa(name));
-
-    if (cxa_demangle_str != demangled_name) {
-      printf("Mismatch\n");
-      printf("cxa demangle: %s\n", cxa_demangle_str.c_str());
-      return 1;
-    } else {
-      printf("Match\n");
-    }
+    if (compare) Compare(name, demangled_name);
   }
   return 0;
 }
diff --git a/fastboot/Android.mk b/fastboot/Android.mk
index 5610cc0..2c578a9 100644
--- a/fastboot/Android.mk
+++ b/fastboot/Android.mk
@@ -51,7 +51,7 @@
 
 LOCAL_SRC_FILES_windows := usb_windows.cpp
 LOCAL_STATIC_LIBRARIES_windows := AdbWinApi
-LOCAL_REQUIRED_MODULES_windows := AdbWinApi
+LOCAL_REQUIRED_MODULES_windows := AdbWinApi AdbWinUsbApi
 LOCAL_LDLIBS_windows := -lws2_32
 LOCAL_C_INCLUDES_windows := development/host/windows/usb/api
 
diff --git a/fastboot/README.md b/fastboot/README.md
index 022d34b..ec7dcb4 100644
--- a/fastboot/README.md
+++ b/fastboot/README.md
@@ -126,6 +126,16 @@
                        space in RAM or "FAIL" if not.  The size of
                        the download is remembered.
 
+    upload             Read data from memory which was staged by the last
+                       command, e.g. an oem command.  The client will reply
+                       with "DATA%08x" if it is ready to send %08x bytes of
+                       data.  If no data was staged in the last command,
+                       the client must reply with "FAIL".  After the client
+                       successfully sends %08x bytes, the client shall send
+                       a single packet starting with "OKAY".  Clients
+                       should not support "upload" unless it supports an
+                       oem command that requires "upload" capabilities.
+
     verify:%08x        Send a digital signature to verify the downloaded
                        data.  Required if the bootloader is "secure"
                        otherwise "flash" and "boot" will be ignored.
diff --git a/fastboot/engine.cpp b/fastboot/engine.cpp
index 728dcb8..56ee816 100644
--- a/fastboot/engine.cpp
+++ b/fastboot/engine.cpp
@@ -44,6 +44,8 @@
 #define OP_NOTICE     4
 #define OP_DOWNLOAD_SPARSE 5
 #define OP_WAIT_FOR_DISCONNECT 6
+#define OP_DOWNLOAD_FD 7
+#define OP_UPLOAD 8
 
 typedef struct Action Action;
 
@@ -56,6 +58,7 @@
     char cmd[CMD_SIZE];
     const char* prod;
     void* data;
+    int fd;
 
     // The protocol only supports 32-bit sizes, so you'll have to break
     // anything larger into chunks.
@@ -142,7 +145,20 @@
     a->msg = mkmsg("erasing '%s'", ptn);
 }
 
-void fb_queue_flash(const char *ptn, void *data, unsigned sz)
+void fb_queue_flash_fd(const char *ptn, int fd, uint32_t sz)
+{
+    Action *a;
+
+    a = queue_action(OP_DOWNLOAD_FD, "");
+    a->fd = fd;
+    a->size = sz;
+    a->msg = mkmsg("sending '%s' (%d KB)", ptn, sz / 1024);
+
+    a = queue_action(OP_COMMAND, "flash:%s", ptn);
+    a->msg = mkmsg("writing '%s'", ptn);
+}
+
+void fb_queue_flash(const char *ptn, void *data, uint32_t sz)
 {
     Action *a;
 
@@ -155,7 +171,7 @@
     a->msg = mkmsg("writing '%s'", ptn);
 }
 
-void fb_queue_flash_sparse(const char* ptn, struct sparse_file* s, unsigned sz, size_t current,
+void fb_queue_flash_sparse(const char* ptn, struct sparse_file* s, uint32_t sz, size_t current,
                            size_t total) {
     Action *a;
 
@@ -282,7 +298,7 @@
     return 0;
 }
 
-void fb_queue_query_save(const char *var, char *dest, unsigned dest_size)
+void fb_queue_query_save(const char *var, char *dest, uint32_t dest_size)
 {
     Action *a;
     a = queue_action(OP_QUERY, "getvar:%s", var);
@@ -309,7 +325,7 @@
     a->msg = msg;
 }
 
-void fb_queue_download(const char *name, void *data, unsigned size)
+void fb_queue_download(const char *name, void *data, uint32_t size)
 {
     Action *a = queue_action(OP_DOWNLOAD, "");
     a->data = data;
@@ -317,6 +333,22 @@
     a->msg = mkmsg("downloading '%s'", name);
 }
 
+void fb_queue_download_fd(const char *name, int fd, uint32_t sz)
+{
+    Action *a;
+    a = queue_action(OP_DOWNLOAD_FD, "");
+    a->fd = fd;
+    a->size = sz;
+    a->msg = mkmsg("sending '%s' (%d KB)", name, sz / 1024);
+}
+
+void fb_queue_upload(char *outfile)
+{
+    Action *a = queue_action(OP_UPLOAD, "");
+    a->data = outfile;
+    a->msg = mkmsg("uploading '%s'", outfile);
+}
+
 void fb_queue_notice(const char *notice)
 {
     Action *a = queue_action(OP_NOTICE, "");
@@ -328,11 +360,11 @@
     queue_action(OP_WAIT_FOR_DISCONNECT, "");
 }
 
-int fb_execute_queue(Transport* transport)
+int64_t fb_execute_queue(Transport* transport)
 {
     Action *a;
     char resp[FB_RESPONSE_SZ+1];
-    int status = 0;
+    int64_t status = 0;
 
     a = action_list;
     if (!a)
@@ -351,6 +383,10 @@
             status = fb_download_data(transport, a->data, a->size);
             status = a->func(a, status, status ? fb_get_error().c_str() : "");
             if (status) break;
+        } else if (a->op == OP_DOWNLOAD_FD) {
+            status = fb_download_data_fd(transport, a->fd, a->size);
+            status = a->func(a, status, status ? fb_get_error().c_str() : "");
+            if (status) break;
         } else if (a->op == OP_COMMAND) {
             status = fb_command(transport, a->cmd);
             status = a->func(a, status, status ? fb_get_error().c_str() : "");
@@ -367,6 +403,9 @@
             if (status) break;
         } else if (a->op == OP_WAIT_FOR_DISCONNECT) {
             transport->WaitForDisconnect();
+        } else if (a->op == OP_UPLOAD) {
+            status = fb_upload_data(transport, reinterpret_cast<char*>(a->data));
+            status = a->func(a, status, status ? fb_get_error().c_str() : "");
         } else {
             die("bogus action");
         }
diff --git a/fastboot/fastboot.cpp b/fastboot/fastboot.cpp
index 2927b16..982545c 100644
--- a/fastboot/fastboot.cpp
+++ b/fastboot/fastboot.cpp
@@ -55,6 +55,7 @@
 #include <android-base/parsenetaddress.h>
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
+#include <android-base/unique_fd.h>
 #include <sparse/sparse.h>
 #include <ziparchive/zip_archive.h>
 
@@ -67,6 +68,8 @@
 #include "udp.h"
 #include "usb.h"
 
+using android::base::unique_fd;
+
 #ifndef O_BINARY
 #define O_BINARY 0
 #endif
@@ -78,6 +81,10 @@
 static const char* cmdline = nullptr;
 static unsigned short vendor_id = 0;
 static int long_listing = 0;
+// Don't resparse files in too-big chunks.
+// libsparse will support INT_MAX, but this results in large allocations, so
+// let's keep it at 1GB to avoid memory pressure on the host.
+static constexpr int64_t RESPARSE_LIMIT = 1 * 1024 * 1024 * 1024;
 static int64_t sparse_limit = -1;
 static int64_t target_sparse_limit = -1;
 
@@ -91,7 +98,7 @@
 static const std::string convert_fbe_marker_filename("convert_fbe");
 
 enum fb_buffer_type {
-    FB_BUFFER,
+    FB_BUFFER_FD,
     FB_BUFFER_SPARSE,
 };
 
@@ -99,6 +106,7 @@
     enum fb_buffer_type type;
     void* data;
     int64_t sz;
+    int fd;
 };
 
 static struct {
@@ -115,6 +123,7 @@
     {"system_other.img", "system.sig", "system", true, true},
     {"vendor.img", "vendor.sig", "vendor", true, false},
     {"vendor_other.img", "vendor.sig", "vendor", true, true},
+    {"vbmeta.img", "vbmeta.sig", "vbmeta", true, false},
 };
 
 static std::string find_item_given_name(const char* img_name, const char* product) {
@@ -144,6 +153,8 @@
         fn = "system.img";
     } else if(!strcmp(item,"vendor")) {
         fn = "vendor.img";
+    } else if(!strcmp(item,"vbmeta")) {
+        fn = "vbmeta.img";
     } else if(!strcmp(item,"userdata")) {
         fn = "userdata.img";
     } else if(!strcmp(item,"cache")) {
@@ -360,6 +371,13 @@
             "  continue                                 Continue with autoboot.\n"
             "  reboot [bootloader|emergency]            Reboot device [into bootloader or emergency mode].\n"
             "  reboot-bootloader                        Reboot device into bootloader.\n"
+            "  oem <parameter1> ... <parameterN>        Executes oem specific command.\n"
+            "  stage <infile>                           Sends contents of <infile> to stage for\n"
+            "                                           the next command. Supported only on\n"
+            "                                           Android Things devices.\n"
+            "  get_staged <outfile>                     Receives data to <outfile> staged by the\n"
+            "                                           last command. Supported only on Android\n"
+            "                                           Things devices.\n"
             "  help                                     Show this help message.\n"
             "\n"
             "options:\n"
@@ -483,8 +501,7 @@
     return bdata;
 }
 
-static void* unzip_file(ZipArchiveHandle zip, const char* entry_name, int64_t* sz)
-{
+static void* unzip_file(ZipArchiveHandle zip, const char* entry_name, int64_t* sz) {
     ZipString zip_entry_name(entry_name);
     ZipEntry zip_entry;
     if (FindEntry(zip, zip_entry_name, &zip_entry) != 0) {
@@ -494,6 +511,7 @@
 
     *sz = zip_entry.uncompressed_length;
 
+    fprintf(stderr, "extracting %s (%" PRId64 " MB)...\n", entry_name, *sz / 1024 / 1024);
     uint8_t* data = reinterpret_cast<uint8_t*>(malloc(zip_entry.uncompressed_length));
     if (data == nullptr) {
         fprintf(stderr, "failed to allocate %" PRId64 " bytes for '%s'\n", *sz, entry_name);
@@ -542,22 +560,39 @@
     return "";
 }
 
+static int make_temporary_fd() {
+    // TODO: reimplement to avoid leaking a FILE*.
+    return fileno(tmpfile());
+}
+
 #else
 
+static std::string make_temporary_template() {
+    const char* tmpdir = getenv("TMPDIR");
+    if (tmpdir == nullptr) tmpdir = P_tmpdir;
+    return std::string(tmpdir) + "/fastboot_userdata_XXXXXX";
+}
+
 static std::string make_temporary_directory() {
-    const char *tmpdir = getenv("TMPDIR");
-    if (tmpdir == nullptr) {
-        tmpdir = P_tmpdir;
-    }
-    std::string result = std::string(tmpdir) + "/fastboot_userdata_XXXXXX";
-    if (mkdtemp(&result[0]) == NULL) {
-        fprintf(stderr, "Unable to create temporary directory: %s\n",
-            strerror(errno));
+    std::string result(make_temporary_template());
+    if (mkdtemp(&result[0]) == nullptr) {
+        fprintf(stderr, "Unable to create temporary directory: %s\n", strerror(errno));
         return "";
     }
     return result;
 }
 
+static int make_temporary_fd() {
+    std::string path_template(make_temporary_template());
+    int fd = mkstemp(&path_template[0]);
+    if (fd == -1) {
+        fprintf(stderr, "Unable to create temporary file: %s\n", strerror(errno));
+        return -1;
+    }
+    unlink(path_template.c_str());
+    return fd;
+}
+
 #endif
 
 static std::string create_fbemarker_tmpdir() {
@@ -592,8 +627,8 @@
 }
 
 static int unzip_to_file(ZipArchiveHandle zip, char* entry_name) {
-    FILE* fp = tmpfile();
-    if (fp == nullptr) {
+    unique_fd fd(make_temporary_fd());
+    if (fd == -1) {
         fprintf(stderr, "failed to create temporary file for '%s': %s\n",
                 entry_name, strerror(errno));
         return -1;
@@ -603,21 +638,20 @@
     ZipEntry zip_entry;
     if (FindEntry(zip, zip_entry_name, &zip_entry) != 0) {
         fprintf(stderr, "archive does not contain '%s'\n", entry_name);
-        fclose(fp);
         return -1;
     }
 
-    int fd = fileno(fp);
+    fprintf(stderr, "extracting %s (%" PRIu32 " MB)...\n", entry_name,
+            zip_entry.uncompressed_length / 1024 / 1024);
     int error = ExtractEntryToFile(zip, &zip_entry, fd);
     if (error != 0) {
         fprintf(stderr, "failed to extract '%s': %s\n", entry_name, ErrorCodeString(error));
-        fclose(fp);
         return -1;
     }
 
     lseek(fd, 0, SEEK_SET);
     // TODO: We're leaking 'fp' here.
-    return fd;
+    return fd.release();
 }
 
 static char *strip(char *s)
@@ -786,7 +820,7 @@
     }
 
     if (size > limit) {
-        return limit;
+        return std::min(limit, RESPARSE_LIMIT);
     }
 
     return 0;
@@ -819,10 +853,9 @@
         buf->type = FB_BUFFER_SPARSE;
         buf->data = s;
     } else {
-        void* data = load_fd(fd, &sz);
-        if (data == nullptr) return -1;
-        buf->type = FB_BUFFER;
-        buf->data = data;
+        buf->type = FB_BUFFER_FD;
+        buf->data = nullptr;
+        buf->fd = fd;
         buf->sz = sz;
     }
 
@@ -830,11 +863,22 @@
 }
 
 static bool load_buf(Transport* transport, const char* fname, struct fastboot_buffer* buf) {
-    int fd = open(fname, O_RDONLY | O_BINARY);
+    unique_fd fd(TEMP_FAILURE_RETRY(open(fname, O_RDONLY | O_BINARY)));
+
     if (fd == -1) {
         return false;
     }
-    return load_buf_fd(transport, fd, buf);
+
+    struct stat s;
+    if (fstat(fd, &s)) {
+        return false;
+    }
+    if (!S_ISREG(s.st_mode)) {
+        errno = S_ISDIR(s.st_mode) ? EISDIR : EINVAL;
+        return false;
+    }
+
+    return load_buf_fd(transport, fd.release(), buf);
 }
 
 static void flash_buf(const char *pname, struct fastboot_buffer *buf)
@@ -857,9 +901,8 @@
             }
             break;
         }
-
-        case FB_BUFFER:
-            fb_queue_flash(pname, buf->data, buf->sz);
+        case FB_BUFFER_FD:
+            fb_queue_flash_fd(pname, buf->fd, buf->sz);
             break;
         default:
             die("unknown buffer type: %d", buf->type);
@@ -1131,7 +1174,7 @@
             }
             flash_buf(partition.c_str(), &buf);
             /* not closing the fd here since the sparse code keeps the fd around
-             * but hasn't mmaped data yet. The tmpfile will get cleaned up when the
+             * but hasn't mmaped data yet. The temporary file will get cleaned up when the
              * program exits.
              */
         };
@@ -1392,7 +1435,8 @@
         return;
     }
 
-    fd = fileno(tmpfile());
+    fd = make_temporary_fd();
+    if (fd == -1) return;
 
     unsigned eraseBlkSize, logicalBlkSize;
     eraseBlkSize = fb_get_flash_block_size(transport, "erase-block-size");
@@ -1536,6 +1580,7 @@
                 setvbuf(stderr, nullptr, _IONBF, 0);
             } else if (strcmp("version", longopts[longindex].name) == 0) {
                 fprintf(stdout, "fastboot version %s\n", FASTBOOT_REVISION);
+                fprintf(stdout, "Installed as %s\n", android::base::GetExecutablePath().c_str());
                 return 0;
             } else if (strcmp("slot", longopts[longindex].name) == 0) {
                 slot_override = std::string(optarg);
@@ -1785,6 +1830,20 @@
             }
             fb_set_active(slot.c_str());
             skip(2);
+        } else if(!strcmp(*argv, "stage")) {
+            require(2);
+            std::string infile(argv[1]);
+            skip(2);
+            struct fastboot_buffer buf;
+            if (!load_buf(transport, infile.c_str(), &buf) || buf.type != FB_BUFFER_FD) {
+                die("cannot load '%s'", infile.c_str());
+            }
+            fb_queue_download_fd(infile.c_str(), buf.fd, buf.sz);
+        } else if(!strcmp(*argv, "get_staged")) {
+            require(2);
+            char *outfile = argv[1];
+            skip(2);
+            fb_queue_upload(outfile);
         } else if(!strcmp(*argv, "oem")) {
             argc = do_oem_command(argc, argv);
         } else if(!strcmp(*argv, "flashing")) {
diff --git a/fastboot/fastboot.h b/fastboot/fastboot.h
index 6699b6a..e30c6de 100644
--- a/fastboot/fastboot.h
+++ b/fastboot/fastboot.h
@@ -41,8 +41,10 @@
 /* protocol.c - fastboot protocol */
 int fb_command(Transport* transport, const char* cmd);
 int fb_command_response(Transport* transport, const char* cmd, char* response);
-int fb_download_data(Transport* transport, const void* data, uint32_t size);
+int64_t fb_download_data(Transport* transport, const void* data, uint32_t size);
+int64_t fb_download_data_fd(Transport* transport, int fd, uint32_t size);
 int fb_download_data_sparse(Transport* transport, struct sparse_file* s);
+int64_t fb_upload_data(Transport* transport, const char* outfile);
 const std::string fb_get_error();
 
 #define FB_COMMAND_SZ 64
@@ -51,6 +53,7 @@
 /* engine.c - high level command queue engine */
 bool fb_getvar(Transport* transport, const std::string& key, std::string* value);
 void fb_queue_flash(const char *ptn, void *data, uint32_t sz);
+void fb_queue_flash_fd(const char *ptn, int fd, uint32_t sz);
 void fb_queue_flash_sparse(const char* ptn, struct sparse_file* s, uint32_t sz, size_t current,
                            size_t total);
 void fb_queue_erase(const char *ptn);
@@ -62,9 +65,11 @@
 void fb_queue_reboot(void);
 void fb_queue_command(const char *cmd, const char *msg);
 void fb_queue_download(const char *name, void *data, uint32_t size);
+void fb_queue_download_fd(const char *name, int fd, uint32_t sz);
+void fb_queue_upload(char *outfile);
 void fb_queue_notice(const char *notice);
 void fb_queue_wait_for_disconnect(void);
-int fb_execute_queue(Transport* transport);
+int64_t fb_execute_queue(Transport* transport);
 void fb_set_active(const char *slot);
 
 /* util stuff */
diff --git a/fastboot/protocol.cpp b/fastboot/protocol.cpp
index bfa83b0..dcdf8f0 100644
--- a/fastboot/protocol.cpp
+++ b/fastboot/protocol.cpp
@@ -29,26 +29,34 @@
 #define round_down(a, b) \
     ({ typeof(a) _a = (a); typeof(b) _b = (b); _a - (_a % _b); })
 
+#include <fcntl.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <errno.h>
 
 #include <algorithm>
+#include <vector>
 
+#include <android-base/file.h>
 #include <android-base/stringprintf.h>
+#include <android-base/unique_fd.h>
 #include <sparse/sparse.h>
+#include <utils/FileMap.h>
 
 #include "fastboot.h"
 #include "transport.h"
 
 static std::string g_error;
 
+using android::base::unique_fd;
+using android::base::WriteStringToFile;
+
 const std::string fb_get_error() {
     return g_error;
 }
 
-static int check_response(Transport* transport, uint32_t size, char* response) {
+static int64_t check_response(Transport* transport, uint32_t size, char* response) {
     char status[65];
 
     while (true) {
@@ -105,7 +113,7 @@
     return -1;
 }
 
-static int _command_start(Transport* transport, const char* cmd, uint32_t size, char* response) {
+static int64_t _command_start(Transport* transport, const char* cmd, uint32_t size, char* response) {
     size_t cmdsize = strlen(cmd);
     if (cmdsize > 64) {
         g_error = android::base::StringPrintf("command too large (%zu)", cmdsize);
@@ -125,37 +133,51 @@
     return check_response(transport, size, response);
 }
 
-static int _command_data(Transport* transport, const void* data, uint32_t size) {
-    int r = transport->Write(data, size);
+static int64_t _command_write_data(Transport* transport, const void* data, uint32_t size) {
+    int64_t r = transport->Write(data, size);
     if (r < 0) {
-        g_error = android::base::StringPrintf("data transfer failure (%s)", strerror(errno));
+        g_error = android::base::StringPrintf("data write failure (%s)", strerror(errno));
         transport->Close();
         return -1;
     }
-    if (r != ((int) size)) {
-        g_error = "data transfer failure (short transfer)";
+    if (r != static_cast<int64_t>(size)) {
+        g_error = "data write failure (short transfer)";
         transport->Close();
         return -1;
     }
     return r;
 }
 
-static int _command_end(Transport* transport) {
+static int64_t _command_read_data(Transport* transport, void* data, uint32_t size) {
+    int64_t r = transport->Read(data, size);
+    if (r < 0) {
+        g_error = android::base::StringPrintf("data read failure (%s)", strerror(errno));
+        transport->Close();
+        return -1;
+    }
+    if (r != (static_cast<int64_t>(size))) {
+        g_error = "data read failure (short transfer)";
+        transport->Close();
+        return -1;
+    }
+    return r;
+}
+
+static int64_t _command_end(Transport* transport) {
     return check_response(transport, 0, 0) < 0 ? -1 : 0;
 }
 
-static int _command_send(Transport* transport, const char* cmd, const void* data, uint32_t size,
+static int64_t _command_send(Transport* transport, const char* cmd, const void* data, uint32_t size,
                          char* response) {
     if (size == 0) {
         return -1;
     }
 
-    int r = _command_start(transport, cmd, size, response);
+    int64_t r = _command_start(transport, cmd, size, response);
     if (r < 0) {
         return -1;
     }
-
-    r = _command_data(transport, data, size);
+    r = _command_write_data(transport, data, size);
     if (r < 0) {
         return -1;
     }
@@ -168,6 +190,39 @@
     return size;
 }
 
+static int64_t _command_send_fd(Transport* transport, const char* cmd, int fd, uint32_t size,
+                                char* response) {
+    static constexpr uint32_t MAX_MAP_SIZE = 512 * 1024 * 1024;
+    off64_t offset = 0;
+    uint32_t remaining = size;
+
+    if (_command_start(transport, cmd, size, response) < 0) {
+        return -1;
+    }
+
+    while (remaining) {
+        android::FileMap filemap;
+        size_t len = std::min(remaining, MAX_MAP_SIZE);
+
+        if (!filemap.create(NULL, fd, offset, len, true)) {
+            return -1;
+        }
+
+        if (_command_write_data(transport, filemap.getDataPtr(), len) < 0) {
+            return -1;
+        }
+
+        remaining -= len;
+        offset += len;
+    }
+
+    if (_command_end(transport) < 0) {
+        return -1;
+    }
+
+    return size;
+}
+
 static int _command_send_no_data(Transport* transport, const char* cmd, char* response) {
     return _command_start(transport, cmd, 0, response);
 }
@@ -180,10 +235,36 @@
     return _command_send_no_data(transport, cmd, response);
 }
 
-int fb_download_data(Transport* transport, const void* data, uint32_t size) {
-    char cmd[64];
-    snprintf(cmd, sizeof(cmd), "download:%08x", size);
-    return _command_send(transport, cmd, data, size, 0) < 0 ? -1 : 0;
+int64_t fb_download_data(Transport* transport, const void* data, uint32_t size) {
+    std::string cmd(android::base::StringPrintf("download:%08x", size));
+    return _command_send(transport, cmd.c_str(), data, size, 0) < 0 ? -1 : 0;
+}
+
+int64_t fb_download_data_fd(Transport* transport, int fd, uint32_t size) {
+    std::string cmd(android::base::StringPrintf("download:%08x", size));
+    return _command_send_fd(transport, cmd.c_str(), fd, size, 0) < 0 ? -1 : 0;
+}
+
+int64_t fb_upload_data(Transport* transport, const char* outfile) {
+    // positive return value is the upload size sent by the device
+    int64_t r = _command_start(transport, "upload", std::numeric_limits<int32_t>::max(), nullptr);
+    if (r <= 0) {
+        g_error = android::base::StringPrintf("command start failed (%s)", strerror(errno));
+        return r;
+    }
+
+    std::string data;
+    data.resize(r);
+    if ((r = _command_read_data(transport, &data[0], data.size())) == -1) {
+        return r;
+    }
+
+    if (!WriteStringToFile(data, outfile, true)) {
+        g_error = android::base::StringPrintf("write to '%s' failed", outfile);
+        return -1;
+    }
+
+    return _command_end(transport);
 }
 
 #define TRANSPORT_BUF_SIZE 1024
@@ -207,7 +288,7 @@
     }
 
     if (transport_buf_len == TRANSPORT_BUF_SIZE) {
-        r = _command_data(transport, transport_buf, TRANSPORT_BUF_SIZE);
+        r = _command_write_data(transport, transport_buf, TRANSPORT_BUF_SIZE);
         if (r != TRANSPORT_BUF_SIZE) {
             return -1;
         }
@@ -220,7 +301,7 @@
             return -1;
         }
         to_write = round_down(len, TRANSPORT_BUF_SIZE);
-        r = _command_data(transport, ptr, to_write);
+        r = _command_write_data(transport, ptr, to_write);
         if (r != to_write) {
             return -1;
         }
@@ -242,7 +323,8 @@
 
 static int fb_download_data_sparse_flush(Transport* transport) {
     if (transport_buf_len > 0) {
-        if (_command_data(transport, transport_buf, transport_buf_len) != transport_buf_len) {
+        int64_t r = _command_write_data(transport, transport_buf, transport_buf_len);
+        if (r != static_cast<int64_t>(transport_buf_len)) {
             return -1;
         }
         transport_buf_len = 0;
@@ -256,9 +338,8 @@
         return -1;
     }
 
-    char cmd[64];
-    snprintf(cmd, sizeof(cmd), "download:%08x", size);
-    int r = _command_start(transport, cmd, size, 0);
+    std::string cmd(android::base::StringPrintf("download:%08x", size));
+    int r = _command_start(transport, cmd.c_str(), size, 0);
     if (r < 0) {
         return -1;
     }
diff --git a/fingerprintd/FingerprintDaemonProxy.cpp b/fingerprintd/FingerprintDaemonProxy.cpp
index 1c7da30..b3c0cd7 100644
--- a/fingerprintd/FingerprintDaemonProxy.cpp
+++ b/fingerprintd/FingerprintDaemonProxy.cpp
@@ -31,7 +31,7 @@
 FingerprintDaemonProxy* FingerprintDaemonProxy::sInstance = NULL;
 
 // Supported fingerprint HAL version
-static const uint16_t kVersion = HARDWARE_MODULE_API_VERSION(2, 0);
+static const uint16_t kVersion = HARDWARE_MODULE_API_VERSION(2, 1);
 
 FingerprintDaemonProxy::FingerprintDaemonProxy() : mModule(NULL), mDevice(NULL), mCallback(NULL) {
 
diff --git a/fs_mgr/fs_mgr.cpp b/fs_mgr/fs_mgr.cpp
index 6c84d73..6e9069e 100644
--- a/fs_mgr/fs_mgr.cpp
+++ b/fs_mgr/fs_mgr.cpp
@@ -31,7 +31,10 @@
 #include <time.h>
 #include <unistd.h>
 
+#include <memory>
+
 #include <android-base/file.h>
+#include <android-base/properties.h>
 #include <android-base/stringprintf.h>
 #include <android-base/unique_fd.h>
 #include <cutils/android_reboot.h>
@@ -44,12 +47,14 @@
 #include <ext4_utils/wipe.h>
 #include <linux/fs.h>
 #include <linux/loop.h>
+#include <linux/magic.h>
+#include <log/log_properties.h>
 #include <logwrap/logwrap.h>
-#include <private/android_filesystem_config.h>
-#include <private/android_logger.h>
 
+#include "fs_mgr.h"
+#include "fs_mgr_avb.h"
 #include "fs_mgr_priv.h"
-#include "fs_mgr_priv_avb.h"
+#include "fs_mgr_priv_dm_ioctl.h"
 
 #define KEY_LOC_PROP   "ro.crypto.keyfile.userdata"
 #define KEY_IN_FOOTER  "footer"
@@ -68,17 +73,18 @@
 
 // record fs stat
 enum FsStatFlags {
-    FS_STAT_IS_EXT4           = 0x0001,
+    FS_STAT_IS_EXT4 = 0x0001,
     FS_STAT_NEW_IMAGE_VERSION = 0x0002,
-    FS_STAT_E2FSCK_F_ALWAYS   = 0x0004,
-    FS_STAT_UNCLEAN_SHUTDOWN  = 0x0008,
-    FS_STAT_QUOTA_ENABLED     = 0x0010,
-    FS_STAT_TUNE2FS_FAILED    = 0x0020,
-    FS_STAT_RO_MOUNT_FAILED   = 0x0040,
+    FS_STAT_E2FSCK_F_ALWAYS = 0x0004,
+    FS_STAT_UNCLEAN_SHUTDOWN = 0x0008,
+    FS_STAT_QUOTA_ENABLED = 0x0010,
+    FS_STAT_TUNE2FS_FAILED = 0x0020,
+    FS_STAT_RO_MOUNT_FAILED = 0x0040,
     FS_STAT_RO_UNMOUNT_FAILED = 0x0080,
     FS_STAT_FULL_MOUNT_FAILED = 0x0100,
-    FS_STAT_E2FSCK_FAILED     = 0x0200,
-    FS_STAT_E2FSCK_FS_FIXED   = 0x0400,
+    FS_STAT_E2FSCK_FAILED = 0x0200,
+    FS_STAT_E2FSCK_FS_FIXED = 0x0400,
+    FS_STAT_EXT4_INVALID_MAGIC = 0x0800,
 };
 
 /*
@@ -122,21 +128,26 @@
     }
 }
 
+static bool should_force_check(int fs_stat) {
+    return fs_stat & (FS_STAT_E2FSCK_F_ALWAYS | FS_STAT_UNCLEAN_SHUTDOWN | FS_STAT_QUOTA_ENABLED |
+                      FS_STAT_TUNE2FS_FAILED | FS_STAT_RO_MOUNT_FAILED | FS_STAT_RO_UNMOUNT_FAILED |
+                      FS_STAT_FULL_MOUNT_FAILED | FS_STAT_E2FSCK_FAILED);
+}
+
 static void check_fs(const char *blk_device, char *fs_type, char *target, int *fs_stat)
 {
     int status;
     int ret;
     long tmpmnt_flags = MS_NOATIME | MS_NOEXEC | MS_NOSUID;
     char tmpmnt_opts[64] = "errors=remount-ro";
-    const char *e2fsck_argv[] = {
-        E2FSCK_BIN,
-        "-f",
-        "-y",
-        blk_device
-    };
+    const char* e2fsck_argv[] = {E2FSCK_BIN, "-y", blk_device};
+    const char* e2fsck_forced_argv[] = {E2FSCK_BIN, "-f", "-y", blk_device};
 
     /* Check for the types of filesystems we know how to check */
     if (!strcmp(fs_type, "ext2") || !strcmp(fs_type, "ext3") || !strcmp(fs_type, "ext4")) {
+        if (*fs_stat & FS_STAT_EXT4_INVALID_MAGIC) {  // will fail, so do not try
+            return;
+        }
         /*
          * First try to mount and unmount the filesystem.  We do this because
          * the kernel is more efficient than e2fsck in running the journal and
@@ -150,32 +161,35 @@
          * filesytsem due to an error, e2fsck is still run to do a full check
          * fix the filesystem.
          */
-        errno = 0;
-        if (!strcmp(fs_type, "ext4")) {
-            // This option is only valid with ext4
-            strlcat(tmpmnt_opts, ",nomblk_io_submit", sizeof(tmpmnt_opts));
-        }
-        ret = mount(blk_device, target, fs_type, tmpmnt_flags, tmpmnt_opts);
-        PINFO << __FUNCTION__ << "(): mount(" << blk_device <<  "," << target
-              << "," << fs_type << ")=" << ret;
-        if (!ret) {
-            int i;
-            for (i = 0; i < 5; i++) {
-                // Try to umount 5 times before continuing on.
-                // Should we try rebooting if all attempts fail?
-                int result = umount(target);
-                if (result == 0) {
-                    LINFO << __FUNCTION__ << "(): unmount(" << target
-                          << ") succeeded";
-                    break;
-                }
-                *fs_stat |= FS_STAT_RO_UNMOUNT_FAILED;
-                PERROR << __FUNCTION__ << "(): umount(" << target << ")="
-                       << result;
-                sleep(1);
+        if (!(*fs_stat & FS_STAT_FULL_MOUNT_FAILED)) {  // already tried if full mount failed
+            errno = 0;
+            if (!strcmp(fs_type, "ext4")) {
+                // This option is only valid with ext4
+                strlcat(tmpmnt_opts, ",nomblk_io_submit", sizeof(tmpmnt_opts));
             }
-        } else {
-            *fs_stat |= FS_STAT_RO_MOUNT_FAILED;
+            ret = mount(blk_device, target, fs_type, tmpmnt_flags, tmpmnt_opts);
+            PINFO << __FUNCTION__ << "(): mount(" << blk_device << "," << target << "," << fs_type
+                  << ")=" << ret;
+            if (!ret) {
+                bool umounted = false;
+                int retry_count = 5;
+                while (retry_count-- > 0) {
+                    umounted = umount(target) == 0;
+                    if (umounted) {
+                        LINFO << __FUNCTION__ << "(): unmount(" << target << ") succeeded";
+                        break;
+                    }
+                    PERROR << __FUNCTION__ << "(): umount(" << target << ") failed";
+                    if (retry_count) sleep(1);
+                }
+                if (!umounted) {
+                    // boot may fail but continue and leave it to later stage for now.
+                    PERROR << __FUNCTION__ << "(): umount(" << target << ") timed out";
+                    *fs_stat |= FS_STAT_RO_UNMOUNT_FAILED;
+                }
+            } else {
+                *fs_stat |= FS_STAT_RO_MOUNT_FAILED;
+            }
         }
 
         /*
@@ -187,14 +201,15 @@
                   << " (executable not in system image)";
         } else {
             LINFO << "Running " << E2FSCK_BIN << " on " << blk_device;
-
-            *fs_stat |= FS_STAT_E2FSCK_F_ALWAYS;
-            ret = android_fork_execvp_ext(ARRAY_SIZE(e2fsck_argv),
-                                          const_cast<char **>(e2fsck_argv),
-                                          &status, true, LOG_KLOG | LOG_FILE,
-                                          true,
-                                          const_cast<char *>(FSCK_LOG_FILE),
-                                          NULL, 0);
+            if (should_force_check(*fs_stat)) {
+                ret = android_fork_execvp_ext(
+                    ARRAY_SIZE(e2fsck_forced_argv), const_cast<char**>(e2fsck_forced_argv), &status,
+                    true, LOG_KLOG | LOG_FILE, true, const_cast<char*>(FSCK_LOG_FILE), NULL, 0);
+            } else {
+                ret = android_fork_execvp_ext(
+                    ARRAY_SIZE(e2fsck_argv), const_cast<char**>(e2fsck_argv), &status, true,
+                    LOG_KLOG | LOG_FILE, true, const_cast<char*>(FSCK_LOG_FILE), NULL, 0);
+            }
 
             if (ret < 0) {
                 /* No need to check for error in fork, we can't really handle it now */
@@ -283,8 +298,16 @@
                     PERROR << "Can't read '" << blk_device << "' super block";
                     return force_check;
                 }
+                if (sb.s_magic != EXT4_SUPER_MAGIC) {
+                    LINFO << "Invalid ext4 magic:0x" << std::hex << sb.s_magic << "," << blk_device;
+                    *fs_stat |= FS_STAT_EXT4_INVALID_MAGIC;
+                    return 0;  // not a valid fs, tune2fs, fsck, and mount  will all fail.
+                }
                 *fs_stat |= FS_STAT_IS_EXT4;
-                //TODO check if it is new version or not
+                LINFO << "superblock s_max_mnt_count:" << sb.s_max_mnt_count << "," << blk_device;
+                if (sb.s_max_mnt_count == 0xffff) {  // -1 (int16) in ext2, but uint16 in ext4
+                    *fs_stat |= FS_STAT_NEW_IMAGE_VERSION;
+                }
                 if ((sb.s_feature_incompat & EXT4_FEATURE_INCOMPAT_RECOVER) != 0 ||
                     (sb.s_state & EXT4_VALID_FS) == 0) {
                     LINFO << __FUNCTION__ << "(): was not clealy shutdown, state flag:"
@@ -540,7 +563,13 @@
             int force_check = do_quota_with_shutdown_check(fstab->recs[i].blk_device,
                                                            fstab->recs[i].fs_type,
                                                            &fstab->recs[i], &fs_stat);
-
+            if (fs_stat & FS_STAT_EXT4_INVALID_MAGIC) {
+                LERROR << __FUNCTION__ << "(): skipping mount, invalid ext4, mountpoint="
+                       << fstab->recs[i].mount_point << " rec[" << i
+                       << "].fs_type=" << fstab->recs[i].fs_type;
+                mount_errno = EINVAL;  // continue bootup for FDE
+                continue;
+            }
             if ((fstab->recs[i].fs_mgr_flags & MF_CHECK) || force_check) {
                 check_fs(fstab->recs[i].blk_device, fstab->recs[i].fs_type,
                          fstab->recs[i].mount_point, &fs_stat);
@@ -551,21 +580,31 @@
                                  &fstab->recs[i], &fs_stat);
             }
 
-            if (!__mount(fstab->recs[i].blk_device, fstab->recs[i].mount_point, &fstab->recs[i])) {
-                *attempted_idx = i;
-                mounted = 1;
-                if (i != start_idx) {
-                    LERROR << __FUNCTION__ << "(): Mounted "
-                           << fstab->recs[i].blk_device << " on "
-                           << fstab->recs[i].mount_point << " with fs_type="
-                           << fstab->recs[i].fs_type << " instead of "
-                           << fstab->recs[start_idx].fs_type;
-                }
-            } else {
-                fs_stat |= FS_STAT_FULL_MOUNT_FAILED;
-                /* back up the first errno for crypto decisions */
-                if (mount_errno == 0) {
-                    mount_errno = errno;
+            int retry_count = 2;
+            while (retry_count-- > 0) {
+                if (!__mount(fstab->recs[i].blk_device, fstab->recs[i].mount_point,
+                             &fstab->recs[i])) {
+                    *attempted_idx = i;
+                    mounted = 1;
+                    if (i != start_idx) {
+                        LERROR << __FUNCTION__ << "(): Mounted " << fstab->recs[i].blk_device
+                               << " on " << fstab->recs[i].mount_point
+                               << " with fs_type=" << fstab->recs[i].fs_type << " instead of "
+                               << fstab->recs[start_idx].fs_type;
+                    }
+                    fs_stat &= ~FS_STAT_FULL_MOUNT_FAILED;
+                    mount_errno = 0;
+                    break;
+                } else {
+                    if (retry_count <= 0) break;  // run check_fs only once
+                    fs_stat |= FS_STAT_FULL_MOUNT_FAILED;
+                    /* back up the first errno for crypto decisions */
+                    if (mount_errno == 0) {
+                        mount_errno = errno;
+                    }
+                    // retry after fsck
+                    check_fs(fstab->recs[i].blk_device, fstab->recs[i].fs_type,
+                             fstab->recs[i].mount_point, &fs_stat);
                 }
             }
             log_fs_stat(fstab->recs[i].blk_device, fs_stat);
@@ -705,6 +744,23 @@
     }
 }
 
+static std::string extract_by_name_prefix(struct fstab* fstab) {
+    // We assume that there's an entry for the /misc mount point in the
+    // fstab file and use that to get the device file by-name prefix.
+    // The device needs not to have an actual /misc partition.
+    // e.g.,
+    //    - /dev/block/platform/soc.0/7824900.sdhci/by-name/misc ->
+    //    - /dev/block/platform/soc.0/7824900.sdhci/by-name/
+    struct fstab_rec* fstab_entry = fs_mgr_get_entry_for_mount_point(fstab, "/misc");
+    if (fstab_entry == nullptr) {
+        LERROR << "/misc mount point not found in fstab";
+        return "";
+    }
+    std::string full_path(fstab_entry->blk_device);
+    size_t end_slash = full_path.find_last_of("/");
+    return full_path.substr(0, end_slash + 1);
+}
+
 // TODO: add ueventd notifiers if they don't exist.
 // This is just doing a wait_for_device for maximum of 1s
 int fs_mgr_test_access(const char *device) {
@@ -748,15 +804,10 @@
     int mret = -1;
     int mount_errno = 0;
     int attempted_idx = -1;
-    int avb_ret = FS_MGR_SETUP_AVB_FAIL;
+    FsManagerAvbUniquePtr avb_handle(nullptr);
 
     if (!fstab) {
-        return -1;
-    }
-
-    if (fs_mgr_is_avb_used() &&
-        (avb_ret = fs_mgr_load_vbmeta_images(fstab)) == FS_MGR_SETUP_AVB_FAIL) {
-        return -1;
+        return FS_MGR_MNTALL_FAIL;
     }
 
     for (i = 0; i < fstab->num_entries; i++) {
@@ -797,16 +848,15 @@
             wait_for_file(fstab->recs[i].blk_device, WAIT_TIMEOUT);
         }
 
-        if (fs_mgr_is_avb_used() && (fstab->recs[i].fs_mgr_flags & MF_AVB)) {
-            /* If HASHTREE_DISABLED is set (cf. 'adb disable-verity'), we
-             * should set up the device without using dm-verity.
-             * The actual mounting still take place in the following
-             * mount_with_alternatives().
-             */
-            if (avb_ret == FS_MGR_SETUP_AVB_HASHTREE_DISABLED) {
-                LINFO << "AVB HASHTREE disabled";
-            } else if (fs_mgr_setup_avb(&fstab->recs[i]) !=
-                       FS_MGR_SETUP_AVB_SUCCESS) {
+        if (fstab->recs[i].fs_mgr_flags & MF_AVB) {
+            if (!avb_handle) {
+                avb_handle = FsManagerAvbHandle::Open(extract_by_name_prefix(fstab));
+                if (!avb_handle) {
+                    LERROR << "Failed to open FsManagerAvbHandle";
+                    return FS_MGR_MNTALL_FAIL;
+                }
+            }
+            if (!avb_handle->SetUpAvb(&fstab->recs[i], true /* wait_for_verity_dev */)) {
                 LERROR << "Failed to set up AVB on partition: "
                        << fstab->recs[i].mount_point << ", skipping!";
                 /* Skips mounting the device. */
@@ -932,12 +982,8 @@
         }
     }
 
-    if (fs_mgr_is_avb_used()) {
-        fs_mgr_unload_vbmeta_images();
-    }
-
     if (error_count) {
-        return -1;
+        return FS_MGR_MNTALL_FAIL;
     } else {
         return encryptable;
     }
@@ -970,19 +1016,13 @@
                     char *tmp_mount_point)
 {
     int i = 0;
-    int ret = FS_MGR_DOMNT_FAILED;
     int mount_errors = 0;
     int first_mount_errno = 0;
-    char *m;
-    int avb_ret = FS_MGR_SETUP_AVB_FAIL;
+    char* mount_point;
+    FsManagerAvbUniquePtr avb_handle(nullptr);
 
     if (!fstab) {
-        return ret;
-    }
-
-    if (fs_mgr_is_avb_used() &&
-        (avb_ret = fs_mgr_load_vbmeta_images(fstab)) == FS_MGR_SETUP_AVB_FAIL) {
-        return ret;
+        return FS_MGR_DOMNT_FAILED;
     }
 
     for (i = 0; i < fstab->num_entries; i++) {
@@ -997,7 +1037,7 @@
             !strcmp(fstab->recs[i].fs_type, "mtd")) {
             LERROR << "Cannot mount filesystem of type "
                    << fstab->recs[i].fs_type << " on " << n_blk_device;
-            goto out;
+            return FS_MGR_DOMNT_FAILED;
         }
 
         /* First check the filesystem if requested */
@@ -1019,16 +1059,15 @@
             do_reserved_size(n_blk_device, fstab->recs[i].fs_type, &fstab->recs[i], &fs_stat);
         }
 
-        if (fs_mgr_is_avb_used() && (fstab->recs[i].fs_mgr_flags & MF_AVB)) {
-            /* If HASHTREE_DISABLED is set (cf. 'adb disable-verity'), we
-             * should set up the device without using dm-verity.
-             * The actual mounting still take place in the following
-             * mount_with_alternatives().
-             */
-            if (avb_ret == FS_MGR_SETUP_AVB_HASHTREE_DISABLED) {
-                LINFO << "AVB HASHTREE disabled";
-            } else if (fs_mgr_setup_avb(&fstab->recs[i]) !=
-                       FS_MGR_SETUP_AVB_SUCCESS) {
+        if (fstab->recs[i].fs_mgr_flags & MF_AVB) {
+            if (!avb_handle) {
+                avb_handle = FsManagerAvbHandle::Open(extract_by_name_prefix(fstab));
+                if (!avb_handle) {
+                    LERROR << "Failed to open FsManagerAvbHandle";
+                    return FS_MGR_DOMNT_FAILED;
+                }
+            }
+            if (!avb_handle->SetUpAvb(&fstab->recs[i], true /* wait_for_verity_dev */)) {
                 LERROR << "Failed to set up AVB on partition: "
                        << fstab->recs[i].mount_point << ", skipping!";
                 /* Skips mounting the device. */
@@ -1046,41 +1085,36 @@
 
         /* Now mount it where requested */
         if (tmp_mount_point) {
-            m = tmp_mount_point;
+            mount_point = tmp_mount_point;
         } else {
-            m = fstab->recs[i].mount_point;
+            mount_point = fstab->recs[i].mount_point;
         }
-        if (__mount(n_blk_device, m, &fstab->recs[i])) {
-            if (!first_mount_errno) first_mount_errno = errno;
-            mount_errors++;
-            fs_stat |= FS_STAT_FULL_MOUNT_FAILED;
-            log_fs_stat(fstab->recs[i].blk_device, fs_stat);
-            continue;
-        } else {
-            ret = 0;
-            log_fs_stat(fstab->recs[i].blk_device, fs_stat);
-            goto out;
+        int retry_count = 2;
+        while (retry_count-- > 0) {
+            if (!__mount(n_blk_device, mount_point, &fstab->recs[i])) {
+                fs_stat &= ~FS_STAT_FULL_MOUNT_FAILED;
+                return FS_MGR_DOMNT_SUCCESS;
+            } else {
+                if (retry_count <= 0) break;  // run check_fs only once
+                if (!first_mount_errno) first_mount_errno = errno;
+                mount_errors++;
+                fs_stat |= FS_STAT_FULL_MOUNT_FAILED;
+                // try again after fsck
+                check_fs(n_blk_device, fstab->recs[i].fs_type, fstab->recs[i].mount_point, &fs_stat);
+            }
         }
-    }
-    if (mount_errors) {
-        PERROR << "Cannot mount filesystem on " << n_blk_device
-               << " at " << m;
-        if (first_mount_errno == EBUSY) {
-            ret = FS_MGR_DOMNT_BUSY;
-        } else {
-            ret = FS_MGR_DOMNT_FAILED;
-        }
-    } else {
-        /* We didn't find a match, say so and return an error */
-        LERROR << "Cannot find mount point " << fstab->recs[i].mount_point
-               << " in fstab";
+        log_fs_stat(fstab->recs[i].blk_device, fs_stat);
     }
 
-out:
-    if (fs_mgr_is_avb_used()) {
-        fs_mgr_unload_vbmeta_images();
+    // Reach here means the mount attempt fails.
+    if (mount_errors) {
+        PERROR << "Cannot mount filesystem on " << n_blk_device << " at " << mount_point;
+        if (first_mount_errno == EBUSY) return FS_MGR_DOMNT_BUSY;
+    } else {
+        /* We didn't find a match, say so and return an error */
+        LERROR << "Cannot find mount point " << n_name << " in fstab";
     }
-    return ret;
+    return FS_MGR_DOMNT_FAILED;
 }
 
 /*
@@ -1257,3 +1291,102 @@
 
     return 0;
 }
+
+bool fs_mgr_load_verity_state(int* mode) {
+    /* return the default mode, unless any of the verified partitions are in
+     * logging mode, in which case return that */
+    *mode = VERITY_MODE_DEFAULT;
+
+    std::unique_ptr<fstab, decltype(&fs_mgr_free_fstab)> fstab(fs_mgr_read_fstab_default(),
+                                                               fs_mgr_free_fstab);
+    if (!fstab) {
+        LERROR << "Failed to read default fstab";
+        return false;
+    }
+
+    for (int i = 0; i < fstab->num_entries; i++) {
+        if (fs_mgr_is_avb(&fstab->recs[i])) {
+            *mode = VERITY_MODE_RESTART;  // avb only supports restart mode.
+            break;
+        } else if (!fs_mgr_is_verified(&fstab->recs[i])) {
+            continue;
+        }
+
+        int current;
+        if (load_verity_state(&fstab->recs[i], &current) < 0) {
+            continue;
+        }
+        if (current != VERITY_MODE_DEFAULT) {
+            *mode = current;
+            break;
+        }
+    }
+
+    return true;
+}
+
+bool fs_mgr_update_verity_state(fs_mgr_verity_state_callback callback) {
+    if (!callback) {
+        return false;
+    }
+
+    int mode;
+    if (!fs_mgr_load_verity_state(&mode)) {
+        return false;
+    }
+
+    android::base::unique_fd fd(TEMP_FAILURE_RETRY(open("/dev/device-mapper", O_RDWR | O_CLOEXEC)));
+    if (fd == -1) {
+        PERROR << "Error opening device mapper";
+        return false;
+    }
+
+    std::unique_ptr<fstab, decltype(&fs_mgr_free_fstab)> fstab(fs_mgr_read_fstab_default(),
+                                                               fs_mgr_free_fstab);
+    if (!fstab) {
+        LERROR << "Failed to read default fstab";
+        return false;
+    }
+
+    alignas(dm_ioctl) char buffer[DM_BUF_SIZE];
+    struct dm_ioctl* io = (struct dm_ioctl*)buffer;
+    bool system_root = android::base::GetProperty("ro.build.system_root_image", "") == "true";
+
+    for (int i = 0; i < fstab->num_entries; i++) {
+        if (!fs_mgr_is_verified(&fstab->recs[i]) && !fs_mgr_is_avb(&fstab->recs[i])) {
+            continue;
+        }
+
+        std::string mount_point;
+        if (system_root && !strcmp(fstab->recs[i].mount_point, "/")) {
+            // In AVB, the dm device name is vroot instead of system.
+            mount_point = fs_mgr_is_avb(&fstab->recs[i]) ? "vroot" : "system";
+        } else {
+            mount_point = basename(fstab->recs[i].mount_point);
+        }
+
+        fs_mgr_verity_ioctl_init(io, mount_point, 0);
+
+        const char* status;
+        if (ioctl(fd, DM_TABLE_STATUS, io)) {
+            if (fstab->recs[i].fs_mgr_flags & MF_VERIFYATBOOT) {
+                status = "V";
+            } else {
+                PERROR << "Failed to query DM_TABLE_STATUS for " << mount_point.c_str();
+                continue;
+            }
+        }
+
+        status = &buffer[io->data_start + sizeof(struct dm_target_spec)];
+
+        // To be consistent in vboot 1.0 and vboot 2.0 (AVB), change the mount_point
+        // back to 'system' for the callback. So it has property [partition.system.verified]
+        // instead of [partition.vroot.verified].
+        if (mount_point == "vroot") mount_point = "system";
+        if (*status == 'C' || *status == 'V') {
+            callback(&fstab->recs[i], mount_point.c_str(), mode, *status);
+        }
+    }
+
+    return true;
+}
diff --git a/fs_mgr/fs_mgr_avb.cpp b/fs_mgr/fs_mgr_avb.cpp
index 2cb7e34..94cea57 100644
--- a/fs_mgr/fs_mgr_avb.cpp
+++ b/fs_mgr/fs_mgr_avb.cpp
@@ -28,6 +28,7 @@
 #include <android-base/file.h>
 #include <android-base/parseint.h>
 #include <android-base/properties.h>
+#include <android-base/stringprintf.h>
 #include <android-base/strings.h>
 #include <android-base/unique_fd.h>
 #include <cutils/properties.h>
@@ -37,9 +38,9 @@
 #include <utils/Compat.h>
 
 #include "fs_mgr.h"
+#include "fs_mgr_avb.h"
 #include "fs_mgr_avb_ops.h"
 #include "fs_mgr_priv.h"
-#include "fs_mgr_priv_avb.h"
 #include "fs_mgr_priv_dm_ioctl.h"
 #include "fs_mgr_priv_sha.h"
 
@@ -85,24 +86,6 @@
         hashtree_desc.fec_offset / hashtree_desc.data_block_size, /* fec_start */  \
         VERITY_TABLE_OPT_IGNZERO, VERITY_TABLE_OPT_RESTART
 
-AvbSlotVerifyData* fs_mgr_avb_verify_data = nullptr;
-AvbOps* fs_mgr_avb_ops = nullptr;
-
-enum HashAlgorithm {
-    kInvalid = 0,
-    kSHA256 = 1,
-    kSHA512 = 2,
-};
-
-struct androidboot_vbmeta {
-    HashAlgorithm hash_alg;
-    uint8_t digest[SHA512_DIGEST_LENGTH];
-    size_t vbmeta_size;
-    bool allow_verification_error;
-};
-
-androidboot_vbmeta fs_mgr_vbmeta_prop;
-
 static inline bool nibble_value(const char& c, uint8_t* value) {
     FS_MGR_CHECK(value != nullptr);
 
@@ -159,27 +142,78 @@
     return hex;
 }
 
-static bool load_vbmeta_prop(androidboot_vbmeta* vbmeta_prop) {
-    FS_MGR_CHECK(vbmeta_prop != nullptr);
+template <typename Hasher>
+static std::pair<size_t, bool> verify_vbmeta_digest(const AvbSlotVerifyData& verify_data,
+                                                    const uint8_t* expected_digest) {
+    size_t total_size = 0;
+    Hasher hasher;
+    for (size_t n = 0; n < verify_data.num_vbmeta_images; n++) {
+        hasher.update(verify_data.vbmeta_images[n].vbmeta_data,
+                      verify_data.vbmeta_images[n].vbmeta_size);
+        total_size += verify_data.vbmeta_images[n].vbmeta_size;
+    }
 
+    bool matched = (memcmp(hasher.finalize(), expected_digest, Hasher::DIGEST_SIZE) == 0);
+
+    return std::make_pair(total_size, matched);
+}
+
+// Reads the following values from kernel cmdline and provides the
+// VerifyVbmetaImages() to verify AvbSlotVerifyData.
+//   - androidboot.vbmeta.device_state
+//   - androidboot.vbmeta.hash_alg
+//   - androidboot.vbmeta.size
+//   - androidboot.vbmeta.digest
+class FsManagerAvbVerifier {
+  public:
+    // The factory method to return a unique_ptr<FsManagerAvbVerifier>
+    static std::unique_ptr<FsManagerAvbVerifier> Create();
+    bool VerifyVbmetaImages(const AvbSlotVerifyData& verify_data);
+    bool IsDeviceUnlocked() { return is_device_unlocked_; }
+
+  protected:
+    FsManagerAvbVerifier() = default;
+
+  private:
+    enum HashAlgorithm {
+        kInvalid = 0,
+        kSHA256 = 1,
+        kSHA512 = 2,
+    };
+
+    HashAlgorithm hash_alg_;
+    uint8_t digest_[SHA512_DIGEST_LENGTH];
+    size_t vbmeta_size_;
+    bool is_device_unlocked_;
+};
+
+std::unique_ptr<FsManagerAvbVerifier> FsManagerAvbVerifier::Create() {
     std::string cmdline;
-    android::base::ReadFileToString("/proc/cmdline", &cmdline);
+    if (!android::base::ReadFileToString("/proc/cmdline", &cmdline)) {
+        PERROR << "Failed to read /proc/cmdline";
+        return nullptr;
+    }
 
-    std::string hash_alg;
+    std::unique_ptr<FsManagerAvbVerifier> avb_verifier(new FsManagerAvbVerifier());
+    if (!avb_verifier) {
+        LERROR << "Failed to create unique_ptr<FsManagerAvbVerifier>";
+        return nullptr;
+    }
+
     std::string digest;
-
+    std::string hash_alg;
     for (const auto& entry : android::base::Split(android::base::Trim(cmdline), " ")) {
         std::vector<std::string> pieces = android::base::Split(entry, "=");
         const std::string& key = pieces[0];
         const std::string& value = pieces[1];
 
         if (key == "androidboot.vbmeta.device_state") {
-            vbmeta_prop->allow_verification_error = (value == "unlocked");
+            avb_verifier->is_device_unlocked_ = (value == "unlocked");
         } else if (key == "androidboot.vbmeta.hash_alg") {
             hash_alg = value;
         } else if (key == "androidboot.vbmeta.size") {
-            if (!android::base::ParseUint(value.c_str(), &vbmeta_prop->vbmeta_size)) {
-                return false;
+            if (!android::base::ParseUint(value.c_str(), &avb_verifier->vbmeta_size_)) {
+                return nullptr;
             }
         } else if (key == "androidboot.vbmeta.digest") {
             digest = value;
@@ -190,48 +224,31 @@
     size_t expected_digest_size = 0;
     if (hash_alg == "sha256") {
         expected_digest_size = SHA256_DIGEST_LENGTH * 2;
-        vbmeta_prop->hash_alg = kSHA256;
+        avb_verifier->hash_alg_ = kSHA256;
     } else if (hash_alg == "sha512") {
         expected_digest_size = SHA512_DIGEST_LENGTH * 2;
-        vbmeta_prop->hash_alg = kSHA512;
+        avb_verifier->hash_alg_ = kSHA512;
     } else {
         LERROR << "Unknown hash algorithm: " << hash_alg.c_str();
-        return false;
+        return nullptr;
     }
 
     // Reads digest.
     if (digest.size() != expected_digest_size) {
         LERROR << "Unexpected digest size: " << digest.size()
                << " (expected: " << expected_digest_size << ")";
-        return false;
+        return nullptr;
     }
 
-    if (!hex_to_bytes(vbmeta_prop->digest, sizeof(vbmeta_prop->digest), digest)) {
+    if (!hex_to_bytes(avb_verifier->digest_, sizeof(avb_verifier->digest_), digest)) {
         LERROR << "Hash digest contains non-hexidecimal character: " << digest.c_str();
-        return false;
+        return nullptr;
     }
 
-    return true;
+    return avb_verifier;
 }
 
-template <typename Hasher>
-static std::pair<size_t, bool> verify_vbmeta_digest(const AvbSlotVerifyData& verify_data,
-                                                    const androidboot_vbmeta& vbmeta_prop) {
-    size_t total_size = 0;
-    Hasher hasher;
-    for (size_t n = 0; n < verify_data.num_vbmeta_images; n++) {
-        hasher.update(verify_data.vbmeta_images[n].vbmeta_data,
-                      verify_data.vbmeta_images[n].vbmeta_size);
-        total_size += verify_data.vbmeta_images[n].vbmeta_size;
-    }
-
-    bool matched = (memcmp(hasher.finalize(), vbmeta_prop.digest, Hasher::DIGEST_SIZE) == 0);
-
-    return std::make_pair(total_size, matched);
-}
-
-static bool verify_vbmeta_images(const AvbSlotVerifyData& verify_data,
-                                 const androidboot_vbmeta& vbmeta_prop) {
+bool FsManagerAvbVerifier::VerifyVbmetaImages(const AvbSlotVerifyData& verify_data) {
     if (verify_data.num_vbmeta_images == 0) {
         LERROR << "No vbmeta images";
         return false;
@@ -240,17 +257,17 @@
     size_t total_size = 0;
     bool digest_matched = false;
 
-    if (vbmeta_prop.hash_alg == kSHA256) {
+    if (hash_alg_ == kSHA256) {
         std::tie(total_size, digest_matched) =
-            verify_vbmeta_digest<SHA256Hasher>(verify_data, vbmeta_prop);
-    } else if (vbmeta_prop.hash_alg == kSHA512) {
+            verify_vbmeta_digest<SHA256Hasher>(verify_data, digest_);
+    } else if (hash_alg_ == kSHA512) {
         std::tie(total_size, digest_matched) =
-            verify_vbmeta_digest<SHA512Hasher>(verify_data, vbmeta_prop);
+            verify_vbmeta_digest<SHA512Hasher>(verify_data, digest_);
     }
 
-    if (total_size != vbmeta_prop.vbmeta_size) {
-        LERROR << "total vbmeta size mismatch: " << total_size
-               << " (expected: " << vbmeta_prop.vbmeta_size << ")";
+    if (total_size != vbmeta_size_) {
+        LERROR << "total vbmeta size mismatch: " << total_size << " (expected: " << vbmeta_size_
+               << ")";
         return false;
     }
 
@@ -319,7 +336,8 @@
 
 static bool hashtree_dm_verity_setup(struct fstab_rec* fstab_entry,
                                      const AvbHashtreeDescriptor& hashtree_desc,
-                                     const std::string& salt, const std::string& root_digest) {
+                                     const std::string& salt, const std::string& root_digest,
+                                     bool wait_for_verity_dev) {
     // Gets the device mapper fd.
     android::base::unique_fd fd(open("/dev/device-mapper", O_RDWR));
     if (fd < 0) {
@@ -358,13 +376,12 @@
     // Marks the underlying block device as read-only.
     fs_mgr_set_blk_ro(fstab_entry->blk_device);
 
-    // TODO(bowgotsai): support verified all partition at boot.
     // Updates fstab_rec->blk_device to verity device name.
     free(fstab_entry->blk_device);
     fstab_entry->blk_device = strdup(verity_blk_name.c_str());
 
     // Makes sure we've set everything up properly.
-    if (fs_mgr_test_access(verity_blk_name.c_str()) < 0) {
+    if (wait_for_verity_dev && fs_mgr_test_access(verity_blk_name.c_str()) < 0) {
         return false;
     }
 
@@ -390,10 +407,12 @@
             continue;
         }
 
-        // Ensures that hashtree descriptor is either in /vbmeta or in
+        // Ensures that hashtree descriptor is in /vbmeta or /boot or in
         // the same partition for verity setup.
         std::string vbmeta_partition_name(verify_data.vbmeta_images[i].partition_name);
-        if (vbmeta_partition_name != "vbmeta" && vbmeta_partition_name != partition_name) {
+        if (vbmeta_partition_name != "vbmeta" &&
+            vbmeta_partition_name != "boot" &&  // for legacy device to append top-level vbmeta
+            vbmeta_partition_name != partition_name) {
             LWARNING << "Skip vbmeta image at " << verify_data.vbmeta_images[i].partition_name
                      << " for partition: " << partition_name.c_str();
             continue;
@@ -406,8 +425,7 @@
                 continue;
             }
             if (desc.tag == AVB_DESCRIPTOR_TAG_HASHTREE) {
-                desc_partition_name =
-                    (const uint8_t*)descriptors[j] + sizeof(AvbHashtreeDescriptor);
+                desc_partition_name = (const uint8_t*)descriptors[j] + sizeof(AvbHashtreeDescriptor);
                 if (!avb_hashtree_descriptor_validate_and_byteswap(
                         (AvbHashtreeDescriptor*)descriptors[j], out_hashtree_desc)) {
                     continue;
@@ -439,134 +457,101 @@
     return true;
 }
 
-static bool init_is_avb_used() {
-    // When AVB is used, boot loader should set androidboot.vbmeta.{hash_alg,
-    // size, digest} in kernel cmdline or in device tree. They will then be
-    // imported by init process to system properties: ro.boot.vbmeta.{hash_alg, size, digest}.
-    //
-    // In case of early mount, init properties are not initialized, so we also
-    // ensure we look into kernel command line and device tree if the property is
-    // not found
-    //
-    // Checks hash_alg as an indicator for whether AVB is used.
-    // We don't have to parse and check all of them here. The check will
-    // be done in fs_mgr_load_vbmeta_images() and FS_MGR_SETUP_AVB_FAIL will
-    // be returned when there is an error.
-
-    std::string hash_alg;
-    if (fs_mgr_get_boot_config("vbmeta.hash_alg", &hash_alg) == 0) {
-        if (hash_alg == "sha256" || hash_alg == "sha512") {
-            return true;
-        }
+FsManagerAvbUniquePtr FsManagerAvbHandle::Open(const std::string& device_file_by_name_prefix) {
+    if (device_file_by_name_prefix.empty()) {
+        LERROR << "Missing device file by-name prefix";
+        return nullptr;
     }
 
-    return false;
-}
-
-bool fs_mgr_is_avb_used() {
-    static bool result = init_is_avb_used();
-    return result;
-}
-
-int fs_mgr_load_vbmeta_images(struct fstab* fstab) {
-    FS_MGR_CHECK(fstab != nullptr);
-
-    // Gets the expected hash value of vbmeta images from
-    // kernel cmdline.
-    if (!load_vbmeta_prop(&fs_mgr_vbmeta_prop)) {
-        return FS_MGR_SETUP_AVB_FAIL;
+    // Gets the expected hash value of vbmeta images from kernel cmdline.
+    std::unique_ptr<FsManagerAvbVerifier> avb_verifier = FsManagerAvbVerifier::Create();
+    if (!avb_verifier) {
+        LERROR << "Failed to create FsManagerAvbVerifier";
+        return nullptr;
     }
 
-    fs_mgr_avb_ops = fs_mgr_dummy_avb_ops_new(fstab);
-    if (fs_mgr_avb_ops == nullptr) {
-        LERROR << "Failed to allocate dummy avb_ops";
-        return FS_MGR_SETUP_AVB_FAIL;
+    FsManagerAvbUniquePtr avb_handle(new FsManagerAvbHandle());
+    if (!avb_handle) {
+        LERROR << "Failed to allocate FsManagerAvbHandle";
+        return nullptr;
     }
 
-    // Invokes avb_slot_verify() to load and verify all vbmeta images.
-    // Sets requested_partitions to nullptr as it's to copy the contents
-    // of HASH partitions into fs_mgr_avb_verify_data, which is not required as
-    // fs_mgr only deals with HASHTREE partitions.
-    const char *requested_partitions[] = {nullptr};
-    std::string ab_suffix;
-    fs_mgr_get_boot_config("slot_suffix", &ab_suffix);
-    AvbSlotVerifyResult verify_result =
-        avb_slot_verify(fs_mgr_avb_ops, requested_partitions, ab_suffix.c_str(),
-                        fs_mgr_vbmeta_prop.allow_verification_error, &fs_mgr_avb_verify_data);
+    FsManagerAvbOps avb_ops(device_file_by_name_prefix);
+    AvbSlotVerifyResult verify_result = avb_ops.AvbSlotVerify(
+        fs_mgr_get_slot_suffix(), avb_verifier->IsDeviceUnlocked(), &avb_handle->avb_slot_data_);
 
     // Only allow two verify results:
     //   - AVB_SLOT_VERIFY_RESULT_OK.
     //   - AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION (for UNLOCKED state).
     if (verify_result == AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION) {
-        if (!fs_mgr_vbmeta_prop.allow_verification_error) {
+        if (!avb_verifier->IsDeviceUnlocked()) {
             LERROR << "ERROR_VERIFICATION isn't allowed";
-            goto fail;
+            return nullptr;
         }
     } else if (verify_result != AVB_SLOT_VERIFY_RESULT_OK) {
         LERROR << "avb_slot_verify failed, result: " << verify_result;
-        goto fail;
+        return nullptr;
     }
 
+    // Sets the MAJOR.MINOR for init to set it into "ro.boot.avb_version".
+    avb_handle->avb_version_ =
+        android::base::StringPrintf("%d.%d", AVB_VERSION_MAJOR, AVB_VERSION_MINOR);
+
     // Verifies vbmeta images against the digest passed from bootloader.
-    if (!verify_vbmeta_images(*fs_mgr_avb_verify_data, fs_mgr_vbmeta_prop)) {
-        LERROR << "verify_vbmeta_images failed";
-        goto fail;
+    if (!avb_verifier->VerifyVbmetaImages(*avb_handle->avb_slot_data_)) {
+        LERROR << "VerifyVbmetaImages failed";
+        return nullptr;
     } else {
         // Checks whether FLAGS_HASHTREE_DISABLED is set.
         AvbVBMetaImageHeader vbmeta_header;
         avb_vbmeta_image_header_to_host_byte_order(
-            (AvbVBMetaImageHeader*)fs_mgr_avb_verify_data->vbmeta_images[0].vbmeta_data,
+            (AvbVBMetaImageHeader*)avb_handle->avb_slot_data_->vbmeta_images[0].vbmeta_data,
             &vbmeta_header);
 
         bool hashtree_disabled =
             ((AvbVBMetaImageFlags)vbmeta_header.flags & AVB_VBMETA_IMAGE_FLAGS_HASHTREE_DISABLED);
         if (hashtree_disabled) {
-            return FS_MGR_SETUP_AVB_HASHTREE_DISABLED;
+            avb_handle->status_ = kFsManagerAvbHandleHashtreeDisabled;
+            return avb_handle;
         }
     }
 
     if (verify_result == AVB_SLOT_VERIFY_RESULT_OK) {
-        return FS_MGR_SETUP_AVB_SUCCESS;
+        avb_handle->status_ = kFsManagerAvbHandleSuccess;
+        return avb_handle;
     }
-
-fail:
-    fs_mgr_unload_vbmeta_images();
-    return FS_MGR_SETUP_AVB_FAIL;
+    return nullptr;
 }
 
-void fs_mgr_unload_vbmeta_images() {
-    if (fs_mgr_avb_verify_data != nullptr) {
-        avb_slot_verify_data_free(fs_mgr_avb_verify_data);
+bool FsManagerAvbHandle::SetUpAvb(struct fstab_rec* fstab_entry, bool wait_for_verity_dev) {
+    if (!fstab_entry) return false;
+    if (!avb_slot_data_ || avb_slot_data_->num_vbmeta_images < 1) {
+        return false;
     }
-
-    if (fs_mgr_avb_ops != nullptr) {
-        fs_mgr_dummy_avb_ops_free(fs_mgr_avb_ops);
+    if (status_ == kFsManagerAvbHandleHashtreeDisabled) {
+        LINFO << "AVB HASHTREE disabled on:" << fstab_entry->mount_point;
+        return true;
     }
-}
-
-int fs_mgr_setup_avb(struct fstab_rec* fstab_entry) {
-    if (!fstab_entry || !fs_mgr_avb_verify_data || fs_mgr_avb_verify_data->num_vbmeta_images < 1) {
-        return FS_MGR_SETUP_AVB_FAIL;
-    }
+    if (status_ != kFsManagerAvbHandleSuccess) return false;
 
     std::string partition_name(basename(fstab_entry->mount_point));
     if (!avb_validate_utf8((const uint8_t*)partition_name.c_str(), partition_name.length())) {
         LERROR << "Partition name: " << partition_name.c_str() << " is not valid UTF-8.";
-        return FS_MGR_SETUP_AVB_FAIL;
+        return false;
     }
 
     AvbHashtreeDescriptor hashtree_descriptor;
     std::string salt;
     std::string root_digest;
-    if (!get_hashtree_descriptor(partition_name, *fs_mgr_avb_verify_data, &hashtree_descriptor,
-                                 &salt, &root_digest)) {
-        return FS_MGR_SETUP_AVB_FAIL;
+    if (!get_hashtree_descriptor(partition_name, *avb_slot_data_, &hashtree_descriptor, &salt,
+                                 &root_digest)) {
+        return false;
     }
 
     // Converts HASHTREE descriptor to verity_table_params.
-    if (!hashtree_dm_verity_setup(fstab_entry, hashtree_descriptor, salt, root_digest)) {
-        return FS_MGR_SETUP_AVB_FAIL;
+    if (!hashtree_dm_verity_setup(fstab_entry, hashtree_descriptor, salt, root_digest,
+                                  wait_for_verity_dev)) {
+        return false;
     }
-
-    return FS_MGR_SETUP_AVB_SUCCESS;
+    return true;
 }
diff --git a/fs_mgr/fs_mgr_avb_ops.cpp b/fs_mgr/fs_mgr_avb_ops.cpp
index dd8c7e7..caee4ec 100644
--- a/fs_mgr/fs_mgr_avb_ops.cpp
+++ b/fs_mgr/fs_mgr_avb_ops.cpp
@@ -39,86 +39,10 @@
 #include "fs_mgr_avb_ops.h"
 #include "fs_mgr_priv.h"
 
-static struct fstab* fs_mgr_fstab = nullptr;
-
-static AvbIOResult read_from_partition(AvbOps* ops ATTRIBUTE_UNUSED, const char* partition,
-                                       int64_t offset, size_t num_bytes, void* buffer,
-                                       size_t* out_num_read) {
-    // The input |partition| name is with ab_suffix, e.g. system_a.
-    // Slot suffix (e.g. _a) will be appended to the device file path
-    // for partitions having 'slotselect' optin in fstab file, but it
-    // won't be appended to the mount point.
-    //
-    // In AVB, we can assume that there's an entry for the /misc mount
-    // point and use that to get the device file for the misc partition.
-    // From there we'll assume that a by-name scheme is used
-    // so we can just replace the trailing "misc" by the given
-    // |partition|, e.g.
-    //
-    //    - /dev/block/platform/soc.0/7824900.sdhci/by-name/misc ->
-    //    - /dev/block/platform/soc.0/7824900.sdhci/by-name/system_a
-
-    struct fstab_rec* fstab_entry = fs_mgr_get_entry_for_mount_point(fs_mgr_fstab, "/misc");
-
-    if (fstab_entry == nullptr) {
-        LERROR << "/misc mount point not found in fstab";
-        return AVB_IO_RESULT_ERROR_IO;
-    }
-
-    std::string partition_name(partition);
-    std::string path(fstab_entry->blk_device);
-    // Replaces the last field of device file if it's not misc.
-    if (!android::base::StartsWith(partition_name, "misc")) {
-        size_t end_slash = path.find_last_of("/");
-        std::string by_name_prefix(path.substr(0, end_slash + 1));
-        path = by_name_prefix + partition_name;
-    }
-
-    // Ensures the device path (a symlink created by init) is ready to
-    // access. fs_mgr_test_access() will test a few iterations if the
-    // path doesn't exist yet.
-    if (fs_mgr_test_access(path.c_str()) < 0) {
-        return AVB_IO_RESULT_ERROR_IO;
-    }
-
-    android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
-
-    if (fd < 0) {
-        PERROR << "Failed to open " << path.c_str();
-        return AVB_IO_RESULT_ERROR_IO;
-    }
-
-    // If offset is negative, interprets its absolute value as the
-    //  number of bytes from the end of the partition.
-    if (offset < 0) {
-        off64_t total_size = lseek64(fd, 0, SEEK_END);
-        if (total_size == -1) {
-            LERROR << "Failed to lseek64 to end of the partition";
-            return AVB_IO_RESULT_ERROR_IO;
-        }
-        offset = total_size + offset;
-        // Repositions the offset to the beginning.
-        if (lseek64(fd, 0, SEEK_SET) == -1) {
-            LERROR << "Failed to lseek64 to the beginning of the partition";
-            return AVB_IO_RESULT_ERROR_IO;
-        }
-    }
-
-    // On Linux, we never get partial reads from block devices (except
-    // for EOF).
-    ssize_t num_read = TEMP_FAILURE_RETRY(pread64(fd, buffer, num_bytes, offset));
-
-    if (num_read < 0 || (size_t)num_read != num_bytes) {
-        PERROR << "Failed to read " << num_bytes << " bytes from " << path.c_str() << " offset "
-               << offset;
-        return AVB_IO_RESULT_ERROR_IO;
-    }
-
-    if (out_num_read != nullptr) {
-        *out_num_read = num_read;
-    }
-
-    return AVB_IO_RESULT_OK;
+static AvbIOResult read_from_partition(AvbOps* ops, const char* partition, int64_t offset,
+                                       size_t num_bytes, void* buffer, size_t* out_num_read) {
+    return FsManagerAvbOps::GetInstanceFromAvbOps(ops)->ReadFromPartition(
+        partition, offset, num_bytes, buffer, out_num_read);
 }
 
 static AvbIOResult dummy_read_rollback_index(AvbOps* ops ATTRIBUTE_UNUSED,
@@ -140,7 +64,6 @@
     // Addtionally, user-space should check
     // androidboot.vbmeta.{hash_alg, size, digest} against the digest
     // of all vbmeta images after invoking avb_slot_verify().
-
     *out_is_trusted = true;
     return AVB_IO_RESULT_OK;
 }
@@ -165,28 +88,88 @@
     return AVB_IO_RESULT_OK;
 }
 
-AvbOps* fs_mgr_dummy_avb_ops_new(struct fstab* fstab) {
-    AvbOps* ops;
-
-    // Assigns the fstab to the static variable for later use.
-    fs_mgr_fstab = fstab;
-
-    ops = (AvbOps*)calloc(1, sizeof(AvbOps));
-    if (ops == nullptr) {
-        LERROR << "Error allocating memory for AvbOps";
-        return nullptr;
+FsManagerAvbOps::FsManagerAvbOps(const std::string& device_file_by_name_prefix)
+    : device_file_by_name_prefix_(device_file_by_name_prefix) {
+    if (device_file_by_name_prefix_.back() != '/') {
+        device_file_by_name_prefix_ += '/';
     }
+    // We only need to provide the implementation of read_from_partition()
+    // operation since that's all what is being used by the avb_slot_verify().
+    // Other I/O operations are only required in bootloader but not in
+    // user-space so we set them as dummy operations. Also zero the entire
+    // struct so operations added in the future will be set to NULL.
+    memset(&avb_ops_, 0, sizeof(AvbOps));
+    avb_ops_.read_from_partition = read_from_partition;
+    avb_ops_.read_rollback_index = dummy_read_rollback_index;
+    avb_ops_.validate_vbmeta_public_key = dummy_validate_vbmeta_public_key;
+    avb_ops_.read_is_device_unlocked = dummy_read_is_device_unlocked;
+    avb_ops_.get_unique_guid_for_partition = dummy_get_unique_guid_for_partition;
 
-    // We only need these operations since that's all what is being used
-    // by the avb_slot_verify(); Most of them are dummy operations because
-    // they're only required in bootloader but not required in user-space.
-    ops->read_from_partition = read_from_partition;
-    ops->read_rollback_index = dummy_read_rollback_index;
-    ops->validate_vbmeta_public_key = dummy_validate_vbmeta_public_key;
-    ops->read_is_device_unlocked = dummy_read_is_device_unlocked;
-    ops->get_unique_guid_for_partition = dummy_get_unique_guid_for_partition;
-
-    return ops;
+    // Sets user_data for GetInstanceFromAvbOps() to convert it back to FsManagerAvbOps.
+    avb_ops_.user_data = this;
 }
 
-void fs_mgr_dummy_avb_ops_free(AvbOps* ops) { free(ops); }
+AvbIOResult FsManagerAvbOps::ReadFromPartition(const char* partition, int64_t offset,
+                                               size_t num_bytes, void* buffer,
+                                               size_t* out_num_read) {
+    // Appends |partition| to the device_file_by_name_prefix_, e.g.,
+    //    - /dev/block/platform/soc.0/7824900.sdhci/by-name/ ->
+    //    - /dev/block/platform/soc.0/7824900.sdhci/by-name/system_a
+    std::string path = device_file_by_name_prefix_ + partition;
+
+    // Ensures the device path (a symlink created by init) is ready to
+    // access. fs_mgr_test_access() will test a few iterations if the
+    // path doesn't exist yet.
+    if (fs_mgr_test_access(path.c_str()) < 0) {
+        return AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION;
+    }
+
+    android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
+    if (fd < 0) {
+        PERROR << "Failed to open " << path.c_str();
+        return AVB_IO_RESULT_ERROR_IO;
+    }
+
+    // If offset is negative, interprets its absolute value as the
+    //  number of bytes from the end of the partition.
+    if (offset < 0) {
+        off64_t total_size = lseek64(fd, 0, SEEK_END);
+        if (total_size == -1) {
+            PERROR << "Failed to lseek64 to end of the partition";
+            return AVB_IO_RESULT_ERROR_IO;
+        }
+        offset = total_size + offset;
+        // Repositions the offset to the beginning.
+        if (lseek64(fd, 0, SEEK_SET) == -1) {
+            PERROR << "Failed to lseek64 to the beginning of the partition";
+            return AVB_IO_RESULT_ERROR_IO;
+        }
+    }
+
+    // On Linux, we never get partial reads from block devices (except
+    // for EOF).
+    ssize_t num_read = TEMP_FAILURE_RETRY(pread64(fd, buffer, num_bytes, offset));
+    if (num_read < 0 || (size_t)num_read != num_bytes) {
+        PERROR << "Failed to read " << num_bytes << " bytes from " << path.c_str() << " offset "
+               << offset;
+        return AVB_IO_RESULT_ERROR_IO;
+    }
+
+    if (out_num_read != nullptr) {
+        *out_num_read = num_read;
+    }
+
+    return AVB_IO_RESULT_OK;
+}
+
+AvbSlotVerifyResult FsManagerAvbOps::AvbSlotVerify(const std::string& ab_suffix,
+                                                   bool allow_verification_error,
+                                                   AvbSlotVerifyData** out_data) {
+    // Invokes avb_slot_verify() to load and verify all vbmeta images.
+    // Sets requested_partitions to nullptr as it's to copy the contents
+    // of HASH partitions into handle>avb_slot_data_, which is not required as
+    // fs_mgr only deals with HASHTREE partitions.
+    const char* requested_partitions[] = {nullptr};
+    return avb_slot_verify(&avb_ops_, requested_partitions, ab_suffix.c_str(),
+                           allow_verification_error, out_data);
+}
diff --git a/fs_mgr/fs_mgr_avb_ops.h b/fs_mgr/fs_mgr_avb_ops.h
index bfdec9a..ec4a8c9 100644
--- a/fs_mgr/fs_mgr_avb_ops.h
+++ b/fs_mgr/fs_mgr_avb_ops.h
@@ -29,31 +29,34 @@
 
 #include "fs_mgr.h"
 
-__BEGIN_DECLS
+// This class provides C++ bindings to interact with libavb, a small
+// self-contained piece of code that's intended to be used in bootloaders.
+// It mainly contains two functions:
+//   - ReadFromPartition(): to read AVB metadata from a given partition.
+//     It provides the implementation of AvbOps.read_from_partition() when
+//     reading metadata through libavb.
+//   - AvbSlotVerify(): the C++ binding of libavb->avb_slot_verify() to
+//     read and verify the metadata and store it into the out_data parameter.
+//     The caller MUST check the integrity of metadata against the
+//     androidboot.vbmeta.{hash_alg, size, digest} values from /proc/cmdline.
+//     e.g., see class FsManagerAvbVerifier for more details.
+//
+class FsManagerAvbOps {
+  public:
+    FsManagerAvbOps(const std::string& device_file_by_name_prefix);
 
-/* Allocates a "dummy" AvbOps instance solely for use in user-space.
- * Returns nullptr on OOM.
- *
- * It mainly provides read_from_partitions() for user-space to get
- * AvbSlotVerifyData.vbmeta_images[] and the caller MUST check their
- * integrity against the androidboot.vbmeta.{hash_alg, size, digest}
- * values from /proc/cmdline, e.g. verify_vbmeta_images()
- * in fs_mgr_avb.cpp.
- *
- * Other I/O operations are only required in boot loader so we set
- * them as dummy operations here.
- *  - Will allow any public key for signing.
- *  - returns 0 for any rollback index location.
- *  - returns device is unlocked regardless of the actual state.
- *  - returns a dummy guid for any partition.
- *
- * Frees with fs_mgr_dummy_avb_ops_free().
- */
-AvbOps* fs_mgr_dummy_avb_ops_new(struct fstab* fstab);
+    static FsManagerAvbOps* GetInstanceFromAvbOps(AvbOps* ops) {
+        return reinterpret_cast<FsManagerAvbOps*>(ops->user_data);
+    }
 
-/* Frees an AvbOps instance previously allocated with fs_mgr_avb_ops_new(). */
-void fs_mgr_dummy_avb_ops_free(AvbOps* ops);
+    AvbIOResult ReadFromPartition(const char* partition, int64_t offset, size_t num_bytes,
+                                  void* buffer, size_t* out_num_read);
 
-__END_DECLS
+    AvbSlotVerifyResult AvbSlotVerify(const std::string& ab_suffix, bool allow_verification_error,
+                                      AvbSlotVerifyData** out_data);
 
+  private:
+    AvbOps avb_ops_;
+    std::string device_file_by_name_prefix_;
+};
 #endif /* __CORE_FS_MGR_AVB_OPS_H */
diff --git a/fs_mgr/fs_mgr_boot_config.cpp b/fs_mgr/fs_mgr_boot_config.cpp
index 5b2f218..ab5beed 100644
--- a/fs_mgr/fs_mgr_boot_config.cpp
+++ b/fs_mgr/fs_mgr_boot_config.cpp
@@ -55,8 +55,6 @@
         if (android::base::ReadFileToString(file_name, out_val)) {
             return true;
         }
-
-        LERROR << "Error finding '" << key << "' in device tree";
     }
 
     return false;
diff --git a/fs_mgr/fs_mgr_fstab.cpp b/fs_mgr/fs_mgr_fstab.cpp
index a4f88ba..dc73c24 100644
--- a/fs_mgr/fs_mgr_fstab.cpp
+++ b/fs_mgr/fs_mgr_fstab.cpp
@@ -526,7 +526,7 @@
         cnt++;
     }
     /* If an A/B partition, modify block device to be the real block device */
-    if (fs_mgr_update_for_slotselect(fstab) != 0) {
+    if (!fs_mgr_update_for_slotselect(fstab)) {
         LERROR << "Error updating for slotselect";
         goto err;
     }
@@ -625,17 +625,6 @@
     return fstab;
 }
 
-/* combines fstab entries passed in from device tree with
- * the ones found from fstab_path
- */
-struct fstab *fs_mgr_read_fstab_with_dt(const char *fstab_path)
-{
-    struct fstab *fstab_dt = fs_mgr_read_fstab_dt();
-    struct fstab *fstab = fs_mgr_read_fstab(fstab_path);
-
-    return in_place_merge(fstab_dt, fstab);
-}
-
 /*
  * tries to load default fstab.<hardware> file from /odm/etc, /vendor/etc
  * or /. loads the first one found and also combines fstab entries passed
@@ -646,7 +635,10 @@
     std::string hw;
     std::string default_fstab;
 
-    if (fs_mgr_get_boot_config("hardware", &hw)) {
+    // Use different fstab paths for normal boot and recovery boot, respectively
+    if (access("/sbin/recovery", F_OK) == 0) {
+        default_fstab = "/etc/recovery.fstab";
+    } else if (fs_mgr_get_boot_config("hardware", &hw)) {  // normal boot
         for (const char *prefix : {"/odm/etc/fstab.","/vendor/etc/fstab.", "/fstab."}) {
             default_fstab = prefix + hw;
             if (access(default_fstab.c_str(), F_OK) == 0) break;
@@ -655,7 +647,12 @@
         LWARNING << __FUNCTION__ << "(): failed to find device hardware name";
     }
 
-    return fs_mgr_read_fstab_with_dt(default_fstab.c_str());
+    // 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);
 }
 
 void fs_mgr_free_fstab(struct fstab *fstab)
@@ -771,6 +768,11 @@
     return fstab->fs_mgr_flags & MF_VERIFY;
 }
 
+int fs_mgr_is_avb(const struct fstab_rec *fstab)
+{
+    return fstab->fs_mgr_flags & MF_AVB;
+}
+
 int fs_mgr_is_verifyatboot(const struct fstab_rec *fstab)
 {
     return fstab->fs_mgr_flags & MF_VERIFYATBOOT;
diff --git a/fs_mgr/fs_mgr_priv.h b/fs_mgr/fs_mgr_priv.h
index 377d2ec..c985462 100644
--- a/fs_mgr/fs_mgr_priv.h
+++ b/fs_mgr/fs_mgr_priv.h
@@ -41,8 +41,6 @@
 #define PWARNING PLOG(WARNING) << FS_MGR_TAG
 #define PERROR   PLOG(ERROR) << FS_MGR_TAG
 
-__BEGIN_DECLS
-
 #define CRYPTO_TMPFS_OPTIONS "size=256m,mode=0771,uid=1000,gid=1000"
 
 #define WAIT_TIMEOUT 20
@@ -114,10 +112,9 @@
 
 int fs_mgr_set_blk_ro(const char *blockdev);
 int fs_mgr_test_access(const char *device);
-int fs_mgr_update_for_slotselect(struct fstab *fstab);
+bool fs_mgr_update_for_slotselect(struct fstab *fstab);
 bool is_dt_compatible();
 bool is_device_secure();
-
-__END_DECLS
+int load_verity_state(struct fstab_rec* fstab, int* mode);
 
 #endif /* __CORE_FS_MGR_PRIV_H */
diff --git a/fs_mgr/fs_mgr_priv_avb.h b/fs_mgr/fs_mgr_priv_avb.h
deleted file mode 100644
index dce9f61..0000000
--- a/fs_mgr/fs_mgr_priv_avb.h
+++ /dev/null
@@ -1,56 +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 __CORE_FS_MGR_PRIV_AVB_H
-#define __CORE_FS_MGR_PRIV_AVB_H
-
-#ifndef __cplusplus
-#include <stdbool.h>
-#endif
-
-#include "fs_mgr.h"
-
-__BEGIN_DECLS
-
-#define FS_MGR_SETUP_AVB_HASHTREE_DISABLED (-2)
-#define FS_MGR_SETUP_AVB_FAIL (-1)
-#define FS_MGR_SETUP_AVB_SUCCESS 0
-
-bool fs_mgr_is_avb_used();
-
-/* Gets AVB metadata through external/avb/libavb for all partitions:
- * AvbSlotVerifyData.vbmeta_images[] and checks their integrity
- * against the androidboot.vbmeta.{hash_alg, size, digest} values
- * from /proc/cmdline.
- *
- * Return values:
- *   - FS_MGR_SETUP_AVB_SUCCESS: the metadata cab be trusted.
- *   - FS_MGR_SETUP_AVB_FAIL: any error when reading and verifying the
- *     metadata, e.g. I/O error, digest value mismatch, size mismatch.
- *   - FS_MGR_SETUP_AVB_HASHTREE_DISABLED: to support the existing
- *     'adb disable-verity' feature in Android. It's very helpful for
- *     developers to make the filesystem writable to allow replacing
- *     binaries on the device.
- */
-int fs_mgr_load_vbmeta_images(struct fstab* fstab);
-
-void fs_mgr_unload_vbmeta_images();
-
-int fs_mgr_setup_avb(struct fstab_rec* fstab_entry);
-
-__END_DECLS
-
-#endif /* __CORE_FS_MGR_PRIV_AVB_H */
diff --git a/fs_mgr/fs_mgr_priv_sha.h b/fs_mgr/fs_mgr_priv_sha.h
index 882411b..5b53eea 100644
--- a/fs_mgr/fs_mgr_priv_sha.h
+++ b/fs_mgr/fs_mgr_priv_sha.h
@@ -20,16 +20,18 @@
 #include <openssl/sha.h>
 
 class SHA256Hasher {
-   private:
+  private:
     SHA256_CTX sha256_ctx;
     uint8_t hash[SHA256_DIGEST_LENGTH];
 
-   public:
+  public:
     enum { DIGEST_SIZE = SHA256_DIGEST_LENGTH };
 
     SHA256Hasher() { SHA256_Init(&sha256_ctx); }
 
-    void update(const void* data, size_t data_size) { SHA256_Update(&sha256_ctx, data, data_size); }
+    void update(const uint8_t* data, size_t data_size) {
+        SHA256_Update(&sha256_ctx, data, data_size);
+    }
 
     const uint8_t* finalize() {
         SHA256_Final(hash, &sha256_ctx);
@@ -38,11 +40,11 @@
 };
 
 class SHA512Hasher {
-   private:
+  private:
     SHA512_CTX sha512_ctx;
     uint8_t hash[SHA512_DIGEST_LENGTH];
 
-   public:
+  public:
     enum { DIGEST_SIZE = SHA512_DIGEST_LENGTH };
 
     SHA512Hasher() { SHA512_Init(&sha512_ctx); }
diff --git a/fs_mgr/fs_mgr_slotselect.cpp b/fs_mgr/fs_mgr_slotselect.cpp
index f3bba7b..9ca15e2 100644
--- a/fs_mgr/fs_mgr_slotselect.cpp
+++ b/fs_mgr/fs_mgr_slotselect.cpp
@@ -16,35 +16,47 @@
 
 #include <stdio.h>
 
+#include <string>
+
 #include "fs_mgr.h"
 #include "fs_mgr_priv.h"
 
-// Updates |fstab| for slot_suffix. Returns 0 on success, -1 on error.
-int fs_mgr_update_for_slotselect(struct fstab *fstab)
-{
+// Returns "_a" or "_b" based on two possible values in kernel cmdline:
+//   - androidboot.slot = a or b OR
+//   - androidboot.slot_suffix = _a or _b
+// TODO: remove slot_suffix once it's deprecated.
+std::string fs_mgr_get_slot_suffix() {
+    std::string slot;
+    std::string ab_suffix;
+
+    if (fs_mgr_get_boot_config("slot", &slot)) {
+        ab_suffix = "_" + slot;
+    } else if (!fs_mgr_get_boot_config("slot_suffix", &ab_suffix)) {
+        ab_suffix = "";
+    }
+    return ab_suffix;
+}
+
+// Updates |fstab| for slot_suffix. Returns true on success, false on error.
+bool fs_mgr_update_for_slotselect(struct fstab *fstab) {
     int n;
-    int got_suffix = 0;
-    std::string suffix;
+    std::string ab_suffix;
 
     for (n = 0; n < fstab->num_entries; n++) {
         if (fstab->recs[n].fs_mgr_flags & MF_SLOTSELECT) {
             char *tmp;
-
-            if (!got_suffix) {
-                if (!fs_mgr_get_boot_config("slot_suffix", &suffix)) {
-                  return -1;
-                }
-                got_suffix = 1;
+            if (ab_suffix.empty()) {
+                ab_suffix = fs_mgr_get_slot_suffix();
+                // Returns false as non A/B devices should not have MF_SLOTSELECT.
+                if (ab_suffix.empty()) return false;
             }
-
-            if (asprintf(&tmp, "%s%s", fstab->recs[n].blk_device,
-                         suffix.c_str()) > 0) {
+            if (asprintf(&tmp, "%s%s", fstab->recs[n].blk_device, ab_suffix.c_str()) > 0) {
                 free(fstab->recs[n].blk_device);
                 fstab->recs[n].blk_device = tmp;
             } else {
-                return -1;
+                return false;
             }
         }
     }
-    return 0;
+    return true;
 }
diff --git a/fs_mgr/fs_mgr_verity.cpp b/fs_mgr/fs_mgr_verity.cpp
index 54a6f71..0bf173b 100644
--- a/fs_mgr/fs_mgr_verity.cpp
+++ b/fs_mgr/fs_mgr_verity.cpp
@@ -39,7 +39,6 @@
 #include <openssl/obj_mac.h>
 #include <openssl/rsa.h>
 #include <openssl/sha.h>
-#include <private/android_filesystem_config.h>
 
 #include "fec/io.h"
 
@@ -654,8 +653,7 @@
                 offset);
 }
 
-static int load_verity_state(struct fstab_rec *fstab, int *mode)
-{
+int load_verity_state(struct fstab_rec* fstab, int* mode) {
     int match = 0;
     off64_t offset = 0;
 
@@ -691,129 +689,6 @@
     return read_verity_state(fstab->verity_loc, offset, mode);
 }
 
-int fs_mgr_load_verity_state(int *mode)
-{
-    int rc = -1;
-    int i;
-    int current;
-    struct fstab *fstab = NULL;
-
-    /* return the default mode, unless any of the verified partitions are in
-     * logging mode, in which case return that */
-    *mode = VERITY_MODE_DEFAULT;
-
-    fstab = fs_mgr_read_fstab_default();
-    if (!fstab) {
-        LERROR << "Failed to read default fstab";
-        goto out;
-    }
-
-    for (i = 0; i < fstab->num_entries; i++) {
-        if (!fs_mgr_is_verified(&fstab->recs[i])) {
-            continue;
-        }
-
-        rc = load_verity_state(&fstab->recs[i], &current);
-        if (rc < 0) {
-            continue;
-        }
-
-        if (current != VERITY_MODE_DEFAULT) {
-            *mode = current;
-            break;
-        }
-    }
-
-    rc = 0;
-
-out:
-    if (fstab) {
-        fs_mgr_free_fstab(fstab);
-    }
-
-    return rc;
-}
-
-int fs_mgr_update_verity_state(fs_mgr_verity_state_callback callback)
-{
-    alignas(dm_ioctl) char buffer[DM_BUF_SIZE];
-    bool system_root = false;
-    std::string mount_point;
-    char propbuf[PROPERTY_VALUE_MAX];
-    const char *status;
-    int fd = -1;
-    int i;
-    int mode;
-    int rc = -1;
-    struct dm_ioctl *io = (struct dm_ioctl *) buffer;
-    struct fstab *fstab = NULL;
-
-    if (!callback) {
-        return -1;
-    }
-
-    if (fs_mgr_load_verity_state(&mode) == -1) {
-        return -1;
-    }
-
-    fd = TEMP_FAILURE_RETRY(open("/dev/device-mapper", O_RDWR | O_CLOEXEC));
-    if (fd == -1) {
-        PERROR << "Error opening device mapper";
-        goto out;
-    }
-
-    property_get("ro.build.system_root_image", propbuf, "");
-    system_root = !strcmp(propbuf, "true");
-    fstab = fs_mgr_read_fstab_default();
-    if (!fstab) {
-        LERROR << "Failed to read default fstab";
-        goto out;
-    }
-
-    for (i = 0; i < fstab->num_entries; i++) {
-        if (!fs_mgr_is_verified(&fstab->recs[i])) {
-            continue;
-        }
-
-        if (system_root && !strcmp(fstab->recs[i].mount_point, "/")) {
-            mount_point = "system";
-        } else {
-            mount_point = basename(fstab->recs[i].mount_point);
-        }
-
-        fs_mgr_verity_ioctl_init(io, mount_point, 0);
-
-        if (ioctl(fd, DM_TABLE_STATUS, io)) {
-            if (fstab->recs[i].fs_mgr_flags & MF_VERIFYATBOOT) {
-                status = "V";
-            } else {
-                PERROR << "Failed to query DM_TABLE_STATUS for "
-                       << mount_point.c_str();
-                continue;
-            }
-        }
-
-        status = &buffer[io->data_start + sizeof(struct dm_target_spec)];
-
-        if (*status == 'C' || *status == 'V') {
-            callback(&fstab->recs[i], mount_point.c_str(), mode, *status);
-        }
-    }
-
-    rc = 0;
-
-out:
-    if (fstab) {
-        fs_mgr_free_fstab(fstab);
-    }
-
-    if (fd) {
-        close(fd);
-    }
-
-    return rc;
-}
-
 static void update_verity_table_blk_device(char *blk_device, char **table)
 {
     std::string result, word;
diff --git a/fs_mgr/include/fs_mgr.h b/fs_mgr/include/fs_mgr.h
index e4aeb48..9079a43 100644
--- a/fs_mgr/include/fs_mgr.h
+++ b/fs_mgr/include/fs_mgr.h
@@ -22,6 +22,12 @@
 #include <stdbool.h>
 #include <linux/dm-ioctl.h>
 
+// C++ only headers
+// TODO: move this into separate header files under include/fs_mgr/*.h
+#ifdef __cplusplus
+#include <string>
+#endif
+
 // Magic number at start of verity metadata
 #define VERITY_METADATA_MAGIC_NUMBER 0xb001b001
 
@@ -29,9 +35,7 @@
 // turn verity off in userdebug builds.
 #define VERITY_METADATA_MAGIC_DISABLE 0x46464f56 // "VOFF"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
+__BEGIN_DECLS
 
 // Verity modes
 enum verity_mode {
@@ -88,7 +92,6 @@
 struct fstab *fs_mgr_read_fstab_default();
 struct fstab *fs_mgr_read_fstab_dt();
 struct fstab *fs_mgr_read_fstab(const char *fstab_path);
-struct fstab *fs_mgr_read_fstab_with_dt(const char *fstab_path);
 void fs_mgr_free_fstab(struct fstab *fstab);
 
 #define FS_MGR_MNTALL_DEV_FILE_ENCRYPTED 5
@@ -102,6 +105,7 @@
 
 #define FS_MGR_DOMNT_FAILED (-1)
 #define FS_MGR_DOMNT_BUSY (-2)
+#define FS_MGR_DOMNT_SUCCESS 0
 
 int fs_mgr_do_mount(struct fstab *fstab, const char *n_name, char *n_blk_device,
                     char *tmp_mount_point);
@@ -110,8 +114,8 @@
 int fs_mgr_unmount_all(struct fstab *fstab);
 int fs_mgr_get_crypt_info(struct fstab *fstab, char *key_loc,
                           char *real_blk_device, int size);
-int fs_mgr_load_verity_state(int *mode);
-int fs_mgr_update_verity_state(fs_mgr_verity_state_callback callback);
+bool fs_mgr_load_verity_state(int* mode);
+bool fs_mgr_update_verity_state(fs_mgr_verity_state_callback callback);
 int fs_mgr_add_entry(struct fstab *fstab,
                      const char *mount_point, const char *fs_type,
                      const char *blk_device);
@@ -120,6 +124,7 @@
 int fs_mgr_is_nonremovable(const struct fstab_rec *fstab);
 int fs_mgr_is_verified(const struct fstab_rec *fstab);
 int fs_mgr_is_verifyatboot(const struct fstab_rec *fstab);
+int fs_mgr_is_avb(const struct fstab_rec *fstab);
 int fs_mgr_is_encryptable(const struct fstab_rec *fstab);
 int fs_mgr_is_file_encrypted(const struct fstab_rec *fstab);
 const char* fs_mgr_get_file_encryption_mode(const struct fstab_rec *fstab);
@@ -140,8 +145,12 @@
 #define FS_MGR_SETUP_VERITY_SUCCESS 0
 int fs_mgr_setup_verity(struct fstab_rec *fstab, bool wait_for_verity_dev);
 
+__END_DECLS
+
+// C++ only functions
+// TODO: move this into separate header files under include/fs_mgr/*.h
 #ifdef __cplusplus
-}
+std::string fs_mgr_get_slot_suffix();
 #endif
 
 #endif /* __CORE_FS_MGR_H */
diff --git a/fs_mgr/include/fs_mgr_avb.h b/fs_mgr/include/fs_mgr_avb.h
new file mode 100644
index 0000000..a66ff42
--- /dev/null
+++ b/fs_mgr/include/fs_mgr_avb.h
@@ -0,0 +1,99 @@
+/*
+ * 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 __CORE_FS_MGR_AVB_H
+#define __CORE_FS_MGR_AVB_H
+
+#include <memory>
+#include <string>
+
+#include <libavb/libavb.h>
+
+#include "fs_mgr.h"
+
+enum FsManagerAvbHandleStatus {
+    kFsManagerAvbHandleSuccess = 0,
+    kFsManagerAvbHandleHashtreeDisabled = 1,
+    kFsManagerAvbHandleFail = 2,
+};
+
+class FsManagerAvbHandle;
+using FsManagerAvbUniquePtr = std::unique_ptr<FsManagerAvbHandle>;
+
+// Provides a factory method to return a unique_ptr pointing to itself and the
+// SetUpAvb() function to extract dm-verity parameters from AVB metadata to
+// load verity table into kernel through ioctl.
+class FsManagerAvbHandle {
+  public:
+    // The factory method to return a FsManagerAvbUniquePtr that holds
+    // the verified AVB (external/avb) metadata of all verified partitions
+    // in avb_slot_data_.vbmeta_images[].
+    //
+    // The metadata is checked against the following values from /proc/cmdline.
+    //   - androidboot.vbmeta.{hash_alg, size, digest}.
+    //
+    // A typical usage will be:
+    //   - FsManagerAvbUniquePtr handle = FsManagerAvbHandle::Open();
+    //
+    // Possible return values:
+    //   - nullptr: any error when reading and verifying the metadata,
+    //     e.g., I/O error, digest value mismatch, size mismatch, etc.
+    //
+    //   - a valid unique_ptr with status kFsMgrAvbHandleHashtreeDisabled:
+    //     to support the existing 'adb disable-verity' feature in Android.
+    //     It's very helpful for developers to make the filesystem writable to
+    //     allow replacing binaries on the device.
+    //
+    //   - a valid unique_ptr with status kFsMgrAvbHandleSuccess: the metadata
+    //     is verified and can be trusted.
+    //
+    static FsManagerAvbUniquePtr Open(const std::string& device_file_by_name_prefix);
+
+    // Sets up dm-verity on the given fstab entry.
+    // The 'wait_for_verity_dev' parameter makes this function wait for the
+    // verity device to get created before return.
+    // Returns true if the mount point is eligible to mount, it includes:
+    //   - status_ is kFsMgrAvbHandleHashtreeDisabled or
+    //   - status_ is kFsMgrAvbHandleSuccess and sending ioctl DM_TABLE_LOAD
+    //     to load verity table is success.
+    // Otherwise, returns false.
+    bool SetUpAvb(fstab_rec* fstab_entry, bool wait_for_verity_dev);
+
+    bool hashtree_disabled() const { return status_ == kFsManagerAvbHandleHashtreeDisabled; }
+    const std::string& avb_version() const { return avb_version_; }
+
+    FsManagerAvbHandle(const FsManagerAvbHandle&) = delete;             // no copy
+    FsManagerAvbHandle& operator=(const FsManagerAvbHandle&) = delete;  // no assignment
+
+    FsManagerAvbHandle(FsManagerAvbHandle&&) noexcept = delete;             // no move
+    FsManagerAvbHandle& operator=(FsManagerAvbHandle&&) noexcept = delete;  // no move assignment
+
+    ~FsManagerAvbHandle() {
+        if (avb_slot_data_) {
+            avb_slot_verify_data_free(avb_slot_data_);
+        }
+    };
+
+  protected:
+    FsManagerAvbHandle() : avb_slot_data_(nullptr), status_(kFsManagerAvbHandleFail) {}
+
+  private:
+    AvbSlotVerifyData* avb_slot_data_;
+    FsManagerAvbHandleStatus status_;
+    std::string avb_version_;
+};
+
+#endif /* __CORE_FS_MGR_AVB_H */
diff --git a/gatekeeperd/gatekeeperd.cpp b/gatekeeperd/gatekeeperd.cpp
index d4a92e5..96bda07 100644
--- a/gatekeeperd/gatekeeperd.cpp
+++ b/gatekeeperd/gatekeeperd.cpp
@@ -166,7 +166,14 @@
                     enrolled_password_handle, enrolled_password_handle_length);
         }
 
-        if (ret == 0) {
+        if (ret == GATEKEEPER_RESPONSE_OK && (*enrolled_password_handle == nullptr ||
+            *enrolled_password_handle_length != sizeof(password_handle_t))) {
+            ret = GATEKEEPER_RESPONSE_ERROR;
+            ALOGE("HAL: password_handle=%p size_of_handle=%" PRIu32 "\n",
+                  *enrolled_password_handle, *enrolled_password_handle_length);
+        }
+
+        if (ret == GATEKEEPER_RESPONSE_OK) {
             gatekeeper::password_handle_t *handle =
                     reinterpret_cast<gatekeeper::password_handle_t *>(*enrolled_password_handle);
             store_sid(uid, handle->user_id);
diff --git a/healthd/Android.mk b/healthd/Android.mk
index 7c5e35b..b292725 100644
--- a/healthd/Android.mk
+++ b/healthd/Android.mk
@@ -21,6 +21,10 @@
 include $(BUILD_STATIC_LIBRARY)
 
 include $(CLEAR_VARS)
+ifeq ($(strip $(BOARD_CHARGER_ENABLE_SUSPEND)),true)
+LOCAL_CFLAGS += -DCHARGER_ENABLE_SUSPEND
+LOCAL_SHARED_LIBRARIES += libsuspend
+endif
 LOCAL_SRC_FILES := \
     healthd_mode_android.cpp \
     healthd_mode_charger.cpp \
@@ -90,6 +94,14 @@
 
 LOCAL_C_INCLUDES := bootable/recovery $(LOCAL_PATH)/include
 
+ifneq ($(BOARD_PERIODIC_CHORES_INTERVAL_FAST),)
+LOCAL_CFLAGS += -DBOARD_PERIODIC_CHORES_INTERVAL_FAST=$(BOARD_PERIODIC_CHORES_INTERVAL_FAST)
+endif
+
+ifneq ($(BOARD_PERIODIC_CHORES_INTERVAL_SLOW),)
+LOCAL_CFLAGS += -DBOARD_PERIODIC_CHORES_INTERVAL_SLOW=$(BOARD_PERIODIC_CHORES_INTERVAL_SLOW)
+endif
+
 LOCAL_STATIC_LIBRARIES := \
     libhealthd_internal \
     libbatterymonitor \
diff --git a/healthd/BatteryPropertiesRegistrar.cpp b/healthd/BatteryPropertiesRegistrar.cpp
index d28ba41..523e1f1 100644
--- a/healthd/BatteryPropertiesRegistrar.cpp
+++ b/healthd/BatteryPropertiesRegistrar.cpp
@@ -77,6 +77,10 @@
     return healthd_get_property(id, val);
 }
 
+void BatteryPropertiesRegistrar::scheduleUpdate() {
+    healthd_battery_update();
+}
+
 status_t BatteryPropertiesRegistrar::dump(int fd, const Vector<String16>& /*args*/) {
     IPCThreadState* self = IPCThreadState::self();
     const int pid = self->getCallingPid();
diff --git a/healthd/BatteryPropertiesRegistrar.h b/healthd/BatteryPropertiesRegistrar.h
index 095f3d3..14e9145 100644
--- a/healthd/BatteryPropertiesRegistrar.h
+++ b/healthd/BatteryPropertiesRegistrar.h
@@ -32,6 +32,7 @@
 public:
     void publish(const sp<BatteryPropertiesRegistrar>& service);
     void notifyListeners(const struct BatteryProperties& props);
+    void scheduleUpdate();
 
 private:
     Mutex mRegistrationLock;
diff --git a/healthd/healthd.cpp b/healthd/healthd.cpp
index 20a6bf6..aa6735d 100644
--- a/healthd/healthd.cpp
+++ b/healthd/healthd.cpp
@@ -35,9 +35,19 @@
 
 using namespace android;
 
-// Periodic chores intervals in seconds
-#define DEFAULT_PERIODIC_CHORES_INTERVAL_FAST (60 * 1)
-#define DEFAULT_PERIODIC_CHORES_INTERVAL_SLOW (60 * 10)
+#ifndef BOARD_PERIODIC_CHORES_INTERVAL_FAST
+  // Periodic chores fast interval in seconds
+  #define DEFAULT_PERIODIC_CHORES_INTERVAL_FAST (60 * 1)
+#else
+  #define DEFAULT_PERIODIC_CHORES_INTERVAL_FAST (BOARD_PERIODIC_CHORES_INTERVAL_FAST)
+#endif
+
+#ifndef BOARD_PERIODIC_CHORES_INTERVAL_SLOW
+  // Periodic chores fast interval in seconds
+  #define DEFAULT_PERIODIC_CHORES_INTERVAL_SLOW (60 * 10)
+#else
+  #define DEFAULT_PERIODIC_CHORES_INTERVAL_SLOW (BOARD_PERIODIC_CHORES_INTERVAL_SLOW)
+#endif
 
 static struct healthd_config healthd_config = {
     .periodic_chores_interval_fast = DEFAULT_PERIODIC_CHORES_INTERVAL_FAST,
@@ -143,10 +153,14 @@
     struct android::BatteryProperties* /*props*/) {
 }
 
-int healthd_register_event(int fd, void (*handler)(uint32_t)) {
+int healthd_register_event(int fd, void (*handler)(uint32_t), EventWakeup wakeup) {
     struct epoll_event ev;
 
-    ev.events = EPOLLIN | EPOLLWAKEUP;
+    ev.events = EPOLLIN;
+
+    if (wakeup == EVENT_WAKEUP_FD)
+        ev.events |= EPOLLWAKEUP;
+
     ev.data.ptr = (void *)handler;
     if (epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &ev) == -1) {
         KLOG_ERROR(LOG_TAG,
@@ -252,7 +266,7 @@
     }
 
     fcntl(uevent_fd, F_SETFL, O_NONBLOCK);
-    if (healthd_register_event(uevent_fd, uevent_event))
+    if (healthd_register_event(uevent_fd, uevent_event, EVENT_WAKEUP_FD))
         KLOG_ERROR(LOG_TAG,
                    "register for uevent events failed\n");
 }
@@ -275,7 +289,7 @@
         return;
     }
 
-    if (healthd_register_event(wakealarm_fd, wakealarm_event))
+    if (healthd_register_event(wakealarm_fd, wakealarm_event, EVENT_WAKEUP_FD))
         KLOG_ERROR(LOG_TAG,
                    "Registration of wakealarm event failed\n");
 
@@ -283,17 +297,22 @@
 }
 
 static void healthd_mainloop(void) {
+    int nevents = 0;
     while (1) {
         struct epoll_event events[eventct];
-        int nevents;
         int timeout = awake_poll_interval;
         int mode_timeout;
 
+        /* Don't wait for first timer timeout to run periodic chores */
+        if (!nevents)
+            periodic_chores();
+
+        healthd_mode_ops->heartbeat();
+
         mode_timeout = healthd_mode_ops->preparetowait();
         if (timeout < 0 || (mode_timeout > 0 && mode_timeout < timeout))
             timeout = mode_timeout;
         nevents = epoll_wait(epollfd, events, eventct, timeout);
-
         if (nevents == -1) {
             if (errno == EINTR)
                 continue;
@@ -305,11 +324,6 @@
             if (events[n].data.ptr)
                 (*(void (*)(int))events[n].data.ptr)(events[n].events);
         }
-
-        if (!nevents)
-            periodic_chores();
-
-        healthd_mode_ops->heartbeat();
     }
 
     return;
diff --git a/healthd/healthd_mode_charger.cpp b/healthd/healthd_mode_charger.cpp
index 2f69372..91774c6 100644
--- a/healthd/healthd_mode_charger.cpp
+++ b/healthd/healthd_mode_charger.cpp
@@ -343,14 +343,19 @@
 
 static void draw_percent(const animation& anim)
 {
-    if (anim.cur_level <= 0 || anim.cur_status != BATTERY_STATUS_CHARGING) return;
+    int cur_level = anim.cur_level;
+    if (anim.cur_status == BATTERY_STATUS_FULL) {
+        cur_level = 100;
+    }
+
+    if (cur_level <= 0) return;
 
     const animation::text_field& field = anim.text_percent;
     if (field.font == nullptr || field.font->char_width == 0 || field.font->char_height == 0) {
         return;
     }
 
-    std::string str = base::StringPrintf("%d%%", anim.cur_level);
+    std::string str = base::StringPrintf("%d%%", cur_level);
 
     int x, y;
     determine_xy(field, str.size(), &x, &y);
@@ -840,7 +845,7 @@
                             std::placeholders::_2));
     if (!ret) {
         epollfd = ev_get_epollfd();
-        healthd_register_event(epollfd, charger_event_handler);
+        healthd_register_event(epollfd, charger_event_handler, EVENT_WAKEUP_FD);
     }
 
     struct animation* anim = init_animation();
diff --git a/healthd/include/healthd/healthd.h b/healthd/include/healthd/healthd.h
index 34ea55f..17efbd6 100644
--- a/healthd/include/healthd/healthd.h
+++ b/healthd/include/healthd/healthd.h
@@ -73,9 +73,14 @@
     bool (*screen_on)(android::BatteryProperties *props);
 };
 
+enum EventWakeup {
+    EVENT_NO_WAKEUP_FD,
+    EVENT_WAKEUP_FD,
+};
+
 // Global helper functions
 
-int healthd_register_event(int fd, void (*handler)(uint32_t));
+int healthd_register_event(int fd, void (*handler)(uint32_t), EventWakeup wakeup = EVENT_NO_WAKEUP_FD);
 void healthd_battery_update();
 android::status_t healthd_get_property(int id,
     struct android::BatteryProperty *val);
diff --git a/include/backtrace b/include/backtrace
new file mode 120000
index 0000000..93ce2b1
--- /dev/null
+++ b/include/backtrace
@@ -0,0 +1 @@
+../libbacktrace/include/backtrace
\ No newline at end of file
diff --git a/include/nativebridge/native_bridge.h b/include/nativebridge/native_bridge.h
index 45266de..929b8ae 100644
--- a/include/nativebridge/native_bridge.h
+++ b/include/nativebridge/native_bridge.h
@@ -116,14 +116,25 @@
 // Use NativeBridgeIsSupported() instead in non-namespace scenario.
 bool NativeBridgeIsPathSupported(const char* path);
 
-// Initializes public and anonymous namespace at native bridge side.
+// Initializes anonymous namespace.
+// NativeBridge's peer of android_init_anonymous_namespace() of dynamic linker.
+//
+// The anonymous namespace is used in the case when a NativeBridge implementation
+// cannot identify the caller of dlopen/dlsym which happens for the code not loaded
+// by dynamic linker; for example calls from the mono-compiled code.
 //
 // Starting with v3, NativeBridge has two scenarios: with/without namespace.
 // Should not use in non-namespace scenario.
-bool NativeBridgeInitNamespace(const char* public_ns_sonames,
-                               const char* anon_ns_library_path);
+bool NativeBridgeInitAnonymousNamespace(const char* public_ns_sonames,
+                                        const char* anon_ns_library_path);
 
-// Create a namespace and pass the key of related namespaces to native bridge.
+// Create new namespace in which native libraries will be loaded.
+// NativeBridge's peer of android_create_namespace() of dynamic linker.
+//
+// The libraries in the namespace are searched by folowing order:
+// 1. ld_library_path (Think of this as namespace-local LD_LIBRARY_PATH)
+// 2. In directories specified by DT_RUNPATH of the "needed by" binary.
+// 3. deault_library_path (This of this as namespace-local default library path)
 //
 // Starting with v3, NativeBridge has two scenarios: with/without namespace.
 // Should not use in non-namespace scenario.
@@ -134,7 +145,17 @@
                                                        const char* permitted_when_isolated_path,
                                                        native_bridge_namespace_t* parent_ns);
 
+// Creates a link which shares some libraries from one namespace to another.
+// NativeBridge's peer of android_link_namespaces() of dynamic linker.
+//
+// Starting with v3, NativeBridge has two scenarios: with/without namespace.
+// Should not use in non-namespace scenario.
+bool NativeBridgeLinkNamespaces(native_bridge_namespace_t* from, native_bridge_namespace_t* to,
+                                const char* shared_libs_sonames);
+
 // Load a shared library with namespace key that is supported by the native bridge.
+// NativeBridge's peer of android_dlopen_ext() of dynamic linker, only supports namespace
+// extension.
 //
 // Starting with v3, NativeBridge has two scenarios: with/without namespace.
 // Use NativeBridgeLoadLibrary() instead in non-namespace scenario.
@@ -152,7 +173,7 @@
   // Parameters:
   //   runtime_cbs [IN] the pointer to NativeBridgeRuntimeCallbacks.
   // Returns:
-  //   true iff initialization was successful.
+  //   true if initialization was successful.
   bool (*initialize)(const NativeBridgeRuntimeCallbacks* runtime_cbs, const char* private_dir,
                      const char* instruction_set);
 
@@ -194,10 +215,10 @@
   // instruction set.
   //
   // Parameters:
-  //    instruction_set [IN] the instruction set of the app
+  //   instruction_set [IN] the instruction set of the app
   // Returns:
-  //    NULL if not supported by native bridge.
-  //    Otherwise, return all environment values to be set after fork.
+  //   NULL if not supported by native bridge.
+  //   Otherwise, return all environment values to be set after fork.
   const struct NativeBridgeRuntimeValues* (*getAppEnv)(const char* instruction_set);
 
   // Added callbacks in version 2.
@@ -206,9 +227,9 @@
   // forwards- or backwards-compatible, and libnativebridge will then stop using it.
   //
   // Parameters:
-  //     bridge_version [IN] the version of libnativebridge.
+  //   bridge_version [IN] the version of libnativebridge.
   // Returns:
-  //     true iff the native bridge supports the given version of libnativebridge.
+  //   true if the native bridge supports the given version of libnativebridge.
   bool (*isCompatibleWith)(uint32_t bridge_version);
 
   // A callback to retrieve a native bridge's signal handler for the specified signal. The runtime
@@ -217,12 +238,12 @@
   // that will potentially lead to cycles.
   //
   // Parameters:
-  //     signal [IN] the signal for which the handler is asked for. Currently, only SIGSEGV is
+  //   signal [IN] the signal for which the handler is asked for. Currently, only SIGSEGV is
   //                 supported by the runtime.
   // Returns:
-  //     NULL if the native bridge doesn't use a handler or doesn't want it to be managed by the
-  //     runtime.
-  //     Otherwise, a pointer to the signal handler.
+  //   NULL if the native bridge doesn't use a handler or doesn't want it to be managed by the
+  //   runtime.
+  //   Otherwise, a pointer to the signal handler.
   NativeBridgeSignalHandlerFn (*getSignalHandler)(int signal);
 
   // Added callbacks in version 3.
@@ -231,7 +252,7 @@
   // to zero then the dynamic library is unloaded.
   //
   // Parameters:
-  //     handle [IN] the handler of a dynamic library.
+  //   handle [IN] the handler of a dynamic library.
   //
   // Returns:
   //   0 on success, and nonzero on error.
@@ -257,33 +278,36 @@
   // Use isSupported instead in non-namespace scenario.
   bool (*isPathSupported)(const char* library_path);
 
-  // Initializes anonymous namespace at native bridge side and pass the key of
-  // two namespaces(default and anonymous) owned by dynamic linker to native bridge.
+  // Initializes anonymous namespace at native bridge side.
+  // NativeBridge's peer of android_init_anonymous_namespace() of dynamic linker.
+  //
+  // The anonymous namespace is used in the case when a NativeBridge implementation
+  // cannot identify the caller of dlopen/dlsym which happens for the code not loaded
+  // by dynamic linker; for example calls from the mono-compiled code.
   //
   // Parameters:
-  //     public_ns_sonames [IN] the name of "public" libraries.
-  //     anon_ns_library_path [IN] the library search path of (anonymous) namespace.
+  //   public_ns_sonames [IN] the name of "public" libraries.
+  //   anon_ns_library_path [IN] the library search path of (anonymous) namespace.
   // Returns:
-  //     true if the pass is ok.
-  //     Otherwise, false.
+  //   true if the pass is ok.
+  //   Otherwise, false.
   //
   // Starting with v3, NativeBridge has two scenarios: with/without namespace.
   // Should not use in non-namespace scenario.
-  bool (*initNamespace)(const char* public_ns_sonames,
-                        const char* anon_ns_library_path);
+  bool (*initAnonymousNamespace)(const char* public_ns_sonames, const char* anon_ns_library_path);
 
-
-  // Create a namespace and pass the key of releated namespaces to native bridge.
+  // Create new namespace in which native libraries will be loaded.
+  // NativeBridge's peer of android_create_namespace() of dynamic linker.
   //
   // Parameters:
-  //     name [IN] the name of the namespace.
-  //     ld_library_path [IN] the first set of library search paths of the namespace.
-  //     default_library_path [IN] the second set of library search path of the namespace.
-  //     type [IN] the attribute of the namespace.
-  //     permitted_when_isolated_path [IN] the permitted path for isolated namespace(if it is).
-  //     parent_ns [IN] the pointer of the parent namespace to be inherited from.
+  //   name [IN] the name of the namespace.
+  //   ld_library_path [IN] the first set of library search paths of the namespace.
+  //   default_library_path [IN] the second set of library search path of the namespace.
+  //   type [IN] the attribute of the namespace.
+  //   permitted_when_isolated_path [IN] the permitted path for isolated namespace(if it is).
+  //   parent_ns [IN] the pointer of the parent namespace to be inherited from.
   // Returns:
-  //     native_bridge_namespace_t* for created namespace or nullptr in the case of error.
+  //   native_bridge_namespace_t* for created namespace or nullptr in the case of error.
   //
   // Starting with v3, NativeBridge has two scenarios: with/without namespace.
   // Should not use in non-namespace scenario.
@@ -294,7 +318,25 @@
                                                 const char* permitted_when_isolated_path,
                                                 native_bridge_namespace_t* parent_ns);
 
+  // Creates a link which shares some libraries from one namespace to another.
+  // NativeBridge's peer of android_link_namespaces() of dynamic linker.
+  //
+  // Parameters:
+  //   from [IN] the namespace where libraries are accessed.
+  //   to [IN] the namespace where libraries are loaded.
+  //   shared_libs_sonames [IN] the libraries to be shared.
+  //
+  // Returns:
+  //   Whether successed or not.
+  //
+  // Starting with v3, NativeBridge has two scenarios: with/without namespace.
+  // Should not use in non-namespace scenario.
+  bool (*linkNamespaces)(native_bridge_namespace_t* from, native_bridge_namespace_t* to,
+                         const char* shared_libs_sonames);
+
   // Load a shared library within a namespace.
+  // NativeBridge's peer of android_dlopen_ext() of dynamic linker, only supports namespace
+  // extension.
   //
   // Parameters:
   //   libpath [IN] path to the shared library
diff --git a/include/private/android_filesystem_capability.h b/include/private/android_filesystem_capability.h
new file mode 120000
index 0000000..f310b35
--- /dev/null
+++ b/include/private/android_filesystem_capability.h
@@ -0,0 +1 @@
+../../libcutils/include/private/android_filesystem_capability.h
\ No newline at end of file
diff --git a/include/private/android_filesystem_config.h b/include/private/android_filesystem_config.h
deleted file mode 100644
index 48a0e61..0000000
--- a/include/private/android_filesystem_config.h
+++ /dev/null
@@ -1,222 +0,0 @@
-/*
- * Copyright (C) 2007 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.
- */
-
-/* This file is used to define the properties of the filesystem
-** images generated by build tools (mkbootfs and mkyaffs2image) and
-** by the device side of adb.
-*/
-
-/*
- * This file is consumed by build/tools/fs_config and is used
- * for generating various files. Anything #define AID_<name>
- * becomes the mapping for getpwnam/getpwuid, etc. The <name>
- * field is lowercased.
- * For example:
- * #define AID_FOO_BAR 6666 becomes a friendly name of "foo_bar"
- *
- * The above holds true with the exception of:
- *   mediacodec
- *   mediaex
- *   mediadrm
- * Whose friendly names do not match the #define statements.
- *
- * Additionally, AID_OEM_RESERVED_START and AID_OEM_RESERVED_END
- * can be used to define reserved OEM ranges used for sanity checks
- * during the build process. The rules are, they must end with START/END
- * The proper convention is incrementing a number like so:
- * AID_OEM_RESERVED_START
- * AID_OEM_RESERVED_1_START
- * AID_OEM_RESERVED_2_START
- * ...
- * The same applies to the END.
- * They are not required to be in order, but must not overlap each other and
- * must define a START and END'ing range. START must be smaller than END.
- */
-
-#ifndef _ANDROID_FILESYSTEM_CONFIG_H_
-#define _ANDROID_FILESYSTEM_CONFIG_H_
-
-#include <sys/cdefs.h>
-#include <sys/types.h>
-#include <stdint.h>
-
-#if defined(__ANDROID__)
-#include <linux/capability.h>
-#else
-#include "android_filesystem_capability.h"
-#endif
-
-#define CAP_MASK_LONG(cap_name)  (1ULL << (cap_name))
-
-/* This is the master Users and Groups config for the platform.
- * DO NOT EVER RENUMBER
- */
-
-#define AID_ROOT             0  /* traditional unix root user */
-
-#define AID_SYSTEM        1000  /* system server */
-
-#define AID_RADIO         1001  /* telephony subsystem, RIL */
-#define AID_BLUETOOTH     1002  /* bluetooth subsystem */
-#define AID_GRAPHICS      1003  /* graphics devices */
-#define AID_INPUT         1004  /* input devices */
-#define AID_AUDIO         1005  /* audio devices */
-#define AID_CAMERA        1006  /* camera devices */
-#define AID_LOG           1007  /* log devices */
-#define AID_COMPASS       1008  /* compass device */
-#define AID_MOUNT         1009  /* mountd socket */
-#define AID_WIFI          1010  /* wifi subsystem */
-#define AID_ADB           1011  /* android debug bridge (adbd) */
-#define AID_INSTALL       1012  /* group for installing packages */
-#define AID_MEDIA         1013  /* mediaserver process */
-#define AID_DHCP          1014  /* dhcp client */
-#define AID_SDCARD_RW     1015  /* external storage write access */
-#define AID_VPN           1016  /* vpn system */
-#define AID_KEYSTORE      1017  /* keystore subsystem */
-#define AID_USB           1018  /* USB devices */
-#define AID_DRM           1019  /* DRM server */
-#define AID_MDNSR         1020  /* MulticastDNSResponder (service discovery) */
-#define AID_GPS           1021  /* GPS daemon */
-#define AID_UNUSED1       1022  /* deprecated, DO NOT USE */
-#define AID_MEDIA_RW      1023  /* internal media storage write access */
-#define AID_MTP           1024  /* MTP USB driver access */
-#define AID_UNUSED2       1025  /* deprecated, DO NOT USE */
-#define AID_DRMRPC        1026  /* group for drm rpc */
-#define AID_NFC           1027  /* nfc subsystem */
-#define AID_SDCARD_R      1028  /* external storage read access */
-#define AID_CLAT          1029  /* clat part of nat464 */
-#define AID_LOOP_RADIO    1030  /* loop radio devices */
-#define AID_MEDIA_DRM     1031  /* MediaDrm plugins */
-#define AID_PACKAGE_INFO  1032  /* access to installed package details */
-#define AID_SDCARD_PICS   1033  /* external storage photos access */
-#define AID_SDCARD_AV     1034  /* external storage audio/video access */
-#define AID_SDCARD_ALL    1035  /* access all users external storage */
-#define AID_LOGD          1036  /* log daemon */
-#define AID_SHARED_RELRO  1037  /* creator of shared GNU RELRO files */
-#define AID_DBUS          1038  /* dbus-daemon IPC broker process */
-#define AID_TLSDATE       1039  /* tlsdate unprivileged user */
-#define AID_MEDIA_EX      1040  /* mediaextractor process */
-#define AID_AUDIOSERVER   1041  /* audioserver process */
-#define AID_METRICS_COLL  1042  /* metrics_collector process */
-#define AID_METRICSD      1043  /* metricsd process */
-#define AID_WEBSERV       1044  /* webservd process */
-#define AID_DEBUGGERD     1045  /* debuggerd unprivileged user */
-#define AID_MEDIA_CODEC   1046  /* mediacodec process */
-#define AID_CAMERASERVER  1047  /* cameraserver process */
-#define AID_FIREWALL      1048  /* firewalld process */
-#define AID_TRUNKS        1049  /* trunksd process (TPM daemon) */
-#define AID_NVRAM         1050  /* Access-controlled NVRAM */
-#define AID_DNS           1051  /* DNS resolution daemon (system: netd) */
-#define AID_DNS_TETHER    1052  /* DNS resolution daemon (tether: dnsmasq) */
-#define AID_WEBVIEW_ZYGOTE 1053 /* WebView zygote process */
-#define AID_VEHICLE_NETWORK 1054 /* Vehicle network service */
-#define AID_MEDIA_AUDIO   1055  /* GID for audio files on internal media storage */
-#define AID_MEDIA_VIDEO   1056  /* GID for video files on internal media storage */
-#define AID_MEDIA_IMAGE   1057  /* GID for image files on internal media storage */
-#define AID_TOMBSTONED    1058  /* tombstoned user */
-#define AID_MEDIA_OBB     1059  /* GID for OBB files on internal media storage */
-#define AID_ESE           1060  /* embedded secure element (eSE) subsystem */
-/* Changes to this file must be made in AOSP, *not* in internal branches. */
-
-#define AID_SHELL         2000  /* adb and debug shell user */
-#define AID_CACHE         2001  /* cache access */
-#define AID_DIAG          2002  /* access to diagnostic resources */
-
-/* The range 2900-2999 is reserved for OEM, and must never be
- * used here */
-#define AID_OEM_RESERVED_START 2900
-#define AID_OEM_RESERVED_END   2999
-
-/* The 3000 series are intended for use as supplemental group id's only.
- * They indicate special Android capabilities that the kernel is aware of. */
-#define AID_NET_BT_ADMIN  3001  /* bluetooth: create any socket */
-#define AID_NET_BT        3002  /* bluetooth: create sco, rfcomm or l2cap sockets */
-#define AID_INET          3003  /* can create AF_INET and AF_INET6 sockets */
-#define AID_NET_RAW       3004  /* can create raw INET sockets */
-#define AID_NET_ADMIN     3005  /* can configure interfaces and routing tables. */
-#define AID_NET_BW_STATS  3006  /* read bandwidth statistics */
-#define AID_NET_BW_ACCT   3007  /* change bandwidth statistics accounting */
-#define AID_READPROC      3009  /* Allow /proc read access */
-#define AID_WAKELOCK      3010  /* Allow system wakelock read/write access */
-
-/* The range 5000-5999 is also reserved for OEM, and must never be used here. */
-#define AID_OEM_RESERVED_2_START 5000
-#define AID_OEM_RESERVED_2_END   5999
-
-#define AID_EVERYBODY     9997  /* shared between all apps in the same profile */
-#define AID_MISC          9998  /* access to misc storage */
-#define AID_NOBODY        9999
-
-#define AID_APP              10000 /* TODO: switch users over to AID_APP_START */
-#define AID_APP_START        10000 /* first app user */
-#define AID_APP_END          19999 /* last app user */
-
-#define AID_CACHE_GID_START  20000 /* start of gids for apps to mark cached data */
-#define AID_CACHE_GID_END    29999 /* end of gids for apps to mark cached data */
-
-#define AID_EXT_GID_START    30000 /* start of gids for apps to mark external data */
-#define AID_EXT_GID_END      39999 /* end of gids for apps to mark external data */
-
-#define AID_SHARED_GID_START 50000 /* start of gids for apps in each user to share */
-#define AID_SHARED_GID_END   59999 /* end of gids for apps in each user to share */
-
-#define AID_ISOLATED_START   99000 /* start of uids for fully isolated sandboxed processes */
-#define AID_ISOLATED_END     99999 /* end of uids for fully isolated sandboxed processes */
-
-#define AID_USER            100000 /* TODO: switch users over to AID_USER_OFFSET */
-#define AID_USER_OFFSET     100000 /* offset for uid ranges for each user */
-
-/*
- * android_ids has moved to pwd/grp functionality.
- * If you need to add one, the structure is now
- * auto-generated based on the AID_ constraints
- * documented at the top of this header file.
- * Also see build/tools/fs_config for more details.
- */
-
-#if !defined(EXCLUDE_FS_CONFIG_STRUCTURES)
-
-struct fs_path_config {
-    unsigned mode;
-    unsigned uid;
-    unsigned gid;
-    uint64_t capabilities;
-    const char *prefix;
-};
-
-/* Rules for directories and files has moved to system/code/libcutils/fs_config.c */
-
-__BEGIN_DECLS
-
-/*
- * Used in:
- *  build/tools/fs_config/fs_config.c
- *  build/tools/fs_get_stats/fs_get_stats.c
- *  system/extras/ext4_utils/make_ext4fs_main.c
- *  external/squashfs-tools/squashfs-tools/android.c
- *  system/core/cpio/mkbootfs.c
- *  system/core/adb/file_sync_service.cpp
- *  system/extras/ext4_utils/canned_fs_config.c
- */
-void fs_config(const char *path, int dir, const char *target_out_path,
-               unsigned *uid, unsigned *gid, unsigned *mode, uint64_t *capabilities);
-
-ssize_t fs_config_generate(char *buffer, size_t length, const struct fs_path_config *pc);
-
-__END_DECLS
-
-#endif
-#endif
diff --git a/include/private/android_filesystem_config.h b/include/private/android_filesystem_config.h
new file mode 120000
index 0000000..f28a564
--- /dev/null
+++ b/include/private/android_filesystem_config.h
@@ -0,0 +1 @@
+../../libcutils/include/private/android_filesystem_config.h
\ No newline at end of file
diff --git a/include/private/canned_fs_config.h b/include/private/canned_fs_config.h
new file mode 120000
index 0000000..8f92b2d
--- /dev/null
+++ b/include/private/canned_fs_config.h
@@ -0,0 +1 @@
+../../libcutils/include/private/canned_fs_config.h
\ No newline at end of file
diff --git a/include/system b/include/system
new file mode 120000
index 0000000..91d45be
--- /dev/null
+++ b/include/system
@@ -0,0 +1 @@
+../libsystem/include/system/
\ No newline at end of file
diff --git a/include/ziparchive/zip_writer.h b/include/ziparchive/zip_writer.h
index 0b6ede4..08ead48 100644
--- a/include/ziparchive/zip_writer.h
+++ b/include/ziparchive/zip_writer.h
@@ -17,15 +17,16 @@
 #ifndef LIBZIPARCHIVE_ZIPWRITER_H_
 #define LIBZIPARCHIVE_ZIPWRITER_H_
 
-#include "android-base/macros.h"
-#include <utils/Compat.h>
-
 #include <cstdio>
 #include <ctime>
+#include <zlib.h>
+
 #include <memory>
 #include <string>
 #include <vector>
-#include <zlib.h>
+
+#include "android-base/macros.h"
+#include "utils/Compat.h"
 
 /**
  * Writes a Zip file via a stateful interface.
@@ -63,6 +64,21 @@
     kAlign32 = 0x02,
   };
 
+  /**
+   * A struct representing a zip file entry.
+   */
+  struct FileEntry {
+    std::string path;
+    uint16_t compression_method;
+    uint32_t crc32;
+    uint32_t compressed_size;
+    uint32_t uncompressed_size;
+    uint16_t last_mod_time;
+    uint16_t last_mod_date;
+    uint32_t padding_length;
+    off64_t local_file_header_offset;
+  };
+
   static const char* ErrorCodeString(int32_t error_code);
 
   /**
@@ -122,6 +138,19 @@
   int32_t FinishEntry();
 
   /**
+   * Discards the last-written entry. Can only be called after an entry has been written using
+   * FinishEntry().
+   * Returns 0 on success, and an error value < 0 on failure.
+   */
+  int32_t DiscardLastEntry();
+
+  /**
+   * Sets `out_entry` to the last entry written after a call to FinishEntry().
+   * Returns 0 on success, and an error value < 0 if no entries have been written.
+   */
+  int32_t GetLastEntry(FileEntry* out_entry);
+
+  /**
    * Writes the Central Directory Headers and flushes the zip file stream.
    * Returns 0 on success, and an error value < 0 on failure.
    */
@@ -130,22 +159,11 @@
 private:
   DISALLOW_COPY_AND_ASSIGN(ZipWriter);
 
-  struct FileInfo {
-    std::string path;
-    uint16_t compression_method;
-    uint32_t crc32;
-    uint32_t compressed_size;
-    uint32_t uncompressed_size;
-    uint16_t last_mod_time;
-    uint16_t last_mod_date;
-    uint32_t local_file_header_offset;
-  };
-
   int32_t HandleError(int32_t error_code);
   int32_t PrepareDeflate();
-  int32_t StoreBytes(FileInfo* file, const void* data, size_t len);
-  int32_t CompressBytes(FileInfo* file, const void* data, size_t len);
-  int32_t FlushCompressedBytes(FileInfo* file);
+  int32_t StoreBytes(FileEntry* file, const void* data, size_t len);
+  int32_t CompressBytes(FileEntry* file, const void* data, size_t len);
+  int32_t FlushCompressedBytes(FileEntry* file);
 
   enum class State {
     kWritingZip,
@@ -155,9 +173,11 @@
   };
 
   FILE* file_;
+  bool seekable_;
   off64_t current_offset_;
   State state_;
-  std::vector<FileInfo> files_;
+  std::vector<FileEntry> files_;
+  FileEntry current_file_entry_;
 
   std::unique_ptr<z_stream, void(*)(z_stream*)> z_stream_;
   std::vector<uint8_t> buffer_;
diff --git a/init/Android.mk b/init/Android.mk
index 2a1ad9c..537bbee 100644
--- a/init/Android.mk
+++ b/init/Android.mk
@@ -5,9 +5,27 @@
 # --
 
 ifneq (,$(filter userdebug eng,$(TARGET_BUILD_VARIANT)))
-init_options += -DALLOW_LOCAL_PROP_OVERRIDE=1 -DALLOW_PERMISSIVE_SELINUX=1
+init_options += \
+    -DALLOW_LOCAL_PROP_OVERRIDE=1 \
+    -DALLOW_PERMISSIVE_SELINUX=1 \
+    -DREBOOT_BOOTLOADER_ON_PANIC=1 \
+    -DWORLD_WRITABLE_KMSG=1 \
+    -DDUMP_ON_UMOUNT_FAILURE=1
 else
-init_options += -DALLOW_LOCAL_PROP_OVERRIDE=0 -DALLOW_PERMISSIVE_SELINUX=0
+init_options += \
+    -DALLOW_LOCAL_PROP_OVERRIDE=0 \
+    -DALLOW_PERMISSIVE_SELINUX=0 \
+    -DREBOOT_BOOTLOADER_ON_PANIC=0 \
+    -DWORLD_WRITABLE_KMSG=0 \
+    -DDUMP_ON_UMOUNT_FAILURE=0
+endif
+
+ifneq (,$(filter eng,$(TARGET_BUILD_VARIANT)))
+init_options += \
+    -DSHUTDOWN_ZERO_TIMEOUT=1
+else
+init_options += \
+    -DSHUTDOWN_ZERO_TIMEOUT=0
 endif
 
 init_options += -DLOG_UEVENTS=0
@@ -48,6 +66,7 @@
     action.cpp \
     capabilities.cpp \
     descriptors.cpp \
+    devices.cpp \
     import_parser.cpp \
     init_parser.cpp \
     log.cpp \
@@ -55,7 +74,7 @@
     service.cpp \
     util.cpp \
 
-LOCAL_STATIC_LIBRARIES := libbase libselinux liblog libprocessgroup libnl
+LOCAL_STATIC_LIBRARIES := libbase libselinux liblog libprocessgroup
 LOCAL_WHOLE_STATIC_LIBRARIES := libcap
 LOCAL_MODULE := libinit
 LOCAL_SANITIZE := integer
@@ -67,13 +86,13 @@
 LOCAL_SRC_FILES:= \
     bootchart.cpp \
     builtins.cpp \
-    devices.cpp \
     init.cpp \
+    init_first_stage.cpp \
     keychords.cpp \
     property_service.cpp \
+    reboot.cpp \
     signal_handler.cpp \
     ueventd.cpp \
-    ueventd_parser.cpp \
     watchdogd.cpp \
 
 LOCAL_MODULE:= init
@@ -92,8 +111,8 @@
     libfec_rs \
     libsquashfs_utils \
     liblogwrap \
-    libcutils \
     libext4_utils \
+    libcutils \
     libbase \
     libc \
     libselinux \
@@ -105,37 +124,8 @@
     libsparse \
     libz \
     libprocessgroup \
-    libnl \
     libavb
 
-# Include SELinux policy. We do this here because different modules
-# need to be included based on the value of PRODUCT_FULL_TREBLE. This
-# type of conditional inclusion cannot be done in top-level files such
-# as build/target/product/embedded.mk.
-# This conditional inclusion closely mimics the conditional logic
-# inside init/init.cpp for loading SELinux policy from files.
-ifeq ($(PRODUCT_FULL_TREBLE),true)
-# Use split SELinux policy
-LOCAL_REQUIRED_MODULES += \
-    mapping_sepolicy.cil \
-    nonplat_sepolicy.cil \
-    plat_sepolicy.cil \
-    plat_sepolicy.cil.sha256 \
-    secilc \
-    nonplat_file_contexts \
-    plat_file_contexts
-
-# Include precompiled policy, unless told otherwise
-ifneq ($(PRODUCT_PRECOMPILED_SEPOLICY),false)
-LOCAL_REQUIRED_MODULES += precompiled_sepolicy precompiled_sepolicy.plat.sha256
-endif
-
-else
-# Use monolithic SELinux policy
-LOCAL_REQUIRED_MODULES += sepolicy \
-    file_contexts.bin
-endif
-
 # Create symlinks.
 LOCAL_POST_INSTALL_CMD := $(hide) mkdir -p $(TARGET_ROOT_OUT)/sbin; \
     ln -sf ../init $(TARGET_ROOT_OUT)/sbin/ueventd; \
@@ -151,18 +141,22 @@
 include $(CLEAR_VARS)
 LOCAL_MODULE := init_tests
 LOCAL_SRC_FILES := \
+    devices_test.cpp \
     init_parser_test.cpp \
+    init_test.cpp \
     property_service_test.cpp \
+    service_test.cpp \
     util_test.cpp \
 
 LOCAL_SHARED_LIBRARIES += \
-    libcutils \
     libbase \
+    libcutils \
+    libselinux \
 
 LOCAL_STATIC_LIBRARIES := libinit
 LOCAL_SANITIZE := integer
 LOCAL_CLANG := true
-LOCAL_CPPFLAGS := -Wall -Wextra -Werror
+LOCAL_CPPFLAGS := -Wall -Wextra -Werror -std=gnu++1z
 include $(BUILD_NATIVE_TEST)
 
 
diff --git a/init/README.md b/init/README.md
index d3dd73a..9fc8d47 100644
--- a/init/README.md
+++ b/init/README.md
@@ -16,9 +16,7 @@
 or options belong to the section most recently declared.  Commands
 or options before the first section are ignored.
 
-Actions and Services have unique names.  If a second Action is defined
-with the same name as an existing one, its commands are appended to
-the commands of the existing action.  If a second Service is defined
+Services have unique names.  If a second Service is defined
 with the same name as an existing one, it is ignored and an error
 message is logged.
 
@@ -31,13 +29,21 @@
 
 /init.rc is the primary .rc file and is loaded by the init executable
 at the beginning of its execution.  It is responsible for the initial
-set up of the system.  It imports /init.${ro.hardware}.rc which is the
-primary vendor supplied .rc file.
+set up of the system.
 
-During the mount\_all command, the init executable loads all of the
-files contained within the /{system,vendor,odm}/etc/init/ directories.
-These directories are intended for all Actions and Services used after
-file system mounting.
+Devices that mount /system, /vendor through the first stage mount mechanism
+load all of the files contained within the
+/{system,vendor,odm}/etc/init/ directories immediately after loading
+the primary /init.rc.  This is explained in more details in the
+Imports section of this file.
+
+Legacy devices without the first stage mount mechanism do the following:
+1. /init.rc imports /init.${ro.hardware}.rc which is the primary
+   vendor supplied .rc file.
+2. During the mount\_all command, the init executable loads all of the
+   files contained within the /{system,vendor,odm}/etc/init/ directories.
+   These directories are intended for all Actions and Services used after
+   file system mounting.
 
 One may specify paths in the mount\_all command line to have it import
 .rc files at the specified paths instead of the default ones listed above.
@@ -89,7 +95,7 @@
 Actions
 -------
 Actions are named sequences of commands.  Actions have a trigger which
-is used to determine when the action should occur.  When an event
+is used to determine when the action is executed.  When an event
 occurs which matches an action's trigger, that action is added to
 the tail of a to-be-executed queue (unless it is already on the
 queue).
@@ -106,6 +112,34 @@
        <command>
        <command>
 
+Actions are added to the queue and executed based on the order that
+the file that contains them was parsed (see the Imports section), then
+sequentially within an individual file.
+
+For example if a file contains:
+
+    on boot
+       setprop a 1
+       setprop b 2
+
+    on boot && property:true=true
+       setprop c 1
+       setprop d 2
+
+    on boot
+       setprop e 1
+       setprop f 2
+
+Then when the `boot` trigger occurs and assuming the property `true`
+equals `true`, then the order of the commands executed will be:
+
+    setprop a 1
+    setprop b 2
+    setprop c 1
+    setprop d 2
+    setprop e 1
+    setprop f 2
+
 
 Services
 --------
@@ -192,18 +226,28 @@
 `oneshot`
 > Do not restart the service when it exits.
 
-`class <name>`
-> Specify a class name for the service.  All services in a
+`class <name> [ <name>\* ]`
+> Specify class names for the service.  All services in a
   named class may be started or stopped together.  A service
   is in the class "default" if one is not specified via the
-  class option.
+  class option. Additional classnames beyond the (required) first
+  one are used to group services.
+`animation class`
+> 'animation' class should include all services necessary for both
+  boot animation and shutdown animation. As these services can be
+  launched very early during bootup and can run until the last stage
+  of shutdown, access to /data partition is not guaranteed. These
+  services can check files under /data but it should not keep files opened
+  and should work when /data is not available.
 
 `onrestart`
 > Execute a Command (see below) when service restarts.
 
-`writepid <file...>`
+`writepid <file> [ <file>\* ]`
 > Write the child's pid to the given files when it forks. Meant for
-  cgroup/cpuset usage.
+  cgroup/cpuset usage. If no files under /dev/cpuset/ are specified, but the
+  system property 'ro.cpuset.default' is set to a non-empty cpuset name (e.g.
+  '/foreground'), then the pid is written to file /dev/cpuset/_cpuset\_name_/tasks.
 
 `priority <priority>`
 > Scheduling priority of the service process. This value has to be in range
@@ -266,7 +310,8 @@
 
 `class_start <serviceclass>`
 > Start all services of the specified class if they are
-  not already running.
+  not already running.  See the start entry for more information on
+  starting services.
 
 `class_stop <serviceclass>`
 > Stop and disable all services of the specified class if they are
@@ -277,9 +322,17 @@
   currently running, without disabling them. They can be restarted
   later using `class_start`.
 
+`class_restart <serviceclass>`
+> Restarts all services of the specified class.
+
 `copy <src> <dst>`
 > Copies a file. Similar to write, but useful for binary/large
   amounts of data.
+  Regarding to the src file, copying from symbolic link file and world-writable
+  or group-writable files are not allowed.
+  Regarding to the dst file, the default mode created is 0600 if it does not
+  exist. And it will be truncated if dst file is a normal regular file and
+  already exists.
 
 `domainname <name>`
 > Set the domain name.
@@ -300,6 +353,12 @@
   groups can be provided. No other commands will be run until this one
   finishes. _seclabel_ can be a - to denote default. Properties are expanded
   within _argument_.
+  Init halts executing commands until the forked process exits.
+
+`exec_start <service>`
+> Start service a given service and halt processing of additional init commands
+  until it returns.  It functions similarly to the `exec` command, but uses an
+  existing service definition instead of providing them as arguments.
 
 `export <name> <value>`
 > Set the environment variable _name_ equal to _value_ in the
@@ -346,12 +405,9 @@
   _options_ include "barrier=1", "noauto\_da\_alloc", "discard", ... as
   a comma separated string, eg: barrier=1,noauto\_da\_alloc
 
-`powerctl`
-> Internal implementation detail used to respond to changes to the
-  "sys.powerctl" system property, used to implement rebooting.
-
 `restart <service>`
-> Like stop, but doesn't disable the service.
+> Stops and restarts a running service, does nothing if the service is currently
+  restarting, otherwise, it just starts the service.
 
 `restorecon <path> [ <path>\* ]`
 > Restore the file named by _path_ to the security context specified
@@ -380,6 +436,16 @@
 
 `start <service>`
 > Start a service running if it is not already running.
+  Note that this is _not_ synchronous, and even if it were, there is
+  no guarantee that the operating system's scheduler will execute the
+  service sufficiently to guarantee anything about the service's status.
+
+> This creates an important consequence that if the service offers
+  functionality to other services, such as providing a
+  communication channel, simply starting this service before those
+  services is _not_ sufficient to guarantee that the channel has
+  been set up before those services ask for it.  There must be a
+  separate mechanism to make any such guarantees.
 
 `stop <service>`
 > Stop a service from running if it is currently running.
@@ -426,21 +492,54 @@
 
 Imports
 -------
-The import keyword is not a command, but rather its own section and is
-handled immediately after the .rc file that contains it has finished
-being parsed.  It takes the below form:
-
 `import <path>`
 > Parse an init config file, extending the current configuration.
   If _path_ is a directory, each file in the directory is parsed as
   a config file. It is not recursive, nested directories will
   not be parsed.
 
-There are only two times where the init executable imports .rc files:
+The import keyword is not a command, but rather its own section,
+meaning that it does not happen as part of an Action, but rather,
+imports are handled as a file is being parsed and follow the below logic.
 
-   1. When it imports /init.rc during initial boot
-   2. When it imports /{system,vendor,odm}/etc/init/ or .rc files at specified
-      paths during mount_all
+There are only three times where the init executable imports .rc files:
+
+   1. When it imports /init.rc or the script indicated by the property
+      `ro.boot.init_rc` during initial boot.
+   2. When it imports /{system,vendor,odm}/etc/init/ for first stage mount
+      devices immediately after importing /init.rc.
+   3. When it imports /{system,vendor,odm}/etc/init/ or .rc files at specified
+      paths during mount_all.
+
+The order that files are imported is a bit complex for legacy reasons
+and to keep backwards compatibility.  It is not strictly guaranteed.
+
+The only correct way to guarantee that a command has been run before a
+different command is to either 1) place it in an Action with an
+earlier executed trigger, or 2) place it in an Action with the same
+trigger within the same file at an earlier line.
+
+Nonetheless, the defacto order for first stage mount devices is:
+1. /init.rc is parsed then recursively each of its imports are
+   parsed.
+2. The contents of /system/etc/init/ are alphabetized and parsed
+   sequentially, with imports happening recursively after each file is
+   parsed.
+3. Step 2 is repeated for /vendor/etc/init then /odm/etc/init
+
+The below pseudocode may explain this more clearly:
+
+    fn Import(file)
+      Parse(file)
+      for (import : file.imports)
+        Import(import)
+
+    Import(/init.rc)
+    Directories = [/system/etc/init, /vendor/etc/init, /odm/etc/init]
+    for (directory : Directories)
+      files = <Alphabetical order of directory's contents>
+      for (file : files)
+        Import(file)
 
 
 Properties
diff --git a/init/action.cpp b/init/action.cpp
index 1bba0f2..21abe02 100644
--- a/init/action.cpp
+++ b/init/action.cpp
@@ -16,25 +16,18 @@
 
 #include "action.h"
 
-#include <errno.h>
-
-#include <android-base/strings.h>
+#include <android-base/logging.h>
+#include <android-base/properties.h>
 #include <android-base/stringprintf.h>
+#include <android-base/strings.h>
 
-#include "builtins.h"
-#include "error.h"
-#include "init_parser.h"
-#include "log.h"
-#include "property_service.h"
 #include "util.h"
 
 using android::base::Join;
 using android::base::StringPrintf;
 
-Command::Command(BuiltinFunction f, const std::vector<std::string>& args,
-                 const std::string& filename, int line)
-    : func_(f), args_(args), filename_(filename), line_(line) {
-}
+Command::Command(BuiltinFunction f, const std::vector<std::string>& args, int line)
+    : func_(f), args_(args), line_(line) {}
 
 int Command::InvokeFunc() const {
     std::vector<std::string> expanded_args;
@@ -54,50 +47,28 @@
     return Join(args_, ' ');
 }
 
-std::string Command::BuildSourceString() const {
-    if (!filename_.empty()) {
-        return StringPrintf(" (%s:%d)", filename_.c_str(), line_);
-    } else {
-        return std::string();
-    }
-}
-
-Action::Action(bool oneshot) : oneshot_(oneshot) {
-}
+Action::Action(bool oneshot, const std::string& filename, int line)
+    : oneshot_(oneshot), filename_(filename), line_(line) {}
 
 const KeywordMap<BuiltinFunction>* Action::function_map_ = nullptr;
 
-bool Action::AddCommand(const std::vector<std::string>& args,
-                        const std::string& filename, int line, std::string* err) {
+bool Action::AddCommand(const std::vector<std::string>& args, int line, std::string* err) {
     if (!function_map_) {
         *err = "no function map available";
         return false;
     }
 
-    if (args.empty()) {
-        *err = "command needed, but not provided";
-        return false;
-    }
-
-    auto function = function_map_->FindFunction(args[0], args.size() - 1, err);
+    auto function = function_map_->FindFunction(args, err);
     if (!function) {
         return false;
     }
 
-    AddCommand(function, args, filename, line);
+    AddCommand(function, args, line);
     return true;
 }
 
-void Action::AddCommand(BuiltinFunction f,
-                        const std::vector<std::string>& args,
-                        const std::string& filename, int line) {
-    commands_.emplace_back(f, args, filename, line);
-}
-
-void Action::CombineAction(const Action& action) {
-    for (const auto& c : action.commands_) {
-        commands_.emplace_back(c);
-    }
+void Action::AddCommand(BuiltinFunction f, const std::vector<std::string>& args, int line) {
+    commands_.emplace_back(f, args, line);
 }
 
 std::size_t Action::NumCommands() const {
@@ -127,7 +98,7 @@
         android::base::GetMinimumLogSeverity() <= android::base::DEBUG) {
         std::string trigger_name = BuildTriggersString();
         std::string cmd_str = command.BuildCommandString();
-        std::string source = command.BuildSourceString();
+        std::string source = StringPrintf(" (%s:%d)", filename_.c_str(), command.line());
 
         LOG(INFO) << "Command '" << cmd_str << "' action=" << trigger_name << source
                   << " returned " << result << " took " << duration_ms << "ms.";
@@ -219,9 +190,8 @@
                 found = true;
             }
         } else {
-            std::string prop_val = property_get(trigger_name.c_str());
-            if (prop_val.empty() || (trigger_value != "*" &&
-                                     trigger_value != prop_val)) {
+            std::string prop_val = android::base::GetProperty(trigger_name, "");
+            if (prop_val.empty() || (trigger_value != "*" && trigger_value != prop_val)) {
                 return false;
             }
         }
@@ -229,20 +199,17 @@
     return found;
 }
 
-bool Action::CheckEventTrigger(const std::string& trigger) const {
-    return !event_trigger_.empty() &&
-        trigger == event_trigger_ &&
-        CheckPropertyTriggers();
+bool Action::CheckEvent(const EventTrigger& event_trigger) const {
+    return event_trigger == event_trigger_ && CheckPropertyTriggers();
 }
 
-bool Action::CheckPropertyTrigger(const std::string& name,
-                                  const std::string& value) const {
+bool Action::CheckEvent(const PropertyChange& property_change) const {
+    const auto& [name, value] = property_change;
     return event_trigger_.empty() && CheckPropertyTriggers(name, value);
 }
 
-bool Action::TriggersEqual(const Action& other) const {
-    return property_triggers_ == other.property_triggers_ &&
-        event_trigger_ == other.event_trigger_;
+bool Action::CheckEvent(const BuiltinAction& builtin_action) const {
+    return this == builtin_action;
 }
 
 std::string Action::BuildTriggersString() const {
@@ -268,41 +235,6 @@
     }
 }
 
-class EventTrigger : public Trigger {
-public:
-    explicit EventTrigger(const std::string& trigger) : trigger_(trigger) {
-    }
-    bool CheckTriggers(const Action& action) const override {
-        return action.CheckEventTrigger(trigger_);
-    }
-private:
-    const std::string trigger_;
-};
-
-class PropertyTrigger : public Trigger {
-public:
-    PropertyTrigger(const std::string& name, const std::string& value)
-        : name_(name), value_(value) {
-    }
-    bool CheckTriggers(const Action& action) const override {
-        return action.CheckPropertyTrigger(name_, value_);
-    }
-private:
-    const std::string name_;
-    const std::string value_;
-};
-
-class BuiltinTrigger : public Trigger {
-public:
-    explicit BuiltinTrigger(Action* action) : action_(action) {
-    }
-    bool CheckTriggers(const Action& action) const override {
-        return action_ == &action;
-    }
-private:
-    const Action* action_;
-};
-
 ActionManager::ActionManager() : current_command_(0) {
 }
 
@@ -312,56 +244,45 @@
 }
 
 void ActionManager::AddAction(std::unique_ptr<Action> action) {
-    auto old_action_it =
-        std::find_if(actions_.begin(), actions_.end(),
-                     [&action] (std::unique_ptr<Action>& a) {
-                         return action->TriggersEqual(*a);
-                     });
-
-    if (old_action_it != actions_.end()) {
-        (*old_action_it)->CombineAction(*action);
-    } else {
-        actions_.emplace_back(std::move(action));
-    }
+    actions_.emplace_back(std::move(action));
 }
 
 void ActionManager::QueueEventTrigger(const std::string& trigger) {
-    trigger_queue_.push(std::make_unique<EventTrigger>(trigger));
+    event_queue_.emplace(trigger);
 }
 
-void ActionManager::QueuePropertyTrigger(const std::string& name,
-                                         const std::string& value) {
-    trigger_queue_.push(std::make_unique<PropertyTrigger>(name, value));
+void ActionManager::QueuePropertyChange(const std::string& name, const std::string& value) {
+    event_queue_.emplace(std::make_pair(name, value));
 }
 
-void ActionManager::QueueAllPropertyTriggers() {
-    QueuePropertyTrigger("", "");
+void ActionManager::QueueAllPropertyActions() {
+    QueuePropertyChange("", "");
 }
 
-void ActionManager::QueueBuiltinAction(BuiltinFunction func,
-                                       const std::string& name) {
-    auto action = std::make_unique<Action>(true);
+void ActionManager::QueueBuiltinAction(BuiltinFunction func, const std::string& name) {
+    auto action = std::make_unique<Action>(true, "<Builtin Action>", 0);
     std::vector<std::string> name_vector{name};
 
     if (!action->InitSingleTrigger(name)) {
         return;
     }
 
-    action->AddCommand(func, name_vector);
+    action->AddCommand(func, name_vector, 0);
 
-    trigger_queue_.push(std::make_unique<BuiltinTrigger>(action.get()));
+    event_queue_.emplace(action.get());
     actions_.emplace_back(std::move(action));
 }
 
 void ActionManager::ExecuteOneCommand() {
-    // Loop through the trigger queue until we have an action to execute
-    while (current_executing_actions_.empty() && !trigger_queue_.empty()) {
+    // Loop through the event queue until we have an action to execute
+    while (current_executing_actions_.empty() && !event_queue_.empty()) {
         for (const auto& action : actions_) {
-            if (trigger_queue_.front()->CheckTriggers(*action)) {
+            if (std::visit([&action](const auto& event) { return action->CheckEvent(event); },
+                           event_queue_.front())) {
                 current_executing_actions_.emplace(action.get());
             }
         }
-        trigger_queue_.pop();
+        event_queue_.pop();
     }
 
     if (current_executing_actions_.empty()) {
@@ -372,7 +293,8 @@
 
     if (current_command_ == 0) {
         std::string trigger_name = action->BuildTriggersString();
-        LOG(INFO) << "processing action (" << trigger_name << ")";
+        LOG(INFO) << "processing action (" << trigger_name << ") from (" << action->filename()
+                  << ":" << action->line() << ")";
     }
 
     action->ExecuteOneCommand(current_command_);
@@ -394,7 +316,7 @@
 }
 
 bool ActionManager::HasMoreCommands() const {
-    return !current_executing_actions_.empty() || !trigger_queue_.empty();
+    return !current_executing_actions_.empty() || !event_queue_.empty();
 }
 
 void ActionManager::DumpState() const {
@@ -403,15 +325,15 @@
     }
 }
 
-bool ActionParser::ParseSection(const std::vector<std::string>& args,
-                                std::string* err) {
+bool ActionParser::ParseSection(std::vector<std::string>&& args, const std::string& filename,
+                                int line, std::string* err) {
     std::vector<std::string> triggers(args.begin() + 1, args.end());
     if (triggers.size() < 1) {
         *err = "actions must have a trigger";
         return false;
     }
 
-    auto action = std::make_unique<Action>(false);
+    auto action = std::make_unique<Action>(false, filename, line);
     if (!action->InitTriggers(triggers, err)) {
         return false;
     }
@@ -420,14 +342,12 @@
     return true;
 }
 
-bool ActionParser::ParseLineSection(const std::vector<std::string>& args,
-                                    const std::string& filename, int line,
-                                    std::string* err) const {
-    return action_ ? action_->AddCommand(args, filename, line, err) : false;
+bool ActionParser::ParseLineSection(std::vector<std::string>&& args, int line, std::string* err) {
+    return action_ ? action_->AddCommand(std::move(args), line, err) : false;
 }
 
 void ActionParser::EndSection() {
     if (action_ && action_->NumCommands() > 0) {
-        ActionManager::GetInstance().AddAction(std::move(action_));
+        action_manager_->AddAction(std::move(action_));
     }
 }
diff --git a/init/action.h b/init/action.h
index 0bae9f0..d006c50 100644
--- a/init/action.h
+++ b/init/action.h
@@ -20,6 +20,7 @@
 #include <map>
 #include <queue>
 #include <string>
+#include <variant>
 #include <vector>
 
 #include "builtins.h"
@@ -27,44 +28,44 @@
 #include "keyword_map.h"
 
 class Command {
-public:
-    Command(BuiltinFunction f, const std::vector<std::string>& args,
-            const std::string& filename, int line);
+  public:
+    Command(BuiltinFunction f, const std::vector<std::string>& args, int line);
 
     int InvokeFunc() const;
     std::string BuildCommandString() const;
-    std::string BuildSourceString() const;
 
-private:
+    int line() const { return line_; }
+
+  private:
     BuiltinFunction func_;
     std::vector<std::string> args_;
-    std::string filename_;
     int line_;
 };
 
-class Action {
-public:
-    explicit Action(bool oneshot = false);
+using EventTrigger = std::string;
+using PropertyChange = std::pair<std::string, std::string>;
+using BuiltinAction = class Action*;
 
-    bool AddCommand(const std::vector<std::string>& args,
-                    const std::string& filename, int line, std::string* err);
-    void AddCommand(BuiltinFunction f,
-                    const std::vector<std::string>& args,
-                    const std::string& filename = "", int line = 0);
-    void CombineAction(const Action& action);
+class Action {
+  public:
+    explicit Action(bool oneshot, const std::string& filename, int line);
+
+    bool AddCommand(const std::vector<std::string>& args, int line, std::string* err);
+    void AddCommand(BuiltinFunction f, const std::vector<std::string>& args, int line);
     bool InitTriggers(const std::vector<std::string>& args, std::string* err);
     bool InitSingleTrigger(const std::string& trigger);
     std::size_t NumCommands() const;
     void ExecuteOneCommand(std::size_t command) const;
     void ExecuteAllCommands() const;
-    bool CheckEventTrigger(const std::string& trigger) const;
-    bool CheckPropertyTrigger(const std::string& name,
-                              const std::string& value) const;
-    bool TriggersEqual(const Action& other) const;
+    bool CheckEvent(const EventTrigger& event_trigger) const;
+    bool CheckEvent(const PropertyChange& property_change) const;
+    bool CheckEvent(const BuiltinAction& builtin_action) const;
     std::string BuildTriggersString() const;
     void DumpState() const;
 
     bool oneshot() const { return oneshot_; }
+    const std::string& filename() const { return filename_; }
+    int line() const { return line_; }
     static void set_function_map(const KeywordMap<BuiltinFunction>* function_map) {
         function_map_ = function_map;
     }
@@ -80,53 +81,48 @@
     std::string event_trigger_;
     std::vector<Command> commands_;
     bool oneshot_;
+    std::string filename_;
+    int line_;
     static const KeywordMap<BuiltinFunction>* function_map_;
 };
 
-class Trigger {
-public:
-    virtual ~Trigger() { }
-    virtual bool CheckTriggers(const Action& action) const = 0;
-};
-
 class ActionManager {
-public:
+  public:
     static ActionManager& GetInstance();
 
+    // Exposed for testing
+    ActionManager();
+
     void AddAction(std::unique_ptr<Action> action);
     void QueueEventTrigger(const std::string& trigger);
-    void QueuePropertyTrigger(const std::string& name, const std::string& value);
-    void QueueAllPropertyTriggers();
+    void QueuePropertyChange(const std::string& name, const std::string& value);
+    void QueueAllPropertyActions();
     void QueueBuiltinAction(BuiltinFunction func, const std::string& name);
     void ExecuteOneCommand();
     bool HasMoreCommands() const;
     void DumpState() const;
 
-private:
-    ActionManager();
-
+  private:
     ActionManager(ActionManager const&) = delete;
     void operator=(ActionManager const&) = delete;
 
     std::vector<std::unique_ptr<Action>> actions_;
-    std::queue<std::unique_ptr<Trigger>> trigger_queue_;
+    std::queue<std::variant<EventTrigger, PropertyChange, BuiltinAction>> event_queue_;
     std::queue<const Action*> current_executing_actions_;
     std::size_t current_command_;
 };
 
 class ActionParser : public SectionParser {
-public:
-    ActionParser() : action_(nullptr) {
-    }
-    bool ParseSection(const std::vector<std::string>& args,
+  public:
+    ActionParser(ActionManager* action_manager)
+        : action_manager_(action_manager), action_(nullptr) {}
+    bool ParseSection(std::vector<std::string>&& args, const std::string& filename, int line,
                       std::string* err) override;
-    bool ParseLineSection(const std::vector<std::string>& args,
-                          const std::string& filename, int line,
-                          std::string* err) const override;
+    bool ParseLineSection(std::vector<std::string>&& args, int line, std::string* err) override;
     void EndSection() override;
-    void EndFile(const std::string&) override {
-    }
-private:
+
+  private:
+    ActionManager* action_manager_;
     std::unique_ptr<Action> action_;
 };
 
diff --git a/init/bootchart.cpp b/init/bootchart.cpp
index 4a9c32e..825603a 100644
--- a/init/bootchart.cpp
+++ b/init/bootchart.cpp
@@ -16,10 +16,7 @@
 
 #include "bootchart.h"
 
-#include "property_service.h"
-
 #include <dirent.h>
-#include <errno.h>
 #include <fcntl.h>
 #include <stdio.h>
 #include <stdlib.h>
@@ -33,12 +30,11 @@
 #include <condition_variable>
 #include <memory>
 #include <mutex>
-#include <string>
 #include <thread>
-#include <vector>
 
 #include <android-base/file.h>
 #include <android-base/logging.h>
+#include <android-base/properties.h>
 #include <android-base/stringprintf.h>
 
 using android::base::StringPrintf;
@@ -72,7 +68,7 @@
   utsname uts;
   if (uname(&uts) == -1) return;
 
-  std::string fingerprint = property_get("ro.build.fingerprint");
+  std::string fingerprint = android::base::GetProperty("ro.build.fingerprint", "");
   if (fingerprint.empty()) return;
 
   std::string kernel_cmdline;
diff --git a/init/builtins.cpp b/init/builtins.cpp
index 43eb378..1d98ef1 100644
--- a/init/builtins.cpp
+++ b/init/builtins.cpp
@@ -19,51 +19,47 @@
 #include <dirent.h>
 #include <errno.h>
 #include <fcntl.h>
+#include <linux/loop.h>
+#include <linux/module.h>
 #include <mntent.h>
 #include <net/if.h>
-#include <signal.h>
 #include <sched.h>
+#include <signal.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#include <sys/socket.h>
 #include <sys/mount.h>
 #include <sys/resource.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
 #include <sys/syscall.h>
+#include <sys/system_properties.h>
 #include <sys/time.h>
 #include <sys/types.h>
-#include <sys/stat.h>
 #include <sys/wait.h>
 #include <unistd.h>
-#include <linux/loop.h>
-#include <linux/module.h>
 
-#include <string>
-#include <thread>
-
-#include <selinux/android.h>
-#include <selinux/selinux.h>
-#include <selinux/label.h>
-
-#include <fs_mgr.h>
 #include <android-base/file.h>
+#include <android-base/logging.h>
 #include <android-base/parseint.h>
-#include <android-base/strings.h>
+#include <android-base/properties.h>
 #include <android-base/stringprintf.h>
+#include <android-base/strings.h>
 #include <bootloader_message/bootloader_message.h>
-#include <cutils/partition_utils.h>
 #include <cutils/android_reboot.h>
 #include <ext4_utils/ext4_crypt.h>
 #include <ext4_utils/ext4_crypt_init_extensions.h>
-#include <logwrap/logwrap.h>
+#include <fs_mgr.h>
+#include <selinux/android.h>
+#include <selinux/label.h>
+#include <selinux/selinux.h>
 
 #include "action.h"
 #include "bootchart.h"
-#include "devices.h"
 #include "init.h"
 #include "init_parser.h"
-#include "log.h"
 #include "property_service.h"
+#include "reboot.h"
 #include "service.h"
 #include "signal_handler.h"
 #include "util.h"
@@ -71,7 +67,6 @@
 using namespace std::literals::string_literals;
 
 #define chmod DO_NOT_USE_CHMOD_USE_FCHMODAT_SYMLINK_NOFOLLOW
-#define UNMOUNT_CHECK_TIMES 10
 
 static constexpr std::chrono::nanoseconds kCommandRetryTimeout = 5s;
 
@@ -116,114 +111,14 @@
     return ret;
 }
 
-// Turn off backlight while we are performing power down cleanup activities.
-static void turnOffBacklight() {
-    static const char off[] = "0";
-
-    android::base::WriteStringToFile(off, "/sys/class/leds/lcd-backlight/brightness");
-
-    static const char backlightDir[] = "/sys/class/backlight";
-    std::unique_ptr<DIR, int(*)(DIR*)> dir(opendir(backlightDir), closedir);
-    if (!dir) {
-        return;
-    }
-
-    struct dirent *dp;
-    while ((dp = readdir(dir.get())) != NULL) {
-        if (((dp->d_type != DT_DIR) && (dp->d_type != DT_LNK)) ||
-                (dp->d_name[0] == '.')) {
-            continue;
-        }
-
-        std::string fileName = android::base::StringPrintf("%s/%s/brightness",
-                                                           backlightDir,
-                                                           dp->d_name);
-        android::base::WriteStringToFile(off, fileName);
-    }
-}
-
 static int reboot_into_recovery(const std::vector<std::string>& options) {
     std::string err;
     if (!write_bootloader_message(options, &err)) {
         LOG(ERROR) << "failed to set bootloader message: " << err;
         return -1;
     }
-    reboot("recovery");
-}
-
-static void unmount_and_fsck(const struct mntent *entry) {
-    if (strcmp(entry->mnt_type, "f2fs") && strcmp(entry->mnt_type, "ext4"))
-        return;
-
-    /* First, lazily unmount the directory. This unmount request finishes when
-     * all processes that open a file or directory in |entry->mnt_dir| exit.
-     */
-    TEMP_FAILURE_RETRY(umount2(entry->mnt_dir, MNT_DETACH));
-
-    /* Next, kill all processes except init, kthreadd, and kthreadd's
-     * children to finish the lazy unmount. Killing all processes here is okay
-     * because this callback function is only called right before reboot().
-     * It might be cleaner to selectively kill processes that actually use
-     * |entry->mnt_dir| rather than killing all, probably by reusing a function
-     * like killProcessesWithOpenFiles() in vold/, but the selinux policy does
-     * not allow init to scan /proc/<pid> files which the utility function
-     * heavily relies on. The policy does not allow the process to execute
-     * killall/pkill binaries either. Note that some processes might
-     * automatically restart after kill(), but that is not really a problem
-     * because |entry->mnt_dir| is no longer visible to such new processes.
-     */
-    ServiceManager::GetInstance().ForEachService([] (Service* s) { s->Stop(); });
-    TEMP_FAILURE_RETRY(kill(-1, SIGKILL));
-
-    // Restart Watchdogd to allow us to complete umounting and fsck
-    Service *svc = ServiceManager::GetInstance().FindServiceByName("watchdogd");
-    if (svc) {
-        do {
-            sched_yield(); // do not be so eager, let cleanup have priority
-            ServiceManager::GetInstance().ReapAnyOutstandingChildren();
-        } while (svc->flags() & SVC_RUNNING); // Paranoid Cargo
-        svc->Start();
-    }
-
-    turnOffBacklight();
-
-    int count = 0;
-    while (count++ < UNMOUNT_CHECK_TIMES) {
-        int fd = TEMP_FAILURE_RETRY(open(entry->mnt_fsname, O_RDONLY | O_EXCL));
-        if (fd >= 0) {
-            /* |entry->mnt_dir| has sucessfully been unmounted. */
-            close(fd);
-            break;
-        } else if (errno == EBUSY) {
-            // Some processes using |entry->mnt_dir| are still alive. Wait for a
-            // while then retry.
-            std::this_thread::sleep_for(5000ms / UNMOUNT_CHECK_TIMES);
-            continue;
-        } else {
-            /* Cannot open the device. Give up. */
-            return;
-        }
-    }
-
-    // NB: With watchdog still running, there is no cap on the time it takes
-    // to complete the fsck, from the users perspective the device graphics
-    // and responses are locked-up and they may choose to hold the power
-    // button in frustration if it drags out.
-
-    int st;
-    if (!strcmp(entry->mnt_type, "f2fs")) {
-        const char *f2fs_argv[] = {
-            "/system/bin/fsck.f2fs", "-f", entry->mnt_fsname,
-        };
-        android_fork_execvp_ext(arraysize(f2fs_argv), (char **)f2fs_argv,
-                                &st, true, LOG_KLOG, true, NULL, NULL, 0);
-    } else if (!strcmp(entry->mnt_type, "ext4")) {
-        const char *ext4_argv[] = {
-            "/system/bin/e2fsck", "-f", "-y", entry->mnt_fsname,
-        };
-        android_fork_execvp_ext(arraysize(ext4_argv), (char **)ext4_argv,
-                                &st, true, LOG_KLOG, true, NULL, NULL, 0);
-    }
+    DoReboot(ANDROID_RB_RESTART2, "reboot", "recovery", false);
+    return 0;
 }
 
 static int do_class_start(const std::vector<std::string>& args) {
@@ -248,8 +143,14 @@
     return 0;
 }
 
+static int do_class_restart(const std::vector<std::string>& args) {
+    ServiceManager::GetInstance().
+        ForEachServiceInClass(args[1], [] (Service* s) { s->Restart(); });
+    return 0;
+}
+
 static int do_domainname(const std::vector<std::string>& args) {
-    return write_file("/proc/sys/kernel/domainname", args[1].c_str()) ? 0 : 1;
+    return write_file("/proc/sys/kernel/domainname", args[1]) ? 0 : 1;
 }
 
 static int do_enable(const std::vector<std::string>& args) {
@@ -261,19 +162,11 @@
 }
 
 static int do_exec(const std::vector<std::string>& args) {
-    Service* svc = ServiceManager::GetInstance().MakeExecOneshotService(args);
-    if (!svc) {
-        return -1;
-    }
-    if (!start_waiting_for_exec()) {
-        return -1;
-    }
-    if (!svc->Start()) {
-        stop_waiting_for_exec();
-        ServiceManager::GetInstance().RemoveService(*svc);
-        return -1;
-    }
-    return 0;
+    return ServiceManager::GetInstance().Exec(args) ? 0 : -1;
+}
+
+static int do_exec_start(const std::vector<std::string>& args) {
+    return ServiceManager::GetInstance().ExecStart(args[1]) ? 0 : -1;
 }
 
 static int do_export(const std::vector<std::string>& args) {
@@ -281,7 +174,7 @@
 }
 
 static int do_hostname(const std::vector<std::string>& args) {
-    return write_file("/proc/sys/kernel/hostname", args[1].c_str()) ? 0 : 1;
+    return write_file("/proc/sys/kernel/hostname", args[1]) ? 0 : 1;
 }
 
 static int do_ifup(const std::vector<std::string>& args) {
@@ -497,7 +390,7 @@
 
     // Turning this on and letting the INFO logging be discarded adds 0.2s to
     // Nexus 9 boot time, so it's disabled by default.
-    if (false) parser.DumpState();
+    if (false) DumpState();
 }
 
 /* mount_fstab
@@ -705,89 +598,6 @@
     return 0;
 }
 
-static int do_powerctl(const std::vector<std::string>& args) {
-    const char* command = args[1].c_str();
-    int len = 0;
-    unsigned int cmd = 0;
-    const char *reboot_target = "";
-    void (*callback_on_ro_remount)(const struct mntent*) = NULL;
-
-    if (strncmp(command, "shutdown", 8) == 0) {
-        cmd = ANDROID_RB_POWEROFF;
-        len = 8;
-    } else if (strncmp(command, "reboot", 6) == 0) {
-        cmd = ANDROID_RB_RESTART2;
-        len = 6;
-    } else if (strncmp(command, "thermal-shutdown", 16) == 0) {
-        cmd = ANDROID_RB_THERMOFF;
-        len = 16;
-    } else {
-        LOG(ERROR) << "powerctl: unrecognized command '" << command << "'";
-        return -EINVAL;
-    }
-
-    if (command[len] == ',') {
-        if (cmd == ANDROID_RB_POWEROFF &&
-            !strcmp(&command[len + 1], "userrequested")) {
-            // The shutdown reason is PowerManager.SHUTDOWN_USER_REQUESTED.
-            // Run fsck once the file system is remounted in read-only mode.
-            callback_on_ro_remount = unmount_and_fsck;
-        } else if (cmd == ANDROID_RB_RESTART2) {
-            reboot_target = &command[len + 1];
-            // When rebooting to the bootloader notify the bootloader writing
-            // also the BCB.
-            if (strcmp(reboot_target, "bootloader") == 0) {
-                std::string err;
-                if (!write_reboot_bootloader(&err)) {
-                    LOG(ERROR) << "reboot-bootloader: Error writing "
-                                  "bootloader_message: " << err;
-                }
-            }
-        }
-    } else if (command[len] != '\0') {
-        LOG(ERROR) << "powerctl: unrecognized reboot target '" << &command[len] << "'";
-        return -EINVAL;
-    }
-
-    std::string timeout = property_get("ro.build.shutdown_timeout");
-    unsigned int delay = 0;
-
-    if (android::base::ParseUint(timeout, &delay) && delay > 0) {
-        Timer t;
-        // Ask all services to terminate.
-        ServiceManager::GetInstance().ForEachService(
-            [] (Service* s) { s->Terminate(); });
-
-        while (t.duration_s() < delay) {
-            ServiceManager::GetInstance().ReapAnyOutstandingChildren();
-
-            int service_count = 0;
-            ServiceManager::GetInstance().ForEachService(
-                [&service_count] (Service* s) {
-                    // Count the number of services running.
-                    // Exclude the console as it will ignore the SIGTERM signal
-                    // and not exit.
-                    // Note: SVC_CONSOLE actually means "requires console" but
-                    // it is only used by the shell.
-                    if (s->pid() != 0 && (s->flags() & SVC_CONSOLE) == 0) {
-                        service_count++;
-                    }
-                });
-
-            if (service_count == 0) {
-                // All terminable services terminated. We can exit early.
-                break;
-            }
-
-            // Wait a bit before recounting the number or running services.
-            std::this_thread::sleep_for(50ms);
-        }
-        LOG(VERBOSE) << "Terminating running services took " << t;
-    }
-
-    return android_reboot_with_callback(cmd, 0, reboot_target, callback_on_ro_remount);
-}
-
 static int do_trigger(const std::vector<std::string>& args) {
     ActionManager::GetInstance().QueueEventTrigger(args[1]);
     return 0;
@@ -815,11 +625,11 @@
 
 static int do_verity_load_state(const std::vector<std::string>& args) {
     int mode = -1;
-    int rc = fs_mgr_load_verity_state(&mode);
-    if (rc == 0 && mode != VERITY_MODE_DEFAULT) {
+    bool loaded = fs_mgr_load_verity_state(&mode);
+    if (loaded && mode != VERITY_MODE_DEFAULT) {
         ActionManager::GetInstance().QueueEventTrigger("verity-logging");
     }
-    return rc;
+    return loaded ? 0 : 1;
 }
 
 static void verity_update_property(fstab_rec *fstab, const char *mount_point,
@@ -829,71 +639,19 @@
 }
 
 static int do_verity_update_state(const std::vector<std::string>& args) {
-    return fs_mgr_update_verity_state(verity_update_property);
+    return fs_mgr_update_verity_state(verity_update_property) ? 0 : 1;
 }
 
 static int do_write(const std::vector<std::string>& args) {
-    const char* path = args[1].c_str();
-    const char* value = args[2].c_str();
-    return write_file(path, value) ? 0 : 1;
+    return write_file(args[1], args[2]) ? 0 : 1;
 }
 
 static int do_copy(const std::vector<std::string>& args) {
-    char *buffer = NULL;
-    int rc = 0;
-    int fd1 = -1, fd2 = -1;
-    struct stat info;
-    int brtw, brtr;
-    char *p;
-
-    if (stat(args[1].c_str(), &info) < 0)
-        return -1;
-
-    if ((fd1 = open(args[1].c_str(), O_RDONLY|O_CLOEXEC)) < 0)
-        goto out_err;
-
-    if ((fd2 = open(args[2].c_str(), O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0660)) < 0)
-        goto out_err;
-
-    if (!(buffer = (char*) malloc(info.st_size)))
-        goto out_err;
-
-    p = buffer;
-    brtr = info.st_size;
-    while(brtr) {
-        rc = read(fd1, p, brtr);
-        if (rc < 0)
-            goto out_err;
-        if (rc == 0)
-            break;
-        p += rc;
-        brtr -= rc;
+    std::string data;
+    if (read_file(args[1], &data)) {
+        return write_file(args[2], data) ? 0 : 1;
     }
-
-    p = buffer;
-    brtw = info.st_size;
-    while(brtw) {
-        rc = write(fd2, p, brtw);
-        if (rc < 0)
-            goto out_err;
-        if (rc == 0)
-            break;
-        p += rc;
-        brtw -= rc;
-    }
-
-    rc = 0;
-    goto out;
-out_err:
-    rc = -1;
-out:
-    if (buffer)
-        free(buffer);
-    if (fd1 >= 0)
-        close(fd1);
-    if (fd2 >= 0)
-        close(fd2);
-    return rc;
+    return 1;
 }
 
 static int do_chown(const std::vector<std::string>& args) {
@@ -1059,35 +817,43 @@
 }
 
 static bool is_file_crypto() {
-    std::string value = property_get("ro.crypto.type");
-    return value == "file";
+    return android::base::GetProperty("ro.crypto.type", "") == "file";
 }
 
 static int do_installkey(const std::vector<std::string>& args) {
     if (!is_file_crypto()) {
         return 0;
     }
-    return e4crypt_create_device_key(args[1].c_str(),
-                                     do_installkeys_ensure_dir_exists);
+    auto unencrypted_dir = args[1] + e4crypt_unencrypted_folder;
+    if (do_installkeys_ensure_dir_exists(unencrypted_dir.c_str())) {
+        PLOG(ERROR) << "Failed to create " << unencrypted_dir;
+        return -1;
+    }
+    std::vector<std::string> exec_args = {"exec", "/system/bin/vdc", "--wait", "cryptfs",
+                                          "enablefilecrypto"};
+    return do_exec(exec_args);
 }
 
 static int do_init_user0(const std::vector<std::string>& args) {
     return e4crypt_do_init_user0();
 }
 
-BuiltinFunctionMap::Map& BuiltinFunctionMap::map() const {
+const BuiltinFunctionMap::Map& BuiltinFunctionMap::map() const {
     constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
+    // clang-format off
     static const Map builtin_functions = {
         {"bootchart",               {1,     1,    do_bootchart}},
         {"chmod",                   {2,     2,    do_chmod}},
         {"chown",                   {2,     3,    do_chown}},
         {"class_reset",             {1,     1,    do_class_reset}},
+        {"class_restart",           {1,     1,    do_class_restart}},
         {"class_start",             {1,     1,    do_class_start}},
         {"class_stop",              {1,     1,    do_class_stop}},
         {"copy",                    {2,     2,    do_copy}},
         {"domainname",              {1,     1,    do_domainname}},
         {"enable",                  {1,     1,    do_enable}},
         {"exec",                    {1,     kMax, do_exec}},
+        {"exec_start",              {1,     1,    do_exec_start}},
         {"export",                  {2,     2,    do_export}},
         {"hostname",                {1,     1,    do_hostname}},
         {"ifup",                    {1,     1,    do_ifup}},
@@ -1101,7 +867,6 @@
         {"mount_all",               {1,     kMax, do_mount_all}},
         {"mount",                   {3,     kMax, do_mount}},
         {"umount",                  {1,     1,    do_umount}},
-        {"powerctl",                {1,     1,    do_powerctl}},
         {"restart",                 {1,     1,    do_restart}},
         {"restorecon",              {1,     kMax, do_restorecon}},
         {"restorecon_recursive",    {1,     kMax, do_restorecon_recursive}},
@@ -1121,5 +886,6 @@
         {"wait_for_prop",           {2,     2,    do_wait_for_prop}},
         {"write",                   {2,     2,    do_write}},
     };
+    // clang-format on
     return builtin_functions;
 }
diff --git a/init/builtins.h b/init/builtins.h
index 53f4a71..e1f0567 100644
--- a/init/builtins.h
+++ b/init/builtins.h
@@ -17,19 +17,20 @@
 #ifndef _INIT_BUILTINS_H
 #define _INIT_BUILTINS_H
 
+#include <functional>
 #include <map>
 #include <string>
 #include <vector>
 
 #include "keyword_map.h"
 
-using BuiltinFunction = int (*) (const std::vector<std::string>& args);
+using BuiltinFunction = std::function<int(const std::vector<std::string>&)>;
 class BuiltinFunctionMap : public KeywordMap<BuiltinFunction> {
-public:
-    BuiltinFunctionMap() {
-    }
-private:
-    Map& map() const override;
+  public:
+    BuiltinFunctionMap() {}
+
+  private:
+    const Map& map() const override;
 };
 
 #endif
diff --git a/init/descriptors.cpp b/init/descriptors.cpp
index 6e457cd..bc6bc8d 100644
--- a/init/descriptors.cpp
+++ b/init/descriptors.cpp
@@ -19,16 +19,15 @@
 #include <ctype.h>
 #include <fcntl.h>
 #include <sys/stat.h>
-#include <sys/types.h>
 #include <unistd.h>
 
+#include <android-base/logging.h>
 #include <android-base/stringprintf.h>
 #include <android-base/unique_fd.h>
 #include <cutils/android_get_control_file.h>
 #include <cutils/sockets.h>
 
 #include "init.h"
-#include "log.h"
 #include "util.h"
 
 DescriptorInfo::DescriptorInfo(const std::string& name, const std::string& type, uid_t uid,
diff --git a/init/devices.cpp b/init/devices.cpp
index 405f92e..11687f0 100644
--- a/init/devices.cpp
+++ b/init/devices.cpp
@@ -14,166 +14,235 @@
  * limitations under the License.
  */
 
+#include "devices.h"
+
 #include <dirent.h>
 #include <errno.h>
 #include <fcntl.h>
 #include <fnmatch.h>
+#include <grp.h>
 #include <libgen.h>
+#include <linux/netlink.h>
+#include <pwd.h>
 #include <stddef.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <sys/sendfile.h>
 #include <sys/socket.h>
-#include <sys/stat.h>
 #include <sys/time.h>
-#include <sys/types.h>
 #include <sys/un.h>
 #include <sys/wait.h>
 #include <unistd.h>
 
-#include <linux/netlink.h>
-
+#include <algorithm>
 #include <memory>
 #include <thread>
 
-#include <selinux/selinux.h>
-#include <selinux/label.h>
-#include <selinux/android.h>
-#include <selinux/avc.h>
-
-#include <private/android_filesystem_config.h>
-
 #include <android-base/file.h>
+#include <android-base/logging.h>
 #include <android-base/stringprintf.h>
+#include <android-base/strings.h>
 #include <android-base/unique_fd.h>
-#include <cutils/list.h>
 #include <cutils/uevent.h>
+#include <private/android_filesystem_config.h>
+#include <selinux/android.h>
+#include <selinux/label.h>
+#include <selinux/selinux.h>
 
-#include "devices.h"
-#include "ueventd_parser.h"
+#include "keyword_map.h"
+#include "ueventd.h"
 #include "util.h"
-#include "log.h"
-
-#define SYSFS_PREFIX    "/sys"
-static const char *firmware_dirs[] = { "/etc/firmware",
-                                       "/vendor/firmware",
-                                       "/firmware/image" };
 
 extern struct selabel_handle *sehandle;
 
 static android::base::unique_fd device_fd;
 
-struct perms_ {
-    char *name;
-    char *attr;
-    mode_t perm;
-    unsigned int uid;
-    unsigned int gid;
-    unsigned short prefix;
-    unsigned short wildcard;
-};
-
-struct perm_node {
-    struct perms_ dp;
-    struct listnode plist;
-};
-
-struct platform_node {
-    char *name;
-    char *path;
-    int path_len;
-    struct listnode list;
-};
-
-static list_declare(sys_perms);
-static list_declare(dev_perms);
-static list_declare(platform_names);
-
-int add_dev_perms(const char *name, const char *attr,
-                  mode_t perm, unsigned int uid, unsigned int gid,
-                  unsigned short prefix,
-                  unsigned short wildcard) {
-    struct perm_node *node = (perm_node*) calloc(1, sizeof(*node));
-    if (!node)
-        return -ENOMEM;
-
-    node->dp.name = strdup(name);
-    if (!node->dp.name) {
-        free(node);
-        return -ENOMEM;
+Permissions::Permissions(const std::string& name, mode_t perm, uid_t uid, gid_t gid)
+    : name_(name), perm_(perm), uid_(uid), gid_(gid), prefix_(false), wildcard_(false) {
+    // If the first * is the last character, then we'll treat name_ as a prefix
+    // Otherwise, if a * is present, then we do a full fnmatch().
+    auto wildcard_position = name_.find('*');
+    if (wildcard_position == name_.length() - 1) {
+        prefix_ = true;
+        name_.pop_back();
+    } else if (wildcard_position != std::string::npos) {
+        wildcard_ = true;
     }
-
-    if (attr) {
-        node->dp.attr = strdup(attr);
-        if (!node->dp.attr) {
-            free(node->dp.name);
-            free(node);
-            return -ENOMEM;
-        }
-    }
-
-    node->dp.perm = perm;
-    node->dp.uid = uid;
-    node->dp.gid = gid;
-    node->dp.prefix = prefix;
-    node->dp.wildcard = wildcard;
-
-    if (attr)
-        list_add_tail(&sys_perms, &node->plist);
-    else
-        list_add_tail(&dev_perms, &node->plist);
-
-    return 0;
 }
 
-static bool perm_path_matches(const char *path, struct perms_ *dp)
-{
-    if (dp->prefix) {
-        if (strncmp(path, dp->name, strlen(dp->name)) == 0)
-            return true;
-    } else if (dp->wildcard) {
-        if (fnmatch(dp->name, path, FNM_PATHNAME) == 0)
-            return true;
+bool Permissions::Match(const std::string& path) const {
+    if (prefix_) {
+        return android::base::StartsWith(path, name_.c_str());
+    } else if (wildcard_) {
+        return fnmatch(name_.c_str(), path.c_str(), FNM_PATHNAME) == 0;
     } else {
-        if (strcmp(path, dp->name) == 0)
-            return true;
+        return path == name_;
     }
 
     return false;
 }
 
-static bool match_subsystem(perms_* dp, const char* pattern,
-                            const char* path, const char* subsystem) {
-    if (!pattern || !subsystem || strstr(dp->name, subsystem) == NULL) {
+bool SysfsPermissions::MatchWithSubsystem(const std::string& path,
+                                          const std::string& subsystem) const {
+    std::string path_basename = android::base::Basename(path);
+    if (name().find(subsystem) != std::string::npos) {
+        if (Match("/sys/class/" + subsystem + "/" + path_basename)) return true;
+        if (Match("/sys/bus/" + subsystem + "/devices/" + path_basename)) return true;
+    }
+    return Match(path);
+}
+
+void SysfsPermissions::SetPermissions(const std::string& path) const {
+    std::string attribute_file = path + "/" + attribute_;
+    LOG(INFO) << "fixup " << attribute_file << " " << uid() << " " << gid() << " " << std::oct
+              << perm();
+    chown(attribute_file.c_str(), uid(), gid());
+    chmod(attribute_file.c_str(), perm());
+}
+
+// TODO: Move these to be member variables of a future devices class.
+std::vector<Permissions> dev_permissions;
+std::vector<SysfsPermissions> sysfs_permissions;
+
+bool ParsePermissionsLine(std::vector<std::string>&& args, std::string* err, bool is_sysfs) {
+    if (is_sysfs && args.size() != 5) {
+        *err = "/sys/ lines must have 5 entries";
         return false;
     }
 
-    std::string subsys_path = android::base::StringPrintf(pattern, subsystem, basename(path));
-    return perm_path_matches(subsys_path.c_str(), dp);
+    if (!is_sysfs && args.size() != 4) {
+        *err = "/dev/ lines must have 4 entries";
+        return false;
+    }
+
+    auto it = args.begin();
+    const std::string& name = *it++;
+
+    std::string sysfs_attribute;
+    if (is_sysfs) sysfs_attribute = *it++;
+
+    // args is now common to both sys and dev entries and contains: <perm> <uid> <gid>
+    std::string& perm_string = *it++;
+    char* end_pointer = 0;
+    mode_t perm = strtol(perm_string.c_str(), &end_pointer, 8);
+    if (end_pointer == nullptr || *end_pointer != '\0') {
+        *err = "invalid mode '" + perm_string + "'";
+        return false;
+    }
+
+    std::string& uid_string = *it++;
+    passwd* pwd = getpwnam(uid_string.c_str());
+    if (!pwd) {
+        *err = "invalid uid '" + uid_string + "'";
+        return false;
+    }
+    uid_t uid = pwd->pw_uid;
+
+    std::string& gid_string = *it++;
+    struct group* grp = getgrnam(gid_string.c_str());
+    if (!grp) {
+        *err = "invalid gid '" + gid_string + "'";
+        return false;
+    }
+    gid_t gid = grp->gr_gid;
+
+    if (is_sysfs) {
+        sysfs_permissions.emplace_back(name, sysfs_attribute, perm, uid, gid);
+    } else {
+        dev_permissions.emplace_back(name, perm, uid, gid);
+    }
+    return true;
 }
 
-static void fixup_sys_perms(const char* upath, const char* subsystem) {
+// TODO: Move this to be a member variable of a future devices class.
+static std::vector<Subsystem> subsystems;
+
+std::string Subsystem::ParseDevPath(uevent* uevent) const {
+    std::string devname = devname_source_ == DevnameSource::DEVNAME_UEVENT_DEVNAME
+                              ? uevent->device_name
+                              : android::base::Basename(uevent->path);
+
+    return dir_name_ + "/" + devname;
+}
+
+bool SubsystemParser::ParseSection(std::vector<std::string>&& args, const std::string& filename,
+                                   int line, std::string* err) {
+    if (args.size() != 2) {
+        *err = "subsystems must have exactly one name";
+        return false;
+    }
+
+    if (std::find(subsystems.begin(), subsystems.end(), args[1]) != subsystems.end()) {
+        *err = "ignoring duplicate subsystem entry";
+        return false;
+    }
+
+    subsystem_.name_ = args[1];
+
+    return true;
+}
+
+bool SubsystemParser::ParseDevName(std::vector<std::string>&& args, std::string* err) {
+    if (args[1] == "uevent_devname") {
+        subsystem_.devname_source_ = Subsystem::DevnameSource::DEVNAME_UEVENT_DEVNAME;
+        return true;
+    }
+    if (args[1] == "uevent_devpath") {
+        subsystem_.devname_source_ = Subsystem::DevnameSource::DEVNAME_UEVENT_DEVPATH;
+        return true;
+    }
+
+    *err = "invalid devname '" + args[1] + "'";
+    return false;
+}
+
+bool SubsystemParser::ParseDirName(std::vector<std::string>&& args, std::string* err) {
+    if (args[1].front() != '/') {
+        *err = "dirname '" + args[1] + " ' does not start with '/'";
+        return false;
+    }
+
+    subsystem_.dir_name_ = args[1];
+    return true;
+}
+
+bool SubsystemParser::ParseLineSection(std::vector<std::string>&& args, int line, std::string* err) {
+    using OptionParser =
+        bool (SubsystemParser::*)(std::vector<std::string> && args, std::string * err);
+    static class OptionParserMap : public KeywordMap<OptionParser> {
+      private:
+        const Map& map() const override {
+            // clang-format off
+            static const Map option_parsers = {
+                {"devname",     {1,     1,      &SubsystemParser::ParseDevName}},
+                {"dirname",     {1,     1,      &SubsystemParser::ParseDirName}},
+            };
+            // clang-format on
+            return option_parsers;
+        }
+    } parser_map;
+
+    auto parser = parser_map.FindFunction(args, err);
+
+    if (!parser) {
+        return false;
+    }
+
+    return (this->*parser)(std::move(args), err);
+}
+
+void SubsystemParser::EndSection() {
+    subsystems.emplace_back(std::move(subsystem_));
+}
+
+static void fixup_sys_permissions(const std::string& upath, const std::string& subsystem) {
     // upaths omit the "/sys" that paths in this list
     // contain, so we prepend it...
-    std::string path = std::string(SYSFS_PREFIX) + upath;
+    std::string path = "/sys" + upath;
 
-    listnode* node;
-    list_for_each(node, &sys_perms) {
-        perms_* dp = &(node_to_item(node, perm_node, plist))->dp;
-        if (match_subsystem(dp, SYSFS_PREFIX "/class/%s/%s", path.c_str(), subsystem)) {
-            ; // matched
-        } else if (match_subsystem(dp, SYSFS_PREFIX "/bus/%s/devices/%s", path.c_str(), subsystem)) {
-            ; // matched
-        } else if (!perm_path_matches(path.c_str(), dp)) {
-            continue;
-        }
-
-        std::string attr_file = path + "/" + dp->attr;
-        LOG(INFO) << "fixup " << attr_file
-                  << " " << dp->uid << " " << dp->gid << " " << std::oct << dp->perm;
-        chown(attr_file.c_str(), dp->uid, dp->gid);
-        chmod(attr_file.c_str(), dp->perm);
+    for (const auto& s : sysfs_permissions) {
+        if (s.MatchWithSubsystem(path, subsystem)) s.SetPermissions(path);
     }
 
     if (access(path.c_str(), F_OK) == 0) {
@@ -182,63 +251,34 @@
     }
 }
 
-static mode_t get_device_perm(const char *path, const char **links,
-                unsigned *uid, unsigned *gid)
-{
-    struct listnode *node;
-    struct perm_node *perm_node;
-    struct perms_ *dp;
-
-    /* search the perms list in reverse so that ueventd.$hardware can
-     * override ueventd.rc
-     */
-    list_for_each_reverse(node, &dev_perms) {
-        bool match = false;
-
-        perm_node = node_to_item(node, struct perm_node, plist);
-        dp = &perm_node->dp;
-
-        if (perm_path_matches(path, dp)) {
-            match = true;
-        } else {
-            if (links) {
-                int i;
-                for (i = 0; links[i]; i++) {
-                    if (perm_path_matches(links[i], dp)) {
-                        match = true;
-                        break;
-                    }
-                }
-            }
-        }
-
-        if (match) {
-            *uid = dp->uid;
-            *gid = dp->gid;
-            return dp->perm;
+static std::tuple<mode_t, uid_t, gid_t> get_device_permissions(
+    const std::string& path, const std::vector<std::string>& links) {
+    // Search the perms list in reverse so that ueventd.$hardware can override ueventd.rc.
+    for (auto it = dev_permissions.rbegin(); it != dev_permissions.rend(); ++it) {
+        if (it->Match(path) || std::any_of(links.begin(), links.end(),
+                                           [it](const auto& link) { return it->Match(link); })) {
+            return {it->perm(), it->uid(), it->gid()};
         }
     }
     /* Default if nothing found. */
-    *uid = 0;
-    *gid = 0;
-    return 0600;
+    return {0600, 0, 0};
 }
 
-static void make_device(const char *path,
-                        const char */*upath*/,
-                        int block, int major, int minor,
-                        const char **links)
-{
-    unsigned uid;
-    unsigned gid;
-    mode_t mode;
+static void make_device(const std::string& path, int block, int major, int minor,
+                        const std::vector<std::string>& links) {
     dev_t dev;
     char *secontext = NULL;
 
-    mode = get_device_perm(path, links, &uid, &gid) | (block ? S_IFBLK : S_IFCHR);
+    auto [mode, uid, gid] = get_device_permissions(path, links);
+    mode |= (block ? S_IFBLK : S_IFCHR);
 
     if (sehandle) {
-        if (selabel_lookup_best_match(sehandle, &secontext, path, links, mode)) {
+        std::vector<const char*> c_links;
+        for (const auto& link : links) {
+            c_links.emplace_back(link.c_str());
+        }
+        c_links.emplace_back(nullptr);
+        if (selabel_lookup_best_match(sehandle, &secontext, path.c_str(), &c_links[0], mode)) {
             PLOG(ERROR) << "Device '" << path << "' not created; cannot find SELinux label";
             return;
         }
@@ -257,10 +297,9 @@
     }
     /* If the node already exists update its SELinux label to handle cases when
      * it was created with the wrong context during coldboot procedure. */
-    if (mknod(path, mode, dev) && (errno == EEXIST) && secontext) {
-
+    if (mknod(path.c_str(), mode, dev) && (errno == EEXIST) && secontext) {
         char* fcon = nullptr;
-        int rc = lgetfilecon(path, &fcon);
+        int rc = lgetfilecon(path.c_str(), &fcon);
         if (rc < 0) {
             PLOG(ERROR) << "Cannot get SELinux label on '" << path << "' device";
             goto out;
@@ -269,13 +308,13 @@
         bool different = strcmp(fcon, secontext) != 0;
         freecon(fcon);
 
-        if (different && lsetfilecon(path, secontext)) {
+        if (different && lsetfilecon(path.c_str(), secontext)) {
             PLOG(ERROR) << "Cannot set '" << secontext << "' SELinux label on '" << path << "' device";
         }
     }
 
 out:
-    chown(path, uid, -1);
+    chown(path.c_str(), uid, -1);
     if (setegid(AID_ROOT)) {
         PLOG(FATAL) << "setegid(AID_ROOT) failed";
     }
@@ -286,151 +325,86 @@
     }
 }
 
-static void add_platform_device(const char *path)
-{
-    int path_len = strlen(path);
-    struct platform_node *bus;
-    const char *name = path;
+// TODO: Move this to be a member variable of a future devices class.
+std::vector<std::string> platform_devices;
 
-    if (!strncmp(path, "/devices/", 9)) {
-        name += 9;
-        if (!strncmp(name, "platform/", 9))
-            name += 9;
-    }
-
-    LOG(VERBOSE) << "adding platform device " << name << " (" << path << ")";
-
-    bus = (platform_node*) calloc(1, sizeof(struct platform_node));
-    bus->path = strdup(path);
-    bus->path_len = path_len;
-    bus->name = bus->path + (name - path);
-    list_add_tail(&platform_names, &bus->list);
-}
-
-/*
- * given a path that may start with a platform device, find the length of the
- * platform device prefix.  If it doesn't start with a platform device, return
- * 0.
- */
-static struct platform_node *find_platform_device(const char *path)
-{
-    int path_len = strlen(path);
-    struct listnode *node;
-    struct platform_node *bus;
-
-    list_for_each_reverse(node, &platform_names) {
-        bus = node_to_item(node, struct platform_node, list);
-        if ((bus->path_len < path_len) &&
-                (path[bus->path_len] == '/') &&
-                !strncmp(path, bus->path, bus->path_len))
-            return bus;
-    }
-
-    return NULL;
-}
-
-static void remove_platform_device(const char *path)
-{
-    struct listnode *node;
-    struct platform_node *bus;
-
-    list_for_each_reverse(node, &platform_names) {
-        bus = node_to_item(node, struct platform_node, list);
-        if (!strcmp(path, bus->path)) {
-            LOG(INFO) << "removing platform device " << bus->name;
-            free(bus->path);
-            list_remove(node);
-            free(bus);
-            return;
+// Given a path that may start with a platform device, find the length of the
+// platform device prefix.  If it doesn't start with a platform device, return false
+bool find_platform_device(const std::string& path, std::string* out_path) {
+    out_path->clear();
+    // platform_devices is searched backwards, since parents are added before their children,
+    // and we want to match as deep of a child as we can.
+    for (auto it = platform_devices.rbegin(); it != platform_devices.rend(); ++it) {
+        auto platform_device_path_length = it->length();
+        if (platform_device_path_length < path.length() &&
+            path[platform_device_path_length] == '/' &&
+            android::base::StartsWith(path, it->c_str())) {
+            *out_path = *it;
+            return true;
         }
     }
-}
-
-static void destroy_platform_devices() {
-    struct listnode* node;
-    struct listnode* n;
-    struct platform_node* bus;
-
-    list_for_each_safe(node, n, &platform_names) {
-        list_remove(node);
-        bus = node_to_item(node, struct platform_node, list);
-        free(bus->path);
-        free(bus);
-    }
+    return false;
 }
 
 /* Given a path that may start with a PCI device, populate the supplied buffer
  * with the PCI domain/bus number and the peripheral ID and return 0.
  * If it doesn't start with a PCI device, or there is some error, return -1 */
-static int find_pci_device_prefix(const char *path, char *buf, ssize_t buf_sz)
-{
-    const char *start, *end;
+static bool find_pci_device_prefix(const std::string& path, std::string* result) {
+    result->clear();
 
-    if (strncmp(path, "/devices/pci", 12))
-        return -1;
+    if (!android::base::StartsWith(path, "/devices/pci")) return false;
 
     /* Beginning of the prefix is the initial "pci" after "/devices/" */
-    start = path + 9;
+    std::string::size_type start = 9;
 
     /* End of the prefix is two path '/' later, capturing the domain/bus number
      * and the peripheral ID. Example: pci0000:00/0000:00:1f.2 */
-    end = strchr(start, '/');
-    if (!end)
-        return -1;
-    end = strchr(end + 1, '/');
-    if (!end)
-        return -1;
+    auto end = path.find('/', start);
+    if (end == std::string::npos) return false;
 
-    /* Make sure we have enough room for the string plus null terminator */
-    if (end - start + 1 > buf_sz)
-        return -1;
+    end = path.find('/', end + 1);
+    if (end == std::string::npos) return false;
 
-    strncpy(buf, start, end - start);
-    buf[end - start] = '\0';
-    return 0;
+    auto length = end - start;
+    if (length <= 4) {
+        // The minimum string that will get to this check is 'pci/', which is malformed,
+        // so return false
+        return false;
+    }
+
+    *result = path.substr(start, length);
+    return true;
 }
 
 /* Given a path that may start with a virtual block device, populate
  * the supplied buffer with the virtual block device ID and return 0.
  * If it doesn't start with a virtual block device, or there is some
  * error, return -1 */
-static int find_vbd_device_prefix(const char *path, char *buf, ssize_t buf_sz)
-{
-    const char *start, *end;
+static bool find_vbd_device_prefix(const std::string& path, std::string* result) {
+    result->clear();
+
+    if (!android::base::StartsWith(path, "/devices/vbd-")) return false;
 
     /* Beginning of the prefix is the initial "vbd-" after "/devices/" */
-    if (strncmp(path, "/devices/vbd-", 13))
-        return -1;
+    std::string::size_type start = 13;
 
     /* End of the prefix is one path '/' later, capturing the
        virtual block device ID. Example: 768 */
-    start = path + 13;
-    end = strchr(start, '/');
-    if (!end)
-        return -1;
+    auto end = path.find('/', start);
+    if (end == std::string::npos) return false;
 
-    /* Make sure we have enough room for the string plus null terminator */
-    if (end - start + 1 > buf_sz)
-        return -1;
+    auto length = end - start;
+    if (length == 0) return false;
 
-    strncpy(buf, start, end - start);
-    buf[end - start] = '\0';
-    return 0;
+    *result = path.substr(start, length);
+    return true;
 }
 
-static void parse_event(const char *msg, struct uevent *uevent)
-{
-    uevent->action = "";
-    uevent->path = "";
-    uevent->subsystem = "";
-    uevent->firmware = "";
+void parse_event(const char* msg, uevent* uevent) {
+    uevent->partition_num = -1;
     uevent->major = -1;
     uevent->minor = -1;
-    uevent->partition_name = NULL;
-    uevent->partition_num = -1;
-    uevent->device_name = NULL;
-
-        /* currently ignoring SEQNUM */
+    // currently ignoring SEQNUM
     while(*msg) {
         if(!strncmp(msg, "ACTION=", 7)) {
             msg += 7;
@@ -461,371 +435,228 @@
             uevent->device_name = msg;
         }
 
-        /* advance to after the next \0 */
+        // advance to after the next \0
         while(*msg++)
             ;
     }
 
     if (LOG_UEVENTS) {
-        LOG(INFO) << android::base::StringPrintf("event { '%s', '%s', '%s', '%s', %d, %d }",
-                                                 uevent->action, uevent->path, uevent->subsystem,
-                                                 uevent->firmware, uevent->major, uevent->minor);
+        LOG(INFO) << "event { '" << uevent->action << "', '" << uevent->path << "', '"
+                  << uevent->subsystem << "', '" << uevent->firmware << "', " << uevent->major
+                  << ", " << uevent->minor << " }";
     }
 }
 
-static char **get_character_device_symlinks(struct uevent *uevent)
-{
-    const char *parent;
-    const char *slash;
-    char **links;
-    int link_num = 0;
-    int width;
-    struct platform_node *pdev;
+std::vector<std::string> get_character_device_symlinks(uevent* uevent) {
+    std::string parent_device;
+    if (!find_platform_device(uevent->path, &parent_device)) return {};
 
-    pdev = find_platform_device(uevent->path);
-    if (!pdev)
-        return NULL;
+    // skip path to the parent driver
+    std::string path = uevent->path.substr(parent_device.length());
 
-    links = (char**) malloc(sizeof(char *) * 2);
-    if (!links)
-        return NULL;
-    memset(links, 0, sizeof(char *) * 2);
+    if (!android::base::StartsWith(path, "/usb")) return {};
 
-    /* skip "/devices/platform/<driver>" */
-    parent = strchr(uevent->path + pdev->path_len, '/');
-    if (!parent)
-        goto err;
+    // skip root hub name and device. use device interface
+    // skip 3 slashes, including the first / by starting the search at the 1st character, not 0th.
+    // then extract what comes between the 3rd and 4th slash
+    // e.g. "/usb/usb_device/name/tty2-1:1.0" -> "name"
 
-    if (!strncmp(parent, "/usb", 4)) {
-        /* skip root hub name and device. use device interface */
-        while (*++parent && *parent != '/');
-        if (*parent)
-            while (*++parent && *parent != '/');
-        if (!*parent)
-            goto err;
-        slash = strchr(++parent, '/');
-        if (!slash)
-            goto err;
-        width = slash - parent;
-        if (width <= 0)
-            goto err;
+    std::string::size_type start = 0;
+    start = path.find('/', start + 1);
+    if (start == std::string::npos) return {};
 
-        if (asprintf(&links[link_num], "/dev/usb/%s%.*s", uevent->subsystem, width, parent) > 0)
-            link_num++;
-        else
-            links[link_num] = NULL;
-        mkdir("/dev/usb", 0755);
-    }
-    else {
-        goto err;
-    }
+    start = path.find('/', start + 1);
+    if (start == std::string::npos) return {};
+
+    auto end = path.find('/', start + 1);
+    if (end == std::string::npos) return {};
+
+    start++;  // Skip the first '/'
+
+    auto length = end - start;
+    if (length == 0) return {};
+
+    auto name_string = path.substr(start, length);
+
+    std::vector<std::string> links;
+    links.emplace_back("/dev/usb/" + uevent->subsystem + name_string);
+
+    mkdir("/dev/usb", 0755);
 
     return links;
-err:
-    free(links);
-    return NULL;
 }
 
-static char **get_block_device_symlinks(struct uevent *uevent)
-{
-    const char *device;
-    struct platform_node *pdev;
-    const char *slash;
-    const char *type;
-    char buf[256];
-    char link_path[256];
-    int link_num = 0;
-    char *p;
+// replaces any unacceptable characters with '_', the
+// length of the resulting string is equal to the input string
+void sanitize_partition_name(std::string* string) {
+    const char* accept =
+        "abcdefghijklmnopqrstuvwxyz"
+        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+        "0123456789"
+        "_-.";
 
-    pdev = find_platform_device(uevent->path);
-    if (pdev) {
-        device = pdev->name;
+    if (!string) return;
+
+    std::string::size_type pos = 0;
+    while ((pos = string->find_first_not_of(accept, pos)) != std::string::npos) {
+        (*string)[pos] = '_';
+    }
+}
+
+std::vector<std::string> get_block_device_symlinks(uevent* uevent) {
+    std::string device;
+    std::string type;
+
+    if (find_platform_device(uevent->path, &device)) {
+        // Skip /devices/platform or /devices/ if present
+        static const std::string devices_platform_prefix = "/devices/platform/";
+        static const std::string devices_prefix = "/devices/";
+
+        if (android::base::StartsWith(device, devices_platform_prefix.c_str())) {
+            device = device.substr(devices_platform_prefix.length());
+        } else if (android::base::StartsWith(device, devices_prefix.c_str())) {
+            device = device.substr(devices_prefix.length());
+        }
+
         type = "platform";
-    } else if (!find_pci_device_prefix(uevent->path, buf, sizeof(buf))) {
-        device = buf;
+    } else if (find_pci_device_prefix(uevent->path, &device)) {
         type = "pci";
-    } else if (!find_vbd_device_prefix(uevent->path, buf, sizeof(buf))) {
-        device = buf;
+    } else if (find_vbd_device_prefix(uevent->path, &device)) {
         type = "vbd";
     } else {
-        return NULL;
+        return {};
     }
 
-    char **links = (char**) malloc(sizeof(char *) * 4);
-    if (!links)
-        return NULL;
-    memset(links, 0, sizeof(char *) * 4);
+    std::vector<std::string> links;
 
     LOG(VERBOSE) << "found " << type << " device " << device;
 
-    snprintf(link_path, sizeof(link_path), "/dev/block/%s/%s", type, device);
+    auto link_path = "/dev/block/" + type + "/" + device;
 
-    if (uevent->partition_name) {
-        p = strdup(uevent->partition_name);
-        sanitize(p);
-        if (strcmp(uevent->partition_name, p)) {
-            LOG(VERBOSE) << "Linking partition '" << uevent->partition_name << "' as '" << p << "'";
+    if (!uevent->partition_name.empty()) {
+        std::string partition_name_sanitized(uevent->partition_name);
+        sanitize_partition_name(&partition_name_sanitized);
+        if (partition_name_sanitized != uevent->partition_name) {
+            LOG(VERBOSE) << "Linking partition '" << uevent->partition_name << "' as '"
+                         << partition_name_sanitized << "'";
         }
-        if (asprintf(&links[link_num], "%s/by-name/%s", link_path, p) > 0)
-            link_num++;
-        else
-            links[link_num] = NULL;
-        free(p);
+        links.emplace_back(link_path + "/by-name/" + partition_name_sanitized);
     }
 
     if (uevent->partition_num >= 0) {
-        if (asprintf(&links[link_num], "%s/by-num/p%d", link_path, uevent->partition_num) > 0)
-            link_num++;
-        else
-            links[link_num] = NULL;
+        links.emplace_back(link_path + "/by-num/p" + std::to_string(uevent->partition_num));
     }
 
-    slash = strrchr(uevent->path, '/');
-    if (asprintf(&links[link_num], "%s/%s", link_path, slash + 1) > 0)
-        link_num++;
-    else
-        links[link_num] = NULL;
+    auto last_slash = uevent->path.rfind('/');
+    links.emplace_back(link_path + "/" + uevent->path.substr(last_slash + 1));
 
     return links;
 }
 
-static void make_link_init(const char* oldpath, const char* newpath) {
-  const char* slash = strrchr(newpath, '/');
-  if (!slash) return;
+static void make_link_init(const std::string& oldpath, const std::string& newpath) {
+    if (mkdir_recursive(dirname(newpath.c_str()), 0755)) {
+        PLOG(ERROR) << "Failed to create directory " << dirname(newpath.c_str());
+    }
 
-  if (mkdir_recursive(dirname(newpath), 0755)) {
-    PLOG(ERROR) << "Failed to create directory " << dirname(newpath);
-  }
-
-  if (symlink(oldpath, newpath) && errno != EEXIST) {
-    PLOG(ERROR) << "Failed to symlink " << oldpath << " to " << newpath;
-  }
+    if (symlink(oldpath.c_str(), newpath.c_str()) && errno != EEXIST) {
+        PLOG(ERROR) << "Failed to symlink " << oldpath << " to " << newpath;
+    }
 }
 
-static void remove_link(const char* oldpath, const char* newpath) {
-  std::string path;
-  if (android::base::Readlink(newpath, &path) && path == oldpath) unlink(newpath);
+static void remove_link(const std::string& oldpath, const std::string& newpath) {
+    std::string path;
+    if (android::base::Readlink(newpath, &path) && path == oldpath) unlink(newpath.c_str());
 }
 
-static void handle_device(const char *action, const char *devpath,
-        const char *path, int block, int major, int minor, char **links)
-{
-    if(!strcmp(action, "add")) {
-        make_device(devpath, path, block, major, minor, (const char **)links);
-        if (links) {
-            for (int i = 0; links[i]; i++) {
-                make_link_init(devpath, links[i]);
-            }
+static void handle_device(const std::string& action, const std::string& devpath, int block,
+                          int major, int minor, const std::vector<std::string>& links) {
+    if (action == "add") {
+        make_device(devpath, block, major, minor, links);
+        for (const auto& link : links) {
+            make_link_init(devpath, link);
         }
     }
 
-    if(!strcmp(action, "remove")) {
-        if (links) {
-            for (int i = 0; links[i]; i++) {
-                remove_link(devpath, links[i]);
-            }
+    if (action == "remove") {
+        for (const auto& link : links) {
+            remove_link(devpath, link);
         }
-        unlink(devpath);
-    }
-
-    if (links) {
-        for (int i = 0; links[i]; i++) {
-            free(links[i]);
-        }
-        free(links);
+        unlink(devpath.c_str());
     }
 }
 
-static void handle_platform_device_event(struct uevent *uevent)
-{
-    const char *path = uevent->path;
-
-    if (!strcmp(uevent->action, "add"))
-        add_platform_device(path);
-    else if (!strcmp(uevent->action, "remove"))
-        remove_platform_device(path);
-}
-
-static const char *parse_device_name(struct uevent *uevent, unsigned int len)
-{
-    const char *name;
-
-    /* if it's not a /dev device, nothing else to do */
-    if((uevent->major < 0) || (uevent->minor < 0))
-        return NULL;
-
-    /* do we have a name? */
-    name = strrchr(uevent->path, '/');
-    if(!name)
-        return NULL;
-    name++;
-
-    /* too-long names would overrun our buffer */
-    if(strlen(name) > len) {
-        LOG(ERROR) << "DEVPATH=" << name << " exceeds " << len << "-character limit on filename; ignoring event";
-        return NULL;
+void handle_platform_device_event(uevent* uevent) {
+    if (uevent->action == "add") {
+        platform_devices.emplace_back(uevent->path);
+    } else if (uevent->action == "remove") {
+        auto it = std::find(platform_devices.begin(), platform_devices.end(), uevent->path);
+        if (it != platform_devices.end()) platform_devices.erase(it);
     }
-
-    return name;
 }
 
-#define DEVPATH_LEN 96
-#define MAX_DEV_NAME 64
+static void handle_block_device_event(uevent* uevent) {
+    // if it's not a /dev device, nothing to do
+    if (uevent->major < 0 || uevent->minor < 0) return;
 
-static void handle_block_device_event(struct uevent *uevent)
-{
-    const char *base = "/dev/block/";
-    const char *name;
-    char devpath[DEVPATH_LEN];
-    char **links = NULL;
-
-    name = parse_device_name(uevent, MAX_DEV_NAME);
-    if (!name)
-        return;
-
-    snprintf(devpath, sizeof(devpath), "%s%s", base, name);
+    const char* base = "/dev/block/";
     make_dir(base, 0755);
 
-    if (!strncmp(uevent->path, "/devices/", 9))
+    std::string name = android::base::Basename(uevent->path);
+    std::string devpath = base + name;
+
+    std::vector<std::string> links;
+    if (android::base::StartsWith(uevent->path, "/devices")) {
         links = get_block_device_symlinks(uevent);
-
-    handle_device(uevent->action, devpath, uevent->path, 1,
-            uevent->major, uevent->minor, links);
-}
-
-static bool assemble_devpath(char *devpath, const char *dirname,
-        const char *devname)
-{
-    int s = snprintf(devpath, DEVPATH_LEN, "%s/%s", dirname, devname);
-    if (s < 0) {
-        PLOG(ERROR) << "failed to assemble device path; ignoring event";
-        return false;
-    } else if (s >= DEVPATH_LEN) {
-        LOG(ERROR) << dirname << "/" << devname
-                   << " exceeds " << DEVPATH_LEN << "-character limit on path; ignoring event";
-        return false;
     }
-    return true;
+
+    handle_device(uevent->action, devpath, 1, uevent->major, uevent->minor, links);
 }
 
-static void mkdir_recursive_for_devpath(const char *devpath)
-{
-    char dir[DEVPATH_LEN];
-    char *slash;
+static void handle_generic_device_event(uevent* uevent) {
+    // if it's not a /dev device, nothing to do
+    if (uevent->major < 0 || uevent->minor < 0) return;
 
-    strcpy(dir, devpath);
-    slash = strrchr(dir, '/');
-    *slash = '\0';
-    mkdir_recursive(dir, 0755);
-}
+    std::string devpath;
 
-static void handle_generic_device_event(struct uevent *uevent)
-{
-    const char *base;
-    const char *name;
-    char devpath[DEVPATH_LEN] = {0};
-    char **links = NULL;
-
-    name = parse_device_name(uevent, MAX_DEV_NAME);
-    if (!name)
-        return;
-
-    struct ueventd_subsystem *subsystem =
-            ueventd_subsystem_find_by_name(uevent->subsystem);
-
-    if (subsystem) {
-        const char *devname;
-
-        switch (subsystem->devname_src) {
-        case DEVNAME_UEVENT_DEVNAME:
-            devname = uevent->device_name;
-            break;
-
-        case DEVNAME_UEVENT_DEVPATH:
-            devname = name;
-            break;
-
-        default:
-            LOG(ERROR) << uevent->subsystem << " subsystem's devpath option is not set; ignoring event";
+    if (android::base::StartsWith(uevent->subsystem, "usb")) {
+        if (uevent->subsystem == "usb") {
+            if (!uevent->device_name.empty()) {
+                devpath = "/dev/" + uevent->device_name;
+            } else {
+                // This imitates the file system that would be created
+                // if we were using devfs instead.
+                // Minors are broken up into groups of 128, starting at "001"
+                int bus_id = uevent->minor / 128 + 1;
+                int device_id = uevent->minor % 128 + 1;
+                devpath = android::base::StringPrintf("/dev/bus/usb/%03d/%03d", bus_id, device_id);
+            }
+        } else {
+            // ignore other USB events
             return;
         }
+    } else if (auto subsystem = std::find(subsystems.begin(), subsystems.end(), uevent->subsystem);
+               subsystem != subsystems.end()) {
+        devpath = subsystem->ParseDevPath(uevent);
+    } else {
+        devpath = "/dev/" + android::base::Basename(uevent->path);
+    }
 
-        if (!assemble_devpath(devpath, subsystem->dirname, devname))
-            return;
-        mkdir_recursive_for_devpath(devpath);
-    } else if (!strncmp(uevent->subsystem, "usb", 3)) {
-         if (!strcmp(uevent->subsystem, "usb")) {
-            if (uevent->device_name) {
-                if (!assemble_devpath(devpath, "/dev", uevent->device_name))
-                    return;
-                mkdir_recursive_for_devpath(devpath);
-             }
-             else {
-                 /* This imitates the file system that would be created
-                  * if we were using devfs instead.
-                  * Minors are broken up into groups of 128, starting at "001"
-                  */
-                 int bus_id = uevent->minor / 128 + 1;
-                 int device_id = uevent->minor % 128 + 1;
-                 /* build directories */
-                 make_dir("/dev/bus", 0755);
-                 make_dir("/dev/bus/usb", 0755);
-                 snprintf(devpath, sizeof(devpath), "/dev/bus/usb/%03d", bus_id);
-                 make_dir(devpath, 0755);
-                 snprintf(devpath, sizeof(devpath), "/dev/bus/usb/%03d/%03d", bus_id, device_id);
-             }
-         } else {
-             /* ignore other USB events */
-             return;
-         }
-     } else if (!strncmp(uevent->subsystem, "graphics", 8)) {
-         base = "/dev/graphics/";
-         make_dir(base, 0755);
-     } else if (!strncmp(uevent->subsystem, "drm", 3)) {
-         base = "/dev/dri/";
-         make_dir(base, 0755);
-     } else if (!strncmp(uevent->subsystem, "oncrpc", 6)) {
-         base = "/dev/oncrpc/";
-         make_dir(base, 0755);
-     } else if (!strncmp(uevent->subsystem, "adsp", 4)) {
-         base = "/dev/adsp/";
-         make_dir(base, 0755);
-     } else if (!strncmp(uevent->subsystem, "msm_camera", 10)) {
-         base = "/dev/msm_camera/";
-         make_dir(base, 0755);
-     } else if(!strncmp(uevent->subsystem, "input", 5)) {
-         base = "/dev/input/";
-         make_dir(base, 0755);
-     } else if(!strncmp(uevent->subsystem, "mtd", 3)) {
-         base = "/dev/mtd/";
-         make_dir(base, 0755);
-     } else if(!strncmp(uevent->subsystem, "sound", 5)) {
-         base = "/dev/snd/";
-         make_dir(base, 0755);
-     } else if(!strncmp(uevent->subsystem, "misc", 4) && !strncmp(name, "log_", 4)) {
-         LOG(INFO) << "kernel logger is deprecated";
-         base = "/dev/log/";
-         make_dir(base, 0755);
-         name += 4;
-     } else
-         base = "/dev/";
-     links = get_character_device_symlinks(uevent);
+    mkdir_recursive(android::base::Dirname(devpath), 0755);
 
-     if (!devpath[0])
-         snprintf(devpath, sizeof(devpath), "%s%s", base, name);
+    auto links = get_character_device_symlinks(uevent);
 
-     handle_device(uevent->action, devpath, uevent->path, 0,
-             uevent->major, uevent->minor, links);
+    handle_device(uevent->action, devpath, 0, uevent->major, uevent->minor, links);
 }
 
 static void handle_device_event(struct uevent *uevent)
 {
-    if (!strcmp(uevent->action,"add") || !strcmp(uevent->action, "change") || !strcmp(uevent->action, "online"))
-        fixup_sys_perms(uevent->path, uevent->subsystem);
+    if (uevent->action == "add" || uevent->action == "change" || uevent->action == "online") {
+        fixup_sys_permissions(uevent->path, uevent->subsystem);
+    }
 
-    if (!strncmp(uevent->subsystem, "block", 5)) {
+    if (uevent->subsystem == "block") {
         handle_block_device_event(uevent);
-    } else if (!strncmp(uevent->subsystem, "platform", 8)) {
+    } else if (uevent->subsystem == "platform") {
         handle_platform_device_event(uevent);
     } else {
         handle_generic_device_event(uevent);
@@ -858,7 +689,7 @@
 
     LOG(INFO) << "firmware: loading '" << uevent->firmware << "' for '" << uevent->path << "'";
 
-    std::string root = android::base::StringPrintf("/sys%s", uevent->path);
+    std::string root = "/sys" + uevent->path;
     std::string loading = root + "/loading";
     std::string data = root + "/data";
 
@@ -874,9 +705,12 @@
         return;
     }
 
+    static const char* firmware_dirs[] = {"/etc/firmware/", "/vendor/firmware/",
+                                          "/firmware/image/"};
+
 try_loading_again:
     for (size_t i = 0; i < arraysize(firmware_dirs); i++) {
-        std::string file = android::base::StringPrintf("%s/%s", firmware_dirs[i], uevent->firmware);
+        std::string file = firmware_dirs[i] + uevent->firmware;
         android::base::unique_fd fw_fd(open(file.c_str(), O_RDONLY|O_CLOEXEC));
         struct stat sb;
         if (fw_fd != -1 && fstat(fw_fd, &sb) != -1) {
@@ -900,8 +734,7 @@
 }
 
 static void handle_firmware_event(uevent* uevent) {
-    if (strcmp(uevent->subsystem, "firmware")) return;
-    if (strcmp(uevent->action, "add")) return;
+    if (uevent->subsystem != "firmware" || uevent->action != "add") return;
 
     // Loading the firmware in a child means we can do that in parallel...
     // (We ignore SIGCHLD rather than wait for our children.)
@@ -935,7 +768,7 @@
         msg[n] = '\0';
         msg[n+1] = '\0';
 
-        struct uevent uevent;
+        uevent uevent;
         parse_event(msg, &uevent);
         coldboot_action_t act = handle_uevent(&uevent);
         if (should_stop_coldboot(act))
@@ -949,15 +782,6 @@
 {
     coldboot_action_t ret = handle_device_fd_with(
         [&](uevent* uevent) -> coldboot_action_t {
-            if (selinux_status_updated() > 0) {
-                struct selabel_handle *sehandle2;
-                sehandle2 = selinux_android_file_context_handle();
-                if (sehandle2) {
-                    selabel_close(sehandle);
-                    sehandle = sehandle2;
-                }
-            }
-
             // default is to always create the devices
             coldboot_action_t act = COLDBOOT_CREATE;
             if (fn) {
@@ -1047,7 +871,6 @@
             return;
         }
         fcntl(device_fd, F_SETFL, O_NONBLOCK);
-        selinux_status_open(true);
     }
 
     if (access(COLDBOOT_DONE, F_OK) == 0) {
@@ -1079,9 +902,8 @@
 }
 
 void device_close() {
-    destroy_platform_devices();
+    platform_devices.clear();
     device_fd.reset();
-    selinux_status_close();
 }
 
 int get_device_fd() {
diff --git a/init/devices.h b/init/devices.h
index 26a064b..647b4c4 100644
--- a/init/devices.h
+++ b/init/devices.h
@@ -17,8 +17,14 @@
 #ifndef _INIT_DEVICES_H
 #define _INIT_DEVICES_H
 
-#include <functional>
 #include <sys/stat.h>
+#include <sys/types.h>
+
+#include <functional>
+#include <string>
+#include <vector>
+
+#include "init_parser.h"
 
 enum coldboot_action_t {
     // coldboot continues without creating the device for the uevent
@@ -33,26 +39,103 @@
 };
 
 struct uevent {
-    const char* action;
-    const char* path;
-    const char* subsystem;
-    const char* firmware;
-    const char* partition_name;
-    const char* device_name;
+    std::string action;
+    std::string path;
+    std::string subsystem;
+    std::string firmware;
+    std::string partition_name;
+    std::string device_name;
     int partition_num;
     int major;
     int minor;
 };
 
+class Permissions {
+  public:
+    Permissions(const std::string& name, mode_t perm, uid_t uid, gid_t gid);
+
+    bool Match(const std::string& path) const;
+
+    mode_t perm() const { return perm_; }
+    uid_t uid() const { return uid_; }
+    gid_t gid() const { return gid_; }
+
+  protected:
+    const std::string& name() const { return name_; }
+
+  private:
+    std::string name_;
+    mode_t perm_;
+    uid_t uid_;
+    gid_t gid_;
+    bool prefix_;
+    bool wildcard_;
+};
+
+class SysfsPermissions : public Permissions {
+  public:
+    SysfsPermissions(const std::string& name, const std::string& attribute, mode_t perm, uid_t uid,
+                     gid_t gid)
+        : Permissions(name, perm, uid, gid), attribute_(attribute) {}
+
+    bool MatchWithSubsystem(const std::string& path, const std::string& subsystem) const;
+    void SetPermissions(const std::string& path) const;
+
+  private:
+    const std::string attribute_;
+};
+
+class Subsystem {
+  public:
+    friend class SubsystemParser;
+
+    Subsystem() {}
+
+    // Returns the full path for a uevent of a device that is a member of this subsystem,
+    // according to the rules parsed from ueventd.rc
+    std::string ParseDevPath(uevent* uevent) const;
+
+    bool operator==(const std::string& string_name) { return name_ == string_name; }
+
+  private:
+    enum class DevnameSource {
+        DEVNAME_UEVENT_DEVNAME,
+        DEVNAME_UEVENT_DEVPATH,
+    };
+
+    std::string name_;
+    std::string dir_name_ = "/dev";
+    DevnameSource devname_source_;
+};
+
+class SubsystemParser : public SectionParser {
+  public:
+    SubsystemParser() {}
+    bool ParseSection(std::vector<std::string>&& args, const std::string& filename, int line,
+                      std::string* err) override;
+    bool ParseLineSection(std::vector<std::string>&& args, int line, std::string* err) override;
+    void EndSection() override;
+
+  private:
+    bool ParseDevName(std::vector<std::string>&& args, std::string* err);
+    bool ParseDirName(std::vector<std::string>&& args, std::string* err);
+
+    Subsystem subsystem_;
+};
+
+bool ParsePermissionsLine(std::vector<std::string>&& args, std::string* err, bool is_sysfs);
 typedef std::function<coldboot_action_t(struct uevent* uevent)> coldboot_callback;
 extern coldboot_action_t handle_device_fd(coldboot_callback fn = nullptr);
 extern void device_init(const char* path = nullptr, coldboot_callback fn = nullptr);
 extern void device_close();
-
-extern int add_dev_perms(const char *name, const char *attr,
-                         mode_t perm, unsigned int uid,
-                         unsigned int gid, unsigned short prefix,
-                         unsigned short wildcard);
 int get_device_fd();
 
-#endif	/* _INIT_DEVICES_H */
+// Exposed for testing
+extern std::vector<std::string> platform_devices;
+bool find_platform_device(const std::string& path, std::string* out_path);
+std::vector<std::string> get_character_device_symlinks(uevent* uevent);
+std::vector<std::string> get_block_device_symlinks(uevent* uevent);
+void sanitize_partition_name(std::string* string);
+void handle_platform_device_event(uevent* uevent);
+
+#endif /* _INIT_DEVICES_H */
diff --git a/init/devices_test.cpp b/init/devices_test.cpp
new file mode 100644
index 0000000..66521db
--- /dev/null
+++ b/init/devices_test.cpp
@@ -0,0 +1,409 @@
+/*
+ * 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 "devices.h"
+
+#include <string>
+#include <vector>
+
+#include <android-base/scopeguard.h>
+#include <gtest/gtest.h>
+
+void add_platform_device(const std::string& path) {
+    uevent uevent = {
+        .action = "add", .subsystem = "platform", .path = path,
+    };
+    handle_platform_device_event(&uevent);
+}
+
+void remove_platform_device(const std::string& path) {
+    uevent uevent = {
+        .action = "remove", .subsystem = "platform", .path = path,
+    };
+    handle_platform_device_event(&uevent);
+}
+
+template <std::vector<std::string> (*Function)(uevent*)>
+void test_get_symlinks(const std::string& platform_device_name, uevent* uevent,
+                       const std::vector<std::string> expected_links) {
+    add_platform_device(platform_device_name);
+    auto platform_device_remover = android::base::make_scope_guard(
+        [&platform_device_name]() { remove_platform_device(platform_device_name); });
+
+    std::vector<std::string> result = Function(uevent);
+
+    auto expected_size = expected_links.size();
+    ASSERT_EQ(expected_size, result.size());
+    if (expected_size == 0) return;
+
+    // Explicitly iterate so the results are visible if a failure occurs
+    for (unsigned int i = 0; i < expected_size; ++i) {
+        EXPECT_EQ(expected_links[i], result[i]);
+    }
+}
+
+TEST(devices, handle_platform_device_event) {
+    platform_devices.clear();
+    add_platform_device("/devices/platform/some_device_name");
+    ASSERT_EQ(1U, platform_devices.size());
+    remove_platform_device("/devices/platform/some_device_name");
+    ASSERT_EQ(0U, platform_devices.size());
+}
+
+TEST(devices, find_platform_device) {
+    platform_devices.clear();
+    add_platform_device("/devices/platform/some_device_name");
+    add_platform_device("/devices/platform/some_device_name/longer");
+    add_platform_device("/devices/platform/other_device_name");
+    EXPECT_EQ(3U, platform_devices.size());
+
+    std::string out_path;
+    EXPECT_FALSE(find_platform_device("/devices/platform/not_found", &out_path));
+    EXPECT_EQ("", out_path);
+
+    EXPECT_FALSE(
+        find_platform_device("/devices/platform/some_device_name_with_same_prefix", &out_path));
+
+    EXPECT_TRUE(
+        find_platform_device("/devices/platform/some_device_name/longer/longer_child", &out_path));
+    EXPECT_EQ("/devices/platform/some_device_name/longer", out_path);
+
+    EXPECT_TRUE(find_platform_device("/devices/platform/some_device_name/other_child", &out_path));
+    EXPECT_EQ("/devices/platform/some_device_name", out_path);
+}
+
+TEST(devices, get_character_device_symlinks_success) {
+    const char* platform_device = "/devices/platform/some_device_name";
+    uevent uevent = {
+        .path = "/devices/platform/some_device_name/usb/usb_device/name/tty2-1:1.0",
+        .subsystem = "tty",
+    };
+    std::vector<std::string> expected_result{"/dev/usb/ttyname"};
+
+    test_get_symlinks<get_character_device_symlinks>(platform_device, &uevent, expected_result);
+}
+
+TEST(devices, get_character_device_symlinks_no_pdev_match) {
+    const char* platform_device = "/devices/platform/some_device_name";
+    uevent uevent = {
+        .path = "/device/name/tty2-1:1.0", .subsystem = "tty",
+    };
+    std::vector<std::string> expected_result;
+
+    test_get_symlinks<get_character_device_symlinks>(platform_device, &uevent, expected_result);
+}
+
+TEST(devices, get_character_device_symlinks_nothing_after_platform_device) {
+    const char* platform_device = "/devices/platform/some_device_name";
+    uevent uevent = {
+        .path = "/devices/platform/some_device_name", .subsystem = "tty",
+    };
+    std::vector<std::string> expected_result;
+
+    test_get_symlinks<get_character_device_symlinks>(platform_device, &uevent, expected_result);
+}
+
+TEST(devices, get_character_device_symlinks_no_usb_found) {
+    const char* platform_device = "/devices/platform/some_device_name";
+    uevent uevent = {
+        .path = "/devices/platform/some_device_name/bad/bad/", .subsystem = "tty",
+    };
+    std::vector<std::string> expected_result;
+
+    test_get_symlinks<get_character_device_symlinks>(platform_device, &uevent, expected_result);
+}
+
+TEST(devices, get_character_device_symlinks_no_roothub) {
+    const char* platform_device = "/devices/platform/some_device_name";
+    uevent uevent = {
+        .path = "/devices/platform/some_device_name/usb/", .subsystem = "tty",
+    };
+    std::vector<std::string> expected_result;
+
+    test_get_symlinks<get_character_device_symlinks>(platform_device, &uevent, expected_result);
+}
+
+TEST(devices, get_character_device_symlinks_no_usb_device) {
+    const char* platform_device = "/devices/platform/some_device_name";
+    uevent uevent = {
+        .path = "/devices/platform/some_device_name/usb/usb_device/", .subsystem = "tty",
+    };
+    std::vector<std::string> expected_result;
+
+    test_get_symlinks<get_character_device_symlinks>(platform_device, &uevent, expected_result);
+}
+
+TEST(devices, get_character_device_symlinks_no_final_slash) {
+    const char* platform_device = "/devices/platform/some_device_name";
+    uevent uevent = {
+        .path = "/devices/platform/some_device_name/usb/usb_device/name", .subsystem = "tty",
+    };
+    std::vector<std::string> expected_result;
+
+    test_get_symlinks<get_character_device_symlinks>(platform_device, &uevent, expected_result);
+}
+
+TEST(devices, get_character_device_symlinks_no_final_name) {
+    const char* platform_device = "/devices/platform/some_device_name";
+    uevent uevent = {
+        .path = "/devices/platform/some_device_name/usb/usb_device//", .subsystem = "tty",
+    };
+    std::vector<std::string> expected_result;
+
+    test_get_symlinks<get_character_device_symlinks>(platform_device, &uevent, expected_result);
+}
+
+TEST(devices, get_block_device_symlinks_success_platform) {
+    // These are actual paths from bullhead
+    const char* platform_device = "/devices/soc.0/f9824900.sdhci";
+    uevent uevent = {
+        .path = "/devices/soc.0/f9824900.sdhci/mmc_host/mmc0/mmc0:0001/block/mmcblk0",
+        .partition_name = "",
+        .partition_num = -1,
+    };
+    std::vector<std::string> expected_result{"/dev/block/platform/soc.0/f9824900.sdhci/mmcblk0"};
+
+    test_get_symlinks<get_block_device_symlinks>(platform_device, &uevent, expected_result);
+}
+
+TEST(devices, get_block_device_symlinks_success_platform_with_partition) {
+    // These are actual paths from bullhead
+    const char* platform_device = "/devices/soc.0/f9824900.sdhci";
+    uevent uevent = {
+        .path = "/devices/soc.0/f9824900.sdhci/mmc_host/mmc0/mmc0:0001/block/mmcblk0p1",
+        .partition_name = "modem",
+        .partition_num = 1,
+    };
+    std::vector<std::string> expected_result{
+        "/dev/block/platform/soc.0/f9824900.sdhci/by-name/modem",
+        "/dev/block/platform/soc.0/f9824900.sdhci/by-num/p1",
+        "/dev/block/platform/soc.0/f9824900.sdhci/mmcblk0p1",
+    };
+
+    test_get_symlinks<get_block_device_symlinks>(platform_device, &uevent, expected_result);
+}
+
+TEST(devices, get_block_device_symlinks_success_platform_with_partition_only_num) {
+    const char* platform_device = "/devices/soc.0/f9824900.sdhci";
+    uevent uevent = {
+        .path = "/devices/soc.0/f9824900.sdhci/mmc_host/mmc0/mmc0:0001/block/mmcblk0p1",
+        .partition_name = "",
+        .partition_num = 1,
+    };
+    std::vector<std::string> expected_result{
+        "/dev/block/platform/soc.0/f9824900.sdhci/by-num/p1",
+        "/dev/block/platform/soc.0/f9824900.sdhci/mmcblk0p1",
+    };
+
+    test_get_symlinks<get_block_device_symlinks>(platform_device, &uevent, expected_result);
+}
+
+TEST(devices, get_block_device_symlinks_success_platform_with_partition_only_name) {
+    const char* platform_device = "/devices/soc.0/f9824900.sdhci";
+    uevent uevent = {
+        .path = "/devices/soc.0/f9824900.sdhci/mmc_host/mmc0/mmc0:0001/block/mmcblk0p1",
+        .partition_name = "modem",
+        .partition_num = -1,
+    };
+    std::vector<std::string> expected_result{
+        "/dev/block/platform/soc.0/f9824900.sdhci/by-name/modem",
+        "/dev/block/platform/soc.0/f9824900.sdhci/mmcblk0p1",
+    };
+
+    test_get_symlinks<get_block_device_symlinks>(platform_device, &uevent, expected_result);
+}
+
+TEST(devices, get_block_device_symlinks_success_pci) {
+    const char* platform_device = "/devices/do/not/match";
+    uevent uevent = {
+        .path = "/devices/pci0000:00/0000:00:1f.2/mmcblk0", .partition_name = "", .partition_num = -1,
+    };
+    std::vector<std::string> expected_result{"/dev/block/pci/pci0000:00/0000:00:1f.2/mmcblk0"};
+
+    test_get_symlinks<get_block_device_symlinks>(platform_device, &uevent, expected_result);
+}
+
+TEST(devices, get_block_device_symlinks_pci_bad_format) {
+    const char* platform_device = "/devices/do/not/match";
+    uevent uevent = {
+        .path = "/devices/pci//mmcblk0", .partition_name = "", .partition_num = -1,
+    };
+    std::vector<std::string> expected_result{};
+
+    test_get_symlinks<get_block_device_symlinks>(platform_device, &uevent, expected_result);
+}
+
+TEST(devices, get_block_device_symlinks_success_vbd) {
+    const char* platform_device = "/devices/do/not/match";
+    uevent uevent = {
+        .path = "/devices/vbd-1234/mmcblk0", .partition_name = "", .partition_num = -1,
+    };
+    std::vector<std::string> expected_result{"/dev/block/vbd/1234/mmcblk0"};
+
+    test_get_symlinks<get_block_device_symlinks>(platform_device, &uevent, expected_result);
+}
+
+TEST(devices, get_block_device_symlinks_vbd_bad_format) {
+    const char* platform_device = "/devices/do/not/match";
+    uevent uevent = {
+        .path = "/devices/vbd-/mmcblk0", .partition_name = "", .partition_num = -1,
+    };
+    std::vector<std::string> expected_result{};
+
+    test_get_symlinks<get_block_device_symlinks>(platform_device, &uevent, expected_result);
+}
+
+TEST(devices, get_block_device_symlinks_no_matches) {
+    const char* platform_device = "/devices/soc.0/f9824900.sdhci";
+    uevent uevent = {
+        .path = "/devices/soc.0/not_the_device/mmc_host/mmc0/mmc0:0001/block/mmcblk0p1",
+        .partition_name = "",
+        .partition_num = -1,
+    };
+    std::vector<std::string> expected_result;
+
+    test_get_symlinks<get_block_device_symlinks>(platform_device, &uevent, expected_result);
+}
+
+TEST(devices, sanitize_null) {
+    sanitize_partition_name(nullptr);
+}
+
+TEST(devices, sanitize_empty) {
+    std::string empty;
+    sanitize_partition_name(&empty);
+    EXPECT_EQ(0u, empty.size());
+}
+
+TEST(devices, sanitize_allgood) {
+    std::string good =
+        "abcdefghijklmnopqrstuvwxyz"
+        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+        "0123456789"
+        "_-.";
+    std::string good_copy = good;
+    sanitize_partition_name(&good);
+    EXPECT_EQ(good_copy, good);
+}
+
+TEST(devices, sanitize_somebad) {
+    std::string string = "abc!@#$%^&*()";
+    sanitize_partition_name(&string);
+    EXPECT_EQ("abc__________", string);
+}
+
+TEST(devices, sanitize_allbad) {
+    std::string string = "!@#$%^&*()";
+    sanitize_partition_name(&string);
+    EXPECT_EQ("__________", string);
+}
+
+TEST(devices, sanitize_onebad) {
+    std::string string = ")";
+    sanitize_partition_name(&string);
+    EXPECT_EQ("_", string);
+}
+
+TEST(devices, DevPermissionsMatchNormal) {
+    // Basic from ueventd.rc
+    // /dev/null                 0666   root       root
+    Permissions permissions("/dev/null", 0666, 0, 0);
+    EXPECT_TRUE(permissions.Match("/dev/null"));
+    EXPECT_FALSE(permissions.Match("/dev/nullsuffix"));
+    EXPECT_FALSE(permissions.Match("/dev/nul"));
+    EXPECT_EQ(0666U, permissions.perm());
+    EXPECT_EQ(0U, permissions.uid());
+    EXPECT_EQ(0U, permissions.gid());
+}
+
+TEST(devices, DevPermissionsMatchPrefix) {
+    // Prefix from ueventd.rc
+    // /dev/dri/*                0666   root       graphics
+    Permissions permissions("/dev/dri/*", 0666, 0, 1000);
+    EXPECT_TRUE(permissions.Match("/dev/dri/some_dri_device"));
+    EXPECT_TRUE(permissions.Match("/dev/dri/some_other_dri_device"));
+    EXPECT_TRUE(permissions.Match("/dev/dri/"));
+    EXPECT_FALSE(permissions.Match("/dev/dr/non_match"));
+    EXPECT_EQ(0666U, permissions.perm());
+    EXPECT_EQ(0U, permissions.uid());
+    EXPECT_EQ(1000U, permissions.gid());
+}
+
+TEST(devices, DevPermissionsMatchWildcard) {
+    // Wildcard example
+    // /dev/device*name                0666   root       graphics
+    Permissions permissions("/dev/device*name", 0666, 0, 1000);
+    EXPECT_TRUE(permissions.Match("/dev/devicename"));
+    EXPECT_TRUE(permissions.Match("/dev/device123name"));
+    EXPECT_TRUE(permissions.Match("/dev/deviceabcname"));
+    EXPECT_FALSE(permissions.Match("/dev/device123name/subdevice"));
+    EXPECT_FALSE(permissions.Match("/dev/deviceame"));
+    EXPECT_EQ(0666U, permissions.perm());
+    EXPECT_EQ(0U, permissions.uid());
+    EXPECT_EQ(1000U, permissions.gid());
+}
+
+TEST(devices, DevPermissionsMatchWildcardPrefix) {
+    // Wildcard+Prefix example
+    // /dev/device*name*                0666   root       graphics
+    Permissions permissions("/dev/device*name*", 0666, 0, 1000);
+    EXPECT_TRUE(permissions.Match("/dev/devicename"));
+    EXPECT_TRUE(permissions.Match("/dev/device123name"));
+    EXPECT_TRUE(permissions.Match("/dev/deviceabcname"));
+    EXPECT_TRUE(permissions.Match("/dev/device123namesomething"));
+    // FNM_PATHNAME doesn't match '/' with *
+    EXPECT_FALSE(permissions.Match("/dev/device123name/something"));
+    EXPECT_FALSE(permissions.Match("/dev/deviceame"));
+    EXPECT_EQ(0666U, permissions.perm());
+    EXPECT_EQ(0U, permissions.uid());
+    EXPECT_EQ(1000U, permissions.gid());
+}
+
+TEST(devices, SysfsPermissionsMatchWithSubsystemNormal) {
+    // /sys/devices/virtual/input/input*   enable      0660  root   input
+    SysfsPermissions permissions("/sys/devices/virtual/input/input*", "enable", 0660, 0, 1001);
+    EXPECT_TRUE(permissions.MatchWithSubsystem("/sys/devices/virtual/input/input0", "input"));
+    EXPECT_FALSE(permissions.MatchWithSubsystem("/sys/devices/virtual/input/not_input0", "input"));
+    EXPECT_EQ(0660U, permissions.perm());
+    EXPECT_EQ(0U, permissions.uid());
+    EXPECT_EQ(1001U, permissions.gid());
+}
+
+TEST(devices, SysfsPermissionsMatchWithSubsystemClass) {
+    // /sys/class/input/event*   enable      0660  root   input
+    SysfsPermissions permissions("/sys/class/input/event*", "enable", 0660, 0, 1001);
+    EXPECT_TRUE(permissions.MatchWithSubsystem(
+        "/sys/devices/soc.0/f9924000.i2c/i2c-2/2-0020/input/input0/event0", "input"));
+    EXPECT_FALSE(permissions.MatchWithSubsystem(
+        "/sys/devices/soc.0/f9924000.i2c/i2c-2/2-0020/input/input0/not_event0", "input"));
+    EXPECT_FALSE(permissions.MatchWithSubsystem(
+        "/sys/devices/soc.0/f9924000.i2c/i2c-2/2-0020/input/input0/event0", "not_input"));
+    EXPECT_EQ(0660U, permissions.perm());
+    EXPECT_EQ(0U, permissions.uid());
+    EXPECT_EQ(1001U, permissions.gid());
+}
+
+TEST(devices, SysfsPermissionsMatchWithSubsystemBus) {
+    // /sys/bus/i2c/devices/i2c-*   enable      0660  root   input
+    SysfsPermissions permissions("/sys/bus/i2c/devices/i2c-*", "enable", 0660, 0, 1001);
+    EXPECT_TRUE(permissions.MatchWithSubsystem("/sys/devices/soc.0/f9967000.i2c/i2c-5", "i2c"));
+    EXPECT_FALSE(permissions.MatchWithSubsystem("/sys/devices/soc.0/f9967000.i2c/not-i2c", "i2c"));
+    EXPECT_FALSE(
+        permissions.MatchWithSubsystem("/sys/devices/soc.0/f9967000.i2c/i2c-5", "not_i2c"));
+    EXPECT_EQ(0660U, permissions.perm());
+    EXPECT_EQ(0U, permissions.uid());
+    EXPECT_EQ(1001U, permissions.gid());
+}
diff --git a/init/import_parser.cpp b/init/import_parser.cpp
index d52247b..99275e5 100644
--- a/init/import_parser.cpp
+++ b/init/import_parser.cpp
@@ -16,16 +16,12 @@
 
 #include "import_parser.h"
 
-#include "errno.h"
+#include <android-base/logging.h>
 
-#include <string>
-#include <vector>
-
-#include "log.h"
 #include "util.h"
 
-bool ImportParser::ParseSection(const std::vector<std::string>& args,
-                                std::string* err) {
+bool ImportParser::ParseSection(std::vector<std::string>&& args, const std::string& filename,
+                                int line, std::string* err) {
     if (args.size() != 2) {
         *err = "single argument needed for import\n";
         return false;
@@ -39,16 +35,18 @@
     }
 
     LOG(INFO) << "Added '" << conf_file << "' to import list";
-    imports_.emplace_back(std::move(conf_file));
+    if (filename_.empty()) filename_ = filename;
+    imports_.emplace_back(std::move(conf_file), line);
     return true;
 }
 
-void ImportParser::EndFile(const std::string& filename) {
+void ImportParser::EndFile() {
     auto current_imports = std::move(imports_);
     imports_.clear();
-    for (const auto& s : current_imports) {
-        if (!Parser::GetInstance().ParseConfig(s)) {
-            PLOG(ERROR) << "could not import file '" << s << "' from '" << filename << "'";
+    for (const auto& [import, line_num] : current_imports) {
+        if (!parser_->ParseConfig(import)) {
+            PLOG(ERROR) << filename_ << ": " << line_num << ": Could not import file '" << import
+                        << "'";
         }
     }
 }
diff --git a/init/import_parser.h b/init/import_parser.h
index 0e91025..45cbfad 100644
--- a/init/import_parser.h
+++ b/init/import_parser.h
@@ -23,21 +23,18 @@
 #include <vector>
 
 class ImportParser : public SectionParser {
-public:
-    ImportParser()  {
-    }
-    bool ParseSection(const std::vector<std::string>& args,
+  public:
+    ImportParser(Parser* parser) : parser_(parser) {}
+    bool ParseSection(std::vector<std::string>&& args, const std::string& filename, int line,
                       std::string* err) override;
-    bool ParseLineSection(const std::vector<std::string>& args,
-                          const std::string& filename, int line,
-                          std::string* err) const override {
-        return true;
-    }
-    void EndSection() override {
-    }
-    void EndFile(const std::string& filename) override;
-private:
-    std::vector<std::string> imports_;
+    void EndFile() override;
+
+  private:
+    Parser* parser_;
+    // Store filename for later error reporting.
+    std::string filename_;
+    // Vector of imports and their line numbers for later error reporting.
+    std::vector<std::pair<std::string, int>> imports_;
 };
 
 #endif
diff --git a/init/init.cpp b/init/init.cpp
index d095685..99ce5e6 100644
--- a/init/init.cpp
+++ b/init/init.cpp
@@ -14,6 +14,8 @@
  * limitations under the License.
  */
 
+#include "init.h"
+
 #include <ctype.h>
 #include <dirent.h>
 #include <errno.h>
@@ -40,38 +42,38 @@
 #include <selinux/label.h>
 #include <selinux/android.h>
 
+#include <android-base/chrono_utils.h>
 #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 <cutils/fs.h>
-#include <cutils/iosched_policy.h>
-#include <cutils/list.h>
-#include <cutils/sockets.h>
 #include <libavb/libavb.h>
 #include <private/android_filesystem_config.h>
 
 #include <fstream>
 #include <memory>
-#include <set>
 #include <vector>
 
 #include "action.h"
 #include "bootchart.h"
 #include "devices.h"
-#include "fs_mgr.h"
 #include "import_parser.h"
-#include "init.h"
+#include "init_first_stage.h"
 #include "init_parser.h"
 #include "keychords.h"
 #include "log.h"
 #include "property_service.h"
+#include "reboot.h"
 #include "service.h"
 #include "signal_handler.h"
 #include "ueventd.h"
 #include "util.h"
 #include "watchdogd.h"
 
+using android::base::boot_clock;
+using android::base::GetProperty;
 using android::base::StringPrintf;
 
 struct selabel_handle *sehandle;
@@ -86,14 +88,17 @@
 
 const char *ENV[32];
 
-static std::unique_ptr<Timer> waiting_for_exec(nullptr);
-
 static int epoll_fd = -1;
 
 static std::unique_ptr<Timer> waiting_for_prop(nullptr);
 static std::string wait_prop_name;
 static std::string wait_prop_value;
 
+void DumpState() {
+    ServiceManager::GetInstance().DumpState();
+    ActionManager::GetInstance().DumpState();
+}
+
 void register_epoll_handler(int fd, void (*fn)()) {
     epoll_event ev;
     ev.events = EPOLLIN;
@@ -135,29 +140,12 @@
     return -1;
 }
 
-bool start_waiting_for_exec()
-{
-    if (waiting_for_exec) {
-        return false;
-    }
-    waiting_for_exec.reset(new Timer());
-    return true;
-}
-
-void stop_waiting_for_exec()
-{
-    if (waiting_for_exec) {
-        LOG(INFO) << "Wait for exec took " << *waiting_for_exec;
-        waiting_for_exec.reset();
-    }
-}
-
 bool start_waiting_for_property(const char *name, const char *value)
 {
     if (waiting_for_prop) {
         return false;
     }
-    if (property_get(name) != value) {
+    if (GetProperty(name, "") != value) {
         // Current property value is not equal to expected value
         wait_prop_name = name;
         wait_prop_value = value;
@@ -169,10 +157,15 @@
     return true;
 }
 
-void property_changed(const char *name, const char *value)
-{
-    if (property_triggers_enabled)
-        ActionManager::GetInstance().QueuePropertyTrigger(name, value);
+void property_changed(const std::string& name, const std::string& value) {
+    // If the property is sys.powerctl, we bypass the event queue and immediately handle it.
+    // This is to ensure that init will always and immediately shutdown/reboot, regardless of
+    // if there are other pending events to process or if init is waiting on an exec service or
+    // waiting on a property.
+    if (name == "sys.powerctl") HandlePowerctlMessage(value);
+
+    if (property_triggers_enabled) ActionManager::GetInstance().QueuePropertyChange(name, value);
+
     if (waiting_for_prop) {
         if (wait_prop_name == name && wait_prop_value == value) {
             wait_prop_name.clear();
@@ -445,7 +438,7 @@
 
 static int console_init_action(const std::vector<std::string>& args)
 {
-    std::string console = property_get("ro.boot.console");
+    std::string console = GetProperty("ro.boot.console", "");
     if (!console.empty()) {
         default_console = "/dev/" + console;
     }
@@ -469,11 +462,11 @@
 }
 
 static void export_oem_lock_status() {
-    if (property_get("ro.oem_unlock_supported") != "1") {
+    if (!android::base::GetBoolProperty("ro.oem_unlock_supported", false)) {
         return;
     }
 
-    std::string value = property_get("ro.boot.verifiedbootstate");
+    std::string value = GetProperty("ro.boot.verifiedbootstate", "");
 
     if (!value.empty()) {
         property_set("ro.boot.flash.locked", value == "orange" ? "0" : "1");
@@ -494,47 +487,17 @@
         { "ro.boot.revision",   "ro.revision",   "0", },
     };
     for (size_t i = 0; i < arraysize(prop_map); i++) {
-        std::string value = property_get(prop_map[i].src_prop);
+        std::string value = GetProperty(prop_map[i].src_prop, "");
         property_set(prop_map[i].dst_prop, (!value.empty()) ? value.c_str() : prop_map[i].default_value);
     }
 }
 
-static constexpr char android_dt_dir[] = "/proc/device-tree/firmware/android";
-
-static bool is_dt_compatible() {
-    std::string dt_value;
-    std::string file_name = StringPrintf("%s/compatible", android_dt_dir);
-
-    if (android::base::ReadFileToString(file_name, &dt_value)) {
-        // trim the trailing '\0' out, otherwise the comparison
-        // will produce false-negatives.
-        dt_value.resize(dt_value.size() - 1);
-        if (dt_value == "android,firmware") {
-            return true;
-        }
-    }
-
-    return false;
-}
-
-static bool is_dt_fstab_compatible() {
-    std::string dt_value;
-    std::string file_name = StringPrintf("%s/%s/compatible", android_dt_dir, "fstab");
-
-    if (android::base::ReadFileToString(file_name, &dt_value)) {
-        dt_value.resize(dt_value.size() - 1);
-        if (dt_value == "android,fstab") {
-            return true;
-        }
-    }
-
-    return false;
-}
-
 static void process_kernel_dt() {
-    if (!is_dt_compatible()) return;
+    if (!is_android_dt_value_expected("compatible", "android,firmware")) {
+        return;
+    }
 
-    std::unique_ptr<DIR, int(*)(DIR*)>dir(opendir(android_dt_dir), closedir);
+    std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(kAndroidDtDir.c_str()), closedir);
     if (!dir) return;
 
     std::string dt_file;
@@ -544,7 +507,7 @@
             continue;
         }
 
-        std::string file_name = StringPrintf("%s/%s", android_dt_dir, dp->d_name);
+        std::string file_name = kAndroidDtDir + dp->d_name;
 
         android::base::ReadFileToString(file_name, &dt_file);
         std::replace(dt_file.begin(), dt_file.end(), ',', '.');
@@ -572,7 +535,7 @@
 static int queue_property_triggers_action(const std::vector<std::string>& args)
 {
     ActionManager::GetInstance().QueueBuiltinAction(property_enable_triggers_action, "enable_property_trigger");
-    ActionManager::GetInstance().QueueAllPropertyTriggers();
+    ActionManager::GetInstance().QueueAllPropertyActions();
     return 0;
 }
 
@@ -735,14 +698,18 @@
         return false;
     }
     std::string actual_plat_id;
-    if (!read_first_line("/system/etc/selinux/plat_sepolicy.cil.sha256", &actual_plat_id)) {
-        PLOG(INFO) << "Failed to read /system/etc/selinux/plat_sepolicy.cil.sha256";
+    if (!read_first_line("/system/etc/selinux/plat_and_mapping_sepolicy.cil.sha256",
+                         &actual_plat_id)) {
+        PLOG(INFO) << "Failed to read "
+                      "/system/etc/selinux/plat_and_mapping_sepolicy.cil.sha256";
         return false;
     }
     std::string precompiled_plat_id;
-    if (!read_first_line("/vendor/etc/selinux/precompiled_sepolicy.plat.sha256",
+    if (!read_first_line("/vendor/etc/selinux/precompiled_sepolicy.plat_and_mapping.sha256",
                          &precompiled_plat_id)) {
-        PLOG(INFO) << "Failed to read /vendor/etc/selinux/precompiled_sepolicy.plat.sha256";
+        PLOG(INFO) << "Failed to read "
+                      "/vendor/etc/selinux/"
+                      "precompiled_sepolicy.plat_and_mapping.sha256";
         return false;
     }
     if ((actual_plat_id.empty()) || (actual_plat_id != precompiled_plat_id)) {
@@ -814,7 +781,7 @@
         "-M", "true",
         // Target the highest policy language version supported by the kernel
         "-c", std::to_string(max_policy_version).c_str(),
-        "/vendor/etc/selinux/mapping_sepolicy.cil",
+        "/system/etc/selinux/mapping_sepolicy.cil",
         "/vendor/etc/selinux/nonplat_sepolicy.cil",
         "-o", compiled_sepolicy,
         // We don't care about file_contexts output by the compiler
@@ -896,6 +863,27 @@
     }
 }
 
+// The files and directories that were created before initial sepolicy load
+// need to have their security context restored to the proper value.
+// This must happen before /dev is populated by ueventd.
+static void selinux_restore_context() {
+    LOG(INFO) << "Running restorecon...";
+    restorecon("/dev");
+    restorecon("/dev/kmsg");
+    if constexpr (WORLD_WRITABLE_KMSG) {
+      restorecon("/dev/kmsg_debug");
+    }
+    restorecon("/dev/socket");
+    restorecon("/dev/random");
+    restorecon("/dev/urandom");
+    restorecon("/dev/__properties__");
+    restorecon("/plat_property_contexts");
+    restorecon("/nonplat_property_contexts");
+    restorecon("/sys", SELINUX_ANDROID_RESTORECON_RECURSE);
+    restorecon("/dev/block", SELINUX_ANDROID_RESTORECON_RECURSE);
+    restorecon("/dev/device-mapper");
+}
+
 // Set the UDC controller for the ConfigFS USB Gadgets.
 // Read the UDC controller in use from "/sys/class/udc".
 // In case of multiple UDC controllers select the first one.
@@ -912,191 +900,29 @@
     }
 }
 
-static bool early_mount_one(struct fstab_rec* rec) {
-    if (rec && fs_mgr_is_verified(rec)) {
-        // setup verity and create the dm-XX block device
-        // needed to mount this partition
-        int ret = fs_mgr_setup_verity(rec, false);
-        if (ret == FS_MGR_SETUP_VERITY_FAIL) {
-            PLOG(ERROR) << "early_mount: Failed to setup verity for '" << rec->mount_point << "'";
-            return false;
-        }
-
-        // The exact block device name is added as a mount source by
-        // fs_mgr_setup_verity() in ->blk_device as "/dev/block/dm-XX"
-        // We create that device by running coldboot on /sys/block/dm-XX
-        std::string dm_device(basename(rec->blk_device));
-        std::string syspath = StringPrintf("/sys/block/%s", dm_device.c_str());
-        device_init(syspath.c_str(), [&](uevent* uevent) -> coldboot_action_t {
-            if (uevent->device_name && !strcmp(dm_device.c_str(), uevent->device_name)) {
-                LOG(VERBOSE) << "early_mount: creating dm-verity device : " << dm_device;
-                return COLDBOOT_STOP;
-            }
-            return COLDBOOT_CONTINUE;
-        });
-    }
-
-    if (rec && fs_mgr_do_mount_one(rec)) {
-        PLOG(ERROR) << "early_mount: Failed to mount '" << rec->mount_point << "'";
-        return false;
-    }
-
-    return true;
-}
-
-// Creates devices with uevent->partition_name matching one in the in/out
-// partition_names. Note that the partition_names MUST have A/B suffix
-// when A/B is used. Found partitions will then be removed from the
-// partition_names for caller to check which devices are NOT created.
-static void early_device_init(std::set<std::string>* partition_names) {
-    if (partition_names->empty()) {
-        return;
-    }
-    device_init(nullptr, [=](uevent* uevent) -> coldboot_action_t {
-        if (!strncmp(uevent->subsystem, "firmware", 8)) {
-            return COLDBOOT_CONTINUE;
-        }
-
-        // we need platform devices to create symlinks
-        if (!strncmp(uevent->subsystem, "platform", 8)) {
-            return COLDBOOT_CREATE;
-        }
-
-        // Ignore everything that is not a block device
-        if (strncmp(uevent->subsystem, "block", 5)) {
-            return COLDBOOT_CONTINUE;
-        }
-
-        if (uevent->partition_name) {
-            // match partition names to create device nodes for partitions
-            // both partition_names and uevent->partition_name have A/B suffix when A/B is used
-            auto iter = partition_names->find(uevent->partition_name);
-            if (iter != partition_names->end()) {
-                LOG(VERBOSE) << "early_mount: found partition: " << *iter;
-                partition_names->erase(iter);
-                if (partition_names->empty()) {
-                    return COLDBOOT_STOP;  // found all partitions, stop coldboot
-                } else {
-                    return COLDBOOT_CREATE;  // create this device and continue to find others
-                }
-            }
-        }
-        // Not found a partition or find an unneeded partition, continue to find others
-        return COLDBOOT_CONTINUE;
-    });
-}
-
-static bool get_early_partitions(const std::vector<fstab_rec*>& early_fstab_recs,
-                                 std::set<std::string>* out_partitions, bool* out_need_verity) {
-    std::string meta_partition;
-    out_partitions->clear();
-    *out_need_verity = false;
-
-    for (auto fstab_rec : early_fstab_recs) {
-        // don't allow verifyatboot for early mounted partitions
-        if (fs_mgr_is_verifyatboot(fstab_rec)) {
-            LOG(ERROR) << "early_mount: partitions can't be verified at boot";
-            return false;
-        }
-        // check for verified partitions
-        if (fs_mgr_is_verified(fstab_rec)) {
-            *out_need_verity = true;
-        }
-        // check if verity metadata is on a separate partition and get partition
-        // name from the end of the ->verity_loc path. verity state is not partition
-        // specific, so there must be only 1 additional partition that carries
-        // verity state.
-        if (fstab_rec->verity_loc) {
-            if (!meta_partition.empty()) {
-                LOG(ERROR) << "early_mount: more than one meta partition found: " << meta_partition
-                           << ", " << basename(fstab_rec->verity_loc);
-                return false;
-            } else {
-                meta_partition = basename(fstab_rec->verity_loc);
-            }
-        }
-    }
-
-    // includes those early mount partitions and meta_partition (if any)
-    // note that fstab_rec->blk_device has A/B suffix updated by fs_mgr when A/B is used
-    for (auto fstab_rec : early_fstab_recs) {
-        out_partitions->emplace(basename(fstab_rec->blk_device));
-    }
-
-    if (!meta_partition.empty()) {
-        out_partitions->emplace(std::move(meta_partition));
-    }
-
-    return true;
-}
-
-/* Early mount vendor and ODM partitions. The fstab is read from device-tree. */
-static bool early_mount() {
-    // skip early mount if we're in recovery mode
-    if (access("/sbin/recovery", F_OK) == 0) {
-        LOG(INFO) << "Early mount skipped (recovery mode)";
-        return true;
-    }
-
-    // first check if device tree fstab entries are compatible
-    if (!is_dt_fstab_compatible()) {
-        LOG(INFO) << "Early mount skipped (missing/incompatible fstab in device tree)";
-        return true;
-    }
-
-    std::unique_ptr<fstab, decltype(&fs_mgr_free_fstab)> tab(
-        fs_mgr_read_fstab_dt(), fs_mgr_free_fstab);
-    if (!tab) {
-        LOG(ERROR) << "Early mount failed to read fstab from device tree";
-        return false;
-    }
-
-    // find out fstab records for odm, system and vendor
-    std::vector<fstab_rec*> early_fstab_recs;
-    for (auto mount_point : {"/odm", "/system", "/vendor"}) {
-        fstab_rec* fstab_rec = fs_mgr_get_entry_for_mount_point(tab.get(), mount_point);
-        if (fstab_rec != nullptr) {
-            early_fstab_recs.push_back(fstab_rec);
-        }
-    }
-
-    // nothing to early mount
-    if (early_fstab_recs.empty()) return true;
-
-    bool need_verity;
-    std::set<std::string> partition_names;
-    // partition_names MUST have A/B suffix when A/B is used
-    if (!get_early_partitions(early_fstab_recs, &partition_names, &need_verity)) {
-        return false;
-    }
-
-    bool success = false;
-    // create the devices we need..
-    early_device_init(&partition_names);
-
-    // early_device_init will remove found partitions from partition_names
-    // So if the partition_names is not empty here, means some partitions
-    // are not found
-    if (!partition_names.empty()) {
-        LOG(ERROR) << "early_mount: partition(s) not found: "
-                   << android::base::Join(partition_names, ", ");
-        goto done;
-    }
-
-    if (need_verity) {
-        // create /dev/device mapper
-        device_init("/sys/devices/virtual/misc/device-mapper",
-                    [&](uevent* uevent) -> coldboot_action_t { return COLDBOOT_STOP; });
-    }
-
-    for (auto fstab_rec : early_fstab_recs) {
-        if (!early_mount_one(fstab_rec)) goto done;
-    }
-    success = true;
-
-done:
-    device_close();
-    return success;
+static void install_reboot_signal_handlers() {
+    // Instead of panic'ing the kernel as is the default behavior when init crashes,
+    // we prefer to reboot to bootloader on development builds, as this will prevent
+    // boot looping bad configurations and allow both developers and test farms to easily
+    // recover.
+    struct sigaction action;
+    memset(&action, 0, sizeof(action));
+    sigfillset(&action.sa_mask);
+    action.sa_handler = [](int) {
+        // panic() reboots to bootloader
+        panic();
+    };
+    action.sa_flags = SA_RESTART;
+    sigaction(SIGABRT, &action, nullptr);
+    sigaction(SIGBUS, &action, nullptr);
+    sigaction(SIGFPE, &action, nullptr);
+    sigaction(SIGILL, &action, nullptr);
+    sigaction(SIGSEGV, &action, nullptr);
+#if defined(SIGSTKFLT)
+    sigaction(SIGSTKFLT, &action, nullptr);
+#endif
+    sigaction(SIGSYS, &action, nullptr);
+    sigaction(SIGTRAP, &action, nullptr);
 }
 
 int main(int argc, char** argv) {
@@ -1108,6 +934,10 @@
         return watchdogd_main(argc, argv);
     }
 
+    if (REBOOT_BOOTLOADER_ON_PANIC) {
+        install_reboot_signal_handlers();
+    }
+
     add_environment("PATH", _PATH_DEFPATH);
 
     bool is_first_stage = (getenv("INIT_SECOND_STAGE") == nullptr);
@@ -1132,7 +962,13 @@
         setgroups(arraysize(groups), groups);
         mount("sysfs", "/sys", "sysfs", 0, NULL);
         mount("selinuxfs", "/sys/fs/selinux", "selinuxfs", 0, NULL);
+
         mknod("/dev/kmsg", S_IFCHR | 0600, makedev(1, 11));
+
+        if constexpr (WORLD_WRITABLE_KMSG) {
+          mknod("/dev/kmsg_debug", S_IFCHR | 0622, makedev(1, 11));
+        }
+
         mknod("/dev/random", S_IFCHR | 0666, makedev(1, 8));
         mknod("/dev/urandom", S_IFCHR | 0666, makedev(1, 9));
 
@@ -1142,11 +978,13 @@
 
         LOG(INFO) << "init first stage started!";
 
-        if (!early_mount()) {
+        if (!DoFirstStageMount()) {
             LOG(ERROR) << "Failed to mount required partitions early ...";
             panic();
         }
 
+        SetInitAvbVersionInRecovery();
+
         // Set up SELinux, loading the SELinux policy.
         selinux_initialize(true);
 
@@ -1196,31 +1034,18 @@
     property_set("ro.boottime.init.selinux", getenv("INIT_SELINUX_TOOK"));
 
     // Set libavb version for Framework-only OTA match in Treble build.
-    property_set("ro.boot.init.avb_version", std::to_string(AVB_MAJOR_VERSION).c_str());
+    const char* avb_version = getenv("INIT_AVB_VERSION");
+    if (avb_version) property_set("ro.boot.avb_version", avb_version);
 
     // Clean up our environment.
     unsetenv("INIT_SECOND_STAGE");
     unsetenv("INIT_STARTED_AT");
     unsetenv("INIT_SELINUX_TOOK");
+    unsetenv("INIT_AVB_VERSION");
 
     // Now set up SELinux for second stage.
     selinux_initialize(false);
-
-    // These directories were necessarily created before initial policy load
-    // and therefore need their security context restored to the proper value.
-    // This must happen before /dev is populated by ueventd.
-    LOG(INFO) << "Running restorecon...";
-    restorecon("/dev");
-    restorecon("/dev/kmsg");
-    restorecon("/dev/socket");
-    restorecon("/dev/random");
-    restorecon("/dev/urandom");
-    restorecon("/dev/__properties__");
-    restorecon("/plat_property_contexts");
-    restorecon("/nonplat_property_contexts");
-    restorecon("/sys", SELINUX_ANDROID_RESTORECON_RECURSE);
-    restorecon("/dev/block", SELINUX_ANDROID_RESTORECON_RECURSE);
-    restorecon("/dev/device-mapper");
+    selinux_restore_context();
 
     epoll_fd = epoll_create1(EPOLL_CLOEXEC);
     if (epoll_fd == -1) {
@@ -1238,11 +1063,14 @@
     const BuiltinFunctionMap function_map;
     Action::set_function_map(&function_map);
 
+    ActionManager& am = ActionManager::GetInstance();
+    ServiceManager& sm = ServiceManager::GetInstance();
     Parser& parser = Parser::GetInstance();
-    parser.AddSectionParser("service",std::make_unique<ServiceParser>());
-    parser.AddSectionParser("on", std::make_unique<ActionParser>());
-    parser.AddSectionParser("import", std::make_unique<ImportParser>());
-    std::string bootscript = property_get("ro.boot.init_rc");
+
+    parser.AddSectionParser("service", std::make_unique<ServiceParser>(&sm));
+    parser.AddSectionParser("on", std::make_unique<ActionParser>(&am));
+    parser.AddSectionParser("import", std::make_unique<ImportParser>(&parser));
+    std::string bootscript = GetProperty("ro.boot.init_rc", "");
     if (bootscript.empty()) {
         parser.ParseConfig("/init.rc");
         parser.set_is_system_etc_init_loaded(
@@ -1259,9 +1087,7 @@
 
     // Turning this on and letting the INFO logging be discarded adds 0.2s to
     // Nexus 9 boot time, so it's disabled by default.
-    if (false) parser.DumpState();
-
-    ActionManager& am = ActionManager::GetInstance();
+    if (false) DumpState();
 
     am.QueueEventTrigger("early-init");
 
@@ -1282,7 +1108,7 @@
     am.QueueBuiltinAction(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_linux_rng");
 
     // Don't mount filesystems or start core system services in charger mode.
-    std::string bootmode = property_get("ro.bootmode");
+    std::string bootmode = GetProperty("ro.bootmode", "");
     if (bootmode == "charger") {
         am.QueueEventTrigger("charger");
     } else {
@@ -1293,22 +1119,24 @@
     am.QueueBuiltinAction(queue_property_triggers_action, "queue_property_triggers");
 
     while (true) {
-        if (!(waiting_for_exec || waiting_for_prop)) {
-            am.ExecuteOneCommand();
-            restart_processes();
-        }
-
         // By default, sleep until something happens.
         int epoll_timeout_ms = -1;
 
-        // If there's a process that needs restarting, wake up in time for that.
-        if (process_needs_restart_at != 0) {
-            epoll_timeout_ms = (process_needs_restart_at - time(nullptr)) * 1000;
-            if (epoll_timeout_ms < 0) epoll_timeout_ms = 0;
+        if (!(waiting_for_prop || sm.IsWaitingForExec())) {
+            am.ExecuteOneCommand();
         }
+        if (!(waiting_for_prop || sm.IsWaitingForExec())) {
+            restart_processes();
 
-        // If there's more work to do, wake up again immediately.
-        if (am.HasMoreCommands()) epoll_timeout_ms = 0;
+            // If there's a process that needs restarting, wake up in time for that.
+            if (process_needs_restart_at != 0) {
+                epoll_timeout_ms = (process_needs_restart_at - time(nullptr)) * 1000;
+                if (epoll_timeout_ms < 0) epoll_timeout_ms = 0;
+            }
+
+            // If there's more work to do, wake up again immediately.
+            if (am.HasMoreCommands()) epoll_timeout_ms = 0;
+        }
 
         epoll_event ev;
         int nr = TEMP_FAILURE_RETRY(epoll_wait(epoll_fd, &ev, 1, epoll_timeout_ms));
diff --git a/init/init.h b/init/init.h
index 3768c02..6add75f 100644
--- a/init/init.h
+++ b/init/init.h
@@ -19,9 +19,6 @@
 
 #include <string>
 
-class Action;
-class Service;
-
 extern const char *ENV[32];
 extern std::string default_console;
 extern struct selabel_handle *sehandle;
@@ -29,16 +26,14 @@
 
 void handle_control_message(const std::string& msg, const std::string& arg);
 
-void property_changed(const char *name, const char *value);
+void property_changed(const std::string& name, const std::string& value);
 
 void register_epoll_handler(int fd, void (*fn)());
 
 int add_environment(const char* key, const char* val);
 
-bool start_waiting_for_exec();
-
-void stop_waiting_for_exec();
-
 bool start_waiting_for_property(const char *name, const char *value);
 
+void DumpState();
+
 #endif  /* _INIT_INIT_H */
diff --git a/init/init_first_stage.cpp b/init/init_first_stage.cpp
new file mode 100644
index 0000000..2fa790d
--- /dev/null
+++ b/init/init_first_stage.cpp
@@ -0,0 +1,436 @@
+/*
+ * 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 "init_first_stage.h"
+
+#include <stdlib.h>
+#include <unistd.h>
+
+#include <memory>
+#include <set>
+#include <string>
+#include <vector>
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/strings.h>
+
+#include "devices.h"
+#include "fs_mgr.h"
+#include "fs_mgr_avb.h"
+#include "util.h"
+
+// Class Declarations
+// ------------------
+class FirstStageMount {
+  public:
+    FirstStageMount();
+    virtual ~FirstStageMount() = default;
+
+    // The factory method to create either FirstStageMountVBootV1 or FirstStageMountVBootV2
+    // based on device tree configurations.
+    static std::unique_ptr<FirstStageMount> Create();
+    bool DoFirstStageMount();  // Mounts fstab entries read from device tree.
+    bool InitDevices();
+
+  protected:
+    void InitRequiredDevices(std::set<std::string>* devices_partition_names);
+    void InitVerityDevice(const std::string& verity_device);
+    bool MountPartitions();
+
+    virtual bool GetRequiredDevices(std::set<std::string>* out_devices_partition_names,
+                                    bool* out_need_dm_verity) = 0;
+    virtual bool SetUpDmVerity(fstab_rec* fstab_rec) = 0;
+
+    // Device tree fstab entries.
+    std::unique_ptr<fstab, decltype(&fs_mgr_free_fstab)> device_tree_fstab_;
+    // Eligible first stage mount candidates, only allow /system, /vendor and/or /odm.
+    std::vector<fstab_rec*> mount_fstab_recs_;
+};
+
+class FirstStageMountVBootV1 : public FirstStageMount {
+  public:
+    FirstStageMountVBootV1() = default;
+    ~FirstStageMountVBootV1() override = default;
+
+  protected:
+    bool GetRequiredDevices(std::set<std::string>* out_devices_partition_names,
+                            bool* out_need_dm_verity) override;
+    bool SetUpDmVerity(fstab_rec* fstab_rec) override;
+};
+
+class FirstStageMountVBootV2 : public FirstStageMount {
+  public:
+    FirstStageMountVBootV2();
+    ~FirstStageMountVBootV2() override = default;
+
+    const std::string& by_name_prefix() const { return device_tree_by_name_prefix_; }
+
+  protected:
+    bool GetRequiredDevices(std::set<std::string>* out_devices_partition_names,
+                            bool* out_need_dm_verity) override;
+    bool SetUpDmVerity(fstab_rec* fstab_rec) override;
+    bool InitAvbHandle();
+
+    std::string device_tree_vbmeta_parts_;
+    std::string device_tree_by_name_prefix_;
+    FsManagerAvbUniquePtr avb_handle_;
+};
+
+// Static Functions
+// ----------------
+static inline bool IsDtVbmetaCompatible() {
+    return is_android_dt_value_expected("vbmeta/compatible", "android,vbmeta");
+}
+
+static bool inline IsRecoveryMode() {
+    return access("/sbin/recovery", F_OK) == 0;
+}
+
+// Class Definitions
+// -----------------
+FirstStageMount::FirstStageMount() : device_tree_fstab_(fs_mgr_read_fstab_dt(), fs_mgr_free_fstab) {
+    if (!device_tree_fstab_) {
+        LOG(ERROR) << "Failed to read fstab from device tree";
+        return;
+    }
+    for (auto mount_point : {"/system", "/vendor", "/odm"}) {
+        fstab_rec* fstab_rec =
+            fs_mgr_get_entry_for_mount_point(device_tree_fstab_.get(), mount_point);
+        if (fstab_rec != nullptr) {
+            mount_fstab_recs_.push_back(fstab_rec);
+        }
+    }
+}
+
+std::unique_ptr<FirstStageMount> FirstStageMount::Create() {
+    if (IsDtVbmetaCompatible()) {
+        return std::make_unique<FirstStageMountVBootV2>();
+    } else {
+        return std::make_unique<FirstStageMountVBootV1>();
+    }
+}
+
+bool FirstStageMount::DoFirstStageMount() {
+    // Nothing to mount.
+    if (mount_fstab_recs_.empty()) return true;
+
+    if (!InitDevices()) return false;
+
+    if (!MountPartitions()) return false;
+
+    return true;
+}
+
+bool FirstStageMount::InitDevices() {
+    bool need_dm_verity;
+    std::set<std::string> devices_partition_names;
+
+    // The partition name in devices_partition_names MUST have A/B suffix when A/B is used.
+    if (!GetRequiredDevices(&devices_partition_names, &need_dm_verity)) return false;
+
+    if (need_dm_verity) {
+        const std::string dm_path = "/devices/virtual/misc/device-mapper";
+        device_init(("/sys" + dm_path).c_str(), [&dm_path](uevent* uevent) -> coldboot_action_t {
+            if (uevent->path == dm_path) return COLDBOOT_STOP;
+            return COLDBOOT_CONTINUE;  // dm_path not found, continue to find it.
+        });
+    }
+
+    bool success = false;
+    InitRequiredDevices(&devices_partition_names);
+
+    // InitRequiredDevices() will remove found partitions from devices_partition_names.
+    // So if it isn't empty here, it means some partitions are not found.
+    if (!devices_partition_names.empty()) {
+        LOG(ERROR) << __FUNCTION__ << "(): partition(s) not found: "
+                   << android::base::Join(devices_partition_names, ", ");
+    } else {
+        success = true;
+    }
+
+    device_close();
+    return success;
+}
+
+// Creates devices with uevent->partition_name matching one in the in/out
+// devices_partition_names. Found partitions will then be removed from the
+// devices_partition_names for the caller to check which devices are NOT created.
+void FirstStageMount::InitRequiredDevices(std::set<std::string>* devices_partition_names) {
+    if (devices_partition_names->empty()) {
+        return;
+    }
+    device_init(nullptr, [=](uevent* uevent) -> coldboot_action_t {
+        // We need platform devices to create symlinks.
+        if (uevent->subsystem == "platform") {
+            return COLDBOOT_CREATE;
+        }
+
+        // Ignores everything that is not a block device.
+        if (uevent->subsystem != "block") {
+            return COLDBOOT_CONTINUE;
+        }
+
+        if (!uevent->partition_name.empty()) {
+            // Matches partition name to create device nodes.
+            // Both devices_partition_names and uevent->partition_name have A/B
+            // suffix when A/B is used.
+            auto iter = devices_partition_names->find(uevent->partition_name);
+            if (iter != devices_partition_names->end()) {
+                LOG(VERBOSE) << __FUNCTION__ << "(): found partition: " << *iter;
+                devices_partition_names->erase(iter);
+                if (devices_partition_names->empty()) {
+                    return COLDBOOT_STOP;  // Found all partitions, stop coldboot.
+                } else {
+                    return COLDBOOT_CREATE;  // Creates this device and continue to find others.
+                }
+            }
+        }
+        // Not found a partition or find an unneeded partition, continue to find others.
+        return COLDBOOT_CONTINUE;
+    });
+}
+
+// Creates "/dev/block/dm-XX" for dm-verity by running coldboot on /sys/block/dm-XX.
+void FirstStageMount::InitVerityDevice(const std::string& verity_device) {
+    const std::string device_name(basename(verity_device.c_str()));
+    const std::string syspath = "/sys/block/" + device_name;
+
+    device_init(syspath.c_str(), [&](uevent* uevent) -> coldboot_action_t {
+        if (uevent->device_name == device_name) {
+            LOG(VERBOSE) << "Creating dm-verity device : " << verity_device;
+            return COLDBOOT_STOP;
+        }
+        return COLDBOOT_CONTINUE;
+    });
+    device_close();
+}
+
+bool FirstStageMount::MountPartitions() {
+    for (auto fstab_rec : mount_fstab_recs_) {
+        if (!SetUpDmVerity(fstab_rec)) {
+            PLOG(ERROR) << "Failed to setup verity for '" << fstab_rec->mount_point << "'";
+            return false;
+        }
+        if (fs_mgr_do_mount_one(fstab_rec)) {
+            PLOG(ERROR) << "Failed to mount '" << fstab_rec->mount_point << "'";
+            return false;
+        }
+    }
+    return true;
+}
+
+bool FirstStageMountVBootV1::GetRequiredDevices(std::set<std::string>* out_devices_partition_names,
+                                                bool* out_need_dm_verity) {
+    std::string verity_loc_device;
+    *out_need_dm_verity = false;
+
+    for (auto fstab_rec : mount_fstab_recs_) {
+        // Don't allow verifyatboot in the first stage.
+        if (fs_mgr_is_verifyatboot(fstab_rec)) {
+            LOG(ERROR) << "Partitions can't be verified at boot";
+            return false;
+        }
+        // Checks for verified partitions.
+        if (fs_mgr_is_verified(fstab_rec)) {
+            *out_need_dm_verity = true;
+        }
+        // Checks if verity metadata is on a separate partition. Note that it is
+        // not partition specific, so there must be only one additional partition
+        // that carries verity state.
+        if (fstab_rec->verity_loc) {
+            if (verity_loc_device.empty()) {
+                verity_loc_device = fstab_rec->verity_loc;
+            } else if (verity_loc_device != fstab_rec->verity_loc) {
+                LOG(ERROR) << "More than one verity_loc found: " << verity_loc_device << ", "
+                           << fstab_rec->verity_loc;
+                return false;
+            }
+        }
+    }
+
+    // Includes the partition names of fstab records and verity_loc_device (if any).
+    // Notes that fstab_rec->blk_device has A/B suffix updated by fs_mgr when A/B is used.
+    for (auto fstab_rec : mount_fstab_recs_) {
+        out_devices_partition_names->emplace(basename(fstab_rec->blk_device));
+    }
+
+    if (!verity_loc_device.empty()) {
+        out_devices_partition_names->emplace(basename(verity_loc_device.c_str()));
+    }
+
+    return true;
+}
+
+bool FirstStageMountVBootV1::SetUpDmVerity(fstab_rec* fstab_rec) {
+    if (fs_mgr_is_verified(fstab_rec)) {
+        int ret = fs_mgr_setup_verity(fstab_rec, false /* wait_for_verity_dev */);
+        if (ret == FS_MGR_SETUP_VERITY_DISABLED) {
+            LOG(INFO) << "Verity disabled for '" << fstab_rec->mount_point << "'";
+        } else if (ret == FS_MGR_SETUP_VERITY_SUCCESS) {
+            // The exact block device name (fstab_rec->blk_device) is changed to "/dev/block/dm-XX".
+            // Needs to create it because ueventd isn't started in init first stage.
+            InitVerityDevice(fstab_rec->blk_device);
+        } else {
+            return false;
+        }
+    }
+    return true;  // Returns true to mount the partition.
+}
+
+// FirstStageMountVBootV2 constructor.
+// Gets the vbmeta configurations from device tree.
+// Specifically, the 'parts' and 'by_name_prefix' below.
+// /{
+//     firmware {
+//         android {
+//             vbmeta {
+//                 compatible = "android,vbmeta";
+//                 parts = "vbmeta,boot,system,vendor"
+//                 by_name_prefix = "/dev/block/platform/soc.0/f9824900.sdhci/by-name/"
+//             };
+//         };
+//     };
+//  }
+FirstStageMountVBootV2::FirstStageMountVBootV2() : avb_handle_(nullptr) {
+    if (!read_android_dt_file("vbmeta/parts", &device_tree_vbmeta_parts_)) {
+        PLOG(ERROR) << "Failed to read vbmeta/parts from device tree";
+        return;
+    }
+
+    // TODO: removes by_name_prefix to allow partitions on different block devices.
+    if (!read_android_dt_file("vbmeta/by_name_prefix", &device_tree_by_name_prefix_)) {
+        PLOG(ERROR) << "Failed to read vbmeta/by_name_prefix from dt";
+        return;
+    }
+}
+
+bool FirstStageMountVBootV2::GetRequiredDevices(std::set<std::string>* out_devices_partition_names,
+                                                bool* out_need_dm_verity) {
+    *out_need_dm_verity = false;
+
+    // fstab_rec->blk_device has A/B suffix.
+    for (auto fstab_rec : mount_fstab_recs_) {
+        if (fs_mgr_is_avb(fstab_rec)) {
+            *out_need_dm_verity = true;
+        }
+        out_devices_partition_names->emplace(basename(fstab_rec->blk_device));
+    }
+
+    // libavb verifies AVB metadata on all verified partitions at once.
+    // e.g., The device_tree_vbmeta_parts_ will be "vbmeta,boot,system,vendor"
+    // for libavb to verify metadata, even if there is only /vendor in the
+    // above mount_fstab_recs_.
+    if (*out_need_dm_verity) {
+        if (device_tree_vbmeta_parts_.empty()) {
+            LOG(ERROR) << "Missing vbmeta parts in device tree";
+            return false;
+        }
+        std::vector<std::string> partitions = android::base::Split(device_tree_vbmeta_parts_, ",");
+        std::string ab_suffix = fs_mgr_get_slot_suffix();
+        for (const auto& partition : partitions) {
+            // out_devices_partition_names is of type std::set so it's not an issue to emplace
+            // a partition twice. e.g., /vendor might be in both places:
+            //   - device_tree_vbmeta_parts_ = "vbmeta,boot,system,vendor"
+            //   - mount_fstab_recs_: /vendor_a
+            out_devices_partition_names->emplace(partition + ab_suffix);
+        }
+    }
+    return true;
+}
+
+bool FirstStageMountVBootV2::SetUpDmVerity(fstab_rec* fstab_rec) {
+    if (fs_mgr_is_avb(fstab_rec)) {
+        if (!InitAvbHandle()) return false;
+        if (avb_handle_->hashtree_disabled()) {
+            LOG(INFO) << "avb hashtree disabled for '" << fstab_rec->mount_point << "'";
+        } else if (avb_handle_->SetUpAvb(fstab_rec, false /* wait_for_verity_dev */)) {
+            // The exact block device name (fstab_rec->blk_device) is changed to "/dev/block/dm-XX".
+            // Needs to create it because ueventd isn't started in init first stage.
+            InitVerityDevice(fstab_rec->blk_device);
+        } else {
+            return false;
+        }
+    }
+    return true;  // Returns true to mount the partition.
+}
+
+bool FirstStageMountVBootV2::InitAvbHandle() {
+    if (avb_handle_) return true;  // Returns true if the handle is already initialized.
+
+    avb_handle_ = FsManagerAvbHandle::Open(device_tree_by_name_prefix_);
+    if (!avb_handle_) {
+        PLOG(ERROR) << "Failed to open FsManagerAvbHandle";
+        return false;
+    }
+    // Sets INIT_AVB_VERSION here for init to set ro.boot.avb_version in the second stage.
+    setenv("INIT_AVB_VERSION", avb_handle_->avb_version().c_str(), 1);
+    return true;
+}
+
+// Public functions
+// ----------------
+// Mounts /system, /vendor, and/or /odm if they are present in the fstab provided by device tree.
+bool DoFirstStageMount() {
+    // Skips first stage mount if we're in recovery mode.
+    if (IsRecoveryMode()) {
+        LOG(INFO) << "First stage mount skipped (recovery mode)";
+        return true;
+    }
+
+    // Firstly checks if device tree fstab entries are compatible.
+    if (!is_android_dt_value_expected("fstab/compatible", "android,fstab")) {
+        LOG(INFO) << "First stage mount skipped (missing/incompatible fstab in device tree)";
+        return true;
+    }
+
+    std::unique_ptr<FirstStageMount> handle = FirstStageMount::Create();
+    if (!handle) {
+        LOG(ERROR) << "Failed to create FirstStageMount";
+        return false;
+    }
+    return handle->DoFirstStageMount();
+}
+
+void SetInitAvbVersionInRecovery() {
+    if (!IsRecoveryMode()) {
+        LOG(INFO) << "Skipped setting INIT_AVB_VERSION (not in recovery mode)";
+        return;
+    }
+
+    if (!IsDtVbmetaCompatible()) {
+        LOG(INFO) << "Skipped setting INIT_AVB_VERSION (not vbmeta compatible)";
+        return;
+    }
+
+    // Initializes required devices for the subsequent FsManagerAvbHandle::Open()
+    // to verify AVB metadata on all partitions in the verified chain.
+    // We only set INIT_AVB_VERSION when the AVB verification succeeds, i.e., the
+    // Open() function returns a valid handle.
+    // We don't need to mount partitions here in recovery mode.
+    FirstStageMountVBootV2 avb_first_mount;
+    if (!avb_first_mount.InitDevices()) {
+        LOG(ERROR) << "Failed to init devices for INIT_AVB_VERSION";
+        return;
+    }
+
+    FsManagerAvbUniquePtr avb_handle = FsManagerAvbHandle::Open(avb_first_mount.by_name_prefix());
+    if (!avb_handle) {
+        PLOG(ERROR) << "Failed to open FsManagerAvbHandle for INIT_AVB_VERSION";
+        return;
+    }
+    setenv("INIT_AVB_VERSION", avb_handle->avb_version().c_str(), 1);
+}
diff --git a/bootstat/uptime_parser.h b/init/init_first_stage.h
similarity index 65%
copy from bootstat/uptime_parser.h
copy to init/init_first_stage.h
index 756ae9b..170a24c 100644
--- a/bootstat/uptime_parser.h
+++ b/init/init_first_stage.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2016 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,16 +14,10 @@
  * limitations under the License.
  */
 
-#ifndef UPTIME_PARSER_H_
-#define UPTIME_PARSER_H_
+#ifndef _INIT_FIRST_STAGE_H
+#define _INIT_FIRST_STAGE_H
 
-#include <time.h>
+bool DoFirstStageMount();
+void SetInitAvbVersionInRecovery();
 
-namespace bootstat {
-
-// Returns the number of seconds the system has been on since reboot.
-time_t ParseUptime();
-
-}  // namespace bootstat
-
-#endif  // UPTIME_PARSER_H_
\ No newline at end of file
+#endif
diff --git a/init/init_parser.cpp b/init/init_parser.cpp
index 326ebf2..620367a 100644
--- a/init/init_parser.cpp
+++ b/init/init_parser.cpp
@@ -14,18 +14,16 @@
  * limitations under the License.
  */
 
-#include <dirent.h>
-#include <errno.h>
-#include <fcntl.h>
-
-#include "action.h"
 #include "init_parser.h"
-#include "log.h"
-#include "parser.h"
-#include "service.h"
-#include "util.h"
 
+#include <dirent.h>
+
+#include <android-base/logging.h>
 #include <android-base/stringprintf.h>
+#include <android-base/strings.h>
+
+#include "parser.h"
+#include "util.h"
 
 Parser::Parser() {
 }
@@ -40,13 +38,16 @@
     section_parsers_[name] = std::move(parser);
 }
 
+void Parser::AddSingleLineParser(const std::string& prefix, LineCallback callback) {
+    line_callbacks_.emplace_back(prefix, callback);
+}
+
 void Parser::ParseData(const std::string& filename, const std::string& data) {
     //TODO: Use a parser with const input and remove this copy
     std::vector<char> data_copy(data.begin(), data.end());
     data_copy.push_back('\0');
 
     parse_state state;
-    state.filename = filename.c_str();
     state.line = 0;
     state.ptr = &data_copy[0];
     state.nexttoken = 0;
@@ -66,21 +67,34 @@
             if (args.empty()) {
                 break;
             }
+            // If we have a line matching a prefix we recognize, call its callback and unset any
+            // 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 (section_parser) section_parser->EndSection();
+
+                    std::string ret_err;
+                    if (!callback(std::move(args), &ret_err)) {
+                        LOG(ERROR) << filename << ": " << state.line << ": " << ret_err;
+                    }
+                    section_parser = nullptr;
+                    break;
+                }
+            }
             if (section_parsers_.count(args[0])) {
                 if (section_parser) {
                     section_parser->EndSection();
                 }
                 section_parser = section_parsers_[args[0]].get();
                 std::string ret_err;
-                if (!section_parser->ParseSection(args, &ret_err)) {
-                    parse_error(&state, "%s\n", ret_err.c_str());
+                if (!section_parser->ParseSection(std::move(args), filename, state.line, &ret_err)) {
+                    LOG(ERROR) << filename << ": " << state.line << ": " << ret_err;
                     section_parser = nullptr;
                 }
             } else if (section_parser) {
                 std::string ret_err;
-                if (!section_parser->ParseLineSection(args, state.filename,
-                                                      state.line, &ret_err)) {
-                    parse_error(&state, "%s\n", ret_err.c_str());
+                if (!section_parser->ParseLineSection(std::move(args), state.line, &ret_err)) {
+                    LOG(ERROR) << filename << ": " << state.line << ": " << ret_err;
                 }
             }
             args.clear();
@@ -96,14 +110,14 @@
     LOG(INFO) << "Parsing file " << path << "...";
     Timer t;
     std::string data;
-    if (!read_file(path.c_str(), &data)) {
+    if (!read_file(path, &data)) {
         return false;
     }
 
     data.push_back('\n'); // TODO: fix parse_config.
     ParseData(path, data);
-    for (const auto& sp : section_parsers_) {
-        sp.second->EndFile(path);
+    for (const auto& [section_name, section_parser] : section_parsers_) {
+        section_parser->EndFile();
     }
 
     LOG(VERBOSE) << "(Parsing " << path << " took " << t << ".)";
@@ -143,8 +157,3 @@
     }
     return ParseConfigFile(path);
 }
-
-void Parser::DumpState() const {
-    ServiceManager::GetInstance().DumpState();
-    ActionManager::GetInstance().DumpState();
-}
diff --git a/init/init_parser.h b/init/init_parser.h
index f66ba52..bd8a178 100644
--- a/init/init_parser.h
+++ b/init/init_parser.h
@@ -18,50 +18,76 @@
 #define _INIT_INIT_PARSER_H_
 
 #include <map>
+#include <memory>
 #include <string>
 #include <vector>
 
+//  SectionParser is an interface that can parse a given 'section' in init.
+//
+//  You can implement up to 4 functions below, with ParseSection() being mandatory.
+//  The first two function return bool with false indicating a failure and has a std::string* err
+//  parameter into which an error string can be written.  It will be reported along with the
+//  filename and line number of where the error occurred.
+//
+//  1) bool ParseSection(std::vector<std::string>&& args, const std::string& filename,
+//                       int line, std::string* err)
+//    This function is called when a section is first encountered.
+//
+//  2) bool ParseLineSection(std::vector<std::string>&& args, int line, std::string* err)
+//    This function is called on each subsequent line until the next section is encountered.
+//
+//  3) bool EndSection()
+//    This function is called either when a new section is found or at the end of the file.
+//    It indicates that parsing of the current section is complete and any relevant objects should
+//    be committed.
+//
+//  4) bool EndFile()
+//    This function is called at the end of the file.
+//    It indicates that the parsing has completed and any relevant objects should be committed.
+
 class SectionParser {
-public:
-    virtual ~SectionParser() {
-    }
-    virtual bool ParseSection(const std::vector<std::string>& args,
-                              std::string* err) = 0;
-    virtual bool ParseLineSection(const std::vector<std::string>& args,
-                                  const std::string& filename, int line,
-                                  std::string* err) const = 0;
-    virtual void EndSection() = 0;
-    virtual void EndFile(const std::string& filename) = 0;
+  public:
+    virtual ~SectionParser() {}
+    virtual bool ParseSection(std::vector<std::string>&& args, const std::string& filename,
+                              int line, std::string* err) = 0;
+    virtual bool ParseLineSection(std::vector<std::string>&&, int, std::string*) { return true; };
+    virtual void EndSection(){};
+    virtual void EndFile(){};
 };
 
 class Parser {
-public:
+  public:
+    //  LineCallback is the type for callbacks that can parse a line starting with a given prefix.
+    //
+    //  They take the form of bool Callback(std::vector<std::string>&& args, std::string* err)
+    //
+    //  Similar to ParseSection() and ParseLineSection(), this function returns bool with false
+    //  indicating a failure and has an std::string* err parameter into which an error string can
+    //  be written.
+    using LineCallback = std::function<bool(std::vector<std::string>&&, std::string*)>;
+
     static Parser& GetInstance();
-    void DumpState() const;
+
+    // Exposed for testing
+    Parser();
+
     bool ParseConfig(const std::string& path);
-    void AddSectionParser(const std::string& name,
-                          std::unique_ptr<SectionParser> parser);
-    void set_is_system_etc_init_loaded(bool loaded) {
-        is_system_etc_init_loaded_ = loaded;
-    }
-    void set_is_vendor_etc_init_loaded(bool loaded) {
-        is_vendor_etc_init_loaded_ = loaded;
-    }
-    void set_is_odm_etc_init_loaded(bool loaded) {
-        is_odm_etc_init_loaded_ = loaded;
-    }
+    void AddSectionParser(const std::string& name, std::unique_ptr<SectionParser> parser);
+    void AddSingleLineParser(const std::string& prefix, LineCallback callback);
+    void set_is_system_etc_init_loaded(bool loaded) { is_system_etc_init_loaded_ = loaded; }
+    void set_is_vendor_etc_init_loaded(bool loaded) { is_vendor_etc_init_loaded_ = loaded; }
+    void set_is_odm_etc_init_loaded(bool loaded) { is_odm_etc_init_loaded_ = loaded; }
     bool is_system_etc_init_loaded() { return is_system_etc_init_loaded_; }
     bool is_vendor_etc_init_loaded() { return is_vendor_etc_init_loaded_; }
     bool is_odm_etc_init_loaded() { return is_odm_etc_init_loaded_; }
 
-private:
-    Parser();
-
+  private:
     void ParseData(const std::string& filename, const std::string& data);
     bool ParseConfigFile(const std::string& path);
     bool ParseConfigDir(const std::string& path);
 
     std::map<std::string, std::unique_ptr<SectionParser>> section_parsers_;
+    std::vector<std::pair<std::string, LineCallback>> line_callbacks_;
     bool is_system_etc_init_loaded_ = false;
     bool is_vendor_etc_init_loaded_ = false;
     bool is_odm_etc_init_loaded_ = false;
diff --git a/init/init_parser_test.cpp b/init/init_parser_test.cpp
index 52aaa37..d8fd2ba 100644
--- a/init/init_parser_test.cpp
+++ b/init/init_parser_test.cpp
@@ -18,9 +18,7 @@
 
 #include "init.h"
 #include "service.h"
-#include "util.h"
 
-#include <errno.h>
 #include <gtest/gtest.h>
 
 #include <string>
diff --git a/init/init_test.cpp b/init/init_test.cpp
new file mode 100644
index 0000000..3da14b5
--- /dev/null
+++ b/init/init_test.cpp
@@ -0,0 +1,186 @@
+/*
+ * 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 <functional>
+
+#include <android-base/file.h>
+#include <android-base/test_utils.h>
+#include <gtest/gtest.h>
+
+#include "action.h"
+#include "builtins.h"
+#include "import_parser.h"
+#include "init_parser.h"
+#include "keyword_map.h"
+#include "util.h"
+
+class TestFunctionMap : public KeywordMap<BuiltinFunction> {
+  public:
+    // Helper for argument-less functions
+    using BuiltinFunctionNoArgs = std::function<void(void)>;
+    void Add(const std::string& name, const BuiltinFunctionNoArgs function) {
+        Add(name, 0, 0, [function](const std::vector<std::string>&) {
+            function();
+            return 0;
+        });
+    }
+
+    void Add(const std::string& name, std::size_t min_parameters, std::size_t max_parameters,
+             const BuiltinFunction function) {
+        builtin_functions_[name] = make_tuple(min_parameters, max_parameters, function);
+    }
+
+  private:
+    Map builtin_functions_ = {};
+
+    const Map& map() const override { return builtin_functions_; }
+};
+
+using ActionManagerCommand = std::function<void(ActionManager&)>;
+
+void TestInit(const std::string& init_script_file, const TestFunctionMap& test_function_map,
+              const std::vector<ActionManagerCommand>& commands) {
+    ActionManager am;
+
+    Action::set_function_map(&test_function_map);
+
+    Parser parser;
+    parser.AddSectionParser("on", std::make_unique<ActionParser>(&am));
+    parser.AddSectionParser("import", std::make_unique<ImportParser>(&parser));
+
+    ASSERT_TRUE(parser.ParseConfig(init_script_file));
+
+    for (const auto& command : commands) {
+        command(am);
+    }
+
+    while (am.HasMoreCommands()) {
+        am.ExecuteOneCommand();
+    }
+}
+
+void TestInitText(const std::string& init_script, const TestFunctionMap& test_function_map,
+                  const std::vector<ActionManagerCommand>& commands) {
+    TemporaryFile tf;
+    ASSERT_TRUE(tf.fd != -1);
+    ASSERT_TRUE(android::base::WriteStringToFd(init_script, tf.fd));
+    TestInit(tf.path, test_function_map, commands);
+}
+
+TEST(init, SimpleEventTrigger) {
+    bool expect_true = false;
+    std::string init_script =
+        R"init(
+on boot
+pass_test
+)init";
+
+    TestFunctionMap test_function_map;
+    test_function_map.Add("pass_test", [&expect_true]() { expect_true = true; });
+
+    ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
+    std::vector<ActionManagerCommand> commands{trigger_boot};
+
+    TestInitText(init_script, test_function_map, commands);
+
+    EXPECT_TRUE(expect_true);
+}
+
+TEST(init, EventTriggerOrder) {
+    std::string init_script =
+        R"init(
+on boot
+execute_first
+
+on boot && property:ro.hardware=*
+execute_second
+
+on boot
+execute_third
+
+)init";
+
+    int num_executed = 0;
+    TestFunctionMap test_function_map;
+    test_function_map.Add("execute_first", [&num_executed]() { EXPECT_EQ(0, num_executed++); });
+    test_function_map.Add("execute_second", [&num_executed]() { EXPECT_EQ(1, num_executed++); });
+    test_function_map.Add("execute_third", [&num_executed]() { EXPECT_EQ(2, num_executed++); });
+
+    ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
+    std::vector<ActionManagerCommand> commands{trigger_boot};
+
+    TestInitText(init_script, test_function_map, commands);
+}
+
+TEST(init, EventTriggerOrderMultipleFiles) {
+    // 6 total files, which should have their triggers executed in the following order:
+    // 1: start - original script parsed
+    // 2: first_import - immediately imported by first_script
+    // 3: dir_a - file named 'a.rc' in dir; dir is imported after first_import
+    // 4: a_import - file imported by dir_a
+    // 5: dir_b - file named 'b.rc' in dir
+    // 6: last_import - imported after dir is imported
+
+    TemporaryFile first_import;
+    ASSERT_TRUE(first_import.fd != -1);
+    ASSERT_TRUE(android::base::WriteStringToFd("on boot\nexecute 2", first_import.fd));
+
+    TemporaryFile dir_a_import;
+    ASSERT_TRUE(dir_a_import.fd != -1);
+    ASSERT_TRUE(android::base::WriteStringToFd("on boot\nexecute 4", dir_a_import.fd));
+
+    TemporaryFile last_import;
+    ASSERT_TRUE(last_import.fd != -1);
+    ASSERT_TRUE(android::base::WriteStringToFd("on boot\nexecute 6", last_import.fd));
+
+    TemporaryDir dir;
+    // clang-format off
+    std::string dir_a_script = "import " + std::string(dir_a_import.path) + "\n"
+                               "on boot\n"
+                               "execute 3";
+    // clang-format on
+    // write_file() ensures the right mode is set
+    ASSERT_TRUE(write_file(std::string(dir.path) + "/a.rc", dir_a_script));
+
+    ASSERT_TRUE(write_file(std::string(dir.path) + "/b.rc", "on boot\nexecute 5"));
+
+    // clang-format off
+    std::string start_script = "import " + std::string(first_import.path) + "\n"
+                               "import " + std::string(dir.path) + "\n"
+                               "import " + std::string(last_import.path) + "\n"
+                               "on boot\n"
+                               "execute 1";
+    // clang-format on
+    TemporaryFile start;
+    ASSERT_TRUE(android::base::WriteStringToFd(start_script, start.fd));
+
+    int num_executed = 0;
+    auto execute_command = [&num_executed](const std::vector<std::string>& args) {
+        EXPECT_EQ(2U, args.size());
+        EXPECT_EQ(++num_executed, std::stoi(args[1]));
+        return 0;
+    };
+
+    TestFunctionMap test_function_map;
+    test_function_map.Add("execute", 1, 1, execute_command);
+
+    ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
+    std::vector<ActionManagerCommand> commands{trigger_boot};
+
+    TestInit(start.path, test_function_map, commands);
+
+    EXPECT_EQ(6, num_executed);
+}
diff --git a/init/keychords.cpp b/init/keychords.cpp
index 3dbb2f0..c572cee 100644
--- a/init/keychords.cpp
+++ b/init/keychords.cpp
@@ -14,18 +14,17 @@
  * limitations under the License.
  */
 
-#include <errno.h>
 #include <fcntl.h>
 #include <stdlib.h>
-#include <string.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <linux/keychord.h>
 #include <unistd.h>
 
+#include <android-base/logging.h>
+#include <android-base/properties.h>
+
 #include "init.h"
-#include "log.h"
-#include "property_service.h"
 #include "service.h"
 
 static struct input_keychord *keychords = 0;
@@ -74,7 +73,7 @@
     }
 
     // Only handle keychords if adb is enabled.
-    std::string adb_enabled = property_get("init.svc.adbd");
+    std::string adb_enabled = android::base::GetProperty("init.svc.adbd", "");
     if (adb_enabled == "running") {
         Service* svc = ServiceManager::GetInstance().FindServiceByKeychord(id);
         if (svc) {
diff --git a/init/keyword_map.h b/init/keyword_map.h
index 693d82a..88bad01 100644
--- a/init/keyword_map.h
+++ b/init/keyword_map.h
@@ -24,18 +24,23 @@
 
 template <typename Function>
 class KeywordMap {
-public:
+  public:
     using FunctionInfo = std::tuple<std::size_t, std::size_t, Function>;
-    using Map = const std::map<std::string, FunctionInfo>;
+    using Map = std::map<std::string, FunctionInfo>;
 
     virtual ~KeywordMap() {
     }
 
-    const Function FindFunction(const std::string& keyword,
-                                size_t num_args,
-                                std::string* err) const {
+    const Function FindFunction(const std::vector<std::string>& args, std::string* err) const {
         using android::base::StringPrintf;
 
+        if (args.empty()) {
+            *err = "keyword needed, but not provided";
+            return nullptr;
+        }
+        auto& keyword = args[0];
+        auto num_args = args.size() - 1;
+
         auto function_info_it = map().find(keyword);
         if (function_info_it == map().end()) {
             *err = StringPrintf("invalid keyword '%s'", keyword.c_str());
@@ -68,10 +73,10 @@
         return std::get<Function>(function_info);
     }
 
-private:
-//Map of keyword ->
-//(minimum number of arguments, maximum number of arguments, function pointer)
-    virtual Map& map() const = 0;
+  private:
+    // Map of keyword ->
+    // (minimum number of arguments, maximum number of arguments, function pointer)
+    virtual const Map& map() const = 0;
 };
 
 #endif
diff --git a/init/log.cpp b/init/log.cpp
index 6b32526..0615730 100644
--- a/init/log.cpp
+++ b/init/log.cpp
@@ -17,10 +17,10 @@
 #include "log.h"
 
 #include <fcntl.h>
+#include <linux/audit.h>
 #include <string.h>
 
-#include <linux/audit.h>
-#include <netlink/netlink.h>
+#include <android-base/logging.h>
 #include <selinux/selinux.h>
 
 void InitKernelLogging(char* argv[]) {
@@ -40,24 +40,6 @@
     android::base::InitLogging(argv, &android::base::KernelLogger);
 }
 
-static void selinux_avc_log(char* buf, size_t buf_len) {
-    size_t str_len = strnlen(buf, buf_len);
-
-    // trim newline at end of string
-    buf[str_len - 1] = '\0';
-
-    struct nl_sock* sk = nl_socket_alloc();
-    if (sk == NULL) {
-        return;
-    }
-    nl_connect(sk, NETLINK_AUDIT);
-    int result;
-    do {
-        result = nl_send_simple(sk, AUDIT_USER_AVC, 0, buf, str_len);
-    } while (result == -NLE_INTR);
-    nl_socket_free(sk);
-}
-
 int selinux_klog_callback(int type, const char *fmt, ...) {
     android::base::LogSeverity severity = android::base::ERROR;
     if (type == SELINUX_WARNING) {
@@ -68,15 +50,8 @@
     char buf[1024];
     va_list ap;
     va_start(ap, fmt);
-    int res = vsnprintf(buf, sizeof(buf), fmt, ap);
+    vsnprintf(buf, sizeof(buf), fmt, ap);
     va_end(ap);
-    if (res <= 0) {
-        return 0;
-    }
-    if (type == SELINUX_AVC) {
-        selinux_avc_log(buf, sizeof(buf));
-    } else {
-        android::base::KernelLogger(android::base::MAIN, severity, "selinux", nullptr, 0, buf);
-    }
+    android::base::KernelLogger(android::base::MAIN, severity, "selinux", nullptr, 0, buf);
     return 0;
 }
diff --git a/init/log.h b/init/log.h
index 8fa6d74..29a27af 100644
--- a/init/log.h
+++ b/init/log.h
@@ -17,7 +17,7 @@
 #ifndef _INIT_LOG_H_
 #define _INIT_LOG_H_
 
-#include <android-base/logging.h>
+#include <sys/cdefs.h>
 
 void InitKernelLogging(char* argv[]);
 
diff --git a/init/parser.cpp b/init/parser.cpp
index 45862b7..0d13cfe 100644
--- a/init/parser.cpp
+++ b/init/parser.cpp
@@ -1,28 +1,5 @@
 #include "parser.h"
 
-#include <stdarg.h>
-#include <stdio.h>
-#include <string.h>
-
-#include "log.h"
-
-void parse_error(struct parse_state *state, const char *fmt, ...)
-{
-    va_list ap;
-    char buf[128];
-    int off;
-
-    snprintf(buf, sizeof(buf), "%s: %d: ", state->filename, state->line);
-    buf[127] = 0;
-    off = strlen(buf);
-
-    va_start(ap, fmt);
-    vsnprintf(buf + off, 128 - off, fmt, ap);
-    va_end(ap);
-    buf[127] = 0;
-    LOG(ERROR) << buf;
-}
-
 int next_token(struct parse_state *state)
 {
     char *x = state->ptr;
diff --git a/init/parser.h b/init/parser.h
index 95e1164..3dcc566 100644
--- a/init/parser.h
+++ b/init/parser.h
@@ -27,14 +27,8 @@
     char *text;
     int line;
     int nexttoken;
-    void *context;
-    void (*parse_line)(struct parse_state *state, int nargs, char **args);
-    const char *filename;
-    void *priv;
 };
 
-void dump_parser_state(void);
 int next_token(struct parse_state *state);
-void parse_error(struct parse_state *state, const char *fmt, ...);
 
 #endif /* PARSER_H_ */
diff --git a/init/property_service.cpp b/init/property_service.cpp
index 983e684..aa47976 100644
--- a/init/property_service.cpp
+++ b/init/property_service.cpp
@@ -14,50 +14,46 @@
  * limitations under the License.
  */
 
+#include "property_service.h"
+
+#include <ctype.h>
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
 #include <inttypes.h>
+#include <limits.h>
+#include <netinet/in.h>
+#include <stdarg.h>
+#include <stddef.h>
 #include <stdio.h>
 #include <stdlib.h>
-#include <unistd.h>
 #include <string.h>
-#include <ctype.h>
-#include <fcntl.h>
-#include <stdarg.h>
-#include <dirent.h>
-#include <limits.h>
-#include <errno.h>
+#include <sys/mman.h>
 #include <sys/poll.h>
-
-#include <memory>
-#include <vector>
-
-#include <cutils/misc.h>
-#include <cutils/sockets.h>
-#include <cutils/multiuser.h>
+#include <sys/select.h>
+#include <sys/types.h>
+#include <sys/un.h>
+#include <unistd.h>
 
 #define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
 #include <sys/_system_properties.h>
 
-#include <sys/socket.h>
-#include <sys/un.h>
-#include <sys/select.h>
-#include <sys/types.h>
-#include <netinet/in.h>
-#include <sys/mman.h>
+#include <memory>
+#include <vector>
 
-#include <selinux/android.h>
-#include <selinux/selinux.h>
-#include <selinux/label.h>
-
-#include <fs_mgr.h>
 #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 "bootimg.h"
+#include <bootimg.h>
+#include <fs_mgr.h>
+#include <selinux/android.h>
+#include <selinux/label.h>
+#include <selinux/selinux.h>
 
-#include "property_service.h"
 #include "init.h"
 #include "util.h"
-#include "log.h"
 
 using android::base::StringPrintf;
 
@@ -118,12 +114,6 @@
     return check_mac_perms(ctl_name, sctx, cr);
 }
 
-std::string property_get(const char* name) {
-    char value[PROP_VALUE_MAX] = {0};
-    __system_property_get(name, value);
-    return value;
-}
-
 static void write_persistent_property(const char *name, const char *value)
 {
     char tempPath[PATH_MAX];
@@ -216,7 +206,7 @@
     if (persistent_properties_loaded && android::base::StartsWith(name, "persist.")) {
         write_persistent_property(name.c_str(), value.c_str());
     }
-    property_changed(name.c_str(), value.c_str());
+    property_changed(name, value);
     return PROP_SUCCESS;
 }
 
@@ -584,18 +574,33 @@
     }
 }
 
+// persist.sys.usb.config values can't be combined on build-time when property
+// files are split into each partition.
+// So we need to apply the same rule of build/make/tools/post_process_props.py
+// on runtime.
+static void update_sys_usb_config() {
+    bool is_debuggable = android::base::GetBoolProperty("ro.debuggable", false);
+    std::string config = android::base::GetProperty("persist.sys.usb.config", "");
+    if (config.empty()) {
+        property_set("persist.sys.usb.config", is_debuggable ? "adb" : "none");
+    } else if (is_debuggable && config.find("adb") == std::string::npos &&
+               config.length() + 4 < PROP_VALUE_MAX) {
+        config.append(",adb");
+        property_set("persist.sys.usb.config", config);
+    }
+}
+
 void property_load_boot_defaults() {
     load_properties_from_file("/default.prop", NULL);
     load_properties_from_file("/odm/default.prop", NULL);
     load_properties_from_file("/vendor/default.prop", NULL);
+
+    update_sys_usb_config();
 }
 
 static void load_override_properties() {
     if (ALLOW_LOCAL_PROP_OVERRIDE) {
-        std::string debuggable = property_get("ro.debuggable");
-        if (debuggable == "1") {
-            load_properties_from_file("/data/local.prop", NULL);
-        }
+        load_properties_from_file("/data/local.prop", NULL);
     }
 }
 
diff --git a/init/property_service.h b/init/property_service.h
index 5d59473..9a5b6f6 100644
--- a/init/property_service.h
+++ b/init/property_service.h
@@ -17,9 +17,8 @@
 #ifndef _INIT_PROPERTY_H
 #define _INIT_PROPERTY_H
 
-#include <stddef.h>
 #include <sys/socket.h>
-#include <sys/system_properties.h>
+
 #include <string>
 
 struct property_audit_data {
@@ -32,7 +31,6 @@
 void load_persist_props(void);
 void load_system_props(void);
 void start_property_service(void);
-std::string property_get(const char* name);
 uint32_t property_set(const std::string& name, const std::string& value);
 bool is_legal_property_name(const std::string& name);
 
diff --git a/init/reboot.cpp b/init/reboot.cpp
new file mode 100644
index 0000000..838406d
--- /dev/null
+++ b/init/reboot.cpp
@@ -0,0 +1,470 @@
+/*
+ * 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 "reboot.h"
+
+#include <dirent.h>
+#include <fcntl.h>
+#include <linux/fs.h>
+#include <mntent.h>
+#include <selinux/selinux.h>
+#include <sys/cdefs.h>
+#include <sys/ioctl.h>
+#include <sys/mount.h>
+#include <sys/reboot.h>
+#include <sys/stat.h>
+#include <sys/syscall.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+
+#include <memory>
+#include <set>
+#include <thread>
+#include <vector>
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/macros.h>
+#include <android-base/properties.h>
+#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
+#include <android-base/unique_fd.h>
+#include <bootloader_message/bootloader_message.h>
+#include <cutils/android_reboot.h>
+#include <fs_mgr.h>
+#include <logwrap/logwrap.h>
+#include <private/android_filesystem_config.h>
+
+#include "property_service.h"
+#include "service.h"
+
+using android::base::StringPrintf;
+
+// represents umount status during reboot / shutdown.
+enum UmountStat {
+    /* umount succeeded. */
+    UMOUNT_STAT_SUCCESS = 0,
+    /* umount was not run. */
+    UMOUNT_STAT_SKIPPED = 1,
+    /* umount failed with timeout. */
+    UMOUNT_STAT_TIMEOUT = 2,
+    /* could not run due to error */
+    UMOUNT_STAT_ERROR = 3,
+    /* not used by init but reserved for other part to use this to represent the
+       the state where umount status before reboot is not found / available. */
+    UMOUNT_STAT_NOT_AVAILABLE = 4,
+};
+
+// Utility for struct mntent
+class MountEntry {
+  public:
+    explicit MountEntry(const mntent& entry)
+        : mnt_fsname_(entry.mnt_fsname),
+          mnt_dir_(entry.mnt_dir),
+          mnt_type_(entry.mnt_type),
+          mnt_opts_(entry.mnt_opts) {}
+
+    bool Umount() {
+        int r = umount2(mnt_dir_.c_str(), 0);
+        if (r == 0) {
+            LOG(INFO) << "umounted " << mnt_fsname_ << ":" << mnt_dir_ << " opts " << mnt_opts_;
+            return true;
+        } else {
+            PLOG(WARNING) << "cannot umount " << mnt_fsname_ << ":" << mnt_dir_ << " opts "
+                          << mnt_opts_;
+            return false;
+        }
+    }
+
+    void DoFsck() {
+        int st;
+        if (IsF2Fs()) {
+            const char* f2fs_argv[] = {
+                "/system/bin/fsck.f2fs", "-f", mnt_fsname_.c_str(),
+            };
+            android_fork_execvp_ext(arraysize(f2fs_argv), (char**)f2fs_argv, &st, true, LOG_KLOG,
+                                    true, nullptr, nullptr, 0);
+        } else if (IsExt4()) {
+            const char* ext4_argv[] = {
+                "/system/bin/e2fsck", "-f", "-y", mnt_fsname_.c_str(),
+            };
+            android_fork_execvp_ext(arraysize(ext4_argv), (char**)ext4_argv, &st, true, LOG_KLOG,
+                                    true, nullptr, nullptr, 0);
+        }
+    }
+
+    static bool IsBlockDevice(const struct mntent& mntent) {
+        return android::base::StartsWith(mntent.mnt_fsname, "/dev/block");
+    }
+
+    static bool IsEmulatedDevice(const struct mntent& mntent) {
+        return android::base::StartsWith(mntent.mnt_fsname, "/data/");
+    }
+
+  private:
+    bool IsF2Fs() const { return mnt_type_ == "f2fs"; }
+
+    bool IsExt4() const { return mnt_type_ == "ext4"; }
+
+    std::string mnt_fsname_;
+    std::string mnt_dir_;
+    std::string mnt_type_;
+    std::string mnt_opts_;
+};
+
+// Turn off backlight while we are performing power down cleanup activities.
+static void TurnOffBacklight() {
+    static constexpr char OFF[] = "0";
+
+    android::base::WriteStringToFile(OFF, "/sys/class/leds/lcd-backlight/brightness");
+
+    static const char backlightDir[] = "/sys/class/backlight";
+    std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(backlightDir), closedir);
+    if (!dir) {
+        return;
+    }
+
+    struct dirent* dp;
+    while ((dp = readdir(dir.get())) != nullptr) {
+        if (((dp->d_type != DT_DIR) && (dp->d_type != DT_LNK)) || (dp->d_name[0] == '.')) {
+            continue;
+        }
+
+        std::string fileName = StringPrintf("%s/%s/brightness", backlightDir, dp->d_name);
+        android::base::WriteStringToFile(OFF, fileName);
+    }
+}
+
+static void ShutdownVold() {
+    const char* vdc_argv[] = {"/system/bin/vdc", "volume", "shutdown"};
+    int status;
+    android_fork_execvp_ext(arraysize(vdc_argv), (char**)vdc_argv, &status, true, LOG_KLOG, true,
+                            nullptr, nullptr, 0);
+}
+
+static void LogShutdownTime(UmountStat stat, Timer* t) {
+    LOG(WARNING) << "powerctl_shutdown_time_ms:" << std::to_string(t->duration_ms()) << ":" << stat;
+}
+
+static void __attribute__((noreturn))
+RebootSystem(unsigned int cmd, const std::string& rebootTarget) {
+    LOG(INFO) << "Reboot ending, jumping to kernel";
+    switch (cmd) {
+        case ANDROID_RB_POWEROFF:
+            reboot(RB_POWER_OFF);
+            break;
+
+        case ANDROID_RB_RESTART2:
+            syscall(__NR_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2,
+                    LINUX_REBOOT_CMD_RESTART2, rebootTarget.c_str());
+            break;
+
+        case ANDROID_RB_THERMOFF:
+            reboot(RB_POWER_OFF);
+            break;
+    }
+    // In normal case, reboot should not return.
+    PLOG(FATAL) << "reboot call returned";
+    abort();
+}
+
+/* Find all read+write block devices and emulated devices in /proc/mounts
+ * and add them to correpsponding list.
+ */
+static bool FindPartitionsToUmount(std::vector<MountEntry>* blockDevPartitions,
+                                   std::vector<MountEntry>* emulatedPartitions, bool dump) {
+    std::unique_ptr<std::FILE, int (*)(std::FILE*)> fp(setmntent("/proc/mounts", "r"), endmntent);
+    if (fp == nullptr) {
+        PLOG(ERROR) << "Failed to open /proc/mounts";
+        return false;
+    }
+    mntent* mentry;
+    while ((mentry = getmntent(fp.get())) != nullptr) {
+        if (dump) {
+            LOG(INFO) << "mount entry " << mentry->mnt_fsname << ":" << mentry->mnt_dir << " opts "
+                      << mentry->mnt_opts << " type " << mentry->mnt_type;
+        } else if (MountEntry::IsBlockDevice(*mentry) && hasmntopt(mentry, "rw")) {
+            blockDevPartitions->emplace(blockDevPartitions->begin(), *mentry);
+        } else if (MountEntry::IsEmulatedDevice(*mentry)) {
+            emulatedPartitions->emplace(emulatedPartitions->begin(), *mentry);
+        }
+    }
+    return true;
+}
+
+static void DumpUmountDebuggingInfo(bool dump_all) {
+    int status;
+    if (!security_getenforce()) {
+        LOG(INFO) << "Run lsof";
+        const char* lsof_argv[] = {"/system/bin/lsof"};
+        android_fork_execvp_ext(arraysize(lsof_argv), (char**)lsof_argv, &status, true, LOG_KLOG,
+                                true, nullptr, nullptr, 0);
+    }
+    FindPartitionsToUmount(nullptr, nullptr, true);
+    if (dump_all) {
+        // dump current tasks, this log can be lengthy, so only dump with dump_all
+        android::base::WriteStringToFile("t", "/proc/sysrq-trigger");
+    }
+}
+
+static UmountStat UmountPartitions(int timeoutMs) {
+    Timer t;
+    UmountStat stat = UMOUNT_STAT_TIMEOUT;
+    int retry = 0;
+    /* data partition needs all pending writes to be completed and all emulated partitions
+     * umounted.If the current waiting is not good enough, give
+     * up and leave it to e2fsck after reboot to fix it.
+     */
+    while (true) {
+        std::vector<MountEntry> block_devices;
+        std::vector<MountEntry> emulated_devices;
+        if (!FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
+            return UMOUNT_STAT_ERROR;
+        }
+        if (block_devices.size() == 0) {
+            stat = UMOUNT_STAT_SUCCESS;
+            break;
+        }
+        if ((timeoutMs < t.duration_ms()) && retry > 0) {  // try umount at least once
+            stat = UMOUNT_STAT_TIMEOUT;
+            break;
+        }
+        if (emulated_devices.size() > 0 &&
+            std::all_of(emulated_devices.begin(), emulated_devices.end(),
+                        [](auto& entry) { return entry.Umount(); })) {
+            sync();
+        }
+        for (auto& entry : block_devices) {
+            entry.Umount();
+        }
+        retry++;
+        std::this_thread::sleep_for(100ms);
+    }
+    return stat;
+}
+
+static void KillAllProcesses() { android::base::WriteStringToFile("i", "/proc/sysrq-trigger"); }
+
+/* Try umounting all emulated file systems R/W block device cfile systems.
+ * This will just try umount and give it up if it fails.
+ * For fs like ext4, this is ok as file system will be marked as unclean shutdown
+ * and necessary check can be done at the next reboot.
+ * For safer shutdown, caller needs to make sure that
+ * all processes / emulated partition for the target fs are all cleaned-up.
+ *
+ * return true when umount was successful. false when timed out.
+ */
+static UmountStat TryUmountAndFsck(bool runFsck, int timeoutMs) {
+    Timer t;
+    std::vector<MountEntry> block_devices;
+    std::vector<MountEntry> emulated_devices;
+
+    TurnOffBacklight();  // this part can take time. save power.
+
+    if (runFsck && !FindPartitionsToUmount(&block_devices, &emulated_devices, false)) {
+        return UMOUNT_STAT_ERROR;
+    }
+
+    UmountStat stat = UmountPartitions(timeoutMs - t.duration_ms());
+    if (stat != UMOUNT_STAT_SUCCESS) {
+        LOG(INFO) << "umount timeout, last resort, kill all and try";
+        if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo(false);
+        KillAllProcesses();
+        // even if it succeeds, still it is timeout and do not run fsck with all processes killed
+        UmountPartitions(0);
+        if (DUMP_ON_UMOUNT_FAILURE) DumpUmountDebuggingInfo(true);
+    }
+
+    if (stat == UMOUNT_STAT_SUCCESS && runFsck) {
+        // fsck part is excluded from timeout check. It only runs for user initiated shutdown
+        // and should not affect reboot time.
+        for (auto& entry : block_devices) {
+            entry.DoFsck();
+        }
+    }
+    return stat;
+}
+
+static void __attribute__((noreturn)) DoThermalOff() {
+    LOG(WARNING) << "Thermal system shutdown";
+    sync();
+    RebootSystem(ANDROID_RB_THERMOFF, "");
+    abort();
+}
+
+void DoReboot(unsigned int cmd, const std::string& reason, const std::string& rebootTarget,
+              bool runFsck) {
+    Timer t;
+    LOG(INFO) << "Reboot start, reason: " << reason << ", rebootTarget: " << rebootTarget;
+
+    android::base::WriteStringToFile(StringPrintf("%s\n", reason.c_str()), LAST_REBOOT_REASON_FILE,
+                                     S_IRUSR | S_IWUSR, AID_SYSTEM, AID_SYSTEM);
+
+    if (cmd == ANDROID_RB_THERMOFF) {  // do not wait if it is thermal
+        DoThermalOff();
+        abort();
+    }
+
+    constexpr unsigned int shutdownTimeoutDefault = 6;
+    unsigned int shutdownTimeout = shutdownTimeoutDefault;
+    if (SHUTDOWN_ZERO_TIMEOUT) {  // eng build
+        shutdownTimeout = 0;
+    } else {
+        shutdownTimeout =
+            android::base::GetUintProperty("ro.build.shutdown_timeout", shutdownTimeoutDefault);
+    }
+    LOG(INFO) << "Shutdown timeout: " << shutdownTimeout;
+
+    // keep debugging tools until non critical ones are all gone.
+    const std::set<std::string> kill_after_apps{"tombstoned", "logd", "adbd"};
+    // watchdogd is a vendor specific component but should be alive to complete shutdown safely.
+    const std::set<std::string> to_starts{"watchdogd", "vold"};
+    ServiceManager::GetInstance().ForEachService([&kill_after_apps, &to_starts](Service* s) {
+        if (kill_after_apps.count(s->name())) {
+            s->SetShutdownCritical();
+        } else if (to_starts.count(s->name())) {
+            s->Start();
+            s->SetShutdownCritical();
+        }
+    });
+
+    Service* bootAnim = ServiceManager::GetInstance().FindServiceByName("bootanim");
+    Service* surfaceFlinger = ServiceManager::GetInstance().FindServiceByName("surfaceflinger");
+    if (bootAnim != nullptr && surfaceFlinger != nullptr && surfaceFlinger->IsRunning()) {
+        ServiceManager::GetInstance().ForEachServiceInClass("animation", [](Service* s) {
+            s->SetShutdownCritical();  // will not check animation class separately
+        });
+    }
+
+    // optional shutdown step
+    // 1. terminate all services except shutdown critical ones. wait for delay to finish
+    if (shutdownTimeout > 0) {
+        LOG(INFO) << "terminating init services";
+
+        // Ask all services to terminate except shutdown critical ones.
+        ServiceManager::GetInstance().ForEachService([](Service* s) {
+            if (!s->IsShutdownCritical()) s->Terminate();
+        });
+
+        int service_count = 0;
+        // Up to half as long as shutdownTimeout or 3 seconds, whichever is lower.
+        unsigned int terminationWaitTimeout = std::min<unsigned int>((shutdownTimeout + 1) / 2, 3);
+        while (t.duration_s() < terminationWaitTimeout) {
+            ServiceManager::GetInstance().ReapAnyOutstandingChildren();
+
+            service_count = 0;
+            ServiceManager::GetInstance().ForEachService([&service_count](Service* s) {
+                // Count the number of services running except shutdown critical.
+                // Exclude the console as it will ignore the SIGTERM signal
+                // and not exit.
+                // Note: SVC_CONSOLE actually means "requires console" but
+                // it is only used by the shell.
+                if (!s->IsShutdownCritical() && s->pid() != 0 && (s->flags() & SVC_CONSOLE) == 0) {
+                    service_count++;
+                }
+            });
+
+            if (service_count == 0) {
+                // All terminable services terminated. We can exit early.
+                break;
+            }
+
+            // Wait a bit before recounting the number or running services.
+            std::this_thread::sleep_for(50ms);
+        }
+        LOG(INFO) << "Terminating running services took " << t
+                  << " with remaining services:" << service_count;
+    }
+
+    // minimum safety steps before restarting
+    // 2. kill all services except ones that are necessary for the shutdown sequence.
+    ServiceManager::GetInstance().ForEachService([](Service* s) {
+        if (!s->IsShutdownCritical()) s->Stop();
+    });
+    ServiceManager::GetInstance().ReapAnyOutstandingChildren();
+
+    // 3. send volume shutdown to vold
+    Service* voldService = ServiceManager::GetInstance().FindServiceByName("vold");
+    if (voldService != nullptr && voldService->IsRunning()) {
+        ShutdownVold();
+        voldService->Stop();
+    } else {
+        LOG(INFO) << "vold not running, skipping vold shutdown";
+    }
+    // logcat stopped here
+    ServiceManager::GetInstance().ForEachService([&kill_after_apps](Service* s) {
+        if (kill_after_apps.count(s->name())) s->Stop();
+    });
+    // 4. sync, try umount, and optionally run fsck for user shutdown
+    sync();
+    UmountStat stat = TryUmountAndFsck(runFsck, shutdownTimeout * 1000 - t.duration_ms());
+    // Follow what linux shutdown is doing: one more sync with little bit delay
+    sync();
+    std::this_thread::sleep_for(100ms);
+    LogShutdownTime(stat, &t);
+    // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
+    RebootSystem(cmd, rebootTarget);
+    abort();
+}
+
+bool HandlePowerctlMessage(const std::string& command) {
+    unsigned int cmd = 0;
+    std::vector<std::string> cmd_params = android::base::Split(command, ",");
+    std::string reboot_target = "";
+    bool run_fsck = false;
+    bool command_invalid = false;
+
+    if (cmd_params.size() > 3) {
+        command_invalid = true;
+    } else if (cmd_params[0] == "shutdown") {
+        cmd = ANDROID_RB_POWEROFF;
+        if (cmd_params.size() == 2 && cmd_params[1] == "userrequested") {
+            // The shutdown reason is PowerManager.SHUTDOWN_USER_REQUESTED.
+            // Run fsck once the file system is remounted in read-only mode.
+            run_fsck = true;
+        }
+    } else if (cmd_params[0] == "reboot") {
+        cmd = ANDROID_RB_RESTART2;
+        if (cmd_params.size() >= 2) {
+            reboot_target = cmd_params[1];
+            // When rebooting to the bootloader notify the bootloader writing
+            // also the BCB.
+            if (reboot_target == "bootloader") {
+                std::string err;
+                if (!write_reboot_bootloader(&err)) {
+                    LOG(ERROR) << "reboot-bootloader: Error writing "
+                                  "bootloader_message: "
+                               << err;
+                }
+            }
+            // If there is an additional bootloader parameter, pass it along
+            if (cmd_params.size() == 3) {
+                reboot_target += "," + cmd_params[2];
+            }
+        }
+    } else if (command == "thermal-shutdown") {  // no additional parameter allowed
+        cmd = ANDROID_RB_THERMOFF;
+    } else {
+        command_invalid = true;
+    }
+    if (command_invalid) {
+        LOG(ERROR) << "powerctl: unrecognized command '" << command << "'";
+        return false;
+    }
+
+    DoReboot(cmd, command, reboot_target, run_fsck);
+    return true;
+}
diff --git a/init/reboot.h b/init/reboot.h
new file mode 100644
index 0000000..b304b3c
--- /dev/null
+++ b/init/reboot.h
@@ -0,0 +1,35 @@
+/*
+ * 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 _INIT_REBOOT_H
+#define _INIT_REBOOT_H
+
+#include <string>
+
+/* Reboot / shutdown the system.
+ * cmd ANDROID_RB_* as defined in android_reboot.h
+ * reason Reason string like "reboot", "userrequested"
+ * rebootTarget Reboot target string like "bootloader". Otherwise, it should be an
+ *              empty string.
+ * runFsck Whether to run fsck after umount is done.
+ */
+void DoReboot(unsigned int cmd, const std::string& reason, const std::string& rebootTarget,
+              bool runFsck) __attribute__((__noreturn__));
+
+// Parses and handles a setprop sys.powerctl message.
+bool HandlePowerctlMessage(const std::string& command);
+
+#endif
diff --git a/init/service.cpp b/init/service.cpp
index ba901fd..3a9f622 100644
--- a/init/service.cpp
+++ b/init/service.cpp
@@ -24,29 +24,27 @@
 #include <sys/prctl.h>
 #include <sys/resource.h>
 #include <sys/stat.h>
+#include <sys/system_properties.h>
 #include <sys/time.h>
-#include <sys/types.h>
 #include <sys/wait.h>
 #include <termios.h>
 #include <unistd.h>
 
-#include <selinux/selinux.h>
-
 #include <android-base/file.h>
+#include <android-base/logging.h>
 #include <android-base/parseint.h>
+#include <android-base/properties.h>
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
+#include <processgroup/processgroup.h>
+#include <selinux/selinux.h>
 #include <system/thread_defs.h>
 
-#include <processgroup/processgroup.h>
-
-#include "action.h"
 #include "init.h"
-#include "init_parser.h"
-#include "log.h"
 #include "property_service.h"
 #include "util.h"
 
+using android::base::boot_clock;
 using android::base::ParseInt;
 using android::base::StringPrintf;
 using android::base::WriteStringToFile;
@@ -149,33 +147,54 @@
     : name(name), value(value) {
 }
 
-Service::Service(const std::string& name, const std::string& classname,
-                 const std::vector<std::string>& args)
-    : name_(name), classname_(classname), flags_(0), pid_(0),
-      crash_count_(0), uid_(0), gid_(0), namespace_flags_(0),
-      seclabel_(""), ioprio_class_(IoSchedClass_NONE), ioprio_pri_(0),
-      priority_(0), oom_score_adjust_(-1000), args_(args) {
+Service::Service(const std::string& name, const std::vector<std::string>& args)
+    : name_(name),
+      classnames_({"default"}),
+      flags_(0),
+      pid_(0),
+      crash_count_(0),
+      uid_(0),
+      gid_(0),
+      namespace_flags_(0),
+      seclabel_(""),
+      onrestart_(false, "<Service '" + name + "' onrestart>", 0),
+      keychord_id_(0),
+      ioprio_class_(IoSchedClass_NONE),
+      ioprio_pri_(0),
+      priority_(0),
+      oom_score_adjust_(-1000),
+      args_(args) {
     onrestart_.InitSingleTrigger("onrestart");
 }
 
-Service::Service(const std::string& name, const std::string& classname,
-                 unsigned flags, uid_t uid, gid_t gid,
-                 const std::vector<gid_t>& supp_gids,
-                 const CapSet& capabilities, unsigned namespace_flags,
-                 const std::string& seclabel,
+Service::Service(const std::string& name, unsigned flags, uid_t uid, gid_t gid,
+                 const std::vector<gid_t>& supp_gids, const CapSet& capabilities,
+                 unsigned namespace_flags, const std::string& seclabel,
                  const std::vector<std::string>& args)
-    : name_(name), classname_(classname), flags_(flags), pid_(0),
-      crash_count_(0), uid_(uid), gid_(gid),
-      supp_gids_(supp_gids), capabilities_(capabilities),
-      namespace_flags_(namespace_flags), seclabel_(seclabel),
-      ioprio_class_(IoSchedClass_NONE), ioprio_pri_(0), priority_(0),
-      oom_score_adjust_(-1000), args_(args) {
+    : name_(name),
+      classnames_({"default"}),
+      flags_(flags),
+      pid_(0),
+      crash_count_(0),
+      uid_(uid),
+      gid_(gid),
+      supp_gids_(supp_gids),
+      capabilities_(capabilities),
+      namespace_flags_(namespace_flags),
+      seclabel_(seclabel),
+      onrestart_(false, "<Service '" + name + "' onrestart>", 0),
+      keychord_id_(0),
+      ioprio_class_(IoSchedClass_NONE),
+      ioprio_pri_(0),
+      priority_(0),
+      oom_score_adjust_(-1000),
+      args_(args) {
     onrestart_.InitSingleTrigger("onrestart");
 }
 
 void Service::NotifyStateChange(const std::string& new_state) const {
-    if ((flags_ & SVC_EXEC) != 0) {
-        // 'exec' commands don't have properties tracking their state.
+    if ((flags_ & SVC_TEMPORARY) != 0) {
+        // Services created by 'exec' are temporary and don't have properties tracking their state.
         return;
     }
 
@@ -193,8 +212,14 @@
     LOG(INFO) << "Sending signal " << signal
               << " to service '" << name_
               << "' (pid " << pid_ << ") process group...";
-    if (killProcessGroup(uid_, pid_, signal) == -1) {
-        PLOG(ERROR) << "killProcessGroup(" << uid_ << ", " << pid_ << ", " << signal << ") failed";
+    int r;
+    if (signal == SIGTERM) {
+        r = killProcessGroupOnce(uid_, pid_, signal);
+    } else {
+        r = killProcessGroup(uid_, pid_, signal);
+    }
+    if (r == -1) {
+        LOG(ERROR) << "killProcessGroup(" << uid_ << ", " << pid_ << ", " << signal << ") failed";
     }
     if (kill(-pid_, signal) == -1) {
         PLOG(ERROR) << "kill(" << pid_ << ", " << signal << ") failed";
@@ -242,7 +267,7 @@
     }
 }
 
-bool Service::Reap() {
+void Service::Reap() {
     if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
         KillProcessGroup(SIGKILL);
     }
@@ -251,9 +276,8 @@
     std::for_each(descriptors_.begin(), descriptors_.end(),
                   std::bind(&DescriptorInfo::Clean, std::placeholders::_1));
 
-    if (flags_ & SVC_EXEC) {
-        LOG(INFO) << "SVC_EXEC pid " << pid_ << " finished...";
-        return true;
+    if (flags_ & SVC_TEMPORARY) {
+        return;
     }
 
     pid_ = 0;
@@ -268,7 +292,7 @@
     // Disabled and reset processes do not get restarted automatically.
     if (flags_ & (SVC_DISABLED | SVC_RESET))  {
         NotifyStateChange("stopped");
-        return false;
+        return;
     }
 
     // If we crash > 4 times in 4 minutes, reboot into recovery.
@@ -292,12 +316,12 @@
     onrestart_.ExecuteAllCommands();
 
     NotifyStateChange("restarting");
-    return false;
+    return;
 }
 
 void Service::DumpState() const {
     LOG(INFO) << "service " << name_;
-    LOG(INFO) << "  class '" << classname_ << "'";
+    LOG(INFO) << "  class '" << android::base::Join(classnames_, " ") << "'";
     LOG(INFO) << "  exec "<< android::base::Join(args_, " ");
     std::for_each(descriptors_.begin(), descriptors_.end(),
                   [] (const auto& info) { LOG(INFO) << *info; });
@@ -334,7 +358,7 @@
 }
 
 bool Service::ParseClass(const std::vector<std::string>& args, std::string* err) {
-    classname_ = args[1];
+    classnames_ = std::set<std::string>(args.begin() + 1, args.end());
     return true;
 }
 
@@ -414,7 +438,8 @@
 
 bool Service::ParseOnrestart(const std::vector<std::string>& args, std::string* err) {
     std::vector<std::string> str_args(args.begin() + 1, args.end());
-    onrestart_.AddCommand(str_args, "", 0, err);
+    int line = onrestart_.NumCommands() + 1;
+    onrestart_.AddCommand(str_args, line, err);
     return true;
 }
 
@@ -507,19 +532,20 @@
 }
 
 class Service::OptionParserMap : public KeywordMap<OptionParser> {
-public:
-    OptionParserMap() {
-    }
-private:
-    Map& map() const override;
+  public:
+    OptionParserMap() {}
+
+  private:
+    const Map& map() const override;
 };
 
-Service::OptionParserMap::Map& Service::OptionParserMap::map() const {
+const Service::OptionParserMap::Map& Service::OptionParserMap::map() const {
     constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
+    // clang-format off
     static const Map option_parsers = {
         {"capabilities",
                         {1,     kMax, &Service::ParseCapabilities}},
-        {"class",       {1,     1,    &Service::ParseClass}},
+        {"class",       {1,     kMax, &Service::ParseClass}},
         {"console",     {0,     1,    &Service::ParseConsole}},
         {"critical",    {0,     0,    &Service::ParseCritical}},
         {"disabled",    {0,     0,    &Service::ParseDisabled}},
@@ -539,17 +565,13 @@
         {"user",        {1,     1,    &Service::ParseUser}},
         {"writepid",    {1,     kMax, &Service::ParseWritepid}},
     };
+    // clang-format on
     return option_parsers;
 }
 
 bool Service::ParseLine(const std::vector<std::string>& args, std::string* err) {
-    if (args.empty()) {
-        *err = "option needed, but not provided";
-        return false;
-    }
-
     static const OptionParserMap parser_map;
-    auto parser = parser_map.FindFunction(args[0], args.size() - 1, err);
+    auto parser = parser_map.FindFunction(args, err);
 
     if (!parser) {
         return false;
@@ -558,6 +580,18 @@
     return (this->*parser)(args, err);
 }
 
+bool Service::ExecStart(std::unique_ptr<Timer>* exec_waiter) {
+    flags_ |= SVC_EXEC | SVC_ONESHOT;
+
+    exec_waiter->reset(new Timer);
+
+    if (!Start()) {
+        exec_waiter->reset();
+        return false;
+    }
+    return true;
+}
+
 bool Service::Start() {
     // Starting a service removes it from the disabled or reset state and
     // immediately takes it out of the restarting state if it was in there.
@@ -598,7 +632,6 @@
     if (!seclabel_.empty()) {
         scon = seclabel_;
     } else {
-        LOG(INFO) << "computing context for service '" << name_ << "'";
         scon = ComputeContextFromExecutable(name_, args_[0]);
         if (scon == "") {
             return false;
@@ -630,6 +663,28 @@
         std::for_each(descriptors_.begin(), descriptors_.end(),
                       std::bind(&DescriptorInfo::CreateAndPublish, std::placeholders::_1, scon));
 
+        // See if there were "writepid" instructions to write to files under /dev/cpuset/.
+        auto cpuset_predicate = [](const std::string& path) {
+            return android::base::StartsWith(path, "/dev/cpuset/");
+        };
+        auto iter = std::find_if(writepid_files_.begin(), writepid_files_.end(), cpuset_predicate);
+        if (iter == writepid_files_.end()) {
+            // There were no "writepid" instructions for cpusets, check if the system default
+            // cpuset is specified to be used for the process.
+            std::string default_cpuset = android::base::GetProperty("ro.cpuset.default", "");
+            if (!default_cpuset.empty()) {
+                // Make sure the cpuset name starts and ends with '/'.
+                // A single '/' means the 'root' cpuset.
+                if (default_cpuset.front() != '/') {
+                    default_cpuset.insert(0, 1, '/');
+                }
+                if (default_cpuset.back() != '/') {
+                    default_cpuset.push_back('/');
+                }
+                writepid_files_.push_back(
+                    StringPrintf("/dev/cpuset%stasks", default_cpuset.c_str()));
+            }
+        }
         std::string pid_str = StringPrintf("%d", getpid());
         for (const auto& file : writepid_files_) {
             if (!WriteStringToFile(pid_str, file)) {
@@ -814,14 +869,38 @@
 }
 
 void ServiceManager::AddService(std::unique_ptr<Service> service) {
-    Service* old_service = FindServiceByName(service->name());
-    if (old_service) {
-        LOG(ERROR) << "ignored duplicate definition of service '" << service->name() << "'";
-        return;
-    }
     services_.emplace_back(std::move(service));
 }
 
+bool ServiceManager::Exec(const std::vector<std::string>& args) {
+    Service* svc = MakeExecOneshotService(args);
+    if (!svc) {
+        LOG(ERROR) << "Could not create exec service";
+        return false;
+    }
+    if (!svc->ExecStart(&exec_waiter_)) {
+        LOG(ERROR) << "Could not start exec service";
+        ServiceManager::GetInstance().RemoveService(*svc);
+        return false;
+    }
+    return true;
+}
+
+bool ServiceManager::ExecStart(const std::string& name) {
+    Service* svc = FindServiceByName(name);
+    if (!svc) {
+        LOG(ERROR) << "ExecStart(" << name << "): Service not found";
+        return false;
+    }
+    if (!svc->ExecStart(&exec_waiter_)) {
+        LOG(ERROR) << "ExecStart(" << name << "): Could not start Service";
+        return false;
+    }
+    return true;
+}
+
+bool ServiceManager::IsWaitingForExec() const { return exec_waiter_ != nullptr; }
+
 Service* ServiceManager::MakeExecOneshotService(const std::vector<std::string>& args) {
     // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
     // SECLABEL can be a - to denote default
@@ -844,8 +923,10 @@
     std::vector<std::string> str_args(args.begin() + command_arg, args.end());
 
     exec_count_++;
-    std::string name = StringPrintf("exec %d (%s)", exec_count_, str_args[0].c_str());
-    unsigned flags = SVC_EXEC | SVC_ONESHOT;
+    std::string name =
+        "exec " + std::to_string(exec_count_) + " (" + android::base::Join(str_args, " ") + ")";
+
+    unsigned flags = SVC_EXEC | SVC_ONESHOT | SVC_TEMPORARY;
     CapSet no_capabilities;
     unsigned namespace_flags = 0;
 
@@ -867,15 +948,10 @@
         }
     }
 
-    std::unique_ptr<Service> svc_p(new Service(name, "default", flags, uid, gid, supp_gids,
-                                               no_capabilities, namespace_flags, seclabel,
-                                               str_args));
-    if (!svc_p) {
-        LOG(ERROR) << "Couldn't allocate service for exec of '" << str_args[0] << "'";
-        return nullptr;
-    }
+    auto svc_p = std::make_unique<Service>(name, flags, uid, gid, supp_gids, no_capabilities,
+                                           namespace_flags, seclabel, str_args);
     Service* svc = svc_p.get();
-    services_.push_back(std::move(svc_p));
+    services_.emplace_back(std::move(svc_p));
 
     return svc;
 }
@@ -923,7 +999,7 @@
 void ServiceManager::ForEachServiceInClass(const std::string& classname,
                                            void (*func)(Service* svc)) const {
     for (const auto& s : services_) {
-        if (classname == s->classname()) {
+        if (s->classnames().find(classname) != s->classnames().end()) {
             func(s.get());
         }
     }
@@ -969,29 +1045,38 @@
     Service* svc = FindServiceByPid(pid);
 
     std::string name;
+    std::string wait_string;
     if (svc) {
         name = android::base::StringPrintf("Service '%s' (pid %d)",
                                            svc->name().c_str(), pid);
+        if (svc->flags() & SVC_EXEC) {
+            wait_string =
+                android::base::StringPrintf(" waiting took %f seconds", exec_waiter_->duration_s());
+        }
     } else {
         name = android::base::StringPrintf("Untracked pid %d", pid);
     }
 
     if (WIFEXITED(status)) {
-        LOG(INFO) << name << " exited with status " << WEXITSTATUS(status);
+        LOG(INFO) << name << " exited with status " << WEXITSTATUS(status) << wait_string;
     } else if (WIFSIGNALED(status)) {
-        LOG(INFO) << name << " killed by signal " << WTERMSIG(status);
+        LOG(INFO) << name << " killed by signal " << WTERMSIG(status) << wait_string;
     } else if (WIFSTOPPED(status)) {
-        LOG(INFO) << name << " stopped by signal " << WSTOPSIG(status);
+        LOG(INFO) << name << " stopped by signal " << WSTOPSIG(status) << wait_string;
     } else {
-        LOG(INFO) << name << " state changed";
+        LOG(INFO) << name << " state changed" << wait_string;
     }
 
     if (!svc) {
         return true;
     }
 
-    if (svc->Reap()) {
-        stop_waiting_for_exec();
+    svc->Reap();
+
+    if (svc->flags() & SVC_EXEC) {
+        exec_waiter_.reset();
+    }
+    if (svc->flags() & SVC_TEMPORARY) {
         RemoveService(*svc);
     }
 
@@ -1003,8 +1088,8 @@
     }
 }
 
-bool ServiceParser::ParseSection(const std::vector<std::string>& args,
-                                 std::string* err) {
+bool ServiceParser::ParseSection(std::vector<std::string>&& args, const std::string& filename,
+                                 int line, std::string* err) {
     if (args.size() < 3) {
         *err = "services must have a name and a program";
         return false;
@@ -1016,20 +1101,24 @@
         return false;
     }
 
+    Service* old_service = service_manager_->FindServiceByName(name);
+    if (old_service) {
+        *err = "ignored duplicate definition of service '" + name + "'";
+        return false;
+    }
+
     std::vector<std::string> str_args(args.begin() + 2, args.end());
-    service_ = std::make_unique<Service>(name, "default", str_args);
+    service_ = std::make_unique<Service>(name, str_args);
     return true;
 }
 
-bool ServiceParser::ParseLineSection(const std::vector<std::string>& args,
-                                     const std::string& filename, int line,
-                                     std::string* err) const {
-    return service_ ? service_->ParseLine(args, err) : false;
+bool ServiceParser::ParseLineSection(std::vector<std::string>&& args, int line, std::string* err) {
+    return service_ ? service_->ParseLine(std::move(args), err) : false;
 }
 
 void ServiceParser::EndSection() {
     if (service_) {
-        ServiceManager::GetInstance().AddService(std::move(service_));
+        service_manager_->AddService(std::move(service_));
     }
 }
 
diff --git a/init/service.h b/init/service.h
index 013e65f..426577f 100644
--- a/init/service.h
+++ b/init/service.h
@@ -19,12 +19,14 @@
 
 #include <sys/types.h>
 
-#include <cutils/iosched_policy.h>
-
 #include <memory>
+#include <set>
 #include <string>
 #include <vector>
 
+#include <android-base/chrono_utils.h>
+#include <cutils/iosched_policy.h>
+
 #include "action.h"
 #include "capabilities.h"
 #include "descriptors.h"
@@ -32,18 +34,24 @@
 #include "keyword_map.h"
 #include "util.h"
 
-#define SVC_DISABLED       0x001  // do not autostart with class
-#define SVC_ONESHOT        0x002  // do not restart on exit
-#define SVC_RUNNING        0x004  // currently active
-#define SVC_RESTARTING     0x008  // waiting to restart
-#define SVC_CONSOLE        0x010  // requires console
-#define SVC_CRITICAL       0x020  // will reboot into recovery if keeps crashing
-#define SVC_RESET          0x040  // Use when stopping a process,
+#define SVC_DISABLED 0x001        // do not autostart with class
+#define SVC_ONESHOT 0x002         // do not restart on exit
+#define SVC_RUNNING 0x004         // currently active
+#define SVC_RESTARTING 0x008      // waiting to restart
+#define SVC_CONSOLE 0x010         // requires console
+#define SVC_CRITICAL 0x020        // will reboot into recovery if keeps crashing
+#define SVC_RESET 0x040           // Use when stopping a process,
                                   // but not disabling so it can be restarted with its class.
-#define SVC_RC_DISABLED    0x080  // Remember if the disabled flag was set in the rc script.
-#define SVC_RESTART        0x100  // Use to safely restart (stop, wait, start) a service.
+#define SVC_RC_DISABLED 0x080     // Remember if the disabled flag was set in the rc script.
+#define SVC_RESTART 0x100         // Use to safely restart (stop, wait, start) a service.
 #define SVC_DISABLED_START 0x200  // A start was requested but it was disabled at the time.
-#define SVC_EXEC           0x400  // This synthetic service corresponds to an 'exec'.
+#define SVC_EXEC 0x400  // This service was started by either 'exec' or 'exec_start' and stops
+                        // init from processing more commands until it completes
+
+#define SVC_SHUTDOWN_CRITICAL 0x800  // This service is critical for shutdown and
+                                     // should not be killed during shutdown
+#define SVC_TEMPORARY 0x1000  // This service was started by 'exec' and should be removed from the
+                              // service list once it is reaped.
 
 #define NR_SVC_SUPP_GIDS 12    // twelve supplementary groups
 
@@ -58,17 +66,17 @@
 };
 
 class Service {
-public:
-    Service(const std::string& name, const std::string& classname,
-            const std::vector<std::string>& args);
+  public:
+    Service(const std::string& name, const std::vector<std::string>& args);
 
-    Service(const std::string& name, const std::string& classname,
-            unsigned flags, uid_t uid, gid_t gid,
+    Service(const std::string& name, unsigned flags, uid_t uid, gid_t gid,
             const std::vector<gid_t>& supp_gids, const CapSet& capabilities,
             unsigned namespace_flags, const std::string& seclabel,
             const std::vector<std::string>& args);
 
+    bool IsRunning() { return (flags_ & SVC_RUNNING) != 0; }
     bool ParseLine(const std::vector<std::string>& args, std::string* err);
+    bool ExecStart(std::unique_ptr<Timer>* exec_waiter);
     bool Start();
     bool StartIfNotDisabled();
     bool Enable();
@@ -77,24 +85,31 @@
     void Terminate();
     void Restart();
     void RestartIfNeeded(time_t* process_needs_restart_at);
-    bool Reap();
+    void Reap();
     void DumpState() const;
+    void SetShutdownCritical() { flags_ |= SVC_SHUTDOWN_CRITICAL; }
+    bool IsShutdownCritical() const { return (flags_ & SVC_SHUTDOWN_CRITICAL) != 0; }
 
     const std::string& name() const { return name_; }
-    const std::string& classname() const { return classname_; }
+    const std::set<std::string>& classnames() const { return classnames_; }
     unsigned flags() const { return flags_; }
     pid_t pid() const { return pid_; }
+    int crash_count() const { return crash_count_; }
     uid_t uid() const { return uid_; }
     gid_t gid() const { return gid_; }
-    int priority() const { return priority_; }
+    unsigned namespace_flags() const { return namespace_flags_; }
     const std::vector<gid_t>& supp_gids() const { return supp_gids_; }
     const std::string& seclabel() const { return seclabel_; }
     const std::vector<int>& keycodes() const { return keycodes_; }
     int keychord_id() const { return keychord_id_; }
     void set_keychord_id(int keychord_id) { keychord_id_ = keychord_id; }
+    IoSchedClass ioprio_class() const { return ioprio_class_; }
+    int ioprio_pri() const { return ioprio_pri_; }
+    int priority() const { return priority_; }
+    int oom_score_adjust() const { return oom_score_adjust_; }
     const std::vector<std::string>& args() const { return args_; }
 
-private:
+  private:
     using OptionParser = bool (Service::*) (const std::vector<std::string>& args,
                                             std::string* err);
     class OptionParserMap;
@@ -130,13 +145,13 @@
     bool AddDescriptor(const std::vector<std::string>& args, std::string* err);
 
     std::string name_;
-    std::string classname_;
+    std::set<std::string> classnames_;
     std::string console_;
 
     unsigned flags_;
     pid_t pid_;
-    boot_clock::time_point time_started_; // time of last start
-    boot_clock::time_point time_crashed_; // first crash within inspection window
+    android::base::boot_clock::time_point time_started_;  // time of last start
+    android::base::boot_clock::time_point time_crashed_;  // first crash within inspection window
     int crash_count_;                     // number of times crashed within window
 
     uid_t uid_;
@@ -171,8 +186,14 @@
 public:
     static ServiceManager& GetInstance();
 
+    // Exposed for testing
+    ServiceManager();
+
     void AddService(std::unique_ptr<Service> service);
     Service* MakeExecOneshotService(const std::vector<std::string>& args);
+    bool Exec(const std::vector<std::string>& args);
+    bool ExecStart(const std::string& name);
+    bool IsWaitingForExec() const;
     Service* FindServiceByName(const std::string& name) const;
     Service* FindServiceByPid(pid_t pid) const;
     Service* FindServiceByKeychord(int keychord_id) const;
@@ -186,31 +207,29 @@
     void DumpState() const;
 
 private:
-    ServiceManager();
-
     // Cleans up a child process that exited.
     // Returns true iff a children was cleaned up.
     bool ReapOneProcess();
 
     static int exec_count_; // Every service needs a unique name.
+    std::unique_ptr<Timer> exec_waiter_;
+
     std::vector<std::unique_ptr<Service>> services_;
 };
 
 class ServiceParser : public SectionParser {
-public:
-    ServiceParser() : service_(nullptr) {
-    }
-    bool ParseSection(const std::vector<std::string>& args,
+  public:
+    ServiceParser(ServiceManager* service_manager)
+        : service_manager_(service_manager), service_(nullptr) {}
+    bool ParseSection(std::vector<std::string>&& args, const std::string& filename, int line,
                       std::string* err) override;
-    bool ParseLineSection(const std::vector<std::string>& args,
-                          const std::string& filename, int line,
-                          std::string* err) const override;
+    bool ParseLineSection(std::vector<std::string>&& args, int line, std::string* err) override;
     void EndSection() override;
-    void EndFile(const std::string&) override {
-    }
-private:
+
+  private:
     bool IsValidName(const std::string& name) const;
 
+    ServiceManager* service_manager_;
     std::unique_ptr<Service> service_;
 };
 
diff --git a/init/service_test.cpp b/init/service_test.cpp
new file mode 100644
index 0000000..4493f25
--- /dev/null
+++ b/init/service_test.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 "service.h"
+
+#include <algorithm>
+#include <memory>
+#include <type_traits>
+#include <vector>
+
+#include <gtest/gtest.h>
+
+TEST(service, pod_initialized) {
+    constexpr auto memory_size = sizeof(Service);
+    alignas(alignof(Service)) char old_memory[memory_size];
+
+    for (std::size_t i = 0; i < memory_size; ++i) {
+        old_memory[i] = 0xFF;
+    }
+
+    std::vector<std::string> dummy_args{"/bin/test"};
+    Service* service_in_old_memory = new (old_memory) Service("test_old_memory", dummy_args);
+
+    EXPECT_EQ(0U, service_in_old_memory->flags());
+    EXPECT_EQ(0, service_in_old_memory->pid());
+    EXPECT_EQ(0, service_in_old_memory->crash_count());
+    EXPECT_EQ(0U, service_in_old_memory->uid());
+    EXPECT_EQ(0U, service_in_old_memory->gid());
+    EXPECT_EQ(0U, service_in_old_memory->namespace_flags());
+    EXPECT_EQ(0, service_in_old_memory->keychord_id());
+    EXPECT_EQ(IoSchedClass_NONE, service_in_old_memory->ioprio_class());
+    EXPECT_EQ(0, service_in_old_memory->ioprio_pri());
+    EXPECT_EQ(0, service_in_old_memory->priority());
+    EXPECT_EQ(-1000, service_in_old_memory->oom_score_adjust());
+
+    for (std::size_t i = 0; i < memory_size; ++i) {
+        old_memory[i] = 0xFF;
+    }
+
+    Service* service_in_old_memory2 = new (old_memory)
+        Service("test_old_memory", 0U, 0U, 0U, std::vector<gid_t>(), CapSet(), 0U, "", dummy_args);
+
+    EXPECT_EQ(0U, service_in_old_memory2->flags());
+    EXPECT_EQ(0, service_in_old_memory2->pid());
+    EXPECT_EQ(0, service_in_old_memory2->crash_count());
+    EXPECT_EQ(0U, service_in_old_memory2->uid());
+    EXPECT_EQ(0U, service_in_old_memory2->gid());
+    EXPECT_EQ(0U, service_in_old_memory2->namespace_flags());
+    EXPECT_EQ(0, service_in_old_memory2->keychord_id());
+    EXPECT_EQ(IoSchedClass_NONE, service_in_old_memory2->ioprio_class());
+    EXPECT_EQ(0, service_in_old_memory2->ioprio_pri());
+    EXPECT_EQ(0, service_in_old_memory2->priority());
+    EXPECT_EQ(-1000, service_in_old_memory2->oom_score_adjust());
+}
diff --git a/init/signal_handler.cpp b/init/signal_handler.cpp
index 1041b82..4d56d84 100644
--- a/init/signal_handler.cpp
+++ b/init/signal_handler.cpp
@@ -14,24 +14,17 @@
  * limitations under the License.
  */
 
-#include <errno.h>
-#include <fcntl.h>
 #include <signal.h>
-#include <stdio.h>
+#include <string.h>
 #include <sys/socket.h>
 #include <sys/types.h>
-#include <sys/wait.h>
 #include <unistd.h>
 
+#include <android-base/logging.h>
 #include <android-base/stringprintf.h>
-#include <cutils/list.h>
-#include <cutils/sockets.h>
 
-#include "action.h"
 #include "init.h"
-#include "log.h"
 #include "service.h"
-#include "util.h"
 
 static int signal_write_fd = -1;
 static int signal_read_fd = -1;
diff --git a/init/ueventd.cpp b/init/ueventd.cpp
index 915afbd..8c0c574 100644
--- a/init/ueventd.cpp
+++ b/init/ueventd.cpp
@@ -14,27 +14,24 @@
  * limitations under the License.
  */
 
+#include "ueventd.h"
+
 #include <ctype.h>
 #include <fcntl.h>
-#include <grp.h>
 #include <poll.h>
-#include <pwd.h>
 #include <signal.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 
-#include <sys/types.h>
-
+#include <android-base/logging.h>
+#include <android-base/properties.h>
 #include <android-base/stringprintf.h>
 #include <selinux/selinux.h>
 
-#include "ueventd.h"
+#include "devices.h"
 #include "log.h"
 #include "util.h"
-#include "devices.h"
-#include "ueventd_parser.h"
-#include "property_service.h"
 
 int ueventd_main(int argc, char **argv)
 {
@@ -60,9 +57,14 @@
     cb.func_log = selinux_klog_callback;
     selinux_set_callback(SELINUX_CB_LOG, cb);
 
-    ueventd_parse_config_file("/ueventd.rc");
-    ueventd_parse_config_file("/vendor/ueventd.rc");
-    ueventd_parse_config_file("/odm/ueventd.rc");
+    Parser& parser = Parser::GetInstance();
+    parser.AddSectionParser("subsystem", std::make_unique<SubsystemParser>());
+    using namespace std::placeholders;
+    parser.AddSingleLineParser("/sys/", std::bind(ParsePermissionsLine, _1, _2, true));
+    parser.AddSingleLineParser("/dev/", std::bind(ParsePermissionsLine, _1, _2, false));
+    parser.ParseConfig("/ueventd.rc");
+    parser.ParseConfig("/vendor/ueventd.rc");
+    parser.ParseConfig("/odm/ueventd.rc");
 
     /*
      * keep the current product name base configuration so
@@ -71,8 +73,8 @@
      * TODO: cleanup platform ueventd.rc to remove vendor specific
      * device node entries (b/34968103)
      */
-    std::string hardware = property_get("ro.hardware");
-    ueventd_parse_config_file(android::base::StringPrintf("/ueventd.%s.rc", hardware.c_str()).c_str());
+    std::string hardware = android::base::GetProperty("ro.hardware", "");
+    parser.ParseConfig("/ueventd." + hardware + ".rc");
 
     device_init();
 
@@ -93,74 +95,3 @@
 
     return 0;
 }
-
-void set_device_permission(int nargs, char **args)
-{
-    char *name;
-    char *attr = 0;
-    mode_t perm;
-    uid_t uid;
-    gid_t gid;
-    int prefix = 0;
-    int wildcard = 0;
-    char *endptr;
-
-    if (nargs == 0)
-        return;
-
-    if (args[0][0] == '#')
-        return;
-
-    name = args[0];
-
-    if (!strncmp(name,"/sys/", 5) && (nargs == 5)) {
-        LOG(INFO) << "/sys/ rule " << args[0] << " " << args[1];
-        attr = args[1];
-        args++;
-        nargs--;
-    }
-
-    if (nargs != 4) {
-        LOG(ERROR) << "invalid line ueventd.rc line for '" << args[0] << "'";
-        return;
-    }
-
-    int len = strlen(name);
-    char *wildcard_chr = strchr(name, '*');
-    if ((name[len - 1] == '*') && (wildcard_chr == (name + len - 1))) {
-        prefix = 1;
-        name[len - 1] = '\0';
-    } else if (wildcard_chr) {
-        wildcard = 1;
-    }
-
-    perm = strtol(args[1], &endptr, 8);
-    if (!endptr || *endptr != '\0') {
-        LOG(ERROR) << "invalid mode '" << args[1] << "'";
-        return;
-    }
-
-    struct passwd* pwd = getpwnam(args[2]);
-    if (!pwd) {
-        LOG(ERROR) << "invalid uid '" << args[2] << "'";
-        return;
-    }
-    uid = pwd->pw_uid;
-
-    struct group* grp = getgrnam(args[3]);
-    if (!grp) {
-        LOG(ERROR) << "invalid gid '" << args[3] << "'";
-        return;
-    }
-    gid = grp->gr_gid;
-
-    if (add_dev_perms(name, attr, perm, uid, gid, prefix, wildcard) != 0) {
-        PLOG(ERROR) << "add_dev_perms(name=" << name <<
-                       ", attr=" << attr <<
-                       ", perm=" << std::oct << perm << std::dec <<
-                       ", uid=" << uid << ", gid=" << gid <<
-                       ", prefix=" << prefix << ", wildcard=" << wildcard <<
-                       ")";
-        return;
-    }
-}
diff --git a/init/ueventd.h b/init/ueventd.h
index d12d7fe..1f424d3 100644
--- a/init/ueventd.h
+++ b/init/ueventd.h
@@ -17,23 +17,6 @@
 #ifndef _INIT_UEVENTD_H_
 #define _INIT_UEVENTD_H_
 
-#include <cutils/list.h>
-#include <sys/types.h>
-
-enum devname_src_t {
-    DEVNAME_UNKNOWN = 0,
-    DEVNAME_UEVENT_DEVNAME,
-    DEVNAME_UEVENT_DEVPATH,
-};
-
-struct ueventd_subsystem {
-    struct listnode slist;
-
-    const char *name;
-    const char *dirname;
-    devname_src_t devname_src;
-};
-
-int ueventd_main(int argc, char **argv);
+int ueventd_main(int argc, char** argv);
 
 #endif
diff --git a/init/ueventd_keywords.h b/init/ueventd_keywords.h
deleted file mode 100644
index 88e8f01..0000000
--- a/init/ueventd_keywords.h
+++ /dev/null
@@ -1,15 +0,0 @@
-#ifndef KEYWORD
-#define __MAKE_KEYWORD_ENUM__
-#define KEYWORD(symbol, flags, nargs) K_##symbol,
-enum {
-    K_UNKNOWN,
-#endif
-    KEYWORD(subsystem,      SECTION,    1)
-    KEYWORD(devname,        OPTION,     1)
-    KEYWORD(dirname,        OPTION,     1)
-#ifdef __MAKE_KEYWORD_ENUM__
-    KEYWORD_COUNT,
-};
-#undef __MAKE_KEYWORD_ENUM__
-#undef KEYWORD
-#endif
diff --git a/init/ueventd_parser.cpp b/init/ueventd_parser.cpp
deleted file mode 100644
index baff58c..0000000
--- a/init/ueventd_parser.cpp
+++ /dev/null
@@ -1,241 +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 <ctype.h>
-#include <errno.h>
-#include <stdio.h>
-#include <unistd.h>
-#include <stdarg.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "ueventd.h"
-#include "ueventd_parser.h"
-#include "parser.h"
-#include "log.h"
-#include "util.h"
-
-static list_declare(subsystem_list);
-
-static void parse_line_device(struct parse_state *state, int nargs, char **args);
-
-#define SECTION 0x01
-#define OPTION  0x02
-
-#include "ueventd_keywords.h"
-
-#define KEYWORD(symbol, flags, nargs) \
-    [ K_##symbol ] = { #symbol, (nargs) + 1, flags, },
-
-static struct {
-    const char *name;
-    unsigned char nargs;
-    unsigned char flags;
-} keyword_info[KEYWORD_COUNT] = {
-    [ K_UNKNOWN ] = { "unknown", 0, 0 },
-#include "ueventd_keywords.h"
-};
-#undef KEYWORD
-
-#define kw_is(kw, type) (keyword_info[kw].flags & (type))
-#define kw_nargs(kw) (keyword_info[kw].nargs)
-
-static int lookup_keyword(const char *s)
-{
-    switch (*s++) {
-    case 'd':
-        if (!strcmp(s, "evname")) return K_devname;
-        if (!strcmp(s, "irname")) return K_dirname;
-        break;
-    case 's':
-        if (!strcmp(s, "ubsystem")) return K_subsystem;
-        break;
-    }
-    return K_UNKNOWN;
-}
-
-static void parse_line_no_op(struct parse_state*, int, char**) {
-}
-
-static int valid_name(const char *name)
-{
-    while (*name) {
-        if (!isalnum(*name) && (*name != '_') && (*name != '-')) {
-            return 0;
-        }
-        name++;
-    }
-    return 1;
-}
-
-struct ueventd_subsystem *ueventd_subsystem_find_by_name(const char *name)
-{
-    struct listnode *node;
-    struct ueventd_subsystem *s;
-
-    list_for_each(node, &subsystem_list) {
-        s = node_to_item(node, struct ueventd_subsystem, slist);
-        if (!strcmp(s->name, name)) {
-            return s;
-        }
-    }
-    return 0;
-}
-
-static void *parse_subsystem(parse_state* state, int /*nargs*/, char** args) {
-    if (!valid_name(args[1])) {
-        parse_error(state, "invalid subsystem name '%s'\n", args[1]);
-        return 0;
-    }
-
-    ueventd_subsystem* s = ueventd_subsystem_find_by_name(args[1]);
-    if (s) {
-        parse_error(state, "ignored duplicate definition of subsystem '%s'\n",
-                args[1]);
-        return 0;
-    }
-
-    s = (ueventd_subsystem*) calloc(1, sizeof(*s));
-    if (!s) {
-        parse_error(state, "out of memory\n");
-        return 0;
-    }
-    s->name = args[1];
-    s->dirname = "/dev";
-    list_add_tail(&subsystem_list, &s->slist);
-    return s;
-}
-
-static void parse_line_subsystem(struct parse_state *state, int nargs,
-        char **args)
-{
-    struct ueventd_subsystem *s = (ueventd_subsystem*) state->context;
-    int kw;
-
-    if (nargs == 0) {
-        return;
-    }
-
-    kw = lookup_keyword(args[0]);
-    switch (kw) {
-    case K_devname:
-        if (!strcmp(args[1], "uevent_devname"))
-            s->devname_src = DEVNAME_UEVENT_DEVNAME;
-        else if (!strcmp(args[1], "uevent_devpath"))
-            s->devname_src = DEVNAME_UEVENT_DEVPATH;
-        else
-            parse_error(state, "invalid devname '%s'\n", args[1]);
-        break;
-
-    case K_dirname:
-        if (args[1][0] == '/')
-            s->dirname = args[1];
-        else
-            parse_error(state, "dirname '%s' does not start with '/'\n",
-                    args[1]);
-        break;
-
-    default:
-        parse_error(state, "invalid option '%s'\n", args[0]);
-    }
-}
-
-static void parse_new_section(struct parse_state *state, int kw,
-                       int nargs, char **args)
-{
-    printf("[ %s %s ]\n", args[0],
-           nargs > 1 ? args[1] : "");
-
-    switch(kw) {
-    case K_subsystem:
-        state->context = parse_subsystem(state, nargs, args);
-        if (state->context) {
-            state->parse_line = parse_line_subsystem;
-            return;
-        }
-        break;
-    }
-    state->parse_line = parse_line_no_op;
-}
-
-static void parse_line(struct parse_state *state, char **args, int nargs)
-{
-    int kw = lookup_keyword(args[0]);
-    int kw_nargs = kw_nargs(kw);
-
-    if (nargs < kw_nargs) {
-        parse_error(state, "%s requires %d %s\n", args[0], kw_nargs - 1,
-            kw_nargs > 2 ? "arguments" : "argument");
-        return;
-    }
-
-    if (kw_is(kw, SECTION)) {
-        parse_new_section(state, kw, nargs, args);
-    } else if (kw_is(kw, OPTION)) {
-        state->parse_line(state, nargs, args);
-    } else {
-        parse_line_device(state, nargs, args);
-    }
-}
-
-static void parse_config(const char *fn, const std::string& data)
-{
-    char *args[UEVENTD_PARSER_MAXARGS];
-
-    int nargs = 0;
-    parse_state state;
-    state.filename = fn;
-    state.line = 1;
-    state.ptr = strdup(data.c_str());  // TODO: fix this code!
-    state.nexttoken = 0;
-    state.parse_line = parse_line_no_op;
-    for (;;) {
-        int token = next_token(&state);
-        switch (token) {
-        case T_EOF:
-            parse_line(&state, args, nargs);
-            return;
-        case T_NEWLINE:
-            if (nargs) {
-                parse_line(&state, args, nargs);
-                nargs = 0;
-            }
-            state.line++;
-            break;
-        case T_TEXT:
-            if (nargs < UEVENTD_PARSER_MAXARGS) {
-                args[nargs++] = state.text;
-            }
-            break;
-        }
-    }
-}
-
-int ueventd_parse_config_file(const char *fn)
-{
-    std::string data;
-    if (!read_file(fn, &data)) {
-        return -1;
-    }
-
-    data.push_back('\n'); // TODO: fix parse_config.
-    parse_config(fn, data);
-    return 0;
-}
-
-static void parse_line_device(parse_state*, int nargs, char** args) {
-    set_device_permission(nargs, args);
-}
diff --git a/init/ueventd_parser.h b/init/ueventd_parser.h
deleted file mode 100644
index 907cc49..0000000
--- a/init/ueventd_parser.h
+++ /dev/null
@@ -1,28 +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.
- */
-
-#ifndef _INIT_UEVENTD_PARSER_H_
-#define _INIT_UEVENTD_PARSER_H_
-
-#include "ueventd.h"
-
-#define UEVENTD_PARSER_MAXARGS 5
-
-int ueventd_parse_config_file(const char *fn);
-void set_device_permission(int nargs, char **args);
-struct ueventd_subsystem *ueventd_subsystem_find_by_name(const char *name);
-
-#endif
diff --git a/init/util.cpp b/init/util.cpp
index 888a366..a101ce5 100644
--- a/init/util.cpp
+++ b/init/util.cpp
@@ -14,42 +14,38 @@
  * limitations under the License.
  */
 
+#include "util.h"
+
 #include <ctype.h>
 #include <errno.h>
 #include <fcntl.h>
-#include <ftw.h>
 #include <pwd.h>
 #include <stdarg.h>
-#include <stdlib.h>
 #include <stdio.h>
+#include <stdlib.h>
 #include <string.h>
+#include <sys/socket.h>
+#include <sys/un.h>
 #include <time.h>
 #include <unistd.h>
 
-#include <selinux/android.h>
-#include <selinux/label.h>
-
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <sys/un.h>
-
 #include <thread>
 
 #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 <cutils/android_reboot.h>
-/* for ANDROID_SOCKET_* */
 #include <cutils/sockets.h>
+#include <selinux/android.h>
+#include <selinux/label.h>
 
 #include "init.h"
-#include "log.h"
-#include "property_service.h"
-#include "util.h"
+#include "reboot.h"
+
+using android::base::boot_clock;
 
 static unsigned int do_decode_uid(const char *s)
 {
@@ -160,10 +156,11 @@
     return -1;
 }
 
-bool read_file(const char* path, std::string* content) {
+bool read_file(const std::string& path, std::string* content) {
     content->clear();
 
-    int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY|O_NOFOLLOW|O_CLOEXEC));
+    android::base::unique_fd fd(
+        TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC)));
     if (fd == -1) {
         return false;
     }
@@ -176,17 +173,16 @@
         return false;
     }
     if ((sb.st_mode & (S_IWGRP | S_IWOTH)) != 0) {
-        PLOG(ERROR) << "skipping insecure file '" << path << "'";
+        LOG(ERROR) << "skipping insecure file '" << path << "'";
         return false;
     }
 
-    bool okay = android::base::ReadFdToString(fd, content);
-    close(fd);
-    return okay;
+    return android::base::ReadFdToString(fd, content);
 }
 
-bool write_file(const char* path, const char* content) {
-    int fd = TEMP_FAILURE_RETRY(open(path, O_WRONLY|O_CREAT|O_NOFOLLOW|O_CLOEXEC, 0600));
+bool write_file(const std::string& path, const std::string& content) {
+    android::base::unique_fd fd(TEMP_FAILURE_RETRY(
+        open(path.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0600)));
     if (fd == -1) {
         PLOG(ERROR) << "write_file: Unable to open '" << path << "'";
         return false;
@@ -195,72 +191,24 @@
     if (!success) {
         PLOG(ERROR) << "write_file: Unable to write to '" << path << "'";
     }
-    close(fd);
     return success;
 }
 
-boot_clock::time_point boot_clock::now() {
-  timespec ts;
-  clock_gettime(CLOCK_BOOTTIME, &ts);
-  return boot_clock::time_point(std::chrono::seconds(ts.tv_sec) +
-                                std::chrono::nanoseconds(ts.tv_nsec));
-}
-
-int mkdir_recursive(const char *pathname, mode_t mode)
-{
-    char buf[128];
-    const char *slash;
-    const char *p = pathname;
-    int width;
-    int ret;
-    struct stat info;
-
-    while ((slash = strchr(p, '/')) != NULL) {
-        width = slash - pathname;
-        p = slash + 1;
-        if (width < 0)
-            break;
-        if (width == 0)
-            continue;
-        if ((unsigned int)width > sizeof(buf) - 1) {
-            LOG(ERROR) << "path too long for mkdir_recursive";
-            return -1;
-        }
-        memcpy(buf, pathname, width);
-        buf[width] = 0;
-        if (stat(buf, &info) != 0) {
-            ret = make_dir(buf, mode);
-            if (ret && errno != EEXIST)
-                return ret;
+int mkdir_recursive(const std::string& path, mode_t mode) {
+    std::string::size_type slash = 0;
+    while ((slash = path.find('/', slash + 1)) != std::string::npos) {
+        auto directory = path.substr(0, slash);
+        struct stat info;
+        if (stat(directory.c_str(), &info) != 0) {
+            auto ret = make_dir(directory.c_str(), mode);
+            if (ret && errno != EEXIST) return ret;
         }
     }
-    ret = make_dir(pathname, mode);
-    if (ret && errno != EEXIST)
-        return ret;
+    auto ret = make_dir(path.c_str(), mode);
+    if (ret && errno != EEXIST) return ret;
     return 0;
 }
 
-/*
- * replaces any unacceptable characters with '_', the
- * length of the resulting string is equal to the input string
- */
-void sanitize(char *s)
-{
-    const char* accept =
-            "abcdefghijklmnopqrstuvwxyz"
-            "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
-            "0123456789"
-            "_-.";
-
-    if (!s)
-        return;
-
-    while (*s) {
-        s += strspn(s, accept);
-        if (*s) *s++ = '_';
-    }
-}
-
 int wait_for_file(const char* filename, std::chrono::nanoseconds timeout) {
     boot_clock::time_point timeout_time = boot_clock::now() + timeout;
     while (boot_clock::now() < timeout_time) {
@@ -396,7 +344,7 @@
             return false;
         }
 
-        std::string prop_val = property_get(prop_name.c_str());
+        std::string prop_val = android::base::GetProperty(prop_name, "");
         if (prop_val.empty()) {
             if (def_val.empty()) {
                 LOG(ERROR) << "property '" << prop_name << "' doesn't exist while expanding '" << src << "'";
@@ -412,21 +360,35 @@
     return true;
 }
 
-void reboot(const char* destination) {
-    android_reboot(ANDROID_RB_RESTART2, 0, destination);
-    // We're init, so android_reboot will actually have been a syscall so there's nothing
-    // to wait for. If android_reboot returns, just abort so that the kernel will reboot
-    // itself when init dies.
-    PLOG(FATAL) << "reboot failed";
-    abort();
-}
-
 void panic() {
     LOG(ERROR) << "panic: rebooting to bootloader";
-    reboot("bootloader");
+    DoReboot(ANDROID_RB_RESTART2, "reboot", "bootloader", false);
 }
 
 std::ostream& operator<<(std::ostream& os, const Timer& t) {
     os << t.duration_s() << " seconds";
     return os;
 }
+
+// Reads the content of device tree file under kAndroidDtDir directory.
+// Returns true if the read is success, false otherwise.
+bool read_android_dt_file(const std::string& sub_path, std::string* dt_content) {
+    const std::string file_name = kAndroidDtDir + sub_path;
+    if (android::base::ReadFileToString(file_name, dt_content)) {
+        if (!dt_content->empty()) {
+            dt_content->pop_back();  // Trims the trailing '\0' out.
+            return true;
+        }
+    }
+    return false;
+}
+
+bool is_android_dt_value_expected(const std::string& sub_path, const std::string& expected_content) {
+    std::string dt_content;
+    if (read_android_dt_file(sub_path, &dt_content)) {
+        if (dt_content == expected_content) {
+            return true;
+        }
+    }
+    return false;
+}
diff --git a/init/util.h b/init/util.h
index 5c38dc3..92b3a1d 100644
--- a/init/util.h
+++ b/init/util.h
@@ -25,50 +25,44 @@
 #include <ostream>
 #include <string>
 
+#include <android-base/chrono_utils.h>
+
 #define COLDBOOT_DONE "/dev/.coldboot_done"
 
+const std::string kAndroidDtDir("/proc/device-tree/firmware/android/");
+
+using android::base::boot_clock;
 using namespace std::chrono_literals;
 
 int create_socket(const char *name, int type, mode_t perm,
                   uid_t uid, gid_t gid, const char *socketcon);
 
-bool read_file(const char* path, std::string* content);
-bool write_file(const char* path, const char* content);
-
-// A std::chrono clock based on CLOCK_BOOTTIME.
-class boot_clock {
- public:
-  typedef std::chrono::nanoseconds duration;
-  typedef std::chrono::time_point<boot_clock, duration> time_point;
-  static constexpr bool is_steady = true;
-
-  static time_point now();
-};
+bool read_file(const std::string& path, std::string* content);
+bool write_file(const std::string& path, const std::string& content);
 
 class Timer {
- public:
-  Timer() : start_(boot_clock::now()) {
-  }
+  public:
+    Timer() : start_(boot_clock::now()) {}
 
-  double duration_s() const {
-    typedef std::chrono::duration<double> double_duration;
-    return std::chrono::duration_cast<double_duration>(boot_clock::now() - start_).count();
-  }
+    double duration_s() const {
+        typedef std::chrono::duration<double> double_duration;
+        return std::chrono::duration_cast<double_duration>(boot_clock::now() - start_).count();
+    }
 
-  int64_t duration_ms() const {
-    return std::chrono::duration_cast<std::chrono::milliseconds>(boot_clock::now() - start_).count();
-  }
+    int64_t duration_ms() const {
+        return std::chrono::duration_cast<std::chrono::milliseconds>(boot_clock::now() - start_)
+            .count();
+    }
 
- private:
-  boot_clock::time_point start_;
+  private:
+    android::base::boot_clock::time_point start_;
 };
 
 std::ostream& operator<<(std::ostream& os, const Timer& t);
 
 unsigned int decode_uid(const char *s);
 
-int mkdir_recursive(const char *pathname, mode_t mode);
-void sanitize(char *p);
+int mkdir_recursive(const std::string& pathname, mode_t mode);
 int wait_for_file(const char *filename, std::chrono::nanoseconds timeout);
 void import_kernel_cmdline(bool in_qemu,
                            const std::function<void(const std::string&, const std::string&, bool)>&);
@@ -78,7 +72,10 @@
 bool is_dir(const char* pathname);
 bool expand_props(const std::string& src, std::string* dst);
 
-void reboot(const char* destination) __attribute__((__noreturn__));
 void panic() __attribute__((__noreturn__));
 
+// Reads or compares the content of device tree file under kAndroidDtDir directory.
+bool read_android_dt_file(const std::string& sub_path, std::string* dt_content);
+bool is_android_dt_value_expected(const std::string& sub_path, const std::string& expected_content);
+
 #endif
diff --git a/init/util_test.cpp b/init/util_test.cpp
index 24c75c4..b8b409a 100644
--- a/init/util_test.cpp
+++ b/init/util_test.cpp
@@ -17,7 +17,11 @@
 #include "util.h"
 
 #include <errno.h>
+#include <fcntl.h>
+#include <sys/stat.h>
 
+#include <android-base/stringprintf.h>
+#include <android-base/test_utils.h>
 #include <gtest/gtest.h>
 
 TEST(util, read_file_ENOENT) {
@@ -28,6 +32,35 @@
   EXPECT_EQ("", s); // s was cleared.
 }
 
+TEST(util, read_file_group_writeable) {
+    std::string s("hello");
+    TemporaryFile tf;
+    ASSERT_TRUE(tf.fd != -1);
+    EXPECT_TRUE(write_file(tf.path, s)) << strerror(errno);
+    EXPECT_NE(-1, fchmodat(AT_FDCWD, tf.path, 0620, AT_SYMLINK_NOFOLLOW)) << strerror(errno);
+    EXPECT_FALSE(read_file(tf.path, &s)) << strerror(errno);
+    EXPECT_EQ("", s);  // s was cleared.
+}
+
+TEST(util, read_file_world_writeable) {
+    std::string s("hello");
+    TemporaryFile tf;
+    ASSERT_TRUE(tf.fd != -1);
+    EXPECT_TRUE(write_file(tf.path, s.c_str())) << strerror(errno);
+    EXPECT_NE(-1, fchmodat(AT_FDCWD, tf.path, 0602, AT_SYMLINK_NOFOLLOW)) << strerror(errno);
+    EXPECT_FALSE(read_file(tf.path, &s)) << strerror(errno);
+    EXPECT_EQ("", s);  // s was cleared.
+}
+
+TEST(util, read_file_symbolic_link) {
+    std::string s("hello");
+    errno = 0;
+    // lrwxrwxrwx 1 root root 13 1970-01-01 00:00 charger -> /sbin/healthd
+    EXPECT_FALSE(read_file("/charger", &s));
+    EXPECT_EQ(ELOOP, errno);
+    EXPECT_EQ("", s);  // s was cleared.
+}
+
 TEST(util, read_file_success) {
   std::string s("hello");
   EXPECT_TRUE(read_file("/proc/version", &s));
@@ -37,8 +70,89 @@
   EXPECT_STREQ("Linux", s.c_str());
 }
 
+TEST(util, write_file_binary) {
+    std::string contents("abcd");
+    contents.push_back('\0');
+    contents.push_back('\0');
+    contents.append("dcba");
+    ASSERT_EQ(10u, contents.size());
+
+    TemporaryFile tf;
+    ASSERT_TRUE(tf.fd != -1);
+    EXPECT_TRUE(write_file(tf.path, contents)) << strerror(errno);
+
+    std::string read_back_contents;
+    EXPECT_TRUE(read_file(tf.path, &read_back_contents)) << strerror(errno);
+    EXPECT_EQ(contents, read_back_contents);
+    EXPECT_EQ(10u, read_back_contents.size());
+}
+
+TEST(util, write_file_not_exist) {
+    std::string s("hello");
+    std::string s2("hello");
+    TemporaryDir test_dir;
+    std::string path = android::base::StringPrintf("%s/does-not-exist", test_dir.path);
+    EXPECT_TRUE(write_file(path, s));
+    EXPECT_TRUE(read_file(path, &s2));
+    EXPECT_EQ(s, s2);
+    struct stat sb;
+    int fd = open(path.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
+    EXPECT_NE(-1, fd);
+    EXPECT_EQ(0, fstat(fd, &sb));
+    EXPECT_EQ((const unsigned int)(S_IRUSR | S_IWUSR), sb.st_mode & 0777);
+    EXPECT_EQ(0, unlink(path.c_str()));
+}
+
+TEST(util, write_file_exist) {
+    std::string s2("");
+    TemporaryFile tf;
+    ASSERT_TRUE(tf.fd != -1);
+    EXPECT_TRUE(write_file(tf.path, "1hello1")) << strerror(errno);
+    EXPECT_TRUE(read_file(tf.path, &s2));
+    EXPECT_STREQ("1hello1", s2.c_str());
+    EXPECT_TRUE(write_file(tf.path, "2ll2"));
+    EXPECT_TRUE(read_file(tf.path, &s2));
+    EXPECT_STREQ("2ll2", s2.c_str());
+}
+
 TEST(util, decode_uid) {
   EXPECT_EQ(0U, decode_uid("root"));
   EXPECT_EQ(UINT_MAX, decode_uid("toot"));
   EXPECT_EQ(123U, decode_uid("123"));
 }
+
+TEST(util, is_dir) {
+    TemporaryDir test_dir;
+    EXPECT_TRUE(is_dir(test_dir.path));
+    TemporaryFile tf;
+    EXPECT_FALSE(is_dir(tf.path));
+}
+
+// sehandle is needed for make_dir()
+// TODO: Remove once sehandle is encapsulated
+#include <selinux/label.h>
+selabel_handle* sehandle;
+
+TEST(util, mkdir_recursive) {
+    TemporaryDir test_dir;
+    std::string path = android::base::StringPrintf("%s/three/directories/deep", test_dir.path);
+    EXPECT_EQ(0, mkdir_recursive(path, 0755));
+    std::string path1 = android::base::StringPrintf("%s/three", test_dir.path);
+    EXPECT_TRUE(is_dir(path1.c_str()));
+    std::string path2 = android::base::StringPrintf("%s/three/directories", test_dir.path);
+    EXPECT_TRUE(is_dir(path1.c_str()));
+    std::string path3 = android::base::StringPrintf("%s/three/directories/deep", test_dir.path);
+    EXPECT_TRUE(is_dir(path1.c_str()));
+}
+
+TEST(util, mkdir_recursive_extra_slashes) {
+    TemporaryDir test_dir;
+    std::string path = android::base::StringPrintf("%s/three////directories/deep//", test_dir.path);
+    EXPECT_EQ(0, mkdir_recursive(path, 0755));
+    std::string path1 = android::base::StringPrintf("%s/three", test_dir.path);
+    EXPECT_TRUE(is_dir(path1.c_str()));
+    std::string path2 = android::base::StringPrintf("%s/three/directories", test_dir.path);
+    EXPECT_TRUE(is_dir(path1.c_str()));
+    std::string path3 = android::base::StringPrintf("%s/three/directories/deep", test_dir.path);
+    EXPECT_TRUE(is_dir(path1.c_str()));
+}
diff --git a/init/watchdogd.cpp b/init/watchdogd.cpp
index b196147..21c1e5b 100644
--- a/init/watchdogd.cpp
+++ b/init/watchdogd.cpp
@@ -16,11 +16,12 @@
 
 #include <errno.h>
 #include <fcntl.h>
+#include <linux/watchdog.h>
 #include <stdlib.h>
 #include <string.h>
 #include <unistd.h>
 
-#include <linux/watchdog.h>
+#include <android-base/logging.h>
 
 #include "log.h"
 #include "util.h"
diff --git a/libappfuse/Android.bp b/libappfuse/Android.bp
index f729faf..e659f79 100644
--- a/libappfuse/Android.bp
+++ b/libappfuse/Android.bp
@@ -24,6 +24,7 @@
 
 cc_test {
     name: "libappfuse_test",
+    test_suites: ["device-tests"],
     defaults: ["libappfuse_defaults"],
     shared_libs: ["libappfuse"],
     srcs: [
diff --git a/libappfuse/AndroidTest.xml b/libappfuse/AndroidTest.xml
new file mode 100644
index 0000000..a9cd754
--- /dev/null
+++ b/libappfuse/AndroidTest.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 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.
+-->
+<configuration description="Config for libappfuse_test">
+    <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
+        <option name="cleanup" value="true" />
+        <option name="push" value="libappfuse_test->/data/local/tmp/libappfuse_test" />
+    </target_preparer>
+    <option name="test-suite-tag" value="apct" />
+    <test class="com.android.tradefed.testtype.GTest" >
+        <option name="native-test-device-path" value="/data/local/tmp" />
+        <option name="module-name" value="libappfuse_test" />
+    </test>
+</configuration>
\ No newline at end of file
diff --git a/libbacktrace/Android.bp b/libbacktrace/Android.bp
index 0e7c6f3..285aa6e 100644
--- a/libbacktrace/Android.bp
+++ b/libbacktrace/Android.bp
@@ -55,8 +55,15 @@
     "UnwindPtrace.cpp",
 ]
 
+cc_library_headers {
+    name: "libbacktrace_headers",
+    vendor_available: true,
+    export_include_dirs: ["include"],
+}
+
 cc_library {
     name: "libbacktrace",
+    vendor_available: true,
     defaults: ["libbacktrace_common"],
     host_supported: true,
 
@@ -64,6 +71,8 @@
         "BacktraceMap.cpp",
     ],
 
+    export_include_dirs: ["include"],
+
     target: {
         darwin: {
             enabled: true,
@@ -114,7 +123,7 @@
         none: true,
     },
     cflags: ["-O0"],
-    srcs: ["backtrace_testlib.c"],
+    srcs: ["backtrace_testlib.cpp"],
 
     target: {
         linux: {
diff --git a/libbacktrace/Backtrace.cpp b/libbacktrace/Backtrace.cpp
index 0d2e11b..3545661 100644
--- a/libbacktrace/Backtrace.cpp
+++ b/libbacktrace/Backtrace.cpp
@@ -52,7 +52,16 @@
   }
 }
 
-std::string Backtrace::GetFunctionName(uintptr_t pc, uintptr_t* offset) {
+std::string Backtrace::GetFunctionName(uintptr_t pc, uintptr_t* offset, const backtrace_map_t* map) {
+  backtrace_map_t map_value;
+  if (map == nullptr) {
+    FillInMap(pc, &map_value);
+    map = &map_value;
+  }
+  // If no map is found, or this map is backed by a device, then return nothing.
+  if (map->start == 0 || (map->flags & PROT_DEVICE_MAP)) {
+    return "";
+  }
   std::string func_name = GetFunctionNameRaw(pc, offset);
   return func_name;
 }
@@ -146,7 +155,7 @@
   case BACKTRACE_UNWIND_ERROR_THREAD_DOESNT_EXIST:
     return "Thread doesn't exist";
   case BACKTRACE_UNWIND_ERROR_THREAD_TIMEOUT:
-    return "Thread has not repsonded to signal in time";
+    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:
diff --git a/libbacktrace/BacktraceCurrent.h b/libbacktrace/BacktraceCurrent.h
index 8aad36d..072ffd2 100644
--- a/libbacktrace/BacktraceCurrent.h
+++ b/libbacktrace/BacktraceCurrent.h
@@ -36,7 +36,7 @@
 class BacktraceMap;
 
 class BacktraceCurrent : public Backtrace {
-public:
+ public:
   BacktraceCurrent(pid_t pid, pid_t tid, BacktraceMap* map) : Backtrace(pid, tid, map) {}
   virtual ~BacktraceCurrent() {}
 
@@ -46,10 +46,10 @@
 
   bool Unwind(size_t num_ignore_frames, ucontext_t* ucontext) override;
 
-protected:
+ protected:
   bool DiscardFrame(const backtrace_frame_data_t& frame);
 
-private:
+ private:
   bool UnwindThread(size_t num_ignore_frames);
 
   virtual bool UnwindFromContext(size_t num_ignore_frames, ucontext_t* ucontext) = 0;
diff --git a/libbacktrace/BacktracePtrace.h b/libbacktrace/BacktracePtrace.h
index 1d49811..760817b 100644
--- a/libbacktrace/BacktracePtrace.h
+++ b/libbacktrace/BacktracePtrace.h
@@ -25,7 +25,7 @@
 class BacktraceMap;
 
 class BacktracePtrace : public Backtrace {
-public:
+ public:
   BacktracePtrace(pid_t pid, pid_t tid, BacktraceMap* map) : Backtrace(pid, tid, map) {}
   virtual ~BacktracePtrace() {}
 
diff --git a/libbacktrace/ThreadEntry.h b/libbacktrace/ThreadEntry.h
index 11924a3..caa5497 100644
--- a/libbacktrace/ThreadEntry.h
+++ b/libbacktrace/ThreadEntry.h
@@ -22,7 +22,7 @@
 #include <ucontext.h>
 
 class ThreadEntry {
-public:
+ public:
   static ThreadEntry* Get(pid_t pid, pid_t tid, bool create = true);
 
   static void Remove(ThreadEntry* entry);
@@ -47,7 +47,7 @@
 
   inline ucontext_t* GetUcontext() { return &ucontext_; }
 
-private:
+ private:
   ThreadEntry(pid_t pid, pid_t tid);
   ~ThreadEntry();
 
diff --git a/libbacktrace/UnwindCurrent.cpp b/libbacktrace/UnwindCurrent.cpp
index 666c481..3c509e6 100644
--- a/libbacktrace/UnwindCurrent.cpp
+++ b/libbacktrace/UnwindCurrent.cpp
@@ -23,12 +23,23 @@
 #define UNW_LOCAL_ONLY
 #include <libunwind.h>
 
+#include <android-base/logging.h>
 #include <backtrace/Backtrace.h>
 
 #include "BacktraceLog.h"
 #include "UnwindCurrent.h"
 
 std::string UnwindCurrent::GetFunctionNameRaw(uintptr_t pc, uintptr_t* offset) {
+  if (!initialized_) {
+    // If init local is not called, then trying to get a function name will
+    // fail, so try to initialize first.
+    std::unique_ptr<unw_cursor_t> cursor(new unw_cursor_t);
+    if (unw_init_local(cursor.get(), &context_) < 0) {
+      return "";
+    }
+    initialized_ = true;
+  }
+
   *offset = 0;
   char buf[512];
   unw_word_t value;
@@ -85,6 +96,7 @@
     error_ = BACKTRACE_UNWIND_ERROR_SETUP_FAILED;
     return false;
   }
+  initialized_ = true;
 
   size_t num_frames = 0;
   do {
@@ -115,7 +127,7 @@
       if (num_ignore_frames == 0) {
         // GetFunctionName is an expensive call, only do it if we are
         // keeping the frame.
-        frame->func_name = GetFunctionName(frame->pc, &frame->func_offset);
+        frame->func_name = GetFunctionName(frame->pc, &frame->func_offset, &frame->map);
         if (num_frames > 0) {
           // Set the stack size for the previous frame.
           backtrace_frame_data_t* prev = &frames_.at(num_frames-1);
@@ -124,8 +136,23 @@
         num_frames++;
       } else {
         num_ignore_frames--;
+        // Set the number of frames to zero to remove the frame added
+        // above. By definition, if we still have frames to ignore
+        // there should only be one frame in the vector.
+        CHECK(num_frames == 0);
+        frames_.resize(0);
       }
     }
+    // If the pc is in a device map, then don't try to step.
+    if (frame->map.flags & PROT_DEVICE_MAP) {
+      break;
+    }
+    // Verify the sp is not in a device map too.
+    backtrace_map_t map;
+    FillInMap(frame->sp, &map);
+    if (map.flags & PROT_DEVICE_MAP) {
+      break;
+    }
     ret = unw_step (cursor.get());
   } while (ret > 0 && num_frames < MAX_BACKTRACE_FRAMES);
 
diff --git a/libbacktrace/UnwindCurrent.h b/libbacktrace/UnwindCurrent.h
index 3023996..3656104 100644
--- a/libbacktrace/UnwindCurrent.h
+++ b/libbacktrace/UnwindCurrent.h
@@ -32,18 +32,20 @@
 #include <libunwind.h>
 
 class UnwindCurrent : public BacktraceCurrent {
-public:
+ public:
   UnwindCurrent(pid_t pid, pid_t tid, BacktraceMap* map) : BacktraceCurrent(pid, tid, map) {}
   virtual ~UnwindCurrent() {}
 
   std::string GetFunctionNameRaw(uintptr_t pc, uintptr_t* offset) override;
 
-private:
+ private:
   void GetUnwContextFromUcontext(const ucontext_t* ucontext);
 
   bool UnwindFromContext(size_t num_ignore_frames, ucontext_t* ucontext) override;
 
   unw_context_t context_;
+
+  bool initialized_ = false;
 };
 
 #endif // _LIBBACKTRACE_UNWIND_CURRENT_H
diff --git a/libbacktrace/UnwindMap.h b/libbacktrace/UnwindMap.h
index d5bec06..6ffdafd 100644
--- a/libbacktrace/UnwindMap.h
+++ b/libbacktrace/UnwindMap.h
@@ -28,28 +28,28 @@
 // libunwind.h first then this header.
 
 class UnwindMap : public BacktraceMap {
-public:
+ public:
   explicit UnwindMap(pid_t pid);
 
   unw_map_cursor_t* GetMapCursor() { return &map_cursor_; }
 
-protected:
+ protected:
   unw_map_cursor_t map_cursor_;
 };
 
 class UnwindMapRemote : public UnwindMap {
-public:
+ public:
   explicit UnwindMapRemote(pid_t pid);
   virtual ~UnwindMapRemote();
 
   bool Build() override;
 
-private:
+ private:
   bool GenerateMap();
 };
 
 class UnwindMapLocal : public UnwindMap {
-public:
+ public:
   UnwindMapLocal();
   virtual ~UnwindMapLocal();
 
@@ -60,7 +60,7 @@
   void LockIterator() override { pthread_rwlock_rdlock(&map_lock_); }
   void UnlockIterator() override { pthread_rwlock_unlock(&map_lock_); }
 
-private:
+ private:
   bool GenerateMap();
 
   bool map_created_;
diff --git a/libbacktrace/UnwindPtrace.cpp b/libbacktrace/UnwindPtrace.cpp
index 306d2ac..42ac1bc 100644
--- a/libbacktrace/UnwindPtrace.cpp
+++ b/libbacktrace/UnwindPtrace.cpp
@@ -37,6 +37,7 @@
     _UPT_destroy(upt_info_);
     upt_info_ = nullptr;
   }
+
   if (addr_space_) {
     // Remove the map from the address space before destroying it.
     // It will be freed in the UnwindMap destructor.
@@ -47,18 +48,14 @@
   }
 }
 
-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;
-    return false;
+bool UnwindPtrace::Init() {
+  if (upt_info_) {
+    return true;
   }
 
-  error_ = BACKTRACE_UNWIND_NO_ERROR;
-
-  if (ucontext) {
-    BACK_LOGW("Unwinding from a specified context not supported yet.");
-    error_ = BACKTRACE_UNWIND_ERROR_UNSUPPORTED_OPERATION;
+  if (addr_space_) {
+    // If somehow the addr_space_ gets initialized but upt_info_ doesn't,
+    // then that indicates there is some kind of failure.
     return false;
   }
 
@@ -79,6 +76,28 @@
     return false;
   }
 
+  return true;
+}
+
+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;
+    return false;
+  }
+
+  error_ = BACKTRACE_UNWIND_NO_ERROR;
+
+  if (ucontext) {
+    BACK_LOGW("Unwinding from a specified context not supported yet.");
+    error_ = BACKTRACE_UNWIND_ERROR_UNSUPPORTED_OPERATION;
+    return false;
+  }
+
+  if (!Init()) {
+    return false;
+  }
+
   unw_cursor_t cursor;
   int ret = unw_init_remote(&cursor, addr_space_, upt_info_);
   if (ret < 0) {
@@ -115,14 +134,30 @@
         prev->stack_size = frame->sp - prev->sp;
       }
 
-      frame->func_name = GetFunctionName(frame->pc, &frame->func_offset);
-
       FillInMap(frame->pc, &frame->map);
 
+      frame->func_name = GetFunctionName(frame->pc, &frame->func_offset, &frame->map);
+
       num_frames++;
+      // If the pc is in a device map, then don't try to step.
+      if (frame->map.flags & PROT_DEVICE_MAP) {
+        break;
+      }
     } else {
+      // If the pc is in a device map, then don't try to step.
+      backtrace_map_t map;
+      FillInMap(pc, &map);
+      if (map.flags & PROT_DEVICE_MAP) {
+        break;
+      }
       num_ignore_frames--;
     }
+    // Verify the sp is not in a device map.
+    backtrace_map_t map;
+    FillInMap(sp, &map);
+    if (map.flags & PROT_DEVICE_MAP) {
+      break;
+    }
     ret = unw_step (&cursor);
   } while (ret > 0 && num_frames < MAX_BACKTRACE_FRAMES);
 
@@ -130,6 +165,10 @@
 }
 
 std::string UnwindPtrace::GetFunctionNameRaw(uintptr_t pc, uintptr_t* offset) {
+  if (!Init()) {
+    return "";
+  }
+
   *offset = 0;
   char buf[512];
   unw_word_t value;
diff --git a/libbacktrace/UnwindPtrace.h b/libbacktrace/UnwindPtrace.h
index ab04abf..4688110 100644
--- a/libbacktrace/UnwindPtrace.h
+++ b/libbacktrace/UnwindPtrace.h
@@ -30,7 +30,7 @@
 #include "BacktracePtrace.h"
 
 class UnwindPtrace : public BacktracePtrace {
-public:
+ public:
   UnwindPtrace(pid_t pid, pid_t tid, BacktraceMap* map);
   virtual ~UnwindPtrace();
 
@@ -38,7 +38,9 @@
 
   std::string GetFunctionNameRaw(uintptr_t pc, uintptr_t* offset) override;
 
-private:
+ private:
+  bool Init();
+
   unw_addr_space_t addr_space_;
   struct UPT_info* upt_info_;
 };
diff --git a/libbacktrace/backtrace_test.cpp b/libbacktrace/backtrace_test.cpp
index e25c8e9..fb463b0 100644
--- a/libbacktrace/backtrace_test.cpp
+++ b/libbacktrace/backtrace_test.cpp
@@ -36,13 +36,16 @@
 #include <algorithm>
 #include <list>
 #include <memory>
+#include <ostream>
 #include <string>
 #include <vector>
 
 #include <backtrace/Backtrace.h>
 #include <backtrace/BacktraceMap.h>
 
+#include <android-base/macros.h>
 #include <android-base/stringprintf.h>
+#include <android-base/unique_fd.h>
 #include <cutils/atomic.h>
 #include <cutils/threads.h>
 
@@ -50,6 +53,7 @@
 
 // For the THREAD_SIGNAL definition.
 #include "BacktraceCurrent.h"
+#include "backtrace_testlib.h"
 #include "thread_utils.h"
 
 // Number of microseconds per milliseconds.
@@ -78,20 +82,13 @@
   int32_t done;
 };
 
-extern "C" {
-// Prototypes for functions in the test library.
-int test_level_one(int, int, int, int, void (*)(void*), void*);
-
-int test_recursive_call(int, void (*)(void*), void*);
-}
-
-uint64_t NanoTime() {
+static uint64_t NanoTime() {
   struct timespec t = { 0, 0 };
   clock_gettime(CLOCK_MONOTONIC, &t);
   return static_cast<uint64_t>(t.tv_sec * NS_PER_SEC + t.tv_nsec);
 }
 
-std::string DumpFrames(Backtrace* backtrace) {
+static std::string DumpFrames(Backtrace* backtrace) {
   if (backtrace->NumFrames() == 0) {
     return "   No frames to dump.\n";
   }
@@ -103,7 +100,7 @@
   return frame;
 }
 
-void WaitForStop(pid_t pid) {
+static void WaitForStop(pid_t pid) {
   uint64_t start = NanoTime();
 
   siginfo_t si;
@@ -116,7 +113,28 @@
   }
 }
 
-bool ReadyLevelBacktrace(Backtrace* backtrace) {
+static void CreateRemoteProcess(pid_t* pid) {
+  if ((*pid = fork()) == 0) {
+    while (true)
+      ;
+    _exit(0);
+  }
+  ASSERT_NE(-1, *pid);
+
+  ASSERT_TRUE(ptrace(PTRACE_ATTACH, *pid, 0, 0) == 0);
+
+  // Wait for the process to get to a stopping point.
+  WaitForStop(*pid);
+}
+
+static void FinishRemoteProcess(pid_t pid) {
+  ASSERT_TRUE(ptrace(PTRACE_DETACH, pid, 0, 0) == 0);
+
+  kill(pid, SIGKILL);
+  ASSERT_EQ(waitpid(pid, nullptr, 0), pid);
+}
+
+static bool ReadyLevelBacktrace(Backtrace* backtrace) {
   // See if test_level_four is in the backtrace.
   bool found = false;
   for (Backtrace::const_iterator it = backtrace->begin(); it != backtrace->end(); ++it) {
@@ -129,7 +147,7 @@
   return found;
 }
 
-void VerifyLevelDump(Backtrace* backtrace) {
+static void VerifyLevelDump(Backtrace* backtrace) {
   ASSERT_GT(backtrace->NumFrames(), static_cast<size_t>(0))
     << DumpFrames(backtrace);
   ASSERT_LT(backtrace->NumFrames(), static_cast<size_t>(MAX_BACKTRACE_FRAMES))
@@ -157,7 +175,7 @@
     << DumpFrames(backtrace);
 }
 
-void VerifyLevelBacktrace(void*) {
+static void VerifyLevelBacktrace(void*) {
   std::unique_ptr<Backtrace> backtrace(
       Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
   ASSERT_TRUE(backtrace.get() != nullptr);
@@ -167,11 +185,11 @@
   VerifyLevelDump(backtrace.get());
 }
 
-bool ReadyMaxBacktrace(Backtrace* backtrace) {
+static bool ReadyMaxBacktrace(Backtrace* backtrace) {
   return (backtrace->NumFrames() == MAX_BACKTRACE_FRAMES);
 }
 
-void VerifyMaxDump(Backtrace* backtrace) {
+static void VerifyMaxDump(Backtrace* backtrace) {
   ASSERT_EQ(backtrace->NumFrames(), static_cast<size_t>(MAX_BACKTRACE_FRAMES))
     << DumpFrames(backtrace);
   // Verify that the last frame is our recursive call.
@@ -179,7 +197,7 @@
     << DumpFrames(backtrace);
 }
 
-void VerifyMaxBacktrace(void*) {
+static void VerifyMaxBacktrace(void*) {
   std::unique_ptr<Backtrace> backtrace(
       Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
   ASSERT_TRUE(backtrace.get() != nullptr);
@@ -189,7 +207,7 @@
   VerifyMaxDump(backtrace.get());
 }
 
-void ThreadSetState(void* data) {
+static void ThreadSetState(void* data) {
   thread_t* thread = reinterpret_cast<thread_t*>(data);
   android_atomic_acquire_store(1, &thread->state);
   volatile int i = 0;
@@ -198,16 +216,7 @@
   }
 }
 
-void VerifyThreadTest(pid_t tid, void (*VerifyFunc)(Backtrace*)) {
-  std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), tid));
-  ASSERT_TRUE(backtrace.get() != nullptr);
-  ASSERT_TRUE(backtrace->Unwind(0));
-  ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError());
-
-  VerifyFunc(backtrace.get());
-}
-
-bool WaitForNonZero(int32_t* value, uint64_t seconds) {
+static bool WaitForNonZero(int32_t* value, uint64_t seconds) {
   uint64_t start = NanoTime();
   do {
     if (android_atomic_acquire_load(value)) {
@@ -240,9 +249,8 @@
   ASSERT_NE(test_level_one(1, 2, 3, 4, VerifyLevelBacktrace, nullptr), 0);
 }
 
-void VerifyIgnoreFrames(
-    Backtrace* bt_all, Backtrace* bt_ign1,
-    Backtrace* bt_ign2, const char* cur_proc) {
+static void VerifyIgnoreFrames(Backtrace* bt_all, Backtrace* bt_ign1, Backtrace* bt_ign2,
+                               const char* cur_proc) {
   EXPECT_EQ(bt_all->NumFrames(), bt_ign1->NumFrames() + 1)
     << "All backtrace:\n" << DumpFrames(bt_all) << "Ignore 1 backtrace:\n" << DumpFrames(bt_ign1);
   EXPECT_EQ(bt_all->NumFrames(), bt_ign2->NumFrames() + 2)
@@ -266,7 +274,7 @@
   }
 }
 
-void VerifyLevelIgnoreFrames(void*) {
+static void VerifyLevelIgnoreFrames(void*) {
   std::unique_ptr<Backtrace> all(
       Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
   ASSERT_TRUE(all.get() != nullptr);
@@ -296,9 +304,8 @@
   ASSERT_NE(test_recursive_call(MAX_BACKTRACE_FRAMES+10, VerifyMaxBacktrace, nullptr), 0);
 }
 
-void VerifyProcTest(pid_t pid, pid_t tid, bool share_map,
-                    bool (*ReadyFunc)(Backtrace*),
-                    void (*VerifyFunc)(Backtrace*)) {
+static void VerifyProcTest(pid_t pid, pid_t tid, bool share_map, bool (*ReadyFunc)(Backtrace*),
+                           void (*VerifyFunc)(Backtrace*)) {
   pid_t ptrace_tid;
   if (tid < 0) {
     ptrace_tid = pid;
@@ -376,7 +383,7 @@
   ASSERT_EQ(waitpid(pid, &status, 0), pid);
 }
 
-void VerifyProcessIgnoreFrames(Backtrace* bt_all) {
+static void VerifyProcessIgnoreFrames(Backtrace* bt_all) {
   std::unique_ptr<Backtrace> ign1(Backtrace::Create(bt_all->Pid(), BACKTRACE_CURRENT_THREAD));
   ASSERT_TRUE(ign1.get() != nullptr);
   ASSERT_TRUE(ign1->Unwind(1));
@@ -404,12 +411,12 @@
 }
 
 // Create a process with multiple threads and dump all of the threads.
-void* PtraceThreadLevelRun(void*) {
+static void* PtraceThreadLevelRun(void*) {
   EXPECT_NE(test_level_one(1, 2, 3, 4, nullptr, nullptr), 0);
   return nullptr;
 }
 
-void GetThreads(pid_t pid, std::vector<pid_t>* threads) {
+static void GetThreads(pid_t pid, std::vector<pid_t>* threads) {
   // Get the list of tasks.
   char task_path[128];
   snprintf(task_path, sizeof(task_path), "/proc/%d/task", pid);
@@ -461,11 +468,8 @@
     }
     VerifyProcTest(pid, *it, false, ReadyLevelBacktrace, VerifyLevelDump);
   }
-  ASSERT_TRUE(ptrace(PTRACE_DETACH, pid, 0, 0) == 0);
 
-  kill(pid, SIGKILL);
-  int status;
-  ASSERT_EQ(waitpid(pid, &status, 0), pid);
+  FinishRemoteProcess(pid);
 }
 
 void VerifyLevelThread(void*) {
@@ -481,7 +485,7 @@
   ASSERT_NE(test_level_one(1, 2, 3, 4, VerifyLevelThread, nullptr), 0);
 }
 
-void VerifyMaxThread(void*) {
+static void VerifyMaxThread(void*) {
   std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), gettid()));
   ASSERT_TRUE(backtrace.get() != nullptr);
   ASSERT_TRUE(backtrace->Unwind(0));
@@ -494,7 +498,7 @@
   ASSERT_NE(test_recursive_call(MAX_BACKTRACE_FRAMES+10, VerifyMaxThread, nullptr), 0);
 }
 
-void* ThreadLevelRun(void* data) {
+static void* ThreadLevelRun(void* data) {
   thread_t* thread = reinterpret_cast<thread_t*>(data);
 
   thread->tid = gettid();
@@ -585,7 +589,7 @@
   android_atomic_acquire_store(0, &thread_data.state);
 }
 
-void* ThreadMaxRun(void* data) {
+static void* ThreadMaxRun(void* data) {
   thread_t* thread = reinterpret_cast<thread_t*>(data);
 
   thread->tid = gettid();
@@ -616,7 +620,7 @@
   android_atomic_acquire_store(0, &thread_data.state);
 }
 
-void* ThreadDump(void* data) {
+static void* ThreadDump(void* data) {
   dump_thread_t* dump = reinterpret_cast<dump_thread_t*>(data);
   while (true) {
     if (android_atomic_acquire_load(dump->now)) {
@@ -873,11 +877,9 @@
   uintptr_t end;
 };
 
-bool map_sort(map_test_t i, map_test_t j) {
-  return i.start < j.start;
-}
+static bool map_sort(map_test_t i, map_test_t j) { return i.start < j.start; }
 
-void VerifyMap(pid_t pid) {
+static void VerifyMap(pid_t pid) {
   char buffer[4096];
   snprintf(buffer, sizeof(buffer), "/proc/%d/maps", pid);
 
@@ -908,29 +910,15 @@
 
 TEST(libbacktrace, verify_map_remote) {
   pid_t pid;
-
-  if ((pid = fork()) == 0) {
-    while (true) {
-    }
-    _exit(0);
-  }
-  ASSERT_LT(0, pid);
-
-  ASSERT_TRUE(ptrace(PTRACE_ATTACH, pid, 0, 0) == 0);
-
-  // Wait for the process to get to a stopping point.
-  WaitForStop(pid);
+  CreateRemoteProcess(&pid);
 
   // The maps should match exactly since the forked process has been paused.
   VerifyMap(pid);
 
-  ASSERT_TRUE(ptrace(PTRACE_DETACH, pid, 0, 0) == 0);
-
-  kill(pid, SIGKILL);
-  ASSERT_EQ(waitpid(pid, nullptr, 0), pid);
+  FinishRemoteProcess(pid);
 }
 
-void InitMemory(uint8_t* memory, size_t bytes) {
+static void InitMemory(uint8_t* memory, size_t bytes) {
   for (size_t i = 0; i < bytes; i++) {
     memory[i] = i;
     if (memory[i] == '\0') {
@@ -941,7 +929,7 @@
   }
 }
 
-void* ThreadReadTest(void* data) {
+static void* ThreadReadTest(void* data) {
   thread_t* thread_data = reinterpret_cast<thread_t*>(data);
 
   thread_data->tid = gettid();
@@ -982,7 +970,7 @@
   return nullptr;
 }
 
-void RunReadTest(Backtrace* backtrace, uintptr_t read_addr) {
+static void RunReadTest(Backtrace* backtrace, uintptr_t read_addr) {
   size_t pagesize = static_cast<size_t>(sysconf(_SC_PAGE_SIZE));
 
   // Create a page of data to use to do quick compares.
@@ -1043,7 +1031,7 @@
 volatile uintptr_t g_ready = 0;
 volatile uintptr_t g_addr = 0;
 
-void ForkedReadTest() {
+static void ForkedReadTest() {
   // Create two map pages.
   size_t pagesize = static_cast<size_t>(sysconf(_SC_PAGE_SIZE));
   uint8_t* memory;
@@ -1117,7 +1105,7 @@
   ASSERT_TRUE(test_executed);
 }
 
-void VerifyFunctionsFound(const std::vector<std::string>& found_functions) {
+static void VerifyFunctionsFound(const std::vector<std::string>& found_functions) {
   // We expect to find these functions in libbacktrace_test. If we don't
   // find them, that's a bug in the memory read handling code in libunwind.
   std::list<std::string> expected_functions;
@@ -1137,7 +1125,7 @@
   ASSERT_TRUE(expected_functions.empty()) << "Not all functions found in shared library.";
 }
 
-const char* CopySharedLibrary() {
+static const char* CopySharedLibrary() {
 #if defined(__LP64__)
   const char* lib_name = "lib64";
 #else
@@ -1293,7 +1281,7 @@
   VerifyFunctionsFound(found_functions);
 }
 
-bool FindFuncFrameInBacktrace(Backtrace* backtrace, uintptr_t test_func, size_t* frame_num) {
+static bool FindFuncFrameInBacktrace(Backtrace* backtrace, uintptr_t test_func, size_t* frame_num) {
   backtrace_map_t map;
   backtrace->FillInMap(test_func, &map);
   if (!BacktraceMap::IsValid(map)) {
@@ -1312,7 +1300,7 @@
   return false;
 }
 
-void VerifyUnreadableElfFrame(Backtrace* backtrace, uintptr_t test_func, size_t frame_num) {
+static void VerifyUnreadableElfFrame(Backtrace* backtrace, uintptr_t test_func, size_t frame_num) {
   ASSERT_LT(backtrace->NumFrames(), static_cast<size_t>(MAX_BACKTRACE_FRAMES))
     << DumpFrames(backtrace);
 
@@ -1324,7 +1312,7 @@
   ASSERT_LT(diff, 200U) << DumpFrames(backtrace);
 }
 
-void VerifyUnreadableElfBacktrace(uintptr_t test_func) {
+static void VerifyUnreadableElfBacktrace(uintptr_t test_func) {
   std::unique_ptr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS,
                                                          BACKTRACE_CURRENT_THREAD));
   ASSERT_TRUE(backtrace.get() != nullptr);
@@ -1418,12 +1406,347 @@
   ASSERT_EQ(BACKTRACE_UNWIND_ERROR_THREAD_DOESNT_EXIST, backtrace->GetError());
 }
 
+TEST(libbacktrace, local_get_function_name_before_unwind) {
+  std::unique_ptr<Backtrace> backtrace(
+      Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
+  ASSERT_TRUE(backtrace.get() != nullptr);
+
+  // Verify that trying to get a function name before doing an unwind works.
+  uintptr_t cur_func_offset = reinterpret_cast<uintptr_t>(&test_level_one) + 1;
+  size_t offset;
+  ASSERT_NE(std::string(""), backtrace->GetFunctionName(cur_func_offset, &offset));
+}
+
+TEST(libbacktrace, remote_get_function_name_before_unwind) {
+  pid_t pid;
+  CreateRemoteProcess(&pid);
+
+  // Now create an unwind object.
+  std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, pid));
+
+  // Verify that trying to get a function name before doing an unwind works.
+  uintptr_t cur_func_offset = reinterpret_cast<uintptr_t>(&test_level_one) + 1;
+  size_t offset;
+  ASSERT_NE(std::string(""), backtrace->GetFunctionName(cur_func_offset, &offset));
+
+  FinishRemoteProcess(pid);
+}
+
+static void SetUcontextSp(uintptr_t sp, ucontext_t* ucontext) {
+#if defined(__arm__)
+  ucontext->uc_mcontext.arm_sp = sp;
+#elif defined(__aarch64__)
+  ucontext->uc_mcontext.sp = sp;
+#elif defined(__i386__)
+  ucontext->uc_mcontext.gregs[REG_ESP] = sp;
+#elif defined(__x86_64__)
+  ucontext->uc_mcontext.gregs[REG_RSP] = sp;
+#else
+  UNUSED(sp);
+  UNUSED(ucontext);
+  ASSERT_TRUE(false) << "Unsupported architecture";
+#endif
+}
+
+static void SetUcontextPc(uintptr_t pc, ucontext_t* ucontext) {
+#if defined(__arm__)
+  ucontext->uc_mcontext.arm_pc = pc;
+#elif defined(__aarch64__)
+  ucontext->uc_mcontext.pc = pc;
+#elif defined(__i386__)
+  ucontext->uc_mcontext.gregs[REG_EIP] = pc;
+#elif defined(__x86_64__)
+  ucontext->uc_mcontext.gregs[REG_RIP] = pc;
+#else
+  UNUSED(pc);
+  UNUSED(ucontext);
+  ASSERT_TRUE(false) << "Unsupported architecture";
+#endif
+}
+
+static void SetUcontextLr(uintptr_t lr, ucontext_t* ucontext) {
+#if defined(__arm__)
+  ucontext->uc_mcontext.arm_lr = lr;
+#elif defined(__aarch64__)
+  ucontext->uc_mcontext.regs[30] = lr;
+#elif defined(__i386__)
+  // The lr is on the stack.
+  ASSERT_TRUE(lr != 0);
+  ASSERT_TRUE(ucontext != nullptr);
+#elif defined(__x86_64__)
+  // The lr is on the stack.
+  ASSERT_TRUE(lr != 0);
+  ASSERT_TRUE(ucontext != nullptr);
+#else
+  UNUSED(lr);
+  UNUSED(ucontext);
+  ASSERT_TRUE(false) << "Unsupported architecture";
+#endif
+}
+
+static constexpr size_t DEVICE_MAP_SIZE = 1024;
+
+static void SetupDeviceMap(void** device_map) {
+  // Make sure that anything in a device map will result in fails
+  // to read.
+  android::base::unique_fd device_fd(open("/dev/zero", O_RDONLY | O_CLOEXEC));
+
+  *device_map = mmap(nullptr, 1024, PROT_READ, MAP_PRIVATE, device_fd, 0);
+  ASSERT_TRUE(*device_map != MAP_FAILED);
+
+  // Make sure the map is readable.
+  ASSERT_EQ(0, reinterpret_cast<int*>(*device_map)[0]);
+}
+
+static void UnwindFromDevice(Backtrace* backtrace, void* device_map) {
+  uintptr_t device_map_uint = reinterpret_cast<uintptr_t>(device_map);
+
+  backtrace_map_t map;
+  backtrace->FillInMap(device_map_uint, &map);
+  // Verify the flag is set.
+  ASSERT_EQ(PROT_DEVICE_MAP, map.flags & PROT_DEVICE_MAP);
+
+  // Quick sanity checks.
+  size_t offset;
+  ASSERT_EQ(std::string(""), backtrace->GetFunctionName(device_map_uint, &offset));
+  ASSERT_EQ(std::string(""), backtrace->GetFunctionName(device_map_uint, &offset, &map));
+  ASSERT_EQ(std::string(""), backtrace->GetFunctionName(0, &offset));
+
+  uintptr_t cur_func_offset = reinterpret_cast<uintptr_t>(&test_level_one) + 1;
+  // Now verify the device map flag actually causes the function name to be empty.
+  backtrace->FillInMap(cur_func_offset, &map);
+  ASSERT_TRUE((map.flags & PROT_DEVICE_MAP) == 0);
+  ASSERT_NE(std::string(""), backtrace->GetFunctionName(cur_func_offset, &offset, &map));
+  map.flags |= PROT_DEVICE_MAP;
+  ASSERT_EQ(std::string(""), backtrace->GetFunctionName(cur_func_offset, &offset, &map));
+
+  ucontext_t ucontext;
+
+  // Create a context that has the pc in the device map, but the sp
+  // in a non-device map.
+  memset(&ucontext, 0, sizeof(ucontext));
+  SetUcontextSp(reinterpret_cast<uintptr_t>(&ucontext), &ucontext);
+  SetUcontextPc(device_map_uint, &ucontext);
+  SetUcontextLr(cur_func_offset, &ucontext);
+
+  ASSERT_TRUE(backtrace->Unwind(0, &ucontext));
+
+  // The buffer should only be a single element.
+  ASSERT_EQ(1U, backtrace->NumFrames());
+  const backtrace_frame_data_t* frame = backtrace->GetFrame(0);
+  ASSERT_EQ(device_map_uint, frame->pc);
+  ASSERT_EQ(reinterpret_cast<uintptr_t>(&ucontext), frame->sp);
+
+  // Check what happens when skipping the first frame.
+  ASSERT_TRUE(backtrace->Unwind(1, &ucontext));
+  ASSERT_EQ(0U, backtrace->NumFrames());
+
+  // Create a context that has the sp in the device map, but the pc
+  // in a non-device map.
+  memset(&ucontext, 0, sizeof(ucontext));
+  SetUcontextSp(device_map_uint, &ucontext);
+  SetUcontextPc(cur_func_offset, &ucontext);
+  SetUcontextLr(cur_func_offset, &ucontext);
+
+  ASSERT_TRUE(backtrace->Unwind(0, &ucontext));
+
+  // The buffer should only be a single element.
+  ASSERT_EQ(1U, backtrace->NumFrames());
+  frame = backtrace->GetFrame(0);
+  ASSERT_EQ(cur_func_offset, frame->pc);
+  ASSERT_EQ(device_map_uint, frame->sp);
+
+  // Check what happens when skipping the first frame.
+  ASSERT_TRUE(backtrace->Unwind(1, &ucontext));
+  ASSERT_EQ(0U, backtrace->NumFrames());
+}
+
+TEST(libbacktrace, unwind_disallow_device_map_local) {
+  void* device_map;
+  SetupDeviceMap(&device_map);
+
+  // Now create an unwind object.
+  std::unique_ptr<Backtrace> backtrace(
+      Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
+  ASSERT_TRUE(backtrace);
+
+  UnwindFromDevice(backtrace.get(), device_map);
+
+  munmap(device_map, DEVICE_MAP_SIZE);
+}
+
+TEST(libbacktrace, unwind_disallow_device_map_remote) {
+  void* device_map;
+  SetupDeviceMap(&device_map);
+
+  // Fork a process to do a remote backtrace.
+  pid_t pid;
+  CreateRemoteProcess(&pid);
+
+  // Now create an unwind object.
+  std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, pid));
+
+  // TODO: Currently unwind from context doesn't work on remote
+  // unwind. Keep this test because the new unwinder should support
+  // this eventually, or we can delete this test.
+  // properly with unwind from context.
+  // UnwindFromDevice(backtrace.get(), device_map);
+
+  FinishRemoteProcess(pid);
+
+  munmap(device_map, DEVICE_MAP_SIZE);
+}
+
+class ScopedSignalHandler {
+ public:
+  ScopedSignalHandler(int signal_number, void (*handler)(int)) : signal_number_(signal_number) {
+    memset(&action_, 0, sizeof(action_));
+    action_.sa_handler = handler;
+    sigaction(signal_number_, &action_, &old_action_);
+  }
+
+  ScopedSignalHandler(int signal_number, void (*action)(int, siginfo_t*, void*))
+      : signal_number_(signal_number) {
+    memset(&action_, 0, sizeof(action_));
+    action_.sa_flags = SA_SIGINFO;
+    action_.sa_sigaction = action;
+    sigaction(signal_number_, &action_, &old_action_);
+  }
+
+  ~ScopedSignalHandler() { sigaction(signal_number_, &old_action_, nullptr); }
+
+ private:
+  struct sigaction action_;
+  struct sigaction old_action_;
+  const int signal_number_;
+};
+
+static void SetValueAndLoop(void* data) {
+  volatile int* value = reinterpret_cast<volatile int*>(data);
+
+  *value = 1;
+  for (volatile int i = 0;; i++)
+    ;
+}
+
+static void UnwindThroughSignal(bool use_action) {
+  volatile int value = 0;
+  pid_t pid;
+  if ((pid = fork()) == 0) {
+    if (use_action) {
+      ScopedSignalHandler ssh(SIGUSR1, test_signal_action);
+
+      test_level_one(1, 2, 3, 4, SetValueAndLoop, const_cast<int*>(&value));
+    } else {
+      ScopedSignalHandler ssh(SIGUSR1, test_signal_handler);
+
+      test_level_one(1, 2, 3, 4, SetValueAndLoop, const_cast<int*>(&value));
+    }
+  }
+  ASSERT_NE(-1, pid);
+
+  int read_value = 0;
+  uint64_t start = NanoTime();
+  while (read_value == 0) {
+    usleep(1000);
+
+    // Loop until the remote function gets into the final function.
+    ASSERT_TRUE(ptrace(PTRACE_ATTACH, pid, 0, 0) == 0);
+
+    WaitForStop(pid);
+
+    std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, pid));
+
+    size_t bytes_read = backtrace->Read(reinterpret_cast<uintptr_t>(const_cast<int*>(&value)),
+                                        reinterpret_cast<uint8_t*>(&read_value), sizeof(read_value));
+    ASSERT_EQ(sizeof(read_value), bytes_read);
+
+    ASSERT_TRUE(ptrace(PTRACE_DETACH, pid, 0, 0) == 0);
+
+    ASSERT_TRUE(NanoTime() - start < 5 * NS_PER_SEC)
+        << "Remote process did not execute far enough in 5 seconds.";
+  }
+
+  // Now need to send a signal to the remote process.
+  kill(pid, SIGUSR1);
+
+  // Wait for the process to get to the signal handler loop.
+  Backtrace::const_iterator frame_iter;
+  start = NanoTime();
+  std::unique_ptr<Backtrace> backtrace;
+  while (true) {
+    usleep(1000);
+
+    ASSERT_TRUE(ptrace(PTRACE_ATTACH, pid, 0, 0) == 0);
+
+    WaitForStop(pid);
+
+    backtrace.reset(Backtrace::Create(pid, pid));
+    ASSERT_TRUE(backtrace->Unwind(0));
+    bool found = false;
+    for (frame_iter = backtrace->begin(); frame_iter != backtrace->end(); ++frame_iter) {
+      if (frame_iter->func_name == "test_loop_forever") {
+        ++frame_iter;
+        found = true;
+        break;
+      }
+    }
+    if (found) {
+      break;
+    }
+
+    ASSERT_TRUE(ptrace(PTRACE_DETACH, pid, 0, 0) == 0);
+
+    ASSERT_TRUE(NanoTime() - start < 5 * NS_PER_SEC)
+        << "Remote process did not get in signal handler in 5 seconds." << std::endl
+        << DumpFrames(backtrace.get());
+  }
+
+  std::vector<std::string> names;
+  // Loop through the frames, and save the function names.
+  size_t frame = 0;
+  for (; frame_iter != backtrace->end(); ++frame_iter) {
+    if (frame_iter->func_name == "test_level_four") {
+      frame = names.size() + 1;
+    }
+    names.push_back(frame_iter->func_name);
+  }
+  ASSERT_NE(0U, frame) << "Unable to find test_level_four in backtrace" << std::endl
+                       << DumpFrames(backtrace.get());
+
+  // The expected order of the frames:
+  //   test_loop_forever
+  //   test_signal_handler|test_signal_action
+  //   <OPTIONAL_FRAME> May or may not exist.
+  //   SetValueAndLoop (but the function name might be empty)
+  //   test_level_four
+  //   test_level_three
+  //   test_level_two
+  //   test_level_one
+  ASSERT_LE(frame + 2, names.size()) << DumpFrames(backtrace.get());
+  ASSERT_LE(2U, frame) << DumpFrames(backtrace.get());
+  if (use_action) {
+    ASSERT_EQ("test_signal_action", names[0]) << DumpFrames(backtrace.get());
+  } else {
+    ASSERT_EQ("test_signal_handler", names[0]) << DumpFrames(backtrace.get());
+  }
+  ASSERT_EQ("test_level_three", names[frame]) << DumpFrames(backtrace.get());
+  ASSERT_EQ("test_level_two", names[frame + 1]) << DumpFrames(backtrace.get());
+  ASSERT_EQ("test_level_one", names[frame + 2]) << DumpFrames(backtrace.get());
+
+  FinishRemoteProcess(pid);
+}
+
+TEST(libbacktrace, unwind_remote_through_signal_using_handler) { UnwindThroughSignal(false); }
+
+TEST(libbacktrace, unwind_remote_through_signal_using_action) { UnwindThroughSignal(true); }
+
 #if defined(ENABLE_PSS_TESTS)
 #include "GetPss.h"
 
 #define MAX_LEAK_BYTES (32*1024UL)
 
-void CheckForLeak(pid_t pid, pid_t tid) {
+static void CheckForLeak(pid_t pid, pid_t tid) {
   // Do a few runs to get the PSS stable.
   for (size_t i = 0; i < 100; i++) {
     Backtrace* backtrace = Backtrace::Create(pid, tid);
@@ -1472,24 +1795,10 @@
 
 TEST(libbacktrace, check_for_leak_remote) {
   pid_t pid;
-
-  if ((pid = fork()) == 0) {
-    while (true) {
-    }
-    _exit(0);
-  }
-  ASSERT_LT(0, pid);
-
-  ASSERT_TRUE(ptrace(PTRACE_ATTACH, pid, 0, 0) == 0);
-
-  // Wait for the process to get to a stopping point.
-  WaitForStop(pid);
+  CreateRemoteProcess(&pid);
 
   CheckForLeak(pid, BACKTRACE_CURRENT_THREAD);
 
-  ASSERT_TRUE(ptrace(PTRACE_DETACH, pid, 0, 0) == 0);
-
-  kill(pid, SIGKILL);
-  ASSERT_EQ(waitpid(pid, nullptr, 0), pid);
+  FinishRemoteProcess(pid);
 }
 #endif
diff --git a/libbacktrace/backtrace_testlib.c b/libbacktrace/backtrace_testlib.cpp
similarity index 61%
rename from libbacktrace/backtrace_testlib.c
rename to libbacktrace/backtrace_testlib.cpp
index 6f6b535..3081d64 100644
--- a/libbacktrace/backtrace_testlib.c
+++ b/libbacktrace/backtrace_testlib.cpp
@@ -15,32 +15,42 @@
  */
 
 #include <libunwind.h>
+#include <signal.h>
 #include <stdio.h>
 
-int test_level_four(int one, int two, int three, int four,
-                    void (*callback_func)(void*), void* data) {
+#include "backtrace_testlib.h"
+
+void test_loop_forever() {
+  while (1)
+    ;
+}
+
+void test_signal_handler(int) { test_loop_forever(); }
+
+void test_signal_action(int, siginfo_t*, void*) { test_loop_forever(); }
+
+int test_level_four(int one, int two, int three, int four, void (*callback_func)(void*),
+                    void* data) {
   if (callback_func != NULL) {
     callback_func(data);
   } else {
-    while (1) {
-    }
+    while (1)
+      ;
   }
   return one + two + three + four;
 }
 
-int test_level_three(int one, int two, int three, int four,
-                     void (*callback_func)(void*), void* data) {
-  return test_level_four(one+3, two+6, three+9, four+12, callback_func, data) + 3;
+int test_level_three(int one, int two, int three, int four, void (*callback_func)(void*),
+                     void* data) {
+  return test_level_four(one + 3, two + 6, three + 9, four + 12, callback_func, data) + 3;
 }
 
-int test_level_two(int one, int two, int three, int four,
-                   void (*callback_func)(void*), void* data) {
-  return test_level_three(one+2, two+4, three+6, four+8, callback_func, data) + 2;
+int test_level_two(int one, int two, int three, int four, void (*callback_func)(void*), void* data) {
+  return test_level_three(one + 2, two + 4, three + 6, four + 8, callback_func, data) + 2;
 }
 
-int test_level_one(int one, int two, int three, int four,
-                   void (*callback_func)(void*), void* data) {
-  return test_level_two(one+1, two+2, three+3, four+4, callback_func, data) + 1;
+int test_level_one(int one, int two, int three, int four, void (*callback_func)(void*), void* data) {
+  return test_level_two(one + 1, two + 2, three + 3, four + 4, callback_func, data) + 1;
 }
 
 int test_recursive_call(int level, void (*callback_func)(void*), void* data) {
diff --git a/libbacktrace/backtrace_testlib.h b/libbacktrace/backtrace_testlib.h
new file mode 100644
index 0000000..16fedc4
--- /dev/null
+++ b/libbacktrace/backtrace_testlib.h
@@ -0,0 +1,38 @@
+/*
+ * 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 _LIBBACKTRACE_BACKTRACE_TESTLIB_H
+#define _LIBBACKTRACE_BACKTRACE_TESTLIB_H
+
+#include <sys/cdefs.h>
+
+#include <libunwind.h>
+
+__BEGIN_DECLS
+
+void test_loop_forever();
+void test_signal_handler(int);
+void test_signal_action(int, siginfo_t*, void*);
+int test_level_four(int, int, int, int, void (*)(void*), void*);
+int test_level_three(int, int, int, int, void (*)(void*), void*);
+int test_level_two(int, int, int, int, void (*)(void*), void*);
+int test_level_one(int, int, int, int, void (*)(void*), void*);
+int test_recursive_call(int, void (*)(void*), void*);
+void test_get_context_and_wait(unw_context_t*, volatile int*);
+
+__END_DECLS
+
+#endif  // _LIBBACKTRACE_BACKTRACE_TESTLIB_H
diff --git a/include/backtrace/Backtrace.h b/libbacktrace/include/backtrace/Backtrace.h
similarity index 97%
rename from include/backtrace/Backtrace.h
rename to libbacktrace/include/backtrace/Backtrace.h
index c896ab8..4f73a65 100644
--- a/include/backtrace/Backtrace.h
+++ b/libbacktrace/include/backtrace/Backtrace.h
@@ -104,8 +104,10 @@
   virtual bool Unwind(size_t num_ignore_frames, ucontext_t* context = NULL) = 0;
 
   // Get the function name and offset into the function given the pc.
-  // If the string is empty, then no valid function name was found.
-  virtual std::string GetFunctionName(uintptr_t pc, uintptr_t* offset);
+  // If the string is empty, then no valid function name was found,
+  // or the pc is not in any valid map.
+  virtual std::string GetFunctionName(uintptr_t pc, uintptr_t* offset,
+                                      const backtrace_map_t* map = NULL);
 
   // Fill in the map data associated with the given pc.
   virtual void FillInMap(uintptr_t pc, backtrace_map_t* map);
diff --git a/include/backtrace/BacktraceMap.h b/libbacktrace/include/backtrace/BacktraceMap.h
similarity index 95%
rename from include/backtrace/BacktraceMap.h
rename to libbacktrace/include/backtrace/BacktraceMap.h
index df48dfe..8ab0dfa 100644
--- a/include/backtrace/BacktraceMap.h
+++ b/libbacktrace/include/backtrace/BacktraceMap.h
@@ -33,6 +33,10 @@
 #include <string>
 #include <vector>
 
+// Special flag to indicate a map is in /dev/. However, a map in
+// /dev/ashmem/... does not set this flag.
+static constexpr int PROT_DEVICE_MAP = 0x8000;
+
 struct backtrace_map_t {
   uintptr_t start = 0;
   uintptr_t end = 0;
diff --git a/include/backtrace/backtrace_constants.h b/libbacktrace/include/backtrace/backtrace_constants.h
similarity index 100%
rename from include/backtrace/backtrace_constants.h
rename to libbacktrace/include/backtrace/backtrace_constants.h
diff --git a/libbinderwrapper/Android.bp b/libbinderwrapper/Android.bp
new file mode 100644
index 0000000..6fac0d8
--- /dev/null
+++ b/libbinderwrapper/Android.bp
@@ -0,0 +1,61 @@
+//
+// 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.
+//
+
+cc_defaults {
+    name: "libbinderwrapper_defaults",
+
+    cflags: [
+        "-Wall",
+        "-Werror",
+        "-Wno-unused-parameter",
+
+        // for libchrome
+        "-Wno-sign-promo",
+    ],
+    export_include_dirs: ["include"],
+    shared_libs: [
+        "libbinder",
+        "libchrome",
+        "libutils",
+    ],
+}
+
+// libbinderwrapper shared library
+// ========================================================
+cc_library_shared {
+    name: "libbinderwrapper",
+    defaults: ["libbinderwrapper_defaults"],
+
+    srcs: [
+        "binder_wrapper.cc",
+        "real_binder_wrapper.cc",
+    ],
+}
+
+// libbinderwrapper_test_support static library
+// ========================================================
+cc_library_static {
+    name: "libbinderwrapper_test_support",
+    defaults: ["libbinderwrapper_defaults"],
+
+    static_libs: ["libgtest"],
+    shared_libs: ["libbinderwrapper"],
+
+    srcs: [
+        "binder_test_base.cc",
+        "stub_binder_wrapper.cc",
+    ],
+}
diff --git a/libbinderwrapper/Android.mk b/libbinderwrapper/Android.mk
deleted file mode 100644
index c768373..0000000
--- a/libbinderwrapper/Android.mk
+++ /dev/null
@@ -1,62 +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.
-#
-
-LOCAL_PATH := $(call my-dir)
-
-binderwrapperCommonCFlags := -Wall -Werror -Wno-unused-parameter
-binderwrapperCommonCFlags += -Wno-sign-promo  # for libchrome
-binderwrapperCommonExportCIncludeDirs := $(LOCAL_PATH)/include
-binderwrapperCommonCIncludes := $(LOCAL_PATH)/include
-binderwrapperCommonSharedLibraries := \
-  libbinder \
-  libchrome \
-  libutils \
-
-# libbinderwrapper shared library
-# ========================================================
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := libbinderwrapper
-LOCAL_CPP_EXTENSION := .cc
-LOCAL_CFLAGS := $(binderwrapperCommonCFlags)
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(binderwrapperCommonExportCIncludeDirs)
-LOCAL_C_INCLUDES := $(binderwrapperCommonCIncludes)
-LOCAL_SHARED_LIBRARIES := $(binderwrapperCommonSharedLibraries)
-LOCAL_SRC_FILES := \
-  binder_wrapper.cc \
-  real_binder_wrapper.cc \
-
-include $(BUILD_SHARED_LIBRARY)
-
-# libbinderwrapper_test_support static library
-# ========================================================
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := libbinderwrapper_test_support
-LOCAL_CPP_EXTENSION := .cc
-LOCAL_CFLAGS := $(binderwrapperCommonCFlags)
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(binderwrapperCommonExportCIncludeDirs)
-LOCAL_C_INCLUDES := $(binderwrapperCommonCIncludes)
-LOCAL_STATIC_LIBRARIES := libgtest
-LOCAL_SHARED_LIBRARIES := \
-  $(binderwrapperCommonSharedLibraries) \
-  libbinderwrapper \
-
-LOCAL_SRC_FILES := \
-  binder_test_base.cc \
-  stub_binder_wrapper.cc \
-
-include $(BUILD_STATIC_LIBRARY)
diff --git a/libcutils/Android.bp b/libcutils/Android.bp
index f668f18..58170ec 100644
--- a/libcutils/Android.bp
+++ b/libcutils/Android.bp
@@ -24,23 +24,20 @@
     "socket_inaddr_any_server_unix.c",
     "socket_local_client_unix.c",
     "socket_local_server_unix.c",
-    "socket_loopback_server_unix.c",
     "socket_network_client_unix.c",
     "sockets_unix.cpp",
     "str_parms.c",
 ]
 
 cc_library_headers {
-    name: "libcutils_vndk_headers",
-    host_supported: true,
-    export_include_dirs: ["include_vndk"],
-}
-
-cc_library_headers {
     name: "libcutils_headers",
+    vendor_available: true,
     host_supported: true,
     export_include_dirs: ["include"],
     target: {
+        vendor: {
+            export_include_dirs: ["include_vndk"],
+        },
         linux_bionic: {
             enabled: true,
         },
@@ -52,6 +49,7 @@
 
 cc_library {
     name: "libcutils",
+    vendor_available: true,
     host_supported: true,
     srcs: [
         "config_utils.c",
@@ -144,7 +142,10 @@
     },
 
     shared_libs: ["liblog"],
-    header_libs: ["libcutils_headers"],
+    header_libs: [
+        "libcutils_headers",
+        "libutils_headers",
+    ],
     export_header_lib_headers: ["libcutils_headers"],
 
     cflags: [
diff --git a/libcutils/android_reboot.c b/libcutils/android_reboot.c
index 06026d1..a33e45f 100644
--- a/libcutils/android_reboot.c
+++ b/libcutils/android_reboot.c
@@ -13,259 +13,39 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
-#include <errno.h>
-#include <fcntl.h>
-#include <mntent.h>
-#include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
-#include <string.h>
-#include <sys/cdefs.h>
-#include <sys/mount.h>
-#include <sys/reboot.h>
-#include <sys/stat.h>
-#include <sys/syscall.h>
-#include <sys/types.h>
-#include <unistd.h>
 
 #include <cutils/android_reboot.h>
-#include <cutils/klog.h>
-#include <cutils/list.h>
+#include <cutils/properties.h>
 
 #define TAG "android_reboot"
-#define READONLY_CHECK_MS 5000
-#define READONLY_CHECK_TIMES 50
 
-typedef struct {
-    struct listnode list;
-    struct mntent entry;
-} mntent_list;
-
-static bool is_block_device(const char* fsname)
-{
-    return !strncmp(fsname, "/dev/block", 10);
-}
-
-/* Find all read+write block devices in /proc/mounts and add them to
- * |rw_entries|.
- */
-static void find_rw(struct listnode* rw_entries)
-{
-    FILE* fp;
-    struct mntent* mentry;
-
-    if ((fp = setmntent("/proc/mounts", "r")) == NULL) {
-        KLOG_WARNING(TAG, "Failed to open /proc/mounts.\n");
-        return;
-    }
-    while ((mentry = getmntent(fp)) != NULL) {
-        if (is_block_device(mentry->mnt_fsname) && hasmntopt(mentry, "rw")) {
-            mntent_list* item = (mntent_list*)calloc(1, sizeof(mntent_list));
-            item->entry = *mentry;
-            item->entry.mnt_fsname = strdup(mentry->mnt_fsname);
-            item->entry.mnt_dir = strdup(mentry->mnt_dir);
-            item->entry.mnt_type = strdup(mentry->mnt_type);
-            item->entry.mnt_opts = strdup(mentry->mnt_opts);
-            list_add_tail(rw_entries, &item->list);
-        }
-    }
-    endmntent(fp);
-}
-
-static void free_entries(struct listnode* entries)
-{
-    struct listnode* node;
-    struct listnode* n;
-    list_for_each_safe(node, n, entries) {
-        mntent_list* item = node_to_item(node, mntent_list, list);
-        free(item->entry.mnt_fsname);
-        free(item->entry.mnt_dir);
-        free(item->entry.mnt_type);
-        free(item->entry.mnt_opts);
-        free(item);
-    }
-}
-
-static mntent_list* find_item(struct listnode* rw_entries, const char* fsname_to_find)
-{
-    struct listnode* node;
-    list_for_each(node, rw_entries) {
-        mntent_list* item = node_to_item(node, mntent_list, list);
-        if (!strcmp(item->entry.mnt_fsname, fsname_to_find)) {
-            return item;
-        }
-    }
-    return NULL;
-}
-
-/* Remounting filesystems read-only is difficult when there are files
- * opened for writing or pending deletes on the filesystem.  There is
- * no way to force the remount with the mount(2) syscall.  The magic sysrq
- * 'u' command does an emergency remount read-only on all writable filesystems
- * that have a block device (i.e. not tmpfs filesystems) by calling
- * emergency_remount(), which knows how to force the remount to read-only.
- * Unfortunately, that is asynchronous, and just schedules the work and
- * returns.  The best way to determine if it is done is to read /proc/mounts
- * repeatedly until there are no more writable filesystems mounted on
- * block devices.
- */
-static void remount_ro(void (*cb_on_remount)(const struct mntent*))
-{
-    int fd, cnt;
-    FILE* fp;
-    struct mntent* mentry;
-    struct listnode* node;
-
-    list_declare(rw_entries);
-    list_declare(ro_entries);
-
-    sync();
-    find_rw(&rw_entries);
-
-    /* Trigger the remount of the filesystems as read-only,
-     * which also marks them clean.
-     */
-    fd = TEMP_FAILURE_RETRY(open("/proc/sysrq-trigger", O_WRONLY));
-    if (fd < 0) {
-        KLOG_WARNING(TAG, "Failed to open sysrq-trigger.\n");
-        /* TODO: Try to remount each rw parition manually in readonly mode.
-         * This may succeed if no process is using the partition.
-         */
-        goto out;
-    }
-    if (TEMP_FAILURE_RETRY(write(fd, "u", 1)) != 1) {
-        close(fd);
-        KLOG_WARNING(TAG, "Failed to write to sysrq-trigger.\n");
-        /* TODO: The same. Manually remount the paritions. */
-        goto out;
-    }
-    close(fd);
-
-    /* Now poll /proc/mounts till it's done */
-    cnt = 0;
-    while (cnt < READONLY_CHECK_TIMES) {
-        if ((fp = setmntent("/proc/mounts", "r")) == NULL) {
-            /* If we can't read /proc/mounts, just give up. */
-            KLOG_WARNING(TAG, "Failed to open /proc/mounts.\n");
-            goto out;
-        }
-        while ((mentry = getmntent(fp)) != NULL) {
-            if (!is_block_device(mentry->mnt_fsname) || !hasmntopt(mentry, "ro")) {
-                continue;
-            }
-            mntent_list* item = find_item(&rw_entries, mentry->mnt_fsname);
-            if (item) {
-                /* |item| has now been ro remounted. */
-                list_remove(&item->list);
-                list_add_tail(&ro_entries, &item->list);
-            }
-        }
-        endmntent(fp);
-        if (list_empty(&rw_entries)) {
-            /* All rw block devices are now readonly. */
-            break;
-        }
-        TEMP_FAILURE_RETRY(
-            usleep(READONLY_CHECK_MS * 1000 / READONLY_CHECK_TIMES));
-        cnt++;
-    }
-
-    list_for_each(node, &rw_entries) {
-        mntent_list* item = node_to_item(node, mntent_list, list);
-        KLOG_WARNING(TAG, "Failed to remount %s in readonly mode.\n",
-                     item->entry.mnt_fsname);
-    }
-
-    if (cb_on_remount) {
-        list_for_each(node, &ro_entries) {
-            mntent_list* item = node_to_item(node, mntent_list, list);
-            cb_on_remount(&item->entry);
-        }
-    }
-
-out:
-    free_entries(&rw_entries);
-    free_entries(&ro_entries);
-}
-
-static void save_reboot_reason(int cmd, const char *arg)
-{
-    FILE *fp;
-    const char *reason = NULL;
-
-    fp = fopen(LAST_REBOOT_REASON_FILE, "w");
-    if (fp == NULL) {
-        KLOG_WARNING(TAG, "Error creating " LAST_REBOOT_REASON_FILE
-                     ": %s\n", strerror(errno));
-        return;
-    }
-    switch (cmd) {
-        case ANDROID_RB_RESTART:
-            reason = "restart";
-            break;
-
-        case ANDROID_RB_POWEROFF:
-            reason = "power-off";
-            break;
-
-        case ANDROID_RB_RESTART2:
-            reason = arg && strlen(arg) ? arg : "restart";
-            break;
-
-        case ANDROID_RB_THERMOFF:
-            reason = "thermal-shutdown";
-            break;
-
-        default:
-            fprintf(fp,"0x%08X\n", cmd);
-            break;
-    }
-
-    if (reason) {
-        if (fprintf(fp, "%s\n", reason) < 0) {
-             KLOG_WARNING(TAG, "Error writing " LAST_REBOOT_REASON_FILE
-                          ": %s\n", strerror(errno));
-        }
-    }
-
-    fclose(fp);
-}
-
-int android_reboot_with_callback(
-    int cmd, int flags __unused, const char *arg,
-    void (*cb_on_remount)(const struct mntent*))
-{
+int android_reboot(int cmd, int flags __unused, const char* arg) {
     int ret;
+    const char* restart_cmd = NULL;
+    char* prop_value;
 
-    save_reboot_reason(cmd, arg);
-    remount_ro(cb_on_remount);
     switch (cmd) {
-        case ANDROID_RB_RESTART:
-            ret = reboot(RB_AUTOBOOT);
-            break;
-
-        case ANDROID_RB_POWEROFF:
-            ret = reboot(RB_POWER_OFF);
-            break;
-
+        case ANDROID_RB_RESTART:  // deprecated
         case ANDROID_RB_RESTART2:
-            ret = syscall(__NR_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2,
-                           LINUX_REBOOT_CMD_RESTART2, arg);
+            restart_cmd = "reboot";
             break;
-
+        case ANDROID_RB_POWEROFF:
+            restart_cmd = "shutdown";
+            break;
         case ANDROID_RB_THERMOFF:
-            ret = reboot(RB_POWER_OFF);
+            restart_cmd = "thermal-shutdown";
             break;
-
-        default:
-            ret = -1;
     }
-
+    if (!restart_cmd) return -1;
+    if (arg) {
+        ret = asprintf(&prop_value, "%s,%s", restart_cmd, arg);
+    } else {
+        ret = asprintf(&prop_value, "%s", restart_cmd);
+    }
+    if (ret < 0) return -1;
+    ret = property_set(ANDROID_RB_PROPERTY, prop_value);
+    free(prop_value);
     return ret;
 }
-
-int android_reboot(int cmd, int flags, const char *arg)
-{
-    return android_reboot_with_callback(cmd, flags, arg, NULL);
-}
diff --git a/libcutils/canned_fs_config.c b/libcutils/canned_fs_config.c
index e0e6a34..96ca566 100644
--- a/libcutils/canned_fs_config.c
+++ b/libcutils/canned_fs_config.c
@@ -17,6 +17,7 @@
 #include <errno.h>
 #include <inttypes.h>
 #include <limits.h>
+#include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -41,7 +42,7 @@
 }
 
 int load_canned_fs_config(const char* fn) {
-    char line[PATH_MAX + 200];
+    char buf[PATH_MAX + 200];
     FILE* f;
 
     f = fopen(fn, "r");
@@ -50,17 +51,21 @@
         return -1;
     }
 
-    while (fgets(line, sizeof(line), f)) {
+    while (fgets(buf, sizeof(buf), f)) {
         Path* p;
         char* token;
+        char* line = buf;
+        bool rootdir;
 
         while (canned_used >= canned_alloc) {
             canned_alloc = (canned_alloc+1) * 2;
             canned_data = (Path*) realloc(canned_data, canned_alloc * sizeof(Path));
         }
         p = canned_data + canned_used;
-        p->path = strdup(strtok(line, " "));
-        p->uid = atoi(strtok(NULL, " "));
+        if (line[0] == '/') line++;
+        rootdir = line[0] == ' ';
+        p->path = strdup(rootdir ? "" : strtok(line, " "));
+        p->uid = atoi(strtok(rootdir ? line : NULL, " "));
         p->gid = atoi(strtok(NULL, " "));
         p->mode = strtol(strtok(NULL, " "), NULL, 8);   // mode is in octal
         p->capabilities = 0;
diff --git a/libcutils/fs_config.c b/libcutils/fs_config.c
index 1915ced..e4541f7 100644
--- a/libcutils/fs_config.c
+++ b/libcutils/fs_config.c
@@ -35,38 +35,25 @@
 
 #include <log/log.h>
 #include <private/android_filesystem_config.h>
+#include <private/fs_config.h>
 #include <utils/Compat.h>
 
 #ifndef O_BINARY
 #define O_BINARY 0
 #endif
 
-/* The following structure is stored little endian */
-struct fs_path_config_from_file {
-    uint16_t len;
-    uint16_t mode;
-    uint16_t uid;
-    uint16_t gid;
-    uint64_t capabilities;
-    char prefix[];
-} __attribute__((__aligned__(sizeof(uint64_t))));
-
 /* My kingdom for <endian.h> */
-static inline uint16_t get2LE(const uint8_t* src)
-{
-    return src[0] | (src[1] << 8);
-}
+static inline uint16_t get2LE(const uint8_t* src) { return src[0] | (src[1] << 8); }
 
-static inline uint64_t get8LE(const uint8_t* src)
-{
+static inline uint64_t get8LE(const uint8_t* src) {
     uint32_t low, high;
 
     low = src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
     high = src[4] | (src[5] << 8) | (src[6] << 16) | (src[7] << 24);
-    return ((uint64_t) high << 32) | (uint64_t) low;
+    return ((uint64_t)high << 32) | (uint64_t)low;
 }
 
-#define ALIGN(x, alignment) ( ((x) + ((alignment) - 1)) & ~((alignment) - 1) )
+#define ALIGN(x, alignment) (((x) + ((alignment)-1)) & ~((alignment)-1))
 
 /* Rules for directories.
 ** These rules are applied based on "first match", so they
@@ -75,35 +62,37 @@
 */
 
 static const struct fs_path_config android_dirs[] = {
-    { 00770, AID_SYSTEM, AID_CACHE,  0, "cache" },
-    { 00500, AID_ROOT,   AID_ROOT,   0, "config" },
-    { 00771, AID_SYSTEM, AID_SYSTEM, 0, "data/app" },
-    { 00771, AID_SYSTEM, AID_SYSTEM, 0, "data/app-private" },
-    { 00771, AID_SYSTEM, AID_SYSTEM, 0, "data/app-ephemeral" },
-    { 00771, AID_ROOT,   AID_ROOT,   0, "data/dalvik-cache" },
-    { 00771, AID_SYSTEM, AID_SYSTEM, 0, "data/data" },
-    { 00771, AID_SHELL,  AID_SHELL,  0, "data/local/tmp" },
-    { 00771, AID_SHELL,  AID_SHELL,  0, "data/local" },
-    { 01771, AID_SYSTEM, AID_MISC,   0, "data/misc" },
-    { 00770, AID_DHCP,   AID_DHCP,   0, "data/misc/dhcp" },
+    /* clang-format off */
+    { 00770, AID_SYSTEM,       AID_CACHE,        0, "cache" },
+    { 00500, AID_ROOT,         AID_ROOT,         0, "config" },
+    { 00771, AID_SYSTEM,       AID_SYSTEM,       0, "data/app" },
+    { 00771, AID_SYSTEM,       AID_SYSTEM,       0, "data/app-private" },
+    { 00771, AID_SYSTEM,       AID_SYSTEM,       0, "data/app-ephemeral" },
+    { 00771, AID_ROOT,         AID_ROOT,         0, "data/dalvik-cache" },
+    { 00771, AID_SYSTEM,       AID_SYSTEM,       0, "data/data" },
+    { 00771, AID_SHELL,        AID_SHELL,        0, "data/local/tmp" },
+    { 00771, AID_SHELL,        AID_SHELL,        0, "data/local" },
+    { 00770, AID_DHCP,         AID_DHCP,         0, "data/misc/dhcp" },
     { 00771, AID_SHARED_RELRO, AID_SHARED_RELRO, 0, "data/misc/shared_relro" },
-    { 00775, AID_MEDIA_RW, AID_MEDIA_RW, 0, "data/media" },
-    { 00775, AID_MEDIA_RW, AID_MEDIA_RW, 0, "data/media/Music" },
-    { 00750, AID_ROOT,   AID_SHELL,  0, "data/nativetest" },
-    { 00750, AID_ROOT,   AID_SHELL,  0, "data/nativetest64" },
-    { 00775, AID_ROOT,   AID_ROOT,   0, "data/preloads" },
-    { 00771, AID_SYSTEM, AID_SYSTEM, 0, "data" },
-    { 00755, AID_ROOT,   AID_SYSTEM, 0, "mnt" },
-    { 00755, AID_ROOT,   AID_ROOT,   0, "root" },
-    { 00750, AID_ROOT,   AID_SHELL,  0, "sbin" },
-    { 00751, AID_ROOT,   AID_SDCARD_R, 0, "storage" },
-    { 00755, AID_ROOT,   AID_SHELL,  0, "system/bin" },
-    { 00755, AID_ROOT,   AID_SHELL,  0, "system/vendor" },
-    { 00755, AID_ROOT,   AID_SHELL,  0, "system/xbin" },
-    { 00755, AID_ROOT,   AID_ROOT,   0, "system/etc/ppp" },
-    { 00755, AID_ROOT,   AID_SHELL,  0, "vendor" },
-    { 00777, AID_ROOT,   AID_ROOT,   0, "sdcard" },
-    { 00755, AID_ROOT,   AID_ROOT,   0, 0 },
+    { 01771, AID_SYSTEM,       AID_MISC,         0, "data/misc" },
+    { 00775, AID_MEDIA_RW,     AID_MEDIA_RW,     0, "data/media/Music" },
+    { 00775, AID_MEDIA_RW,     AID_MEDIA_RW,     0, "data/media" },
+    { 00750, AID_ROOT,         AID_SHELL,        0, "data/nativetest" },
+    { 00750, AID_ROOT,         AID_SHELL,        0, "data/nativetest64" },
+    { 00775, AID_ROOT,         AID_ROOT,         0, "data/preloads" },
+    { 00771, AID_SYSTEM,       AID_SYSTEM,       0, "data" },
+    { 00755, AID_ROOT,         AID_SYSTEM,       0, "mnt" },
+    { 00755, AID_ROOT,         AID_ROOT,         0, "root" },
+    { 00750, AID_ROOT,         AID_SHELL,        0, "sbin" },
+    { 00777, AID_ROOT,         AID_ROOT,         0, "sdcard" },
+    { 00751, AID_ROOT,         AID_SDCARD_R,     0, "storage" },
+    { 00755, AID_ROOT,         AID_SHELL,        0, "system/bin" },
+    { 00755, AID_ROOT,         AID_ROOT,         0, "system/etc/ppp" },
+    { 00755, AID_ROOT,         AID_SHELL,        0, "system/vendor" },
+    { 00755, AID_ROOT,         AID_SHELL,        0, "system/xbin" },
+    { 00755, AID_ROOT,         AID_SHELL,        0, "vendor" },
+    { 00755, AID_ROOT,         AID_ROOT,         0, 0 },
+    /* clang-format on */
 };
 
 /* Rules for files.
@@ -112,34 +101,87 @@
 ** way up to the root. Prefixes ending in * denotes wildcard
 ** and will allow partial matches.
 */
-static const char conf_dir[] = "/system/etc/fs_config_dirs";
-static const char conf_file[] = "/system/etc/fs_config_files";
+static const char sys_conf_dir[] = "/system/etc/fs_config_dirs";
+static const char sys_conf_file[] = "/system/etc/fs_config_files";
+/* No restrictions are placed on the vendor and oem file-system config files,
+ * although the developer is advised to restrict the scope to the /vendor or
+ * oem/ file-system since the intent is to provide support for customized
+ * portions of a separate vendor.img or oem.img.  Has to remain open so that
+ * customization can also land on /system/vendor, /system/oem or /system/odm.
+ * We expect build-time checking or filtering when constructing the associated
+ * fs_config_* files (see build/tools/fs_config/fs_config_generate.c)
+ */
+static const char ven_conf_dir[] = "/vendor/etc/fs_config_dirs";
+static const char ven_conf_file[] = "/vendor/etc/fs_config_files";
+static const char oem_conf_dir[] = "/oem/etc/fs_config_dirs";
+static const char oem_conf_file[] = "/oem/etc/fs_config_files";
+static const char odm_conf_dir[] = "/odm/etc/fs_config_dirs";
+static const char odm_conf_file[] = "/odm/etc/fs_config_files";
+static const char* conf[][2] = {
+    {sys_conf_file, sys_conf_dir},
+    {ven_conf_file, ven_conf_dir},
+    {oem_conf_file, oem_conf_dir},
+    {odm_conf_file, odm_conf_dir},
+};
 
 static const struct fs_path_config android_files[] = {
+    /* clang-format off */
+    { 00644, AID_SYSTEM,    AID_SYSTEM,    0, "data/app/*" },
+    { 00644, AID_SYSTEM,    AID_SYSTEM,    0, "data/app-ephemeral/*" },
+    { 00644, AID_SYSTEM,    AID_SYSTEM,    0, "data/app-private/*" },
+    { 00644, AID_APP,       AID_APP,       0, "data/data/*" },
+    { 00644, AID_MEDIA_RW,  AID_MEDIA_RW,  0, "data/media/*" },
+    { 00640, AID_ROOT,      AID_SHELL,     0, "data/nativetest/tests.txt" },
+    { 00640, AID_ROOT,      AID_SHELL,     0, "data/nativetest64/tests.txt" },
+    { 00750, AID_ROOT,      AID_SHELL,     0, "data/nativetest/*" },
+    { 00750, AID_ROOT,      AID_SHELL,     0, "data/nativetest64/*" },
+    { 00600, AID_ROOT,      AID_ROOT,      0, "default.prop" },
+    { 00600, AID_ROOT,      AID_ROOT,      0, "odm/build.prop" },
+    { 00600, AID_ROOT,      AID_ROOT,      0, "odm/default.prop" },
+    { 00444, AID_ROOT,      AID_ROOT,      0, odm_conf_dir + 1 },
+    { 00444, AID_ROOT,      AID_ROOT,      0, odm_conf_file + 1 },
+    { 00600, AID_ROOT,      AID_ROOT,      0, "system/odm/build.prop" },
+    { 00600, AID_ROOT,      AID_ROOT,      0, "system/odm/default.prop" },
+    { 00444, AID_ROOT,      AID_ROOT,      0, "system/odm/etc/fs_config_dirs" },
+    { 00444, AID_ROOT,      AID_ROOT,      0, "system/odm/etc/fs_config_files" },
+    { 00444, AID_ROOT,      AID_ROOT,      0, oem_conf_dir + 1 },
+    { 00444, AID_ROOT,      AID_ROOT,      0, oem_conf_file + 1 },
+    { 00444, AID_ROOT,      AID_ROOT,      0, "system/oem/etc/fs_config_dirs" },
+    { 00444, AID_ROOT,      AID_ROOT,      0, "system/oem/etc/fs_config_files" },
+    { 00750, AID_ROOT,      AID_SHELL,     0, "sbin/fs_mgr" },
+    { 00755, AID_ROOT,      AID_SHELL,     0, "system/bin/crash_dump32" },
+    { 00755, AID_ROOT,      AID_SHELL,     0, "system/bin/crash_dump64" },
+    { 00755, AID_ROOT,      AID_SHELL,     0, "system/bin/debuggerd" },
+    { 00750, AID_ROOT,      AID_ROOT,      0, "system/bin/install-recovery.sh" },
+    { 00700, AID_ROOT,      AID_ROOT,      0, "system/bin/secilc" },
+    { 00750, AID_ROOT,      AID_ROOT,      0, "system/bin/uncrypt" },
+    { 00600, AID_ROOT,      AID_ROOT,      0, "system/build.prop" },
+    { 00444, AID_ROOT,      AID_ROOT,      0, sys_conf_dir + 1 },
+    { 00444, AID_ROOT,      AID_ROOT,      0, sys_conf_file + 1 },
     { 00440, AID_ROOT,      AID_SHELL,     0, "system/etc/init.goldfish.rc" },
     { 00550, AID_ROOT,      AID_SHELL,     0, "system/etc/init.goldfish.sh" },
     { 00550, AID_ROOT,      AID_SHELL,     0, "system/etc/init.ril" },
     { 00555, AID_ROOT,      AID_ROOT,      0, "system/etc/ppp/*" },
     { 00555, AID_ROOT,      AID_ROOT,      0, "system/etc/rc.*" },
     { 00440, AID_ROOT,      AID_ROOT,      0, "system/etc/recovery.img" },
-    { 00444, AID_ROOT,      AID_ROOT,      0, conf_dir + 1 },
-    { 00444, AID_ROOT,      AID_ROOT,      0, conf_file + 1 },
-    { 00644, AID_SYSTEM,    AID_SYSTEM,    0, "data/app/*" },
-    { 00644, AID_MEDIA_RW,  AID_MEDIA_RW,  0, "data/media/*" },
-    { 00644, AID_SYSTEM,    AID_SYSTEM,    0, "data/app-private/*" },
-    { 00644, AID_SYSTEM,    AID_SYSTEM,    0, "data/app-ephemeral/*" },
-    { 00644, AID_APP,       AID_APP,       0, "data/data/*" },
-    { 00640, AID_ROOT,      AID_SHELL,     0, "data/nativetest/tests.txt" },
-    { 00640, AID_ROOT,      AID_SHELL,     0, "data/nativetest64/tests.txt" },
-    { 00750, AID_ROOT,      AID_SHELL,     0, "data/nativetest/*" },
-    { 00750, AID_ROOT,      AID_SHELL,     0, "data/nativetest64/*" },
+    { 00600, AID_ROOT,      AID_ROOT,      0, "system/vendor/build.prop" },
+    { 00600, AID_ROOT,      AID_ROOT,      0, "system/vendor/default.prop" },
+    { 00444, AID_ROOT,      AID_ROOT,      0, "system/vendor/etc/fs_config_dirs" },
+    { 00444, AID_ROOT,      AID_ROOT,      0, "system/vendor/etc/fs_config_files" },
+    { 00600, AID_ROOT,      AID_ROOT,      0, "vendor/build.prop" },
+    { 00600, AID_ROOT,      AID_ROOT,      0, "vendor/default.prop" },
+    { 00444, AID_ROOT,      AID_ROOT,      0, ven_conf_dir + 1 },
+    { 00444, AID_ROOT,      AID_ROOT,      0, ven_conf_file + 1 },
 
     /* the following two files are INTENTIONALLY set-uid, but they
      * are NOT included on user builds. */
-    { 04750, AID_ROOT,      AID_SHELL,     0, "system/xbin/su" },
     { 06755, AID_ROOT,      AID_ROOT,      0, "system/xbin/procmem" },
+    { 04750, AID_ROOT,      AID_SHELL,     0, "system/xbin/su" },
 
-    /* the following files have enhanced capabilities and ARE included in user builds. */
+    /* the following files have enhanced capabilities and ARE included
+     * in user builds. */
+    { 00700, AID_SYSTEM,    AID_SHELL,     CAP_MASK_LONG(CAP_BLOCK_SUSPEND),
+                                              "system/bin/inputflinger" },
     { 00550, AID_LOGD,      AID_LOGD,      CAP_MASK_LONG(CAP_SYSLOG) |
                                            CAP_MASK_LONG(CAP_AUDIT_CONTROL) |
                                            CAP_MASK_LONG(CAP_SETGID),
@@ -147,27 +189,35 @@
     { 00750, AID_ROOT,      AID_SHELL,     CAP_MASK_LONG(CAP_SETUID) |
                                            CAP_MASK_LONG(CAP_SETGID),
                                               "system/bin/run-as" },
-    { 00700, AID_SYSTEM,    AID_SHELL,     CAP_MASK_LONG(CAP_BLOCK_SUSPEND),
-                                              "system/bin/inputflinger" },
 
     /* Support FIFO scheduling mode in SurfaceFlinger. */
-    { 00755, AID_SYSTEM,    AID_GRAPHICS,     CAP_MASK_LONG(CAP_SYS_NICE), "system/bin/surfaceflinger" },
+    { 00755, AID_SYSTEM,    AID_GRAPHICS,  CAP_MASK_LONG(CAP_SYS_NICE),
+                                              "system/bin/surfaceflinger" },
 
     /* Support hostapd administering a network interface. */
     { 00755, AID_WIFI,      AID_WIFI,      CAP_MASK_LONG(CAP_NET_ADMIN) |
                                            CAP_MASK_LONG(CAP_NET_RAW),
                                               "system/bin/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) |
+                                           CAP_MASK_LONG(CAP_SYS_NICE),
+                                              "system/vendor/bin/hw/android.hardware.bluetooth@1.0-service" },
+    { 00700, AID_BLUETOOTH, AID_BLUETOOTH, CAP_MASK_LONG(CAP_NET_ADMIN) |
+                                           CAP_MASK_LONG(CAP_SYS_NICE),
+                                              "vendor/bin/hw/android.hardware.bluetooth@1.0-service" },
+
     /* Support wifi_hal_legacy administering a network interface. */
     { 00755, AID_WIFI,      AID_WIFI,      CAP_MASK_LONG(CAP_NET_ADMIN) |
                                            CAP_MASK_LONG(CAP_NET_RAW),
+                                              "system/vendor/bin/hw/android.hardware.wifi@1.0-service" },
+    { 00755, AID_WIFI,      AID_WIFI,      CAP_MASK_LONG(CAP_NET_ADMIN) |
+                                           CAP_MASK_LONG(CAP_NET_RAW),
                                               "vendor/bin/hw/android.hardware.wifi@1.0-service" },
 
-    /* Support Bluetooth legacy hal accessing /sys/class/rfkill */
-    { 00700, AID_BLUETOOTH, AID_BLUETOOTH, CAP_MASK_LONG(CAP_NET_ADMIN),
-                                              "vendor/bin/hw/android.hardware.bluetooth@1.0-service" },
-
-    /* A non-privileged zygote that spawns isolated processes for web rendering. */
+    /* A non-privileged zygote that spawns
+     * isolated processes for web rendering. */
     { 0750,  AID_ROOT,      AID_ROOT,      CAP_MASK_LONG(CAP_SETUID) |
                                            CAP_MASK_LONG(CAP_SETGID) |
                                            CAP_MASK_LONG(CAP_SETPCAP),
@@ -177,62 +227,52 @@
                                            CAP_MASK_LONG(CAP_SETPCAP),
                                               "system/bin/webview_zygote64" },
 
-    { 00755, AID_ROOT,      AID_SHELL,     0, "system/bin/crash_dump32" },
-    { 00755, AID_ROOT,      AID_SHELL,     0, "system/bin/crash_dump64" },
-    { 00755, AID_ROOT,      AID_SHELL,     0, "system/bin/debuggerd" },
-    { 00700, AID_ROOT,      AID_ROOT,      0, "system/bin/secilc" },
-    { 00750, AID_ROOT,      AID_ROOT,      0, "system/bin/uncrypt" },
-    { 00750, AID_ROOT,      AID_ROOT,      0, "system/bin/install-recovery.sh" },
+    /* generic defaults */
+    { 00755, AID_ROOT,      AID_ROOT,      0, "bin/*" },
+    { 00640, AID_ROOT,      AID_SHELL,     0, "fstab.*" },
+    { 00750, AID_ROOT,      AID_SHELL,     0, "init*" },
+    { 00750, AID_ROOT,      AID_SHELL,     0, "sbin/*" },
     { 00755, AID_ROOT,      AID_SHELL,     0, "system/bin/*" },
     { 00755, AID_ROOT,      AID_ROOT,      0, "system/lib/valgrind/*" },
     { 00755, AID_ROOT,      AID_ROOT,      0, "system/lib64/valgrind/*" },
-    { 00755, AID_ROOT,      AID_SHELL,     0, "system/xbin/*" },
     { 00755, AID_ROOT,      AID_SHELL,     0, "system/vendor/bin/*" },
     { 00755, AID_ROOT,      AID_SHELL,     0, "system/vendor/xbin/*" },
+    { 00755, AID_ROOT,      AID_SHELL,     0, "system/xbin/*" },
     { 00755, AID_ROOT,      AID_SHELL,     0, "vendor/bin/*" },
     { 00755, AID_ROOT,      AID_SHELL,     0, "vendor/xbin/*" },
-    { 00750, AID_ROOT,      AID_SHELL,     0, "sbin/*" },
-    { 00755, AID_ROOT,      AID_ROOT,      0, "bin/*" },
-    { 00750, AID_ROOT,      AID_SHELL,     0, "init*" },
-    { 00750, AID_ROOT,      AID_SHELL,     0, "sbin/fs_mgr" },
-    { 00640, AID_ROOT,      AID_SHELL,     0, "fstab.*" },
-    { 00600, AID_ROOT,      AID_ROOT,      0, "system/build.prop" },
-    { 00600, AID_ROOT,      AID_ROOT,      0, "vendor/build.prop" },
-    { 00600, AID_ROOT,      AID_ROOT,      0, "odm/build.prop" },
-    { 00600, AID_ROOT,      AID_ROOT,      0, "default.prop" },
-    { 00600, AID_ROOT,      AID_ROOT,      0, "vendor/default.prop" },
-    { 00600, AID_ROOT,      AID_ROOT,      0, "odm/default.prop" },
     { 00644, AID_ROOT,      AID_ROOT,      0, 0 },
+    /* clang-format on */
 };
 
-static int fs_config_open(int dir, const char *target_out_path)
-{
+static size_t strip(const char* path, size_t len, const char suffix[]) {
+    if (len < strlen(suffix)) return len;
+    if (strncmp(path + len - strlen(suffix), suffix, strlen(suffix))) return len;
+    return len - strlen(suffix);
+}
+
+static int fs_config_open(int dir, int which, const char* target_out_path) {
     int fd = -1;
 
     if (target_out_path && *target_out_path) {
-        /* target_out_path is the path to the directory holding content of system partition
-           but as we cannot guaranty it ends with '/system' we need this below skip_len logic */
-        char *name = NULL;
-        int target_out_path_len = strlen(target_out_path);
-        int skip_len = strlen("/system");
-
-        if (target_out_path[target_out_path_len] == '/') {
-            skip_len++;
-        }
-        if (asprintf(&name, "%s%s", target_out_path, (dir ? conf_dir : conf_file) + skip_len) != -1) {
+        /* target_out_path is the path to the directory holding content of
+         * system partition but as we cannot guarantee it ends with '/system'
+         * or with or without a trailing slash, need to strip them carefully. */
+        char* name = NULL;
+        size_t len = strlen(target_out_path);
+        len = strip(target_out_path, len, "/");
+        len = strip(target_out_path, len, "/system");
+        if (asprintf(&name, "%.*s%s", (int)len, target_out_path, conf[which][dir]) != -1) {
             fd = TEMP_FAILURE_RETRY(open(name, O_RDONLY | O_BINARY));
             free(name);
         }
     }
     if (fd < 0) {
-        fd = TEMP_FAILURE_RETRY(open(dir ? conf_dir : conf_file, O_RDONLY | O_BINARY));
+        fd = TEMP_FAILURE_RETRY(open(conf[which][dir], O_RDONLY | O_BINARY));
     }
     return fd;
 }
 
-static bool fs_config_cmp(bool dir, const char *prefix, size_t len,
-                                    const char *path, size_t plen)
-{
+static bool fs_config_cmp(bool dir, const char* prefix, size_t len, const char* path, size_t plen) {
     if (dir) {
         if (plen < len) {
             return false;
@@ -249,11 +289,10 @@
     return !strncmp(prefix, path, len);
 }
 
-void fs_config(const char *path, int dir, const char *target_out_path,
-               unsigned *uid, unsigned *gid, unsigned *mode, uint64_t *capabilities)
-{
-    const struct fs_path_config *pc;
-    int fd, plen;
+void fs_config(const char* path, int dir, const char* target_out_path, unsigned* uid, unsigned* gid,
+               unsigned* mode, uint64_t* capabilities) {
+    const struct fs_path_config* pc;
+    size_t which, plen;
 
     if (path[0] == '/') {
         path++;
@@ -261,41 +300,43 @@
 
     plen = strlen(path);
 
-    fd = fs_config_open(dir, target_out_path);
-    if (fd >= 0) {
+    for (which = 0; which < (sizeof(conf) / sizeof(conf[0])); ++which) {
         struct fs_path_config_from_file header;
 
+        int fd = fs_config_open(dir, which, target_out_path);
+        if (fd < 0) continue;
+
         while (TEMP_FAILURE_RETRY(read(fd, &header, sizeof(header))) == sizeof(header)) {
-            char *prefix;
-            uint16_t host_len = get2LE((const uint8_t *)&header.len);
+            char* prefix;
+            uint16_t host_len = get2LE((const uint8_t*)&header.len);
             ssize_t len, remainder = host_len - sizeof(header);
             if (remainder <= 0) {
-                ALOGE("%s len is corrupted", dir ? conf_dir : conf_file);
+                ALOGE("%s len is corrupted", conf[which][dir]);
                 break;
             }
             prefix = calloc(1, remainder);
             if (!prefix) {
-                ALOGE("%s out of memory", dir ? conf_dir : conf_file);
+                ALOGE("%s out of memory", conf[which][dir]);
                 break;
             }
             if (TEMP_FAILURE_RETRY(read(fd, prefix, remainder)) != remainder) {
                 free(prefix);
-                ALOGE("%s prefix is truncated", dir ? conf_dir : conf_file);
+                ALOGE("%s prefix is truncated", conf[which][dir]);
                 break;
             }
             len = strnlen(prefix, remainder);
             if (len >= remainder) { /* missing a terminating null */
                 free(prefix);
-                ALOGE("%s is corrupted", dir ? conf_dir : conf_file);
+                ALOGE("%s is corrupted", conf[which][dir]);
                 break;
             }
             if (fs_config_cmp(dir, prefix, len, path, plen)) {
                 free(prefix);
                 close(fd);
-                *uid = get2LE((const uint8_t *)&(header.uid));
-                *gid = get2LE((const uint8_t *)&(header.gid));
-                *mode = (*mode & (~07777)) | get2LE((const uint8_t *)&(header.mode));
-                *capabilities = get8LE((const uint8_t *)&(header.capabilities));
+                *uid = get2LE((const uint8_t*)&(header.uid));
+                *gid = get2LE((const uint8_t*)&(header.gid));
+                *mode = (*mode & (~07777)) | get2LE((const uint8_t*)&(header.mode));
+                *capabilities = get8LE((const uint8_t*)&(header.capabilities));
                 return;
             }
             free(prefix);
@@ -303,8 +344,7 @@
         close(fd);
     }
 
-    pc = dir ? android_dirs : android_files;
-    for(; pc->prefix; pc++){
+    for (pc = dir ? android_dirs : android_files; pc->prefix; pc++) {
         if (fs_config_cmp(dir, pc->prefix, strlen(pc->prefix), path, plen)) {
             break;
         }
@@ -315,9 +355,8 @@
     *capabilities = pc->capabilities;
 }
 
-ssize_t fs_config_generate(char *buffer, size_t length, const struct fs_path_config *pc)
-{
-    struct fs_path_config_from_file *p = (struct fs_path_config_from_file *)buffer;
+ssize_t fs_config_generate(char* buffer, size_t length, const struct fs_path_config* pc) {
+    struct fs_path_config_from_file* p = (struct fs_path_config_from_file*)buffer;
     size_t len = ALIGN(sizeof(*p) + strlen(pc->prefix) + 1, sizeof(uint64_t));
 
     if ((length < len) || (len > UINT16_MAX)) {
@@ -325,11 +364,11 @@
     }
     memset(p, 0, len);
     uint16_t host_len = len;
-    p->len = get2LE((const uint8_t *)&host_len);
-    p->mode = get2LE((const uint8_t *)&(pc->mode));
-    p->uid = get2LE((const uint8_t *)&(pc->uid));
-    p->gid = get2LE((const uint8_t *)&(pc->gid));
-    p->capabilities = get8LE((const uint8_t *)&(pc->capabilities));
+    p->len = get2LE((const uint8_t*)&host_len);
+    p->mode = get2LE((const uint8_t*)&(pc->mode));
+    p->uid = get2LE((const uint8_t*)&(pc->uid));
+    p->gid = get2LE((const uint8_t*)&(pc->gid));
+    p->capabilities = get8LE((const uint8_t*)&(pc->capabilities));
     strcpy(p->prefix, pc->prefix);
     return len;
 }
diff --git a/libcutils/include/cutils/android_reboot.h b/libcutils/include/cutils/android_reboot.h
index 2e3b429..716567a 100644
--- a/libcutils/include/cutils/android_reboot.h
+++ b/libcutils/include/cutils/android_reboot.h
@@ -17,12 +17,11 @@
 #ifndef __CUTILS_ANDROID_REBOOT_H__
 #define __CUTILS_ANDROID_REBOOT_H__
 
-#include <mntent.h>
 
 __BEGIN_DECLS
 
 /* Commands */
-#define ANDROID_RB_RESTART  0xDEAD0001
+#define ANDROID_RB_RESTART 0xDEAD0001 /* deprecated. Use RESTART2. */
 #define ANDROID_RB_POWEROFF 0xDEAD0002
 #define ANDROID_RB_RESTART2 0xDEAD0003
 #define ANDROID_RB_THERMOFF 0xDEAD0004
@@ -33,10 +32,12 @@
 /* Android reboot reason stored in this file */
 #define LAST_REBOOT_REASON_FILE "/data/misc/reboot/last_reboot_reason"
 
+/* Reboot or shutdown the system.
+ * This call uses ANDROID_RB_PROPERTY to request reboot to init process.
+ * Due to that, process calling this should have proper selinux permission
+ * to write to the property. Otherwise, the call will fail.
+ */
 int android_reboot(int cmd, int flags, const char *arg);
-int android_reboot_with_callback(
-    int cmd, int flags, const char *arg,
-    void (*cb_on_remount)(const struct mntent*));
 
 __END_DECLS
 
diff --git a/libcutils/include/cutils/bitops.h b/libcutils/include/cutils/bitops.h
index 045830d..38d2840 100644
--- a/libcutils/include/cutils/bitops.h
+++ b/libcutils/include/cutils/bitops.h
@@ -24,94 +24,15 @@
 
 __BEGIN_DECLS
 
-/*
- * Bitmask Operations
- *
- * Note this doesn't provide any locking/exclusion, and isn't atomic.
- * Additionally no bounds checking is done on the bitmask array.
- *
- * Example:
- *
- * int num_resources;
- * unsigned int resource_bits[BITS_TO_WORDS(num_resources)];
- * bitmask_init(resource_bits, num_resources);
- * ...
- * int bit = bitmask_ffz(resource_bits, num_resources);
- * bitmask_set(resource_bits, bit);
- * ...
- * if (bitmask_test(resource_bits, bit)) { ... }
- * ...
- * bitmask_clear(resource_bits, bit);
- *
- */
-
-#define BITS_PER_WORD    (sizeof(unsigned int) * 8)
-#define BITS_TO_WORDS(x) (((x) + BITS_PER_WORD - 1) / BITS_PER_WORD)
-#define BIT_IN_WORD(x)   ((x) % BITS_PER_WORD)
-#define BIT_WORD(x)      ((x) / BITS_PER_WORD)
-#define BIT_MASK(x)      (1 << BIT_IN_WORD(x))
-
-static inline void bitmask_init(unsigned int *bitmask, int num_bits)
-{
-    memset(bitmask, 0, BITS_TO_WORDS(num_bits)*sizeof(unsigned int));
-}
-
-static inline int bitmask_ffz(unsigned int *bitmask, int num_bits)
-{
-    int bit, result;
-    size_t i;
-
-    for (i = 0; i < BITS_TO_WORDS(num_bits); i++) {
-        bit = ffs(~bitmask[i]);
-        if (bit) {
-            // ffs is 1-indexed, return 0-indexed result
-            bit--;
-            result = BITS_PER_WORD * i + bit;
-            if (result >= num_bits)
-                return -1;
-            return result;
-        }
-    }
-    return -1;
-}
-
-static inline int bitmask_weight(unsigned int *bitmask, int num_bits)
-{
-    size_t i;
-    int weight = 0;
-
-    for (i = 0; i < BITS_TO_WORDS(num_bits); i++)
-        weight += __builtin_popcount(bitmask[i]);
-    return weight;
-}
-
-static inline void bitmask_set(unsigned int *bitmask, int bit)
-{
-    bitmask[BIT_WORD(bit)] |= BIT_MASK(bit);
-}
-
-static inline void bitmask_clear(unsigned int *bitmask, int bit)
-{
-    bitmask[BIT_WORD(bit)] &= ~BIT_MASK(bit);
-}
-
-static inline bool bitmask_test(unsigned int *bitmask, int bit)
-{
-    return bitmask[BIT_WORD(bit)] & BIT_MASK(bit);
-}
-
-static inline int popcount(unsigned int x)
-{
+static inline int popcount(unsigned int x) {
     return __builtin_popcount(x);
 }
 
-static inline int popcountl(unsigned long x)
-{
+static inline int popcountl(unsigned long x) {
     return __builtin_popcountl(x);
 }
 
-static inline int popcountll(unsigned long long x)
-{
+static inline int popcountll(unsigned long long x) {
     return __builtin_popcountll(x);
 }
 
diff --git a/libcutils/include/cutils/multiuser.h b/libcutils/include/cutils/multiuser.h
index 5bd9c7b..9a2305c 100644
--- a/libcutils/include/cutils/multiuser.h
+++ b/libcutils/include/cutils/multiuser.h
@@ -33,6 +33,7 @@
 
 extern gid_t multiuser_get_cache_gid(userid_t user_id, appid_t app_id);
 extern gid_t multiuser_get_ext_gid(userid_t user_id, appid_t app_id);
+extern gid_t multiuser_get_ext_cache_gid(userid_t user_id, appid_t app_id);
 extern gid_t multiuser_get_shared_gid(userid_t user_id, appid_t app_id);
 
 /* TODO: switch callers over to multiuser_get_shared_gid() */
diff --git a/libcutils/include/cutils/sockets.h b/libcutils/include/cutils/sockets.h
index d724dd6..b24468b 100644
--- a/libcutils/include/cutils/sockets.h
+++ b/libcutils/include/cutils/sockets.h
@@ -88,8 +88,6 @@
 cutils_socket_t socket_network_client(const char* host, int port, int type);
 int socket_network_client_timeout(const char* host, int port, int type,
                                   int timeout, int* getaddrinfo_error);
-int socket_loopback_server(int port, int type);
-int socket_loopback_server6(int port, int type);
 int socket_local_server(const char* name, int namespaceId, int type);
 int socket_local_server_bind(int s, const char* name, int namespaceId);
 int socket_local_client_connect(int fd, const char *name, int namespaceId,
diff --git a/include/private/android_filesystem_capability.h b/libcutils/include/private/android_filesystem_capability.h
similarity index 86%
rename from include/private/android_filesystem_capability.h
rename to libcutils/include/private/android_filesystem_capability.h
index b92d3db..0227b1d 100644
--- a/include/private/android_filesystem_capability.h
+++ b/libcutils/include/private/android_filesystem_capability.h
@@ -35,15 +35,15 @@
 #define _LINUX_CAPABILITY_U32S_3 2
 
 typedef struct __user_cap_header_struct {
- __u32 version;
- int pid;
-} __user *cap_user_header_t;
+    __u32 version;
+    int pid;
+} __user* cap_user_header_t;
 
 typedef struct __user_cap_data_struct {
- __u32 effective;
- __u32 permitted;
- __u32 inheritable;
-} __user *cap_user_data_t;
+    __u32 effective;
+    __u32 permitted;
+    __u32 inheritable;
+} __user* cap_user_data_t;
 
 #define VFS_CAP_REVISION_MASK 0xFF000000
 #define VFS_CAP_REVISION_SHIFT 24
@@ -51,20 +51,20 @@
 #define VFS_CAP_FLAGS_EFFECTIVE 0x000001
 #define VFS_CAP_REVISION_1 0x01000000
 #define VFS_CAP_U32_1 1
-#define XATTR_CAPS_SZ_1 (sizeof(__le32)*(1 + 2*VFS_CAP_U32_1))
+#define XATTR_CAPS_SZ_1 (sizeof(__le32) * (1 + 2 * VFS_CAP_U32_1))
 #define VFS_CAP_REVISION_2 0x02000000
 #define VFS_CAP_U32_2 2
-#define XATTR_CAPS_SZ_2 (sizeof(__le32)*(1 + 2*VFS_CAP_U32_2))
+#define XATTR_CAPS_SZ_2 (sizeof(__le32) * (1 + 2 * VFS_CAP_U32_2))
 #define XATTR_CAPS_SZ XATTR_CAPS_SZ_2
 #define VFS_CAP_U32 VFS_CAP_U32_2
 #define VFS_CAP_REVISION VFS_CAP_REVISION_2
 
 struct vfs_cap_data {
- __le32 magic_etc;
- struct {
- __le32 permitted;
- __le32 inheritable;
- } data[VFS_CAP_U32];
+    __le32 magic_etc;
+    struct {
+        __le32 permitted;
+        __le32 inheritable;
+    } data[VFS_CAP_U32];
 };
 
 #define _LINUX_CAPABILITY_VERSION _LINUX_CAPABILITY_VERSION_1
@@ -110,7 +110,7 @@
 #define CAP_LAST_CAP CAP_AUDIT_READ
 #define cap_valid(x) ((x) >= 0 && (x) <= CAP_LAST_CAP)
 #define CAP_TO_INDEX(x) ((x) >> 5)
-#define CAP_TO_MASK(x) (1 << ((x) & 31))
+#define CAP_TO_MASK(x) (1 << ((x)&31))
 
 #undef __user
 #undef __u32
diff --git a/libcutils/include/private/android_filesystem_config.h b/libcutils/include/private/android_filesystem_config.h
new file mode 100644
index 0000000..bbba853
--- /dev/null
+++ b/libcutils/include/private/android_filesystem_config.h
@@ -0,0 +1,226 @@
+/*
+ * Copyright (C) 2007 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.
+ */
+
+/* This file is used to define the properties of the filesystem
+** images generated by build tools (mkbootfs and mkyaffs2image) and
+** by the device side of adb.
+*/
+
+/*
+ * This file is consumed by build/tools/fs_config and is used
+ * for generating various files. Anything #define AID_<name>
+ * becomes the mapping for getpwnam/getpwuid, etc. The <name>
+ * field is lowercased.
+ * For example:
+ * #define AID_FOO_BAR 6666 becomes a friendly name of "foo_bar"
+ *
+ * The above holds true with the exception of:
+ *   mediacodec
+ *   mediaex
+ *   mediadrm
+ * Whose friendly names do not match the #define statements.
+ *
+ * Additionally, AID_OEM_RESERVED_START and AID_OEM_RESERVED_END
+ * can be used to define reserved OEM ranges used for sanity checks
+ * during the build process. The rules are, they must end with START/END
+ * The proper convention is incrementing a number like so:
+ * AID_OEM_RESERVED_START
+ * AID_OEM_RESERVED_1_START
+ * AID_OEM_RESERVED_2_START
+ * ...
+ * The same applies to the END.
+ * They are not required to be in order, but must not overlap each other and
+ * must define a START and END'ing range. START must be smaller than END.
+ */
+
+#ifndef _ANDROID_FILESYSTEM_CONFIG_H_
+#define _ANDROID_FILESYSTEM_CONFIG_H_
+
+#include <stdint.h>
+#include <sys/cdefs.h>
+#include <sys/types.h>
+
+#if defined(__ANDROID__)
+#include <linux/capability.h>
+#else
+#include "android_filesystem_capability.h"
+#endif
+
+#define CAP_MASK_LONG(cap_name) (1ULL << (cap_name))
+
+/* This is the master Users and Groups config for the platform.
+ * DO NOT EVER RENUMBER
+ */
+
+#define AID_ROOT 0 /* traditional unix root user */
+
+#define AID_SYSTEM 1000 /* system server */
+
+#define AID_RADIO 1001           /* telephony subsystem, RIL */
+#define AID_BLUETOOTH 1002       /* bluetooth subsystem */
+#define AID_GRAPHICS 1003        /* graphics devices */
+#define AID_INPUT 1004           /* input devices */
+#define AID_AUDIO 1005           /* audio devices */
+#define AID_CAMERA 1006          /* camera devices */
+#define AID_LOG 1007             /* log devices */
+#define AID_COMPASS 1008         /* compass device */
+#define AID_MOUNT 1009           /* mountd socket */
+#define AID_WIFI 1010            /* wifi subsystem */
+#define AID_ADB 1011             /* android debug bridge (adbd) */
+#define AID_INSTALL 1012         /* group for installing packages */
+#define AID_MEDIA 1013           /* mediaserver process */
+#define AID_DHCP 1014            /* dhcp client */
+#define AID_SDCARD_RW 1015       /* external storage write access */
+#define AID_VPN 1016             /* vpn system */
+#define AID_KEYSTORE 1017        /* keystore subsystem */
+#define AID_USB 1018             /* USB devices */
+#define AID_DRM 1019             /* DRM server */
+#define AID_MDNSR 1020           /* MulticastDNSResponder (service discovery) */
+#define AID_GPS 1021             /* GPS daemon */
+#define AID_UNUSED1 1022         /* deprecated, DO NOT USE */
+#define AID_MEDIA_RW 1023        /* internal media storage write access */
+#define AID_MTP 1024             /* MTP USB driver access */
+#define AID_UNUSED2 1025         /* deprecated, DO NOT USE */
+#define AID_DRMRPC 1026          /* group for drm rpc */
+#define AID_NFC 1027             /* nfc subsystem */
+#define AID_SDCARD_R 1028        /* external storage read access */
+#define AID_CLAT 1029            /* clat part of nat464 */
+#define AID_LOOP_RADIO 1030      /* loop radio devices */
+#define AID_MEDIA_DRM 1031       /* MediaDrm plugins */
+#define AID_PACKAGE_INFO 1032    /* access to installed package details */
+#define AID_SDCARD_PICS 1033     /* external storage photos access */
+#define AID_SDCARD_AV 1034       /* external storage audio/video access */
+#define AID_SDCARD_ALL 1035      /* access all users external storage */
+#define AID_LOGD 1036            /* log daemon */
+#define AID_SHARED_RELRO 1037    /* creator of shared GNU RELRO files */
+#define AID_DBUS 1038            /* dbus-daemon IPC broker process */
+#define AID_TLSDATE 1039         /* tlsdate unprivileged user */
+#define AID_MEDIA_EX 1040        /* mediaextractor process */
+#define AID_AUDIOSERVER 1041     /* audioserver process */
+#define AID_METRICS_COLL 1042    /* metrics_collector process */
+#define AID_METRICSD 1043        /* metricsd process */
+#define AID_WEBSERV 1044         /* webservd process */
+#define AID_DEBUGGERD 1045       /* debuggerd unprivileged user */
+#define AID_MEDIA_CODEC 1046     /* mediacodec process */
+#define AID_CAMERASERVER 1047    /* cameraserver process */
+#define AID_FIREWALL 1048        /* firewalld process */
+#define AID_TRUNKS 1049          /* trunksd process (TPM daemon) */
+#define AID_NVRAM 1050           /* Access-controlled NVRAM */
+#define AID_DNS 1051             /* DNS resolution daemon (system: netd) */
+#define AID_DNS_TETHER 1052      /* DNS resolution daemon (tether: dnsmasq) */
+#define AID_WEBVIEW_ZYGOTE 1053  /* WebView zygote process */
+#define AID_VEHICLE_NETWORK 1054 /* Vehicle network service */
+#define AID_MEDIA_AUDIO 1055     /* GID for audio files on internal media storage */
+#define AID_MEDIA_VIDEO 1056     /* GID for video files on internal media storage */
+#define AID_MEDIA_IMAGE 1057     /* GID for image files on internal media storage */
+#define AID_TOMBSTONED 1058      /* tombstoned user */
+#define AID_MEDIA_OBB 1059       /* GID for OBB files on internal media storage */
+#define AID_ESE 1060             /* embedded secure element (eSE) subsystem */
+#define AID_OTA_UPDATE 1061      /* resource tracking UID for OTA updates */
+/* Changes to this file must be made in AOSP, *not* in internal branches. */
+
+#define AID_SHELL 2000 /* adb and debug shell user */
+#define AID_CACHE 2001 /* cache access */
+#define AID_DIAG 2002  /* access to diagnostic resources */
+
+/* The range 2900-2999 is reserved for OEM, and must never be
+ * used here */
+#define AID_OEM_RESERVED_START 2900
+#define AID_OEM_RESERVED_END 2999
+
+/* The 3000 series are intended for use as supplemental group id's only.
+ * They indicate special Android capabilities that the kernel is aware of. */
+#define AID_NET_BT_ADMIN 3001 /* bluetooth: create any socket */
+#define AID_NET_BT 3002       /* bluetooth: create sco, rfcomm or l2cap sockets */
+#define AID_INET 3003         /* can create AF_INET and AF_INET6 sockets */
+#define AID_NET_RAW 3004      /* can create raw INET sockets */
+#define AID_NET_ADMIN 3005    /* can configure interfaces and routing tables. */
+#define AID_NET_BW_STATS 3006 /* read bandwidth statistics */
+#define AID_NET_BW_ACCT 3007  /* change bandwidth statistics accounting */
+#define AID_READPROC 3009     /* Allow /proc read access */
+#define AID_WAKELOCK 3010     /* Allow system wakelock read/write access */
+
+/* The range 5000-5999 is also reserved for OEM, and must never be used here. */
+#define AID_OEM_RESERVED_2_START 5000
+#define AID_OEM_RESERVED_2_END 5999
+
+#define AID_EVERYBODY 9997 /* shared between all apps in the same profile */
+#define AID_MISC 9998      /* access to misc storage */
+#define AID_NOBODY 9999
+
+#define AID_APP 10000       /* TODO: switch users over to AID_APP_START */
+#define AID_APP_START 10000 /* first app user */
+#define AID_APP_END 19999   /* last app user */
+
+#define AID_CACHE_GID_START 20000 /* start of gids for apps to mark cached data */
+#define AID_CACHE_GID_END 29999   /* end of gids for apps to mark cached data */
+
+#define AID_EXT_GID_START 30000 /* start of gids for apps to mark external data */
+#define AID_EXT_GID_END 39999   /* end of gids for apps to mark external data */
+
+#define AID_EXT_CACHE_GID_START 40000 /* start of gids for apps to mark external cached data */
+#define AID_EXT_CACHE_GID_END 49999   /* end of gids for apps to mark external cached data */
+
+#define AID_SHARED_GID_START 50000 /* start of gids for apps in each user to share */
+#define AID_SHARED_GID_END 59999   /* end of gids for apps in each user to share */
+
+#define AID_ISOLATED_START 99000 /* start of uids for fully isolated sandboxed processes */
+#define AID_ISOLATED_END 99999   /* end of uids for fully isolated sandboxed processes */
+
+#define AID_USER 100000        /* TODO: switch users over to AID_USER_OFFSET */
+#define AID_USER_OFFSET 100000 /* offset for uid ranges for each user */
+
+/*
+ * android_ids has moved to pwd/grp functionality.
+ * If you need to add one, the structure is now
+ * auto-generated based on the AID_ constraints
+ * documented at the top of this header file.
+ * Also see build/tools/fs_config for more details.
+ */
+
+#if !defined(EXCLUDE_FS_CONFIG_STRUCTURES)
+
+struct fs_path_config {
+    unsigned mode;
+    unsigned uid;
+    unsigned gid;
+    uint64_t capabilities;
+    const char* prefix;
+};
+
+/* Rules for directories and files has moved to system/code/libcutils/fs_config.c */
+
+__BEGIN_DECLS
+
+/*
+ * Used in:
+ *  build/tools/fs_config/fs_config.c
+ *  build/tools/fs_get_stats/fs_get_stats.c
+ *  system/extras/ext4_utils/make_ext4fs_main.c
+ *  external/squashfs-tools/squashfs-tools/android.c
+ *  system/core/cpio/mkbootfs.c
+ *  system/core/adb/file_sync_service.cpp
+ *  system/extras/ext4_utils/canned_fs_config.c
+ */
+void fs_config(const char* path, int dir, const char* target_out_path, unsigned* uid, unsigned* gid,
+               unsigned* mode, uint64_t* capabilities);
+
+ssize_t fs_config_generate(char* buffer, size_t length, const struct fs_path_config* pc);
+
+__END_DECLS
+
+#endif
+#endif
diff --git a/include/private/canned_fs_config.h b/libcutils/include/private/canned_fs_config.h
similarity index 88%
rename from include/private/canned_fs_config.h
rename to libcutils/include/private/canned_fs_config.h
index d9f51ca..71e1537 100644
--- a/include/private/canned_fs_config.h
+++ b/libcutils/include/private/canned_fs_config.h
@@ -20,7 +20,7 @@
 #include <inttypes.h>
 
 int load_canned_fs_config(const char* fn);
-void canned_fs_config(const char* path, int dir, const char* target_out_path,
-                      unsigned* uid, unsigned* gid, unsigned* mode, uint64_t* capabilities);
+void canned_fs_config(const char* path, int dir, const char* target_out_path, unsigned* uid,
+                      unsigned* gid, unsigned* mode, uint64_t* capabilities);
 
 #endif
diff --git a/libcutils/include/private/fs_config.h b/libcutils/include/private/fs_config.h
new file mode 100644
index 0000000..7dad668
--- /dev/null
+++ b/libcutils/include/private/fs_config.h
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2007 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 _LIBS_CUTILS_PRIVATE_FS_CONFIG_H
+#define _LIBS_CUTILS_PRIVATE_FS_CONFIG_H
+
+#include <stdint.h>
+
+/*
+ * binary format for the runtime <partition>/etc/fs_config_(dirs|files)
+ * filesystem override files.
+ */
+
+/* The following structure is stored little endian */
+struct fs_path_config_from_file {
+    uint16_t len;
+    uint16_t mode;
+    uint16_t uid;
+    uint16_t gid;
+    uint64_t capabilities;
+    char prefix[];
+} __attribute__((__aligned__(sizeof(uint64_t))));
+
+#endif /* _LIBS_CUTILS_PRIVATE_FS_CONFIG_H */
diff --git a/libcutils/include_vndk/cutils/log.h b/libcutils/include_vndk/cutils/log.h
index ae74024..21dc11e 100644
--- a/libcutils/include_vndk/cutils/log.h
+++ b/libcutils/include_vndk/cutils/log.h
@@ -16,6 +16,32 @@
 */
 #ifndef _LIBS_CUTIL_LOG_H
 #define _LIBS_CUTIL_LOG_H
-#warning "Deprecated: don't include cutils/log.h, use either android/log.h or log/log.h"
+
+/* We do not know if developer wanted log/log.h or subset android/log.h */
 #include <log/log.h>
+
+#if defined(__GNUC__)
+#if defined( __clang__)
+#pragma GCC diagnostic push
+#pragma GCC diagnostic warning "-W#warnings"
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wpedantic"
+#elif (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR > 9))
+#pragma GCC diagnostic push
+#pragma GCC diagnostic warning "-W#warnings"
+#else
+#pragma GCC diagnostic push
+#pragma GCC diagnostic warning "-Wcpp"
+#endif
+#endif
+
+#warning "Deprecated: don't include cutils/log.h, use either android/log.h or log/log.h"
+
+#if defined(__GNUC__)
+#if defined( __clang__)
+#pragma clang diagnostic pop
+#endif
+#pragma GCC diagnostic pop
+#endif
+
 #endif /* _LIBS_CUTIL_LOG_H */
diff --git a/libcutils/include_vndk/private b/libcutils/include_vndk/private
new file mode 120000
index 0000000..2245a85
--- /dev/null
+++ b/libcutils/include_vndk/private
@@ -0,0 +1 @@
+../include/private
\ No newline at end of file
diff --git a/libcutils/multiuser.c b/libcutils/multiuser.c
index 08d4d6c..61403f4 100644
--- a/libcutils/multiuser.c
+++ b/libcutils/multiuser.c
@@ -45,6 +45,14 @@
     }
 }
 
+gid_t multiuser_get_ext_cache_gid(userid_t user_id, appid_t app_id) {
+    if (app_id >= AID_APP_START && app_id <= AID_APP_END) {
+        return multiuser_get_uid(user_id, (app_id - AID_APP_START) + AID_EXT_CACHE_GID_START);
+    } else {
+        return -1;
+    }
+}
+
 gid_t multiuser_get_shared_gid(userid_t user_id, appid_t app_id) {
     if (app_id >= AID_APP_START && app_id <= AID_APP_END) {
         return multiuser_get_uid(user_id, (app_id - AID_APP_START) + AID_SHARED_GID_START);
diff --git a/libcutils/native_handle.c b/libcutils/native_handle.c
index 9f4840a..95bbc41 100644
--- a/libcutils/native_handle.c
+++ b/libcutils/native_handle.c
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-#define LOG_TAG "NativeHandle"
+#include <cutils/native_handle.h>
 
 #include <errno.h>
 #include <stdint.h>
@@ -22,15 +22,12 @@
 #include <string.h>
 #include <unistd.h>
 
-#include <android/log.h>
-#include <cutils/native_handle.h>
-
 static const int kMaxNativeFds = 1024;
 static const int kMaxNativeInts = 1024;
 
-native_handle_t* native_handle_init(char* storage, int numFds, int numInts)
-{
+native_handle_t* native_handle_init(char* storage, int numFds, int numInts) {
     if ((uintptr_t) storage % alignof(native_handle_t)) {
+        errno = EINVAL;
         return NULL;
     }
 
@@ -38,13 +35,12 @@
     handle->version = sizeof(native_handle_t);
     handle->numFds = numFds;
     handle->numInts = numInts;
-
     return handle;
 }
 
-native_handle_t* native_handle_create(int numFds, int numInts)
-{
+native_handle_t* native_handle_create(int numFds, int numInts) {
     if (numFds < 0 || numInts < 0 || numFds > kMaxNativeFds || numInts > kMaxNativeInts) {
+        errno = EINVAL;
         return NULL;
     }
 
@@ -58,14 +54,13 @@
     return h;
 }
 
-native_handle_t* native_handle_clone(const native_handle_t* handle)
-{
+native_handle_t* native_handle_clone(const native_handle_t* handle) {
     native_handle_t* clone = native_handle_create(handle->numFds, handle->numInts);
-    int i;
+    if (clone == NULL) return NULL;
 
-    for (i = 0; i < handle->numFds; i++) {
+    for (int i = 0; i < handle->numFds; i++) {
         clone->data[i] = dup(handle->data[i]);
-        if (clone->data[i] < 0) {
+        if (clone->data[i] == -1) {
             clone->numFds = i;
             native_handle_close(clone);
             native_handle_delete(clone);
@@ -74,30 +69,27 @@
     }
 
     memcpy(&clone->data[handle->numFds], &handle->data[handle->numFds],
-            sizeof(int) * handle->numInts);
+           sizeof(int) * handle->numInts);
 
     return clone;
 }
 
-int native_handle_delete(native_handle_t* h)
-{
+int native_handle_delete(native_handle_t* h) {
     if (h) {
-        if (h->version != sizeof(native_handle_t))
-            return -EINVAL;
+        if (h->version != sizeof(native_handle_t)) return -EINVAL;
         free(h);
     }
     return 0;
 }
 
-int native_handle_close(const native_handle_t* h)
-{
-    if (h->version != sizeof(native_handle_t))
-        return -EINVAL;
+int native_handle_close(const native_handle_t* h) {
+    if (h->version != sizeof(native_handle_t)) return -EINVAL;
 
+    int saved_errno = errno;
     const int numFds = h->numFds;
-    int i;
-    for (i=0 ; i<numFds ; i++) {
+    for (int i = 0; i < numFds; ++i) {
         close(h->data[i]);
     }
+    errno = saved_errno;
     return 0;
 }
diff --git a/libcutils/sched_policy.cpp b/libcutils/sched_policy.cpp
index 7e3ad59..e29a844 100644
--- a/libcutils/sched_policy.cpp
+++ b/libcutils/sched_policy.cpp
@@ -28,6 +28,13 @@
 
 #define UNUSED __attribute__((__unused__))
 
+#ifndef SLOGE
+#define SLOGE ALOGE
+#endif
+#ifndef SLOGW
+#define SLOGW ALOGW
+#endif
+
 /* Re-map SP_DEFAULT to the system default policy, and leave other values unchanged.
  * Call this any place a SchedPolicy is used as an input parameter.
  * Returns the possibly re-mapped policy.
@@ -51,13 +58,8 @@
 
 static pthread_once_t the_once = PTHREAD_ONCE_INIT;
 
-static int __sys_supports_schedgroups = -1;
 static int __sys_supports_timerslack = -1;
 
-// File descriptors open to /dev/cpuctl/../tasks, setup by initialize, or -1 on error.
-static int bg_cgroup_fd = -1;
-static int fg_cgroup_fd = -1;
-
 // File descriptors open to /dev/cpuset/../tasks, setup by initialize, or -1 on error
 static int system_bg_cpuset_fd = -1;
 static int bg_cpuset_fd = -1;
@@ -151,23 +153,6 @@
 
 static void __initialize() {
     const char* filename;
-    if (!access("/dev/cpuctl/tasks", W_OK)) {
-        __sys_supports_schedgroups = 1;
-
-        filename = "/dev/cpuctl/tasks";
-        fg_cgroup_fd = open(filename, O_WRONLY | O_CLOEXEC);
-        if (fg_cgroup_fd < 0) {
-            SLOGE("open of %s failed: %s\n", filename, strerror(errno));
-        }
-
-        filename = "/dev/cpuctl/bg_non_interactive/tasks";
-        bg_cgroup_fd = open(filename, O_WRONLY | O_CLOEXEC);
-        if (bg_cgroup_fd < 0) {
-            SLOGE("open of %s failed: %s\n", filename, strerror(errno));
-        }
-    } else {
-        __sys_supports_schedgroups = 0;
-    }
 
     if (cpusets_enabled()) {
         if (!access("/dev/cpuset/tasks", W_OK)) {
@@ -276,48 +261,28 @@
     }
     pthread_once(&the_once, __initialize);
 
-    if (__sys_supports_schedgroups) {
-        char grpBuf[32];
+    char grpBuf[32];
 
-        if (cpusets_enabled()) {
-            if (getCGroupSubsys(tid, "cpuset", grpBuf, sizeof(grpBuf)) < 0)
-                return -1;
-            if (grpBuf[0] == '\0') {
-                *policy = SP_FOREGROUND;
-            } else if (!strcmp(grpBuf, "foreground")) {
-                *policy = SP_FOREGROUND;
-            } else if (!strcmp(grpBuf, "background")) {
-                *policy = SP_BACKGROUND;
-            } else if (!strcmp(grpBuf, "top-app")) {
-                *policy = SP_TOP_APP;
-            } else {
-                errno = ERANGE;
-                return -1;
-            }
-        } else {
-            if (getCGroupSubsys(tid, "cpu", grpBuf, sizeof(grpBuf)) < 0)
-                return -1;
-            if (grpBuf[0] == '\0') {
-                *policy = SP_FOREGROUND;
-            } else if (!strcmp(grpBuf, "bg_non_interactive")) {
-                *policy = SP_BACKGROUND;
-            } else {
-                errno = ERANGE;
-                return -1;
-            }
-        }
+    grpBuf[0] = '\0';
+    if (schedboost_enabled()) {
+        if (getCGroupSubsys(tid, "schedtune", grpBuf, sizeof(grpBuf)) < 0) return -1;
+    }
+    if ((grpBuf[0] == '\0') && cpusets_enabled()) {
+        if (getCGroupSubsys(tid, "cpuset", grpBuf, sizeof(grpBuf)) < 0) return -1;
+    }
+    if (grpBuf[0] == '\0') {
+        *policy = SP_FOREGROUND;
+    } else if (!strcmp(grpBuf, "foreground")) {
+        *policy = SP_FOREGROUND;
+    } else if (!strcmp(grpBuf, "system-background")) {
+        *policy = SP_SYSTEM;
+    } else if (!strcmp(grpBuf, "background")) {
+        *policy = SP_BACKGROUND;
+    } else if (!strcmp(grpBuf, "top-app")) {
+        *policy = SP_TOP_APP;
     } else {
-        int rc = sched_getscheduler(tid);
-        if (rc < 0)
-            return -1;
-        else if (rc == SCHED_NORMAL)
-            *policy = SP_FOREGROUND;
-        else if (rc == SCHED_BATCH)
-            *policy = SP_BACKGROUND;
-        else {
-            errno = ERANGE;
-            return -1;
-        }
+        errno = ERANGE;
+        return -1;
     }
     return 0;
 }
@@ -378,16 +343,25 @@
 static void set_timerslack_ns(int tid, unsigned long long slack) {
     // v4.6+ kernels support the /proc/<tid>/timerslack_ns interface.
     // TODO: once we've backported this, log if the open(2) fails.
-    char buf[64];
-    snprintf(buf, sizeof(buf), "/proc/%d/timerslack_ns", tid);
-    int fd = open(buf, O_WRONLY | O_CLOEXEC);
-    if (fd != -1) {
-        int len = snprintf(buf, sizeof(buf), "%llu", slack);
-        if (write(fd, buf, len) != len) {
-            SLOGE("set_timerslack_ns write failed: %s\n", strerror(errno));
+    if (__sys_supports_timerslack) {
+        char buf[64];
+        snprintf(buf, sizeof(buf), "/proc/%d/timerslack_ns", tid);
+        int fd = open(buf, O_WRONLY | O_CLOEXEC);
+        if (fd != -1) {
+            int len = snprintf(buf, sizeof(buf), "%llu", slack);
+            if (write(fd, buf, len) != len) {
+                SLOGE("set_timerslack_ns write failed: %s\n", strerror(errno));
+            }
+            close(fd);
+            return;
         }
-        close(fd);
-        return;
+    }
+
+    // TODO: Remove when /proc/<tid>/timerslack_ns interface is backported.
+    if ((tid == 0) || (tid == gettid())) {
+        if (prctl(PR_SET_TIMERSLACK, slack) == -1) {
+            SLOGE("set_timerslack_ns prctl failed: %s\n", strerror(errno));
+        }
     }
 }
 
@@ -440,55 +414,33 @@
     }
 #endif
 
-    if (__sys_supports_schedgroups) {
-        int fd = -1;
+    if (schedboost_enabled()) {
         int boost_fd = -1;
         switch (policy) {
         case SP_BACKGROUND:
-            fd = bg_cgroup_fd;
             boost_fd = bg_schedboost_fd;
             break;
         case SP_FOREGROUND:
         case SP_AUDIO_APP:
         case SP_AUDIO_SYS:
-            fd = fg_cgroup_fd;
             boost_fd = fg_schedboost_fd;
             break;
         case SP_TOP_APP:
-            fd = fg_cgroup_fd;
             boost_fd = ta_schedboost_fd;
             break;
         default:
-            fd = -1;
             boost_fd = -1;
             break;
         }
 
-        if (add_tid_to_cgroup(tid, fd) != 0) {
+        if (boost_fd > 0 && add_tid_to_cgroup(tid, boost_fd) != 0) {
             if (errno != ESRCH && errno != ENOENT)
                 return -errno;
         }
 
-        if (schedboost_enabled()) {
-            if (boost_fd > 0 && add_tid_to_cgroup(tid, boost_fd) != 0) {
-                if (errno != ESRCH && errno != ENOENT)
-                    return -errno;
-            }
-        }
-    } else {
-        struct sched_param param;
-
-        param.sched_priority = 0;
-        sched_setscheduler(tid,
-                           (policy == SP_BACKGROUND) ?
-                           SCHED_BATCH : SCHED_NORMAL,
-                           &param);
     }
 
-    if (__sys_supports_timerslack) {
-        set_timerslack_ns(tid, policy == SP_BACKGROUND ?
-                               TIMER_SLACK_BG : TIMER_SLACK_FG);
-    }
+    set_timerslack_ns(tid, policy == SP_BACKGROUND ? TIMER_SLACK_BG : TIMER_SLACK_FG);
 
     return 0;
 }
diff --git a/libcutils/socket_loopback_server_unix.c b/libcutils/socket_loopback_server_unix.c
deleted file mode 100644
index 7b92fd6..0000000
--- a/libcutils/socket_loopback_server_unix.c
+++ /dev/null
@@ -1,88 +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.
-*/
-
-#include <errno.h>
-#include <stddef.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-#define LISTEN_BACKLOG 4
-
-#if !defined(_WIN32)
-#include <sys/socket.h>
-#include <sys/select.h>
-#include <sys/types.h>
-#include <netinet/in.h>
-#endif
-
-#include <cutils/sockets.h>
-
-static int _socket_loopback_server(int family, int type, struct sockaddr * addr, size_t size)
-{
-    int s, n;
-
-    s = socket(family, type, 0);
-    if(s < 0)
-        return -1;
-
-    n = 1;
-    setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *) &n, sizeof(n));
-
-    if(bind(s, addr, size) < 0) {
-        close(s);
-        return -1;
-    }
-
-    if (type == SOCK_STREAM) {
-        int ret;
-
-        ret = listen(s, LISTEN_BACKLOG);
-
-        if (ret < 0) {
-            close(s);
-            return -1;
-        }
-    }
-
-    return s;
-}
-
-/* open listen() port on loopback IPv6 interface */
-int socket_loopback_server6(int port, int type)
-{
-    struct sockaddr_in6 addr;
-
-    memset(&addr, 0, sizeof(addr));
-    addr.sin6_family = AF_INET6;
-    addr.sin6_port = htons(port);
-    addr.sin6_addr = in6addr_loopback;
-
-    return _socket_loopback_server(AF_INET6, type, (struct sockaddr *) &addr, sizeof(addr));
-}
-
-/* open listen() port on loopback interface */
-int socket_loopback_server(int port, int type)
-{
-    struct sockaddr_in addr;
-
-    memset(&addr, 0, sizeof(addr));
-    addr.sin_family = AF_INET;
-    addr.sin_port = htons(port);
-    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
-
-    return _socket_loopback_server(AF_INET, type, (struct sockaddr *) &addr, sizeof(addr));
-}
diff --git a/libcutils/tests/Android.bp b/libcutils/tests/Android.bp
index 718d76b..a0b1d7b 100644
--- a/libcutils/tests/Android.bp
+++ b/libcutils/tests/Android.bp
@@ -62,6 +62,7 @@
 
 cc_test {
     name: "libcutils_test",
+    test_suites: ["device-tests"],
     defaults: ["libcutils_test_default"],
     host_supported: true,
     shared_libs: test_libraries,
@@ -69,6 +70,7 @@
 
 cc_test {
     name: "libcutils_test_static",
+    test_suites: ["device-tests"],
     defaults: ["libcutils_test_default"],
     static_libs: ["libc"] + test_libraries,
     stl: "libc++_static",
diff --git a/libcutils/tests/AndroidTest.xml b/libcutils/tests/AndroidTest.xml
new file mode 100644
index 0000000..dd7aca2
--- /dev/null
+++ b/libcutils/tests/AndroidTest.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 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.
+-->
+<configuration description="Config for libcutils_test">
+    <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
+        <option name="cleanup" value="true" />
+        <option name="push" value="libcutils_test->/data/local/tmp/libcutils_test" />
+    </target_preparer>
+    <option name="test-suite-tag" value="apct" />
+    <test class="com.android.tradefed.testtype.GTest" >
+        <option name="native-test-device-path" value="/data/local/tmp" />
+        <option name="module-name" value="libcutils_test" />
+    </test>
+</configuration>
\ No newline at end of file
diff --git a/libcutils/tests/multiuser_test.cpp b/libcutils/tests/multiuser_test.cpp
index ae5c416..2f9d854 100644
--- a/libcutils/tests/multiuser_test.cpp
+++ b/libcutils/tests/multiuser_test.cpp
@@ -68,6 +68,14 @@
     EXPECT_EQ(1030000U, multiuser_get_ext_gid(10, 10000));
 }
 
+TEST(MultiuserTest, TestExtCache) {
+    EXPECT_EQ(ERR_GID, multiuser_get_ext_cache_gid(0, 0));
+    EXPECT_EQ(ERR_GID, multiuser_get_ext_cache_gid(0, 1000));
+    EXPECT_EQ(40000U, multiuser_get_ext_cache_gid(0, 10000));
+    EXPECT_EQ(ERR_GID, multiuser_get_ext_cache_gid(0, 50000));
+    EXPECT_EQ(1040000U, multiuser_get_ext_cache_gid(10, 10000));
+}
+
 TEST(MultiuserTest, TestShared) {
     EXPECT_EQ(ERR_GID, multiuser_get_shared_gid(0, 0));
     EXPECT_EQ(ERR_GID, multiuser_get_shared_gid(0, 1000));
diff --git a/libcutils/trace-dev.c b/libcutils/trace-dev.c
index 113f423..d45e5a9 100644
--- a/libcutils/trace-dev.c
+++ b/libcutils/trace-dev.c
@@ -29,7 +29,8 @@
 #include <cutils/compiler.h>
 #include <cutils/properties.h>
 #include <cutils/trace.h>
-#include <private/android_logger.h>
+#include <log/log.h>
+#include <log/log_properties.h>
 
 /**
  * Maximum size of a message that can be logged to the trace buffer.
diff --git a/liblog/Android.bp b/liblog/Android.bp
index bb8c3af..e74aa82 100644
--- a/liblog/Android.bp
+++ b/liblog/Android.bp
@@ -107,14 +107,16 @@
     license: "NOTICE",
 }
 
-cc_library_headers {
-    name: "liblog_vndk_headers",
-    export_include_dirs: ["include_vndk"],
-}
-
 ndk_library {
-    name: "liblog.ndk",
+    name: "liblog",
     symbol_file: "liblog.map.txt",
     first_version: "9",
     unversioned_until: "current",
 }
+
+llndk_library {
+    name: "liblog",
+    symbol_file: "liblog.map.txt",
+    unversioned: true,
+    export_include_dirs: ["include_vndk"],
+}
diff --git a/liblog/event.logtags b/liblog/event.logtags
index 301e885..0a3b650 100644
--- a/liblog/event.logtags
+++ b/liblog/event.logtags
@@ -29,6 +29,7 @@
 # 4: Number of allocations
 # 5: Id
 # 6: Percent
+# s: Number of seconds (monotonic time)
 # Default value for data of type int/long is 2 (bytes).
 #
 # TODO: generate ".java" and ".h" files with integer constants from this file.
diff --git a/liblog/event_tag_map.cpp b/liblog/event_tag_map.cpp
index bdad2c2..5fc7e35 100644
--- a/liblog/event_tag_map.cpp
+++ b/liblog/event_tag_map.cpp
@@ -31,6 +31,7 @@
 #include <unordered_map>
 
 #include <log/event_tag_map.h>
+#include <log/log_properties.h>
 #include <private/android_logger.h>
 #include <utils/FastStrcmp.h>
 #include <utils/RWLock.h>
@@ -229,9 +230,16 @@
   return it->second;
 }
 
+// The position after the end of a valid section of the tag string,
+// caller makes sure delimited appropriately.
+static const char* endOfTag(const char* cp) {
+  while (*cp && (isalnum(*cp) || strchr("_.-@,", *cp))) ++cp;
+  return cp;
+}
+
 // Scan one tag line.
 //
-// "*pData" should be pointing to the first digit in the tag number.  On
+// "pData" should be pointing to the first digit in the tag number.  On
 // successful return, it will be pointing to the last character in the
 // tag line (i.e. the character before the start of the next line).
 //
@@ -241,10 +249,11 @@
 // data and it will outlive the call.
 //
 // Returns 0 on success, nonzero on failure.
-static int scanTagLine(EventTagMap* map, char** pData, int lineNum) {
-  char* cp;
-  unsigned long val = strtoul(*pData, &cp, 10);
-  if (cp == *pData) {
+static int scanTagLine(EventTagMap* map, const char*& pData, int lineNum) {
+  char* ep;
+  unsigned long val = strtoul(pData, &ep, 10);
+  const char* cp = ep;
+  if (cp == pData) {
     if (lineNum) {
       fprintf(stderr, OUT_TAG ": malformed tag number on line %d\n", lineNum);
     }
@@ -273,14 +282,13 @@
   }
 
   const char* tag = cp;
-  // Determine whether "c" is a valid tag char.
-  while (isalnum(*++cp) || (*cp == '_')) {
-  }
+  cp = endOfTag(cp);
   size_t tagLen = cp - tag;
 
   if (!isspace(*cp)) {
     if (lineNum) {
-      fprintf(stderr, OUT_TAG ": invalid tag chars on line %d\n", lineNum);
+      fprintf(stderr, OUT_TAG ": invalid tag char %c on line %d\n", *cp,
+              lineNum);
     }
     errno = EINVAL;
     return -1;
@@ -311,9 +319,9 @@
 
   while (*cp != '\n') ++cp;
 #ifdef DEBUG
-  fprintf(stderr, "%d: %p: %.*s\n", lineNum, tag, (int)(cp - *pData), *pData);
+  fprintf(stderr, "%d: %p: %.*s\n", lineNum, tag, (int)(cp - pData), pData);
 #endif
-  *pData = cp;
+  pData = cp;
 
   if (lineNum) {
     if (map->emplaceUnique(tagIndex,
@@ -341,9 +349,9 @@
 
 // Parse the tags out of the file.
 static int parseMapLines(EventTagMap* map, size_t which) {
-  char* cp = static_cast<char*>(map->mapAddr[which]);
+  const char* cp = static_cast<char*>(map->mapAddr[which]);
   size_t len = map->mapLen[which];
-  char* endp = cp + len;
+  const char* endp = cp + len;
 
   // insist on EOL at EOF; simplifies parsing and null-termination
   if (!len || (*(endp - 1) != '\n')) {
@@ -370,7 +378,7 @@
         lineStart = false;
       } else if (isdigit(*cp)) {
         // looks like a tag; scan it out
-        if (scanTagLine(map, &cp, lineNum) != 0) {
+        if (scanTagLine(map, cp, lineNum) != 0) {
           if (!which || (errno != EMLINK)) {
             return -1;
           }
@@ -445,7 +453,7 @@
           mmap(NULL, end[which], which ? PROT_READ : PROT_READ | PROT_WRITE,
                which ? MAP_SHARED : MAP_PRIVATE, fd[which], 0);
       save_errno = errno;
-      close(fd[which]);
+      close(fd[which]); /* fd DONE */
       fd[which] = -1;
       if ((newTagMap->mapAddr[which] != MAP_FAILED) &&
           (newTagMap->mapAddr[which] != NULL)) {
@@ -465,6 +473,7 @@
       delete newTagMap;
       return NULL;
     }
+    /* See 'fd DONE' comments above and below, no need to clean up here */
   }
 
   return newTagMap;
@@ -473,7 +482,7 @@
   save_errno = EINVAL;
   delete newTagMap;
 fail_close:
-  for (which = 0; which < NUM_MAPS; ++which) close(fd[which]);
+  for (which = 0; which < NUM_MAPS; ++which) close(fd[which]); /* fd DONE */
 fail_errno:
   errno = save_errno;
   return NULL;
@@ -494,14 +503,13 @@
   int ret = asprintf(&buf, command_template, tag);
   if (ret > 0) {
     // Add some buffer margin for an estimate of the full return content.
-    char* cp;
     size_t size =
         ret - strlen(command_template) +
         strlen("65535\n4294967295\t?\t\t\t?\t# uid=32767\n\n\f?success?");
     if (size > (size_t)ret) {
-      cp = static_cast<char*>(realloc(buf, size));
-      if (cp) {
-        buf = cp;
+      char* np = static_cast<char*>(realloc(buf, size));
+      if (np) {
+        buf = np;
       } else {
         size = ret;
       }
@@ -511,10 +519,12 @@
     // Ask event log tag service for an existing entry
     if (__send_log_msg(buf, size) >= 0) {
       buf[size - 1] = '\0';
-      unsigned long val = strtoul(buf, &cp, 10);        // return size
+      char* ep;
+      unsigned long val = strtoul(buf, &ep, 10);  // return size
+      const char* cp = ep;
       if ((buf != cp) && (val > 0) && (*cp == '\n')) {  // truncation OK
         ++cp;
-        if (!scanTagLine(map, &cp, 0)) {
+        if (!scanTagLine(map, cp, 0)) {
           free(buf);
           return map->find(tag);
         }
@@ -572,8 +582,9 @@
 LIBLOG_ABI_PUBLIC int android_lookupEventTagNum(EventTagMap* map,
                                                 const char* tagname,
                                                 const char* format, int prio) {
-  size_t len = strlen(tagname);
-  if (!len) {
+  const char* ep = endOfTag(tagname);
+  size_t len = ep - tagname;
+  if (!len || *ep) {
     errno = EINVAL;
     return -1;
   }
diff --git a/liblog/include/log/log.h b/liblog/include/log/log.h
index 6758c84..3a215e9 100644
--- a/liblog/include/log/log.h
+++ b/liblog/include/log/log.h
@@ -32,6 +32,7 @@
 #include <log/log_main.h>
 #include <log/log_radio.h>
 #include <log/log_read.h>
+#include <log/log_safetynet.h>
 #include <log/log_system.h>
 #include <log/log_time.h>
 #include <log/uio.h> /* helper to define iovec for portability */
@@ -167,31 +168,6 @@
 
 /* --------------------------------------------------------------------- */
 
-#ifndef _ANDROID_USE_LIBLOG_SAFETYNET_INTERFACE
-#ifndef __ANDROID_API__
-#define __ANDROID_USE_LIBLOG_SAFETYNET_INTERFACE 1
-#elif __ANDROID_API__ > 22 /* > Lollipop */
-#define __ANDROID_USE_LIBLOG_SAFETYNET_INTERFACE 1
-#else
-#define __ANDROID_USE_LIBLOG_SAFETYNET_INTERFACE 0
-#endif
-#endif
-
-#if __ANDROID_USE_LIBLOG_SAFETYNET_INTERFACE
-
-#define android_errorWriteLog(tag, subTag) \
-  __android_log_error_write(tag, subTag, -1, NULL, 0)
-
-#define android_errorWriteWithInfoLog(tag, subTag, uid, data, dataLen) \
-  __android_log_error_write(tag, subTag, uid, data, dataLen)
-
-int __android_log_error_write(int tag, const char* subTag, int32_t uid,
-                              const char* data, uint32_t dataLen);
-
-#endif /* __ANDROID_USE_LIBLOG_SAFETYNET_INTERFACE */
-
-/* --------------------------------------------------------------------- */
-
 #ifndef __ANDROID_USE_LIBLOG_CLOSE_INTERFACE
 #ifndef __ANDROID_API__
 #define __ANDROID_USE_LIBLOG_CLOSE_INTERFACE 1
diff --git a/liblog/include/log/log_event_list.h b/liblog/include/log/log_event_list.h
index 55953fc..057be5d 100644
--- a/liblog/include/log/log_event_list.h
+++ b/liblog/include/log/log_event_list.h
@@ -17,6 +17,7 @@
 #ifndef _LIBS_LOG_EVENT_LIST_H
 #define _LIBS_LOG_EVENT_LIST_H
 
+#include <errno.h>
 #include <stdint.h>
 
 #if (defined(__cplusplus) && defined(_USING_LIBCXX))
@@ -148,6 +149,7 @@
     return ctx;
   }
 
+  /* return errors or transmit status */
   int status() const {
     return ret;
   }
@@ -209,14 +211,16 @@
   }
 
   int write(log_id_t id = LOG_ID_EVENTS) {
+    /* facilitate -EBUSY retry */
+    if ((ret == -EBUSY) || (ret > 0)) ret = 0;
     int retval = android_log_write_list(ctx, id);
-    if (retval < 0) ret = retval;
+    /* existing errors trump transmission errors */
+    if (!ret) ret = retval;
     return ret;
   }
 
   int operator<<(log_id_t id) {
-    int retval = android_log_write_list(ctx, id);
-    if (retval < 0) ret = retval;
+    write(id);
     android_log_destroy(&ctx);
     return ret;
   }
diff --git a/liblog/include/log/log_properties.h b/liblog/include/log/log_properties.h
new file mode 100644
index 0000000..7d398a6
--- /dev/null
+++ b/liblog/include/log/log_properties.h
@@ -0,0 +1,35 @@
+/*
+**
+** Copyright 2017, The Android Open Source Project
+**
+** This file is dual licensed.  It may be redistributed and/or modified
+** under the terms of the Apache 2.0 License OR version 2 of the GNU
+** General Public License.
+*/
+
+#ifndef _LIBS_LOG_PROPERTIES_H
+#define _LIBS_LOG_PROPERTIES_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef __ANDROID_USE_LIBLOG_IS_DEBUGGABLE_INTERFACE
+#ifndef __ANDROID_API__
+#define __ANDROID_USE_LIBLOG_IS_DEBUGGABLE_INTERFACE 1
+#elif __ANDROID_API__ > 24 /* > Nougat */
+#define __ANDROID_USE_LIBLOG_IS_DEBUGGABLE_INTERFACE 1
+#else
+#define __ANDROID_USE_LIBLOG_IS_DEBUGGABLE_INTERFACE 0
+#endif
+#endif
+
+#if __ANDROID_USE_LIBLOG_IS_DEBUGGABLE_INTERFACE
+int __android_log_is_debuggable();
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _LIBS_LOG_PROPERTIES_H */
diff --git a/liblog/include/log/log_safetynet.h b/liblog/include/log/log_safetynet.h
new file mode 100644
index 0000000..b8ca475
--- /dev/null
+++ b/liblog/include/log/log_safetynet.h
@@ -0,0 +1,44 @@
+/*
+**
+** Copyright 2017, The Android Open Source Project
+**
+** This file is dual licensed.  It may be redistributed and/or modified
+** under the terms of the Apache 2.0 License OR version 2 of the GNU
+** General Public License.
+*/
+
+#ifndef _LIBS_LOG_SAFETYNET_H
+#define _LIBS_LOG_SAFETYNET_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef _ANDROID_USE_LIBLOG_SAFETYNET_INTERFACE
+#ifndef __ANDROID_API__
+#define __ANDROID_USE_LIBLOG_SAFETYNET_INTERFACE 1
+#elif __ANDROID_API__ > 22 /* > Lollipop */
+#define __ANDROID_USE_LIBLOG_SAFETYNET_INTERFACE 1
+#else
+#define __ANDROID_USE_LIBLOG_SAFETYNET_INTERFACE 0
+#endif
+#endif
+
+#if __ANDROID_USE_LIBLOG_SAFETYNET_INTERFACE
+
+#define android_errorWriteLog(tag, subTag) \
+  __android_log_error_write(tag, subTag, -1, NULL, 0)
+
+#define android_errorWriteWithInfoLog(tag, subTag, uid, data, dataLen) \
+  __android_log_error_write(tag, subTag, uid, data, dataLen)
+
+int __android_log_error_write(int tag, const char* subTag, int32_t uid,
+                              const char* data, uint32_t dataLen);
+
+#endif /* __ANDROID_USE_LIBLOG_SAFETYNET_INTERFACE */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _LIBS_LOG_SAFETYNET_H */
diff --git a/liblog/include/log/log_time.h b/liblog/include/log/log_time.h
index 5f70f7d..3764faf 100644
--- a/liblog/include/log/log_time.h
+++ b/liblog/include/log/log_time.h
@@ -22,6 +22,8 @@
 
 /* struct log_time is a wire-format variant of struct timespec */
 #define NS_PER_SEC 1000000000ULL
+#define US_PER_SEC 1000000ULL
+#define MS_PER_SEC 1000ULL
 
 #ifndef __struct_log_time_defined
 #define __struct_log_time_defined
@@ -41,13 +43,12 @@
   static const uint32_t tv_sec_max = 0xFFFFFFFFUL;
   static const uint32_t tv_nsec_max = 999999999UL;
 
-  log_time(const timespec& T) {
-    tv_sec = static_cast<uint32_t>(T.tv_sec);
-    tv_nsec = static_cast<uint32_t>(T.tv_nsec);
+  log_time(const timespec& T)
+      : tv_sec(static_cast<uint32_t>(T.tv_sec)),
+        tv_nsec(static_cast<uint32_t>(T.tv_nsec)) {
   }
-  log_time(uint32_t sec, uint32_t nsec) {
-    tv_sec = sec;
-    tv_nsec = nsec;
+  explicit log_time(uint32_t sec, uint32_t nsec = 0)
+      : tv_sec(sec), tv_nsec(nsec) {
   }
 #ifdef _SYSTEM_CORE_INCLUDE_PRIVATE_ANDROID_LOGGER_H_
 #define __struct_log_time_private_defined
@@ -56,14 +57,14 @@
   log_time() {
   }
 #ifdef __linux__
-  log_time(clockid_t id) {
+  explicit log_time(clockid_t id) {
     timespec T;
     clock_gettime(id, &T);
     tv_sec = static_cast<uint32_t>(T.tv_sec);
     tv_nsec = static_cast<uint32_t>(T.tv_nsec);
   }
 #endif
-  log_time(const char* T) {
+  explicit log_time(const char* T) {
     const uint8_t* c = reinterpret_cast<const uint8_t*>(T);
     tv_sec = c[0] | (static_cast<uint32_t>(c[1]) << 8) |
              (static_cast<uint32_t>(c[2]) << 16) |
@@ -149,6 +150,14 @@
   uint64_t nsec() const {
     return static_cast<uint64_t>(tv_sec) * NS_PER_SEC + tv_nsec;
   }
+  uint64_t usec() const {
+    return static_cast<uint64_t>(tv_sec) * US_PER_SEC +
+           tv_nsec / (NS_PER_SEC / US_PER_SEC);
+  }
+  uint64_t msec() const {
+    return static_cast<uint64_t>(tv_sec) * MS_PER_SEC +
+           tv_nsec / (NS_PER_SEC / MS_PER_SEC);
+  }
 
 #ifdef _SYSTEM_CORE_INCLUDE_PRIVATE_ANDROID_LOGGER_H_
   static const char default_format[];
diff --git a/liblog/include/private/android_logger.h b/liblog/include/private/android_logger.h
index e3ccfcf..965de37 100644
--- a/liblog/include/private/android_logger.h
+++ b/liblog/include/private/android_logger.h
@@ -135,8 +135,6 @@
 int __android_log_security_bswrite(int32_t tag, const char* payload);
 int __android_log_security(); /* Device Owner is present */
 
-int __android_log_is_debuggable();
-
 #define BOOL_DEFAULT_FLAG_TRUE_FALSE 0x1
 #define BOOL_DEFAULT_FALSE 0x0        /* false if property not present   */
 #define BOOL_DEFAULT_TRUE 0x1         /* true if property not present    */
diff --git a/liblog/include_vndk/log/log.h b/liblog/include_vndk/log/log.h
index f93b377..01623df 100644
--- a/liblog/include_vndk/log/log.h
+++ b/liblog/include_vndk/log/log.h
@@ -8,6 +8,7 @@
 #include <log/log_main.h>
 #include <log/log_radio.h>
 #include <log/log_read.h>
+#include <log/log_safetynet.h>
 #include <log/log_time.h>
 
 /*
diff --git a/liblog/include_vndk/log/log_properties.h b/liblog/include_vndk/log/log_properties.h
new file mode 120000
index 0000000..bbec426
--- /dev/null
+++ b/liblog/include_vndk/log/log_properties.h
@@ -0,0 +1 @@
+../../include/log/log_properties.h
\ No newline at end of file
diff --git a/liblog/include_vndk/log/log_safetynet.h b/liblog/include_vndk/log/log_safetynet.h
new file mode 120000
index 0000000..a4614e7
--- /dev/null
+++ b/liblog/include_vndk/log/log_safetynet.h
@@ -0,0 +1 @@
+../../include/log/log_safetynet.h
\ No newline at end of file
diff --git a/liblog/liblog.map.txt b/liblog/liblog.map.txt
index 599dc90..3c4c1f1 100644
--- a/liblog/liblog.map.txt
+++ b/liblog/liblog.map.txt
@@ -1,6 +1,10 @@
 LIBLOG {
   global:
+    android_name_to_log_id; # vndk
+    android_log_id_to_name; # vndk
     __android_log_assert;
+    __android_log_buf_print; # vndk
+    __android_log_buf_write; # vndk
     __android_log_print;
     __android_log_vprint;
     __android_log_write;
@@ -8,12 +12,33 @@
     *;
 };
 
+LIBLOG_L {
+  global:
+    android_logger_clear; # vndk
+    android_logger_get_id; # vndk
+    android_logger_get_log_readable_size; # vndk
+    android_logger_get_log_version; # vndk
+    android_logger_get_log_size; # vndk
+    android_logger_list_alloc; # vndk
+    android_logger_list_alloc_time; # vndk
+    android_logger_list_free; # vndk
+    android_logger_list_open; # vndk
+    android_logger_list_read; # vndk
+    android_logger_open; # vndk
+    android_logger_set_log_size; # vndk
+};
+
 LIBLOG_M {
   global:
+    android_logger_get_prune_list; # vndk
+    android_logger_set_prune_list; # vndk
+    android_logger_get_statistics; # vndk
+    __android_log_error_write; # vndk
     __android_log_is_loggable;
 };
 
 LIBLOG_O {
   global:
     __android_log_is_loggable_len;
+    __android_log_is_debuggable; # vndk
 };
diff --git a/liblog/logger_write.c b/liblog/logger_write.c
index d322c0f..84feb20 100644
--- a/liblog/logger_write.c
+++ b/liblog/logger_write.c
@@ -410,16 +410,46 @@
   if (!tag) tag = "";
 
   /* XXX: This needs to go! */
-  if ((bufID != LOG_ID_RADIO) &&
-      (!strcmp(tag, "HTC_RIL") ||
-       !strncmp(tag, "RIL", 3) || /* Any log tag with "RIL" as the prefix */
-       !strncmp(tag, "IMS", 3) || /* Any log tag with "IMS" as the prefix */
-       !strcmp(tag, "AT") || !strcmp(tag, "GSM") || !strcmp(tag, "STK") ||
-       !strcmp(tag, "CDMA") || !strcmp(tag, "PHONE") || !strcmp(tag, "SMS"))) {
-    bufID = LOG_ID_RADIO;
-    /* Inform third party apps/ril/radio.. to use Rlog or RLOG */
-    snprintf(tmp_tag, sizeof(tmp_tag), "use-Rlog/RLOG-%s", tag);
-    tag = tmp_tag;
+  if (bufID != LOG_ID_RADIO) {
+    switch (tag[0]) {
+      case 'H':
+        if (strcmp(tag + 1, "HTC_RIL" + 1)) break;
+        goto inform;
+      case 'R':
+        /* Any log tag with "RIL" as the prefix */
+        if (strncmp(tag + 1, "RIL" + 1, strlen("RIL") - 1)) break;
+        goto inform;
+      case 'Q':
+        /* Any log tag with "QC_RIL" as the prefix */
+        if (strncmp(tag + 1, "QC_RIL" + 1, strlen("QC_RIL") - 1)) break;
+        goto inform;
+      case 'I':
+        /* Any log tag with "IMS" as the prefix */
+        if (strncmp(tag + 1, "IMS" + 1, strlen("IMS") - 1)) break;
+        goto inform;
+      case 'A':
+        if (strcmp(tag + 1, "AT" + 1)) break;
+        goto inform;
+      case 'G':
+        if (strcmp(tag + 1, "GSM" + 1)) break;
+        goto inform;
+      case 'S':
+        if (strcmp(tag + 1, "STK" + 1) && strcmp(tag + 1, "SMS" + 1)) break;
+        goto inform;
+      case 'C':
+        if (strcmp(tag + 1, "CDMA" + 1)) break;
+        goto inform;
+      case 'P':
+        if (strcmp(tag + 1, "PHONE" + 1)) break;
+      /* FALLTHRU */
+      inform:
+        bufID = LOG_ID_RADIO;
+        snprintf(tmp_tag, sizeof(tmp_tag), "use-Rlog/RLOG-%s", tag);
+        tag = tmp_tag;
+      /* FALLTHRU */
+      default:
+        break;
+    }
   }
 
 #if __BIONIC__
diff --git a/liblog/logprint.c b/liblog/logprint.c
index 2ade7b0..b62f8b4 100644
--- a/liblog/logprint.c
+++ b/liblog/logprint.c
@@ -326,6 +326,7 @@
   else if (!strcmp(formatString, "uid")) format = FORMAT_MODIFIER_UID;
   else if (!strcmp(formatString, "descriptive")) format = FORMAT_MODIFIER_DESCRIPT;
   /* clang-format on */
+
 #ifndef __MINGW32__
   else {
     extern char* tzname[2];
@@ -637,7 +638,8 @@
   TYPE_MILLISECONDS = '3',
   TYPE_ALLOCATIONS = '4',
   TYPE_ID = '5',
-  TYPE_PERCENT = '6'
+  TYPE_PERCENT = '6',
+  TYPE_MONOTONIC = 's'
 };
 
 static int android_log_printBinaryEvent(const unsigned char** pEventData,
@@ -651,7 +653,7 @@
   size_t outBufLen = *pOutBufLen;
   size_t outBufLenSave = outBufLen;
   unsigned char type;
-  size_t outCount;
+  size_t outCount = 0;
   int result = 0;
   const char* cp;
   size_t len;
@@ -690,6 +692,7 @@
    * 4: Number of allocations
    * 5: Id
    * 6: Percent
+   * s: Number of seconds (monotonic time)
    * Default value for data of type int/long is 2 (bytes).
    */
   if (!cp || !findChar(&cp, &len, '(')) {
@@ -921,6 +924,42 @@
             outCount = snprintf(outBuf, outBufLen, "ms");
           }
           break;
+        case TYPE_MONOTONIC: {
+          static const uint64_t minute = 60;
+          static const uint64_t hour = 60 * minute;
+          static const uint64_t day = 24 * hour;
+
+          /* Repaint as unsigned seconds, minutes, hours ... */
+          outBuf -= outCount;
+          outBufLen += outCount;
+          uint64_t val = lval;
+          if (val >= day) {
+            outCount = snprintf(outBuf, outBufLen, "%" PRIu64 "d ", val / day);
+            if (outCount >= outBufLen) break;
+            outBuf += outCount;
+            outBufLen -= outCount;
+            val = (val % day) + day;
+          }
+          if (val >= minute) {
+            if (val >= hour) {
+              outCount = snprintf(outBuf, outBufLen, "%" PRIu64 ":",
+                                  (val / hour) % (day / hour));
+              if (outCount >= outBufLen) break;
+              outBuf += outCount;
+              outBufLen -= outCount;
+            }
+            outCount =
+                snprintf(outBuf, outBufLen,
+                         (val >= hour) ? "%02" PRIu64 ":" : "%" PRIu64 ":",
+                         (val / minute) % (hour / minute));
+            if (outCount >= outBufLen) break;
+            outBuf += outCount;
+            outBufLen -= outCount;
+          }
+          outCount = snprintf(outBuf, outBufLen,
+                              (val >= minute) ? "%02" PRIu64 : "%" PRIu64 "s",
+                              val % minute);
+        } break;
         case TYPE_ALLOCATIONS:
           outCount = 0;
           /* outCount = snprintf(outBuf, outBufLen, " allocations"); */
diff --git a/liblog/pmsg_writer.c b/liblog/pmsg_writer.c
index e71c176..dc42856 100644
--- a/liblog/pmsg_writer.c
+++ b/liblog/pmsg_writer.c
@@ -26,6 +26,7 @@
 #include <sys/types.h>
 #include <time.h>
 
+#include <log/log_properties.h>
 #include <private/android_filesystem_config.h>
 #include <private/android_logger.h>
 
diff --git a/liblog/properties.c b/liblog/properties.c
index 0b0ef52..11be827 100644
--- a/liblog/properties.c
+++ b/liblog/properties.c
@@ -95,7 +95,7 @@
   /* calculate the size of our key temporary buffer */
   const size_t taglen = tag ? len : 0;
   /* sizeof(log_namespace) = strlen(log_namespace) + 1 */
-  char key[sizeof(log_namespace) + taglen]; /* may be > PROP_NAME_MAX */
+  char key[sizeof(log_namespace) + taglen];
   char* kp;
   size_t i;
   char c = 0;
@@ -108,7 +108,8 @@
    * Where the missing tag matches all tags and becomes the
    * system global default. We do not support ro.log.tag* .
    */
-  static char last_tag[PROP_NAME_MAX];
+  static char* last_tag;
+  static size_t last_tag_len;
   static uint32_t global_serial;
   /* some compilers erroneously see uninitialized use. !not_locked */
   uint32_t current_global_serial = 0;
@@ -147,25 +148,29 @@
   if (taglen) {
     int local_change_detected = change_detected;
     if (!not_locked) {
-      if (!last_tag[0] || (last_tag[0] != tag[0]) ||
-          strncmp(
-              last_tag + 1, tag + 1,
-              (len < sizeof(last_tag)) ? (len - 1) : (sizeof(last_tag) - 1)) ||
-          ((len < sizeof(last_tag)) && last_tag[len])) {
+      if (!last_tag || !last_tag[0] || (last_tag[0] != tag[0]) ||
+          strncmp(last_tag + 1, tag + 1, last_tag_len - 1)) {
         /* invalidate log.tag.<tag> cache */
         for (i = 0; i < (sizeof(tag_cache) / sizeof(tag_cache[0])); ++i) {
           tag_cache[i].cache.pinfo = NULL;
           tag_cache[i].c = '\0';
         }
-        last_tag[0] = '\0';
+        if (last_tag) last_tag[0] = '\0';
         local_change_detected = 1;
       }
-      if (!last_tag[0]) {
-        if (len < sizeof(last_tag)) {
+      if (!last_tag || !last_tag[0]) {
+        if (!last_tag) {
+          last_tag = calloc(1, len + 1);
+          last_tag_len = 0;
+          if (last_tag) last_tag_len = len + 1;
+        } else if (len >= last_tag_len) {
+          last_tag = realloc(last_tag, len + 1);
+          last_tag_len = 0;
+          if (last_tag) last_tag_len = len + 1;
+        }
+        if (last_tag) {
           strncpy(last_tag, tag, len);
           last_tag[len] = '\0';
-        } else {
-          strncpy(last_tag, tag, sizeof(last_tag));
         }
       }
     }
@@ -272,7 +277,7 @@
   return logLevel >= 0 && prio >= logLevel;
 }
 
-LIBLOG_ABI_PRIVATE int __android_log_is_debuggable() {
+LIBLOG_ABI_PUBLIC int __android_log_is_debuggable() {
   static uint32_t serial;
   static struct cache_char tag_cache;
   static const char key[] = "ro.debuggable";
@@ -435,7 +440,7 @@
                                                            int flag) {
   struct cache_property property = { { NULL, -1 }, { 0 } };
   if (flag & BOOL_DEFAULT_FLAG_PERSIST) {
-    char newkey[PROP_NAME_MAX];
+    char newkey[strlen("persist.") + strlen(key) + 1];
     snprintf(newkey, sizeof(newkey), "ro.%s", key);
     refresh_cache_property(&property, newkey);
     property.cache.pinfo = NULL;
@@ -454,6 +459,9 @@
   if (check_flag(property.property, "false")) {
     return false;
   }
+  if (property.property[0]) {
+    flag &= ~(BOOL_DEFAULT_FLAG_ENG | BOOL_DEFAULT_FLAG_SVELTE);
+  }
   if (check_flag(property.property, "eng")) {
     flag |= BOOL_DEFAULT_FLAG_ENG;
   }
@@ -600,8 +608,8 @@
     evaluate_property_get_size
     /* clang-format on */
   };
-  char key_persist[PROP_NAME_MAX];
-  char key_ro[PROP_NAME_MAX];
+  char key_persist[strlen(global_tunable) + strlen(".security") + 1];
+  char key_ro[strlen(global_default) + strlen(".security") + 1];
   struct cache2_property_size local = {
     /* clang-format off */
     PTHREAD_MUTEX_INITIALIZER, 0,
diff --git a/liblog/tests/liblog_benchmark.cpp b/liblog/tests/liblog_benchmark.cpp
index 3f79552..c4bf959 100644
--- a/liblog/tests/liblog_benchmark.cpp
+++ b/liblog/tests/liblog_benchmark.cpp
@@ -527,11 +527,13 @@
 /*
  *	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 dozen or so syscall periods (40us)
+ * 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();
+    // log tag number 0 is not known, nor shall it ever be known
     __android_log_btwrite(0, EVENT_TYPE_LONG, &i, sizeof(i));
     StopBenchmarkTiming();
     logd_yield();
@@ -539,6 +541,28 @@
 }
 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)
+ */
+static void BM_log_event_overhead_42(int iters) {
+  for (unsigned long long i = 0; i < (unsigned)iters; ++i) {
+    StartBenchmarkTiming();
+    // In system/core/logcat/event.logtags:
+    // # These are used for testing, do not modify without updating
+    // # tests/framework-tests/src/android/util/EventLogFunctionalTest.java.
+    // # system/core/liblog/tests/liblog_benchmark.cpp
+    // # 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();
+    logd_yield();
+  }
+}
+BENCHMARK(BM_log_event_overhead_42);
+
 static void BM_log_event_overhead_null(int iters) {
   set_log_null();
   BM_log_event_overhead(iters);
diff --git a/liblog/tests/liblog_test.cpp b/liblog/tests/liblog_test.cpp
index cc95425..ec32da0 100644
--- a/liblog/tests/liblog_test.cpp
+++ b/liblog/tests/liblog_test.cpp
@@ -1839,6 +1839,7 @@
   // that it can be determined the property is not set.
   static const char nothing_val[] = "_NOTHING_TO_SEE_HERE_";
   char persist[PROP_VALUE_MAX];
+  char persist_hold[PROP_VALUE_MAX];
   char readonly[PROP_VALUE_MAX];
 
   // First part of this test requires the test itself to have the appropriate
@@ -1846,19 +1847,38 @@
   // bail rather than give a failing grade.
   property_get(persist_key, persist, "");
   fprintf(stderr, "INFO: getprop %s -> %s\n", persist_key, persist);
+  strncpy(persist_hold, persist, PROP_VALUE_MAX);
   property_get(readonly_key, readonly, nothing_val);
   fprintf(stderr, "INFO: getprop %s -> %s\n", readonly_key, readonly);
 
   if (!strcmp(readonly, nothing_val)) {
+    // Lets check if we can set the value (we should not be allowed to do so)
     EXPECT_FALSE(__android_log_security());
     fprintf(stderr, "WARNING: setting ro.device_owner to a domain\n");
     static const char domain[] = "com.google.android.SecOps.DeviceOwner";
-    property_set(readonly_key, domain);
-    usleep(20000);  // property system does not guarantee performance, rest ...
-    property_get(readonly_key, readonly, nothing_val);
-    EXPECT_STREQ(readonly, domain);
-  } else if (!strcasecmp(readonly, "false") || !readonly[0]) {
-    // not enough permissions to run
+    EXPECT_NE(0, property_set(readonly_key, domain));
+    useconds_t total_time = 0;
+    static const useconds_t seconds = 1000000;
+    static const useconds_t max_time = 5 * seconds;  // not going to happen
+    static const useconds_t rest = 20 * 1000;
+    for (; total_time < max_time; total_time += rest) {
+      usleep(rest);  // property system does not guarantee performance.
+      property_get(readonly_key, readonly, nothing_val);
+      if (!strcmp(readonly, domain)) {
+        if (total_time > rest) {
+          fprintf(stderr, "INFO: took %u.%06u seconds to set property\n",
+                  (unsigned)(total_time / seconds),
+                  (unsigned)(total_time % seconds));
+        }
+        break;
+      }
+    }
+    EXPECT_STRNE(domain, readonly);
+  }
+
+  if (!strcasecmp(readonly, "false") || !readonly[0] ||
+      !strcmp(readonly, nothing_val)) {
+    // not enough permissions to run tests surrounding persist.logd.security
     EXPECT_FALSE(__android_log_security());
     return;
   }
@@ -1869,16 +1889,51 @@
     EXPECT_FALSE(__android_log_security());
   }
   property_set(persist_key, "TRUE");
-  EXPECT_TRUE(__android_log_security());
+  property_get(persist_key, persist, "");
+  uid_t uid = getuid();
+  gid_t gid = getgid();
+  bool perm = (gid == AID_ROOT) || (uid == AID_ROOT);
+  EXPECT_STREQ(perm ? "TRUE" : persist_hold, persist);
+  if (!strcasecmp(persist, "true")) {
+    EXPECT_TRUE(__android_log_security());
+  } else {
+    EXPECT_FALSE(__android_log_security());
+  }
   property_set(persist_key, "FALSE");
-  EXPECT_FALSE(__android_log_security());
+  property_get(persist_key, persist, "");
+  EXPECT_STREQ(perm ? "FALSE" : persist_hold, persist);
+  if (!strcasecmp(persist, "true")) {
+    EXPECT_TRUE(__android_log_security());
+  } else {
+    EXPECT_FALSE(__android_log_security());
+  }
   property_set(persist_key, "true");
-  EXPECT_TRUE(__android_log_security());
+  property_get(persist_key, persist, "");
+  EXPECT_STREQ(perm ? "true" : persist_hold, persist);
+  if (!strcasecmp(persist, "true")) {
+    EXPECT_TRUE(__android_log_security());
+  } else {
+    EXPECT_FALSE(__android_log_security());
+  }
   property_set(persist_key, "false");
-  EXPECT_FALSE(__android_log_security());
+  property_get(persist_key, persist, "");
+  EXPECT_STREQ(perm ? "false" : persist_hold, persist);
+  if (!strcasecmp(persist, "true")) {
+    EXPECT_TRUE(__android_log_security());
+  } else {
+    EXPECT_FALSE(__android_log_security());
+  }
   property_set(persist_key, "");
-  EXPECT_FALSE(__android_log_security());
-  property_set(persist_key, persist);
+  property_get(persist_key, persist, "");
+  EXPECT_STREQ(perm ? "" : persist_hold, persist);
+  if (!strcasecmp(persist, "true")) {
+    EXPECT_TRUE(__android_log_security());
+  } else {
+    EXPECT_FALSE(__android_log_security());
+  }
+  property_set(persist_key, persist_hold);
+  property_get(persist_key, persist, "");
+  EXPECT_STREQ(persist_hold, persist);
 #else
   GTEST_LOG_(INFO) << "This test does nothing.\n";
 #endif
@@ -1970,6 +2025,8 @@
 
   EXPECT_EQ(0, setuid(AID_SYSTEM));  // only one that can read security buffer
 
+  uid = getuid();
+  gid = getgid();
   pid_t pid = getpid();
 
   ASSERT_TRUE(NULL !=
diff --git a/libnativebridge/.clang-format b/libnativebridge/.clang-format
new file mode 120000
index 0000000..fd0645f
--- /dev/null
+++ b/libnativebridge/.clang-format
@@ -0,0 +1 @@
+../.clang-format-2
\ No newline at end of file
diff --git a/libnativebridge/native_bridge.cc b/libnativebridge/native_bridge.cc
index 83f35b1..050373a 100644
--- a/libnativebridge/native_bridge.cc
+++ b/libnativebridge/native_bridge.cc
@@ -573,11 +573,11 @@
   return false;
 }
 
-bool NativeBridgeInitNamespace(const char* public_ns_sonames,
-                               const char* anon_ns_library_path) {
+bool NativeBridgeInitAnonymousNamespace(const char* public_ns_sonames,
+                                        const char* anon_ns_library_path) {
   if (NativeBridgeInitialized()) {
     if (isCompatibleWith(NAMESPACE_VERSION)) {
-      return callbacks->initNamespace(public_ns_sonames, anon_ns_library_path);
+      return callbacks->initAnonymousNamespace(public_ns_sonames, anon_ns_library_path);
     } else {
       ALOGE("not compatible with version %d, cannot init namespace", NAMESPACE_VERSION);
     }
@@ -608,6 +608,19 @@
   return nullptr;
 }
 
+bool NativeBridgeLinkNamespaces(native_bridge_namespace_t* from, native_bridge_namespace_t* to,
+                                const char* shared_libs_sonames) {
+  if (NativeBridgeInitialized()) {
+    if (isCompatibleWith(NAMESPACE_VERSION)) {
+      return callbacks->linkNamespaces(from, to, shared_libs_sonames);
+    } else {
+      ALOGE("not compatible with version %d, cannot init namespace", NAMESPACE_VERSION);
+    }
+  }
+
+  return false;
+}
+
 void* NativeBridgeLoadLibraryExt(const char* libpath, int flag, native_bridge_namespace_t* ns) {
   if (NativeBridgeInitialized()) {
     if (isCompatibleWith(NAMESPACE_VERSION)) {
diff --git a/libnativebridge/tests/Android.mk b/libnativebridge/tests/Android.mk
index 4c3e862..c9468f0 100644
--- a/libnativebridge/tests/Android.mk
+++ b/libnativebridge/tests/Android.mk
@@ -24,7 +24,7 @@
     NativeBridge3UnloadLibrary_test.cpp \
     NativeBridge3GetError_test.cpp \
     NativeBridge3IsPathSupported_test.cpp \
-    NativeBridge3InitNamespace_test.cpp \
+    NativeBridge3InitAnonymousNamespace_test.cpp \
     NativeBridge3CreateNamespace_test.cpp \
     NativeBridge3LoadLibraryExt_test.cpp
 
diff --git a/libnativebridge/tests/DummyNativeBridge3.cpp b/libnativebridge/tests/DummyNativeBridge3.cpp
index 13fce85..4ef1c82 100644
--- a/libnativebridge/tests/DummyNativeBridge3.cpp
+++ b/libnativebridge/tests/DummyNativeBridge3.cpp
@@ -76,8 +76,8 @@
   return true;
 }
 
-extern "C" bool native_bridge3_initNamespace(const char* /* public_ns_sonames */,
-                                        const char* /* anon_ns_library_path */) {
+extern "C" bool native_bridge3_initAnonymousNamespace(const char* /* public_ns_sonames */,
+                                                      const char* /* anon_ns_library_path */) {
   return true;
 }
 
@@ -91,30 +91,34 @@
   return nullptr;
 }
 
+extern "C" bool native_bridge3_linkNamespaces(android::native_bridge_namespace_t* /* from */,
+                                              android::native_bridge_namespace_t* /* to */,
+                                              const char* /* shared_libs_soname */) {
+  return true;
+}
+
 extern "C" void* native_bridge3_loadLibraryExt(const char* /* libpath */,
                                                int /* flag */,
                                                android::native_bridge_namespace_t* /* ns */) {
   return nullptr;
 }
 
-
-android::NativeBridgeCallbacks NativeBridgeItf {
-  // v1
-  .version = 3,
-  .initialize = &native_bridge3_initialize,
-  .loadLibrary = &native_bridge3_loadLibrary,
-  .getTrampoline = &native_bridge3_getTrampoline,
-  .isSupported = &native_bridge3_isSupported,
-  .getAppEnv = &native_bridge3_getAppEnv,
-  // v2
-  .isCompatibleWith = &native_bridge3_isCompatibleWith,
-  .getSignalHandler = &native_bridge3_getSignalHandler,
-  // v3
-  .unloadLibrary = &native_bridge3_unloadLibrary,
-  .getError = &native_bridge3_getError,
-  .isPathSupported  = &native_bridge3_isPathSupported,
-  .initNamespace = &native_bridge3_initNamespace,
-  .createNamespace = &native_bridge3_createNamespace,
-  .loadLibraryExt = &native_bridge3_loadLibraryExt
-};
-
+android::NativeBridgeCallbacks NativeBridgeItf{
+    // v1
+    .version = 3,
+    .initialize = &native_bridge3_initialize,
+    .loadLibrary = &native_bridge3_loadLibrary,
+    .getTrampoline = &native_bridge3_getTrampoline,
+    .isSupported = &native_bridge3_isSupported,
+    .getAppEnv = &native_bridge3_getAppEnv,
+    // v2
+    .isCompatibleWith = &native_bridge3_isCompatibleWith,
+    .getSignalHandler = &native_bridge3_getSignalHandler,
+    // v3
+    .unloadLibrary = &native_bridge3_unloadLibrary,
+    .getError = &native_bridge3_getError,
+    .isPathSupported = &native_bridge3_isPathSupported,
+    .initAnonymousNamespace = &native_bridge3_initAnonymousNamespace,
+    .createNamespace = &native_bridge3_createNamespace,
+    .linkNamespaces = &native_bridge3_linkNamespaces,
+    .loadLibraryExt = &native_bridge3_loadLibraryExt};
diff --git a/libnativebridge/tests/NativeBridge3InitAnonymousNamespace_test.cpp b/libnativebridge/tests/NativeBridge3InitAnonymousNamespace_test.cpp
new file mode 100644
index 0000000..b0d6b09
--- /dev/null
+++ b/libnativebridge/tests/NativeBridge3InitAnonymousNamespace_test.cpp
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "NativeBridgeTest.h"
+
+namespace android {
+
+constexpr const char* kNativeBridgeLibrary3 = "libnativebridge3-dummy.so";
+
+TEST_F(NativeBridgeTest, V3_InitAnonymousNamespace) {
+  // Init
+  ASSERT_TRUE(LoadNativeBridge(kNativeBridgeLibrary3, nullptr));
+  ASSERT_TRUE(NativeBridgeAvailable());
+  ASSERT_TRUE(PreInitializeNativeBridge(".", "isa"));
+  ASSERT_TRUE(NativeBridgeAvailable());
+  ASSERT_TRUE(InitializeNativeBridge(nullptr, nullptr));
+  ASSERT_TRUE(NativeBridgeAvailable());
+
+  ASSERT_EQ(3U, NativeBridgeGetVersion());
+  ASSERT_EQ(true, NativeBridgeInitAnonymousNamespace(nullptr, nullptr));
+
+  // Clean-up code_cache
+  ASSERT_EQ(0, rmdir(kCodeCache));
+}
+
+}  // namespace android
diff --git a/libnativebridge/tests/NativeBridge3InitNamespace_test.cpp b/libnativebridge/tests/NativeBridge3InitNamespace_test.cpp
deleted file mode 100644
index ae0fd2b..0000000
--- a/libnativebridge/tests/NativeBridge3InitNamespace_test.cpp
+++ /dev/null
@@ -1,39 +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.
- */
-
-#include "NativeBridgeTest.h"
-
-namespace android {
-
-constexpr const char* kNativeBridgeLibrary3 = "libnativebridge3-dummy.so";
-
-TEST_F(NativeBridgeTest, V3_InitNamespace) {
-    // Init
-    ASSERT_TRUE(LoadNativeBridge(kNativeBridgeLibrary3, nullptr));
-    ASSERT_TRUE(NativeBridgeAvailable());
-    ASSERT_TRUE(PreInitializeNativeBridge(".", "isa"));
-    ASSERT_TRUE(NativeBridgeAvailable());
-    ASSERT_TRUE(InitializeNativeBridge(nullptr, nullptr));
-    ASSERT_TRUE(NativeBridgeAvailable());
-
-    ASSERT_EQ(3U, NativeBridgeGetVersion());
-    ASSERT_EQ(true, NativeBridgeInitNamespace(nullptr, nullptr));
-
-    // Clean-up code_cache
-    ASSERT_EQ(0, rmdir(kCodeCache));
-}
-
-}  // namespace android
diff --git a/libnativeloader/.clang-format b/libnativeloader/.clang-format
new file mode 120000
index 0000000..fd0645f
--- /dev/null
+++ b/libnativeloader/.clang-format
@@ -0,0 +1 @@
+../.clang-format-2
\ No newline at end of file
diff --git a/libnativeloader/native_loader.cpp b/libnativeloader/native_loader.cpp
index 74f2f1d..f3391d1 100644
--- a/libnativeloader/native_loader.cpp
+++ b/libnativeloader/native_loader.cpp
@@ -183,6 +183,11 @@
         return false;
       }
 
+      if (!NativeBridgeLinkNamespaces(ns, nullptr, public_libraries_.c_str())) {
+        *error_msg = NativeBridgeGetError();
+        return false;
+      }
+
       native_loader_ns = NativeLoaderNamespace(ns);
     }
 
@@ -324,8 +329,8 @@
 
     // and now initialize native bridge namespaces if necessary.
     if (NativeBridgeInitialized()) {
-      initialized_ = NativeBridgeInitNamespace(public_libraries_.c_str(),
-                                               is_native_bridge ? library_path : nullptr);
+      initialized_ = NativeBridgeInitAnonymousNamespace(public_libraries_.c_str(),
+                                                        is_native_bridge ? library_path : nullptr);
       if (!initialized_) {
         *error_msg = NativeBridgeGetError();
       }
diff --git a/libnetutils/Android.bp b/libnetutils/Android.bp
new file mode 100644
index 0000000..f710ba2
--- /dev/null
+++ b/libnetutils/Android.bp
@@ -0,0 +1,19 @@
+cc_library_shared {
+    name: "libnetutils",
+
+    srcs: [
+        "dhcpclient.c",
+        "dhcpmsg.c",
+        "ifc_utils.c",
+        "packet.c",
+    ],
+
+    shared_libs: [
+        "libcutils",
+        "liblog",
+    ],
+
+    cflags: ["-Werror"],
+
+    export_include_dirs: ["include"],
+}
diff --git a/libnetutils/Android.mk b/libnetutils/Android.mk
deleted file mode 100644
index 2150279..0000000
--- a/libnetutils/Android.mk
+++ /dev/null
@@ -1,21 +0,0 @@
-LOCAL_PATH := $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := \
-        dhcpclient.c \
-        dhcpmsg.c \
-        ifc_utils.c \
-        packet.c
-
-LOCAL_SHARED_LIBRARIES := \
-        libcutils \
-        liblog
-
-LOCAL_MODULE := libnetutils
-
-LOCAL_CFLAGS := -Werror
-
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
-
-include $(BUILD_SHARED_LIBRARY)
diff --git a/libprocessgroup/Android.bp b/libprocessgroup/Android.bp
new file mode 100644
index 0000000..37e4dbf
--- /dev/null
+++ b/libprocessgroup/Android.bp
@@ -0,0 +1,10 @@
+cc_library {
+    srcs: ["processgroup.cpp"],
+    name: "libprocessgroup",
+    shared_libs: ["libbase"],
+    export_include_dirs: ["include"],
+    cflags: [
+        "-Wall",
+        "-Werror",
+    ],
+}
diff --git a/libprocessgroup/Android.mk b/libprocessgroup/Android.mk
deleted file mode 100644
index 0bfc391..0000000
--- a/libprocessgroup/Android.mk
+++ /dev/null
@@ -1,19 +0,0 @@
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := processgroup.cpp
-LOCAL_MODULE := libprocessgroup
-LOCAL_STATIC_LIBRARIES := libbase
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_CFLAGS := -Wall -Werror
-include $(BUILD_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := processgroup.cpp
-LOCAL_MODULE := libprocessgroup
-LOCAL_SHARED_LIBRARIES := libbase
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_CFLAGS := -Wall -Werror
-include $(BUILD_SHARED_LIBRARY)
diff --git a/libprocessgroup/include/processgroup/processgroup.h b/libprocessgroup/include/processgroup/processgroup.h
index 11bd8cc..47f6ff3 100644
--- a/libprocessgroup/include/processgroup/processgroup.h
+++ b/libprocessgroup/include/processgroup/processgroup.h
@@ -24,6 +24,8 @@
 
 int killProcessGroup(uid_t uid, int initialPid, int signal);
 
+int killProcessGroupOnce(uid_t uid, int initialPid, int signal);
+
 int createProcessGroup(uid_t uid, int initialPid);
 
 void removeAllProcessGroups(void);
diff --git a/libprocessgroup/processgroup.cpp b/libprocessgroup/processgroup.cpp
index eb66727..1572cb3 100644
--- a/libprocessgroup/processgroup.cpp
+++ b/libprocessgroup/processgroup.cpp
@@ -252,8 +252,7 @@
     }
 }
 
-static int killProcessGroupOnce(uid_t uid, int initialPid, int signal)
-{
+static int doKillProcessGroupOnce(uid_t uid, int initialPid, int signal) {
     int processes = 0;
     struct ctx ctx;
     pid_t pid;
@@ -282,13 +281,11 @@
     return processes;
 }
 
-int killProcessGroup(uid_t uid, int initialPid, int signal)
-{
+static int killProcessGroup(uid_t uid, int initialPid, int signal, int retry) {
     std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
 
-    int retry = 40;
     int processes;
-    while ((processes = killProcessGroupOnce(uid, initialPid, signal)) > 0) {
+    while ((processes = doKillProcessGroupOnce(uid, initialPid, signal)) > 0) {
         LOG(VERBOSE) << "killed " << processes << " processes for processgroup " << initialPid;
         if (retry > 0) {
             std::this_thread::sleep_for(5ms);
@@ -313,6 +310,14 @@
     }
 }
 
+int killProcessGroup(uid_t uid, int initialPid, int signal) {
+    return killProcessGroup(uid, initialPid, signal, 40 /*maxRetry*/);
+}
+
+int killProcessGroupOnce(uid_t uid, int initialPid, int signal) {
+    return killProcessGroup(uid, initialPid, signal, 0 /*maxRetry*/);
+}
+
 static bool mkdirAndChown(const char *path, mode_t mode, uid_t uid, gid_t gid)
 {
     if (mkdir(path, mode) == -1 && errno != EEXIST) {
diff --git a/libsparse/Android.bp b/libsparse/Android.bp
index dd8b5fd..6ec0991 100644
--- a/libsparse/Android.bp
+++ b/libsparse/Android.bp
@@ -10,17 +10,23 @@
         "sparse.c",
         "sparse_crc32.c",
         "sparse_err.c",
-        "sparse_read.c",
+        "sparse_read.cpp",
     ],
     cflags: ["-Werror"],
     local_include_dirs: ["include"],
     export_include_dirs: ["include"],
     target: {
         host: {
-            shared_libs: ["libz-host"],
+            shared_libs: [
+                "libz-host",
+                "libbase",
+            ],
         },
         android: {
-            shared_libs: ["libz"],
+            shared_libs: [
+                "libz",
+                "libbase",
+            ],
         },
         windows: {
             enabled: true,
@@ -38,6 +44,7 @@
     static_libs: [
         "libsparse",
         "libz",
+        "libbase",
     ],
 
     cflags: ["-Werror"],
@@ -50,6 +57,7 @@
     static_libs: [
         "libsparse",
         "libz",
+        "libbase",
     ],
 
     cflags: ["-Werror"],
@@ -61,6 +69,7 @@
     static_libs: [
         "libsparse",
         "libz",
+        "libbase",
     ],
 
     cflags: ["-Werror"],
diff --git a/libsparse/output_file.c b/libsparse/output_file.c
index 2115998..51e60ef 100644
--- a/libsparse/output_file.c
+++ b/libsparse/output_file.c
@@ -584,7 +584,7 @@
 				.file_hdr_sz = SPARSE_HEADER_LEN,
 				.chunk_hdr_sz = CHUNK_HEADER_LEN,
 				.blk_sz = out->block_size,
-				.total_blks = out->len / out->block_size,
+				.total_blks = DIV_ROUND_UP(out->len, out->block_size),
 				.total_chunks = chunks,
 				.image_checksum = 0
 		};
diff --git a/libsparse/output_file.h b/libsparse/output_file.h
index 474c1fc..b67e94e 100644
--- a/libsparse/output_file.h
+++ b/libsparse/output_file.h
@@ -17,6 +17,10 @@
 #ifndef _OUTPUT_FILE_H_
 #define _OUTPUT_FILE_H_
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 #include <sparse/sparse.h>
 
 struct output_file;
@@ -38,4 +42,8 @@
 
 int read_all(int fd, void *buf, size_t len);
 
+#ifdef __cplusplus
+}
+#endif
+
 #endif
diff --git a/libsparse/sparse_file.h b/libsparse/sparse_file.h
index 91a12e6..763f43f 100644
--- a/libsparse/sparse_file.h
+++ b/libsparse/sparse_file.h
@@ -17,6 +17,10 @@
 #ifndef _LIBSPARSE_SPARSE_FILE_H_
 #define _LIBSPARSE_SPARSE_FILE_H_
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 #include <sparse/sparse.h>
 
 struct sparse_file {
@@ -28,5 +32,8 @@
 	struct output_file *out;
 };
 
+#ifdef __cplusplus
+}
+#endif
 
 #endif /* _LIBSPARSE_SPARSE_FILE_H_ */
diff --git a/libsparse/sparse_format.h b/libsparse/sparse_format.h
index c41f12a..779e038 100644
--- a/libsparse/sparse_format.h
+++ b/libsparse/sparse_format.h
@@ -18,6 +18,10 @@
 #define _LIBSPARSE_SPARSE_FORMAT_H_
 #include "sparse_defs.h"
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 typedef struct sparse_header {
   __le32	magic;		/* 0xed26ff3a */
   __le16	major_version;	/* (0x1) - reject images with higher major versions */
@@ -52,4 +56,8 @@
  *  For a CRC32 chunk, it's 4 bytes of CRC32
  */
 
+#ifdef __cplusplus
+}
+#endif
+
 #endif
diff --git a/libsparse/sparse_read.c b/libsparse/sparse_read.cpp
similarity index 88%
rename from libsparse/sparse_read.c
rename to libsparse/sparse_read.cpp
index a188202..bd66873 100644
--- a/libsparse/sparse_read.c
+++ b/libsparse/sparse_read.cpp
@@ -14,10 +14,10 @@
  * limitations under the License.
  */
 
-#define _GNU_SOURCE
 #define _FILE_OFFSET_BITS 64
 #define _LARGEFILE64_SOURCE 1
 
+#include <algorithm>
 #include <inttypes.h>
 #include <fcntl.h>
 #include <stdarg.h>
@@ -25,17 +25,19 @@
 #include <stdint.h>
 #include <stdio.h>
 #include <stdlib.h>
-#include <string.h>
+#include <string>
 #include <unistd.h>
 
 #include <sparse/sparse.h>
 
+#include "android-base/stringprintf.h"
 #include "defs.h"
 #include "output_file.h"
 #include "sparse_crc32.h"
 #include "sparse_file.h"
 #include "sparse_format.h"
 
+
 #if defined(__APPLE__) && defined(__MACH__)
 #define lseek64 lseek
 #define off64_t off_t
@@ -45,57 +47,30 @@
 #define SPARSE_HEADER_LEN       (sizeof(sparse_header_t))
 #define CHUNK_HEADER_LEN (sizeof(chunk_header_t))
 
-#define COPY_BUF_SIZE (1024U*1024U)
+static constexpr int64_t COPY_BUF_SIZE = 1024 * 1024;
 static char *copybuf;
 
-#define min(a, b) \
-	({ typeof(a) _a = (a); typeof(b) _b = (b); (_a < _b) ? _a : _b; })
+static std::string ErrorString(int err)
+{
+	if (err == -EOVERFLOW) return "EOF while reading file";
+	if (err == -EINVAL) return "Invalid sparse file format";
+	if (err == -ENOMEM) return "Failed allocation while reading file";
+	return android::base::StringPrintf("Unknown error %d", err);
+}
 
 static void verbose_error(bool verbose, int err, const char *fmt, ...)
 {
-	char *s = "";
-	char *at = "";
+	if (!verbose) return;
+
+	std::string msg = ErrorString(err);
 	if (fmt) {
+		msg += " at ";
 		va_list argp;
-		int size;
-
 		va_start(argp, fmt);
-		size = vsnprintf(NULL, 0, fmt, argp);
+		android::base::StringAppendV(&msg, fmt, argp);
 		va_end(argp);
-
-		if (size < 0) {
-			return;
-		}
-
-		at = malloc(size + 1);
-		if (at == NULL) {
-			return;
-		}
-
-		va_start(argp, fmt);
-		vsnprintf(at, size, fmt, argp);
-		va_end(argp);
-		at[size] = 0;
-		s = " at ";
 	}
-	if (verbose) {
-#ifndef _WIN32
-		if (err == -EOVERFLOW) {
-			sparse_print_verbose("EOF while reading file%s%s\n", s, at);
-		} else
-#endif
-		if (err == -EINVAL) {
-			sparse_print_verbose("Invalid sparse file format%s%s\n", s, at);
-		} else if (err == -ENOMEM) {
-			sparse_print_verbose("Failed allocation while reading file%s%s\n",
-					s, at);
-		} else {
-			sparse_print_verbose("Unknown error %d%s%s\n", err, s, at);
-		}
-	}
-	if (fmt) {
-		free(at);
-	}
+	sparse_print_verbose("%s\n", msg.c_str());
 }
 
 static int process_raw_chunk(struct sparse_file *s, unsigned int chunk_size,
@@ -104,7 +79,7 @@
 {
 	int ret;
 	int chunk;
-	unsigned int len = blocks * s->block_size;
+	int64_t len = blocks * s->block_size;
 
 	if (chunk_size % s->block_size != 0) {
 		return -EINVAL;
@@ -121,7 +96,7 @@
 
 	if (crc32) {
 		while (len) {
-			chunk = min(len, COPY_BUF_SIZE);
+			chunk = std::min(len, COPY_BUF_SIZE);
 			ret = read_all(fd, copybuf, chunk);
 			if (ret < 0) {
 				return ret;
@@ -168,7 +143,7 @@
 		}
 
 		while (len) {
-			chunk = min(len, COPY_BUF_SIZE);
+			chunk = std::min(len, COPY_BUF_SIZE);
 			*crc32 = sparse_crc32(*crc32, copybuf, chunk);
 			len -= chunk;
 		}
@@ -190,7 +165,7 @@
 		memset(copybuf, 0, COPY_BUF_SIZE);
 
 		while (len) {
-			int chunk = min(len, COPY_BUF_SIZE);
+			int chunk = std::min(len, COPY_BUF_SIZE);
 			*crc32 = sparse_crc32(*crc32, copybuf, chunk);
 			len -= chunk;
 		}
@@ -284,7 +259,7 @@
 	off64_t offset;
 
 	if (!copybuf) {
-		copybuf = malloc(COPY_BUF_SIZE);
+		copybuf = (char *)malloc(COPY_BUF_SIZE);
 	}
 
 	if (!copybuf) {
@@ -357,7 +332,7 @@
 static int sparse_file_read_normal(struct sparse_file *s, int fd)
 {
 	int ret;
-	uint32_t *buf = malloc(s->block_size);
+	uint32_t *buf = (uint32_t *)malloc(s->block_size);
 	unsigned int block = 0;
 	int64_t remain = s->len;
 	int64_t offset = 0;
@@ -370,7 +345,7 @@
 	}
 
 	while (remain > 0) {
-		to_read = min(remain, s->block_size);
+		to_read = std::min(remain, (int64_t)(s->block_size));
 		ret = read_all(fd, buf, to_read);
 		if (ret < 0) {
 			error("failed to read sparse file");
diff --git a/libsuspend/autosuspend_wakeup_count.c b/libsuspend/autosuspend_wakeup_count.c
index 2da204a..4dedf7f 100644
--- a/libsuspend/autosuspend_wakeup_count.c
+++ b/libsuspend/autosuspend_wakeup_count.c
@@ -24,7 +24,6 @@
 #include <stddef.h>
 #include <stdbool.h>
 #include <string.h>
-#include <sys/param.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
@@ -36,24 +35,12 @@
 #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)))
 {
@@ -61,12 +48,10 @@
     char wakeup_count[20];
     int wakeup_count_len;
     int ret;
-    bool success = true;
+    bool success;
 
     while (1) {
-        update_sleep_time(success);
-        usleep(sleep_time);
-        success = false;
+        usleep(100000);
         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,
@@ -90,6 +75,7 @@
             continue;
         }
 
+        success = true;
         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) {
@@ -98,8 +84,8 @@
         } 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;
+            if (ret < 0) {
+                success = false;
             }
             void (*func)(bool success) = wakeup_func;
             if (func != NULL) {
diff --git a/libsync/Android.bp b/libsync/Android.bp
index a4e5599..4bafb08 100644
--- a/libsync/Android.bp
+++ b/libsync/Android.bp
@@ -8,6 +8,7 @@
 
 cc_library_shared {
     name: "libsync",
+    vendor_available: true,
     defaults: ["libsync_defaults"],
 }
 
diff --git a/libsystem/Android.bp b/libsystem/Android.bp
new file mode 100644
index 0000000..846a585
--- /dev/null
+++ b/libsystem/Android.bp
@@ -0,0 +1,15 @@
+cc_library_headers {
+    name: "libsystem_headers",
+    vendor_available: true,
+    host_supported: true,
+    export_include_dirs: ["include"],
+
+    target: {
+        linux_bionic: {
+            enabled: true,
+        },
+        windows: {
+            enabled: true,
+        },
+    }
+}
diff --git a/include/system/camera.h b/libsystem/include/system/camera.h
similarity index 100%
rename from include/system/camera.h
rename to libsystem/include/system/camera.h
diff --git a/include/system/graphics.h b/libsystem/include/system/graphics.h
similarity index 100%
rename from include/system/graphics.h
rename to libsystem/include/system/graphics.h
diff --git a/libsystem/include/system/qemu_pipe.h b/libsystem/include/system/qemu_pipe.h
new file mode 100644
index 0000000..af25079
--- /dev/null
+++ b/libsystem/include/system/qemu_pipe.h
@@ -0,0 +1,134 @@
+/*
+ * 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 ANDROID_INCLUDE_SYSTEM_QEMU_PIPE_H
+#define ANDROID_INCLUDE_SYSTEM_QEMU_PIPE_H
+
+#include <unistd.h>
+#include <fcntl.h>
+#include <string.h>
+#include <errno.h>
+
+// Define QEMU_PIPE_DEBUG if you want to print error messages when an error
+// occurs during pipe operations. The macro should simply take a printf-style
+// formatting string followed by optional arguments.
+#ifndef QEMU_PIPE_DEBUG
+#  define  QEMU_PIPE_DEBUG(...)   (void)0
+#endif
+
+// Try to open a new Qemu fast-pipe. This function returns a file descriptor
+// that can be used to communicate with a named service managed by the
+// emulator.
+//
+// This file descriptor can be used as a standard pipe/socket descriptor.
+//
+// 'pipeName' is the name of the emulator service you want to connect to,
+// and must begin with 'pipe:' (e.g. 'pipe:camera' or 'pipe:opengles').
+//
+// On success, return a valid file descriptor, or -1/errno on failure. E.g.:
+//
+// EINVAL  -> unknown/unsupported pipeName
+// ENOSYS  -> fast pipes not available in this system.
+//
+// ENOSYS should never happen, except if you're trying to run within a
+// misconfigured emulator.
+//
+// You should be able to open several pipes to the same pipe service,
+// except for a few special cases (e.g. GSM modem), where EBUSY will be
+// returned if more than one client tries to connect to it.
+static __inline__ int qemu_pipe_open(const char* pipeName) {
+    // Sanity check.
+    if (!pipeName || memcmp(pipeName, "pipe:", 5) != 0) {
+        errno = EINVAL;
+        return -1;
+    }
+
+    int fd = TEMP_FAILURE_RETRY(open("/dev/qemu_pipe", O_RDWR));
+    if (fd < 0) {
+        QEMU_PIPE_DEBUG("%s: Could not open /dev/qemu_pipe: %s", __FUNCTION__,
+                        strerror(errno));
+        return -1;
+    }
+
+    // Write the pipe name, *including* the trailing zero which is necessary.
+    size_t pipeNameLen = strlen(pipeName);
+    ssize_t ret = TEMP_FAILURE_RETRY(write(fd, pipeName, pipeNameLen + 1U));
+    if (ret != (ssize_t)pipeNameLen + 1) {
+        QEMU_PIPE_DEBUG("%s: Could not connect to %s pipe service: %s",
+                        __FUNCTION__, pipeName, strerror(errno));
+        if (ret == 0) {
+            errno = ECONNRESET;
+        } else if (ret > 0) {
+            errno = EINVAL;
+        }
+        return -1;
+    }
+    return fd;
+}
+
+// Send a framed message |buff| of |len| bytes through the |fd| descriptor.
+// This really adds a 4-hexchar prefix describing the payload size.
+// Returns 0 on success, and -1 on error.
+static int __inline__ qemu_pipe_frame_send(int fd,
+                                           const void* buff,
+                                           size_t len) {
+    char header[5];
+    snprintf(header, sizeof(header), "%04zx", len);
+    ssize_t ret = TEMP_FAILURE_RETRY(write(fd, header, 4));
+    if (ret != 4) {
+        QEMU_PIPE_DEBUG("Can't write qemud frame header: %s", strerror(errno));
+        return -1;
+    }
+    ret = TEMP_FAILURE_RETRY(write(fd, buff, len));
+    if (ret != (ssize_t)len) {
+        QEMU_PIPE_DEBUG("Can't write qemud frame payload: %s", strerror(errno));
+        return -1;
+    }
+    return 0;
+}
+
+// Read a frame message from |fd|, and store it into |buff| of |len| bytes.
+// If the framed message is larger than |len|, then this returns -1 and the
+// content is lost. Otherwise, this returns the size of the message. NOTE:
+// empty messages are possible in a framed wire protocol and do not mean
+// end-of-stream.
+static int __inline__ qemu_pipe_frame_recv(int fd, void* buff, size_t len) {
+    char header[5];
+    ssize_t ret = TEMP_FAILURE_RETRY(read(fd, header, 4));
+    if (ret != 4) {
+        QEMU_PIPE_DEBUG("Can't read qemud frame header: %s", strerror(errno));
+        return -1;
+    }
+    header[4] = '\0';
+    size_t size;
+    if (sscanf(header, "%04zx", &size) != 1) {
+        QEMU_PIPE_DEBUG("Malformed qemud frame header: [%.*s]", 4, header);
+        return -1;
+    }
+    if (size > len) {
+        QEMU_PIPE_DEBUG("Oversized qemud frame (% bytes, expected <= %)", size,
+                        len);
+        return -1;
+    }
+    ret = TEMP_FAILURE_RETRY(read(fd, buff, size));
+    if (ret != (ssize_t)size) {
+        QEMU_PIPE_DEBUG("Could not read qemud frame payload: %s",
+                        strerror(errno));
+        return -1;
+    }
+    return size;
+}
+
+#endif /* ANDROID_INCLUDE_HARDWARE_QEMUD_PIPE_H */
diff --git a/include/system/radio.h b/libsystem/include/system/radio.h
similarity index 100%
rename from include/system/radio.h
rename to libsystem/include/system/radio.h
diff --git a/include/system/thread_defs.h b/libsystem/include/system/thread_defs.h
similarity index 100%
rename from include/system/thread_defs.h
rename to libsystem/include/system/thread_defs.h
diff --git a/include/system/window.h b/libsystem/include/system/window.h
similarity index 100%
rename from include/system/window.h
rename to libsystem/include/system/window.h
diff --git a/libsysutils/Android.bp b/libsysutils/Android.bp
new file mode 100644
index 0000000..296bd26
--- /dev/null
+++ b/libsysutils/Android.bp
@@ -0,0 +1,25 @@
+cc_library_shared {
+    name: "libsysutils",
+    srcs: [
+        "src/SocketListener.cpp",
+        "src/FrameworkListener.cpp",
+        "src/NetlinkListener.cpp",
+        "src/NetlinkEvent.cpp",
+        "src/FrameworkCommand.cpp",
+        "src/SocketClient.cpp",
+        "src/ServiceManager.cpp",
+    ],
+
+    logtags: ["EventLogTags.logtags"],
+
+    cflags: ["-Werror"],
+
+    shared_libs: [
+        "libbase",
+        "libcutils",
+        "liblog",
+        "libnl",
+    ],
+
+    export_include_dirs: ["include"],
+}
diff --git a/libsysutils/Android.mk b/libsysutils/Android.mk
deleted file mode 100644
index 584e5a2..0000000
--- a/libsysutils/Android.mk
+++ /dev/null
@@ -1,27 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES:=                             \
-                  src/SocketListener.cpp      \
-                  src/FrameworkListener.cpp   \
-                  src/NetlinkListener.cpp     \
-                  src/NetlinkEvent.cpp        \
-                  src/FrameworkCommand.cpp    \
-                  src/SocketClient.cpp        \
-                  src/ServiceManager.cpp      \
-                  EventLogTags.logtags
-
-LOCAL_MODULE:= libsysutils
-
-LOCAL_CFLAGS := -Werror
-
-LOCAL_SHARED_LIBRARIES := \
-        libbase \
-        libcutils \
-        liblog \
-        libnl
-
-LOCAL_EXPORT_C_INCLUDE_DIRS := system/core/libsysutils/include
-
-include $(BUILD_SHARED_LIBRARY)
diff --git a/libunwindstack/.clang-format b/libunwindstack/.clang-format
new file mode 120000
index 0000000..fd0645f
--- /dev/null
+++ b/libunwindstack/.clang-format
@@ -0,0 +1 @@
+../.clang-format-2
\ No newline at end of file
diff --git a/libunwindstack/Android.bp b/libunwindstack/Android.bp
index ece623b..32ed6c3 100644
--- a/libunwindstack/Android.bp
+++ b/libunwindstack/Android.bp
@@ -47,12 +47,18 @@
 
     srcs: [
         "ArmExidx.cpp",
+        "DwarfCfa.cpp",
+        "DwarfMemory.cpp",
+        "DwarfOp.cpp",
         "Elf.cpp",
         "ElfInterface.cpp",
         "ElfInterfaceArm.cpp",
         "Log.cpp",
         "Regs.cpp",
+        "MapInfo.cpp",
+        "Maps.cpp",
         "Memory.cpp",
+        "Symbols.cpp",
     ],
 
     shared_libs: [
@@ -87,16 +93,24 @@
     srcs: [
         "tests/ArmExidxDecodeTest.cpp",
         "tests/ArmExidxExtractTest.cpp",
+        "tests/DwarfCfaLogTest.cpp",
+        "tests/DwarfCfaTest.cpp",
+        "tests/DwarfMemoryTest.cpp",
+        "tests/DwarfOpLogTest.cpp",
+        "tests/DwarfOpTest.cpp",
         "tests/ElfInterfaceArmTest.cpp",
         "tests/ElfInterfaceTest.cpp",
         "tests/ElfTest.cpp",
         "tests/LogFake.cpp",
+        "tests/MapInfoTest.cpp",
+        "tests/MapsTest.cpp",
         "tests/MemoryFake.cpp",
         "tests/MemoryFileTest.cpp",
         "tests/MemoryLocalTest.cpp",
         "tests/MemoryRangeTest.cpp",
         "tests/MemoryRemoteTest.cpp",
         "tests/RegsTest.cpp",
+        "tests/SymbolsTest.cpp",
     ],
 
     cflags: [
diff --git a/libunwindstack/DwarfCfa.cpp b/libunwindstack/DwarfCfa.cpp
new file mode 100644
index 0000000..006f039
--- /dev/null
+++ b/libunwindstack/DwarfCfa.cpp
@@ -0,0 +1,713 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <inttypes.h>
+#include <stdint.h>
+
+#include <string>
+#include <type_traits>
+#include <vector>
+
+#include <android-base/stringprintf.h>
+
+#include "DwarfCfa.h"
+#include "DwarfEncoding.h"
+#include "DwarfMemory.h"
+#include "DwarfOp.h"
+#include "DwarfStructs.h"
+#include "Log.h"
+
+template <typename AddressType>
+constexpr typename DwarfCfa<AddressType>::process_func DwarfCfa<AddressType>::kCallbackTable[64];
+
+template <typename AddressType>
+bool DwarfCfa<AddressType>::GetLocationInfo(uint64_t pc, uint64_t start_offset, uint64_t end_offset,
+                                            dwarf_loc_regs_t* loc_regs) {
+  if (cie_loc_regs_ != nullptr) {
+    for (const auto& entry : *cie_loc_regs_) {
+      (*loc_regs)[entry.first] = entry.second;
+    }
+  }
+  last_error_ = DWARF_ERROR_NONE;
+
+  memory_->set_cur_offset(start_offset);
+  uint64_t cfa_offset;
+  cur_pc_ = fde_->pc_start;
+  while ((cfa_offset = memory_->cur_offset()) < end_offset && cur_pc_ <= pc) {
+    operands_.clear();
+    // Read the cfa information.
+    uint8_t cfa_value;
+    if (!memory_->ReadBytes(&cfa_value, 1)) {
+      last_error_ = DWARF_ERROR_MEMORY_INVALID;
+      return false;
+    }
+    uint8_t cfa_low = cfa_value & 0x3f;
+    // Check the 2 high bits.
+    switch (cfa_value >> 6) {
+      case 1:
+        cur_pc_ += cfa_low * fde_->cie->code_alignment_factor;
+        break;
+      case 2: {
+        uint64_t offset;
+        if (!memory_->ReadULEB128(&offset)) {
+          last_error_ = DWARF_ERROR_MEMORY_INVALID;
+          return false;
+        }
+        SignedType signed_offset =
+            static_cast<SignedType>(offset) * fde_->cie->data_alignment_factor;
+        (*loc_regs)[cfa_low] = {.type = DWARF_LOCATION_OFFSET,
+                                .values = {static_cast<uint64_t>(signed_offset)}};
+        break;
+      }
+      case 3: {
+        if (cie_loc_regs_ == nullptr) {
+          log(0, "restore while processing cie");
+          last_error_ = DWARF_ERROR_ILLEGAL_STATE;
+          return false;
+        }
+
+        auto reg_entry = cie_loc_regs_->find(cfa_low);
+        if (reg_entry == cie_loc_regs_->end()) {
+          loc_regs->erase(cfa_low);
+        } else {
+          (*loc_regs)[cfa_low] = reg_entry->second;
+        }
+        break;
+      }
+      case 0: {
+        const auto handle_func = DwarfCfa<AddressType>::kCallbackTable[cfa_low];
+        if (handle_func == nullptr) {
+          last_error_ = DWARF_ERROR_ILLEGAL_VALUE;
+          return false;
+        }
+
+        const auto cfa = &DwarfCfaInfo::kTable[cfa_low];
+        for (size_t i = 0; i < cfa->num_operands; i++) {
+          if (cfa->operands[i] == DW_EH_PE_block) {
+            uint64_t block_length;
+            if (!memory_->ReadULEB128(&block_length)) {
+              last_error_ = DWARF_ERROR_MEMORY_INVALID;
+              return false;
+            }
+            operands_.push_back(block_length);
+            memory_->set_cur_offset(memory_->cur_offset() + block_length);
+            continue;
+          }
+          uint64_t value;
+          if (!memory_->ReadEncodedValue<AddressType>(cfa->operands[i], &value)) {
+            last_error_ = DWARF_ERROR_MEMORY_INVALID;
+            return false;
+          }
+          operands_.push_back(value);
+        }
+
+        if (!(this->*handle_func)(loc_regs)) {
+          return false;
+        }
+        break;
+      }
+    }
+  }
+  return true;
+}
+
+template <typename AddressType>
+std::string DwarfCfa<AddressType>::GetOperandString(uint8_t operand, uint64_t value,
+                                                    uint64_t* cur_pc) {
+  std::string string;
+  switch (operand) {
+    case DwarfCfaInfo::DWARF_DISPLAY_REGISTER:
+      string = " register(" + std::to_string(value) + ")";
+      break;
+    case DwarfCfaInfo::DWARF_DISPLAY_SIGNED_NUMBER:
+      string += " " + std::to_string(static_cast<SignedType>(value));
+      break;
+    case DwarfCfaInfo::DWARF_DISPLAY_ADVANCE_LOC:
+      *cur_pc += value;
+    // Fall through to log the value.
+    case DwarfCfaInfo::DWARF_DISPLAY_NUMBER:
+      string += " " + std::to_string(value);
+      break;
+    case DwarfCfaInfo::DWARF_DISPLAY_SET_LOC:
+      *cur_pc = value;
+    // Fall through to log the value.
+    case DwarfCfaInfo::DWARF_DISPLAY_ADDRESS:
+      if (std::is_same<AddressType, uint32_t>::value) {
+        string += android::base::StringPrintf(" 0x%" PRIx32, static_cast<uint32_t>(value));
+      } else {
+        string += android::base::StringPrintf(" 0x%" PRIx64, static_cast<uint64_t>(value));
+      }
+      break;
+    default:
+      string = " unknown";
+  }
+  return string;
+}
+
+template <typename AddressType>
+bool DwarfCfa<AddressType>::LogOffsetRegisterString(uint32_t indent, uint64_t cfa_offset,
+                                                    uint8_t reg) {
+  uint64_t offset;
+  if (!memory_->ReadULEB128(&offset)) {
+    return false;
+  }
+  uint64_t end_offset = memory_->cur_offset();
+  memory_->set_cur_offset(cfa_offset);
+
+  std::string raw_data = "Raw Data:";
+  for (uint64_t i = cfa_offset; i < end_offset; i++) {
+    uint8_t value;
+    if (!memory_->ReadBytes(&value, 1)) {
+      return false;
+    }
+    raw_data += android::base::StringPrintf(" 0x%02x", value);
+  }
+  log(indent, "DW_CFA_offset register(%d) %" PRId64, reg, offset);
+  log(indent, "%s", raw_data.c_str());
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfCfa<AddressType>::LogInstruction(uint32_t indent, uint64_t cfa_offset, uint8_t op,
+                                           uint64_t* cur_pc) {
+  const auto* cfa = &DwarfCfaInfo::kTable[op];
+  if (cfa->name == nullptr) {
+    log(indent, "Illegal");
+    log(indent, "Raw Data: 0x%02x", op);
+    return true;
+  }
+
+  std::string log_string(cfa->name);
+  std::vector<std::string> expression_lines;
+  for (size_t i = 0; i < cfa->num_operands; i++) {
+    if (cfa->operands[i] == DW_EH_PE_block) {
+      // This is a Dwarf Expression.
+      uint64_t end_offset;
+      if (!memory_->ReadULEB128(&end_offset)) {
+        return false;
+      }
+      log_string += " " + std::to_string(end_offset);
+      end_offset += memory_->cur_offset();
+
+      DwarfOp<AddressType> op(memory_, nullptr);
+      op.GetLogInfo(memory_->cur_offset(), end_offset, &expression_lines);
+      memory_->set_cur_offset(end_offset);
+    } else {
+      uint64_t value;
+      if (!memory_->ReadEncodedValue<AddressType>(cfa->operands[i], &value)) {
+        return false;
+      }
+      log_string += GetOperandString(cfa->display_operands[i], value, cur_pc);
+    }
+  }
+  log(indent, "%s", log_string.c_str());
+
+  // Get the raw bytes of the data.
+  uint64_t end_offset = memory_->cur_offset();
+  memory_->set_cur_offset(cfa_offset);
+  std::string raw_data("Raw Data:");
+  for (uint64_t i = 0; i < end_offset - cfa_offset; i++) {
+    uint8_t value;
+    if (!memory_->ReadBytes(&value, 1)) {
+      return false;
+    }
+
+    // Only show 10 raw bytes per line.
+    if ((i % 10) == 0 && i != 0) {
+      log(indent, "%s", raw_data.c_str());
+      raw_data.clear();
+    }
+    if (raw_data.empty()) {
+      raw_data = "Raw Data:";
+    }
+    raw_data += android::base::StringPrintf(" 0x%02x", value);
+  }
+  if (!raw_data.empty()) {
+    log(indent, "%s", raw_data.c_str());
+  }
+
+  // Log any of the expression data.
+  for (const auto line : expression_lines) {
+    log(indent + 1, "%s", line.c_str());
+  }
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfCfa<AddressType>::Log(uint32_t indent, uint64_t pc, uint64_t load_bias,
+                                uint64_t start_offset, uint64_t end_offset) {
+  memory_->set_cur_offset(start_offset);
+  uint64_t cfa_offset;
+  uint64_t cur_pc = fde_->pc_start;
+  uint64_t old_pc = cur_pc;
+  while ((cfa_offset = memory_->cur_offset()) < end_offset && cur_pc <= pc) {
+    // Read the cfa information.
+    uint8_t cfa_value;
+    if (!memory_->ReadBytes(&cfa_value, 1)) {
+      return false;
+    }
+
+    // Check the 2 high bits.
+    uint8_t cfa_low = cfa_value & 0x3f;
+    switch (cfa_value >> 6) {
+      case 0:
+        if (!LogInstruction(indent, cfa_offset, cfa_low, &cur_pc)) {
+          return false;
+        }
+        break;
+      case 1:
+        log(indent, "DW_CFA_advance_loc %d", cfa_low);
+        log(indent, "Raw Data: 0x%02x", cfa_value);
+        cur_pc += cfa_low * fde_->cie->code_alignment_factor;
+        break;
+      case 2:
+        if (!LogOffsetRegisterString(indent, cfa_offset, cfa_low)) {
+          return false;
+        }
+        break;
+      case 3:
+        log(indent, "DW_CFA_restore register(%d)", cfa_low);
+        log(indent, "Raw Data: 0x%02x", cfa_value);
+        break;
+    }
+    if (cur_pc != old_pc) {
+      log(indent, "");
+      log(indent, "PC 0x%" PRIx64, cur_pc + load_bias);
+    }
+    old_pc = cur_pc;
+  }
+  return true;
+}
+
+// Static data.
+template <typename AddressType>
+bool DwarfCfa<AddressType>::cfa_nop(dwarf_loc_regs_t*) {
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfCfa<AddressType>::cfa_set_loc(dwarf_loc_regs_t*) {
+  AddressType cur_pc = cur_pc_;
+  AddressType new_pc = operands_[0];
+  if (new_pc < cur_pc) {
+    if (std::is_same<AddressType, uint32_t>::value) {
+      log(0, "Warning: PC is moving backwards: old 0x%" PRIx32 " new 0x%" PRIx32, cur_pc, new_pc);
+    } else {
+      log(0, "Warning: PC is moving backwards: old 0x%" PRIx64 " new 0x%" PRIx64, cur_pc, new_pc);
+    }
+  }
+  cur_pc_ = new_pc;
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfCfa<AddressType>::cfa_advance_loc(dwarf_loc_regs_t*) {
+  cur_pc_ += operands_[0] * fde_->cie->code_alignment_factor;
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfCfa<AddressType>::cfa_offset(dwarf_loc_regs_t* loc_regs) {
+  AddressType reg = operands_[0];
+  (*loc_regs)[reg] = {.type = DWARF_LOCATION_OFFSET, .values = {operands_[1]}};
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfCfa<AddressType>::cfa_restore(dwarf_loc_regs_t* loc_regs) {
+  AddressType reg = operands_[0];
+  if (cie_loc_regs_ == nullptr) {
+    log(0, "restore while processing cie");
+    last_error_ = DWARF_ERROR_ILLEGAL_STATE;
+    return false;
+  }
+  auto reg_entry = cie_loc_regs_->find(reg);
+  if (reg_entry == cie_loc_regs_->end()) {
+    loc_regs->erase(reg);
+  } else {
+    (*loc_regs)[reg] = reg_entry->second;
+  }
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfCfa<AddressType>::cfa_undefined(dwarf_loc_regs_t* loc_regs) {
+  AddressType reg = operands_[0];
+  (*loc_regs)[reg] = {.type = DWARF_LOCATION_UNDEFINED};
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfCfa<AddressType>::cfa_same_value(dwarf_loc_regs_t* loc_regs) {
+  AddressType reg = operands_[0];
+  loc_regs->erase(reg);
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfCfa<AddressType>::cfa_register(dwarf_loc_regs_t* loc_regs) {
+  AddressType reg = operands_[0];
+  AddressType reg_dst = operands_[1];
+  (*loc_regs)[reg] = {.type = DWARF_LOCATION_REGISTER, .values = {reg_dst}};
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfCfa<AddressType>::cfa_remember_state(dwarf_loc_regs_t* loc_regs) {
+  loc_reg_state_.push(*loc_regs);
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfCfa<AddressType>::cfa_restore_state(dwarf_loc_regs_t* loc_regs) {
+  if (loc_reg_state_.size() == 0) {
+    log(0, "Warning: Attempt to restore without remember.");
+    return true;
+  }
+  *loc_regs = loc_reg_state_.top();
+  loc_reg_state_.pop();
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfCfa<AddressType>::cfa_def_cfa(dwarf_loc_regs_t* loc_regs) {
+  (*loc_regs)[CFA_REG] = {.type = DWARF_LOCATION_REGISTER, .values = {operands_[0], operands_[1]}};
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfCfa<AddressType>::cfa_def_cfa_register(dwarf_loc_regs_t* loc_regs) {
+  auto cfa_location = loc_regs->find(CFA_REG);
+  if (cfa_location == loc_regs->end() || cfa_location->second.type != DWARF_LOCATION_REGISTER) {
+    log(0, "Attempt to set new register, but cfa is not already set to a register.");
+    last_error_ = DWARF_ERROR_ILLEGAL_STATE;
+    return false;
+  }
+
+  cfa_location->second.values[0] = operands_[0];
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfCfa<AddressType>::cfa_def_cfa_offset(dwarf_loc_regs_t* loc_regs) {
+  // Changing the offset if this is not a register is illegal.
+  auto cfa_location = loc_regs->find(CFA_REG);
+  if (cfa_location == loc_regs->end() || cfa_location->second.type != DWARF_LOCATION_REGISTER) {
+    log(0, "Attempt to set offset, but cfa is not set to a register.");
+    last_error_ = DWARF_ERROR_ILLEGAL_STATE;
+    return false;
+  }
+  cfa_location->second.values[1] = operands_[0];
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfCfa<AddressType>::cfa_def_cfa_expression(dwarf_loc_regs_t* loc_regs) {
+  (*loc_regs)[CFA_REG] = {.type = DWARF_LOCATION_EXPRESSION,
+                          .values = {operands_[0], memory_->cur_offset()}};
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfCfa<AddressType>::cfa_expression(dwarf_loc_regs_t* loc_regs) {
+  AddressType reg = operands_[0];
+  (*loc_regs)[reg] = {.type = DWARF_LOCATION_EXPRESSION,
+                      .values = {operands_[1], memory_->cur_offset()}};
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfCfa<AddressType>::cfa_offset_extended_sf(dwarf_loc_regs_t* loc_regs) {
+  AddressType reg = operands_[0];
+  SignedType value = static_cast<SignedType>(operands_[1]) * fde_->cie->data_alignment_factor;
+  (*loc_regs)[reg] = {.type = DWARF_LOCATION_OFFSET, .values = {static_cast<uint64_t>(value)}};
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfCfa<AddressType>::cfa_def_cfa_sf(dwarf_loc_regs_t* loc_regs) {
+  SignedType offset = static_cast<SignedType>(operands_[1]) * fde_->cie->data_alignment_factor;
+  (*loc_regs)[CFA_REG] = {.type = DWARF_LOCATION_REGISTER,
+                          .values = {operands_[0], static_cast<uint64_t>(offset)}};
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfCfa<AddressType>::cfa_def_cfa_offset_sf(dwarf_loc_regs_t* loc_regs) {
+  // Changing the offset if this is not a register is illegal.
+  auto cfa_location = loc_regs->find(CFA_REG);
+  if (cfa_location == loc_regs->end() || cfa_location->second.type != DWARF_LOCATION_REGISTER) {
+    log(0, "Attempt to set offset, but cfa is not set to a register.");
+    last_error_ = DWARF_ERROR_ILLEGAL_STATE;
+    return false;
+  }
+  SignedType offset = static_cast<SignedType>(operands_[0]) * fde_->cie->data_alignment_factor;
+  cfa_location->second.values[1] = static_cast<uint64_t>(offset);
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfCfa<AddressType>::cfa_val_offset(dwarf_loc_regs_t* loc_regs) {
+  AddressType reg = operands_[0];
+  SignedType offset = static_cast<SignedType>(operands_[1]) * fde_->cie->data_alignment_factor;
+  (*loc_regs)[reg] = {.type = DWARF_LOCATION_VAL_OFFSET, .values = {static_cast<uint64_t>(offset)}};
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfCfa<AddressType>::cfa_val_offset_sf(dwarf_loc_regs_t* loc_regs) {
+  AddressType reg = operands_[0];
+  SignedType offset = static_cast<SignedType>(operands_[1]) * fde_->cie->data_alignment_factor;
+  (*loc_regs)[reg] = {.type = DWARF_LOCATION_VAL_OFFSET, .values = {static_cast<uint64_t>(offset)}};
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfCfa<AddressType>::cfa_val_expression(dwarf_loc_regs_t* loc_regs) {
+  AddressType reg = operands_[0];
+  (*loc_regs)[reg] = {.type = DWARF_LOCATION_VAL_EXPRESSION,
+                      .values = {operands_[1], memory_->cur_offset()}};
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfCfa<AddressType>::cfa_gnu_negative_offset_extended(dwarf_loc_regs_t* loc_regs) {
+  AddressType reg = operands_[0];
+  SignedType offset = -static_cast<SignedType>(operands_[1]);
+  (*loc_regs)[reg] = {.type = DWARF_LOCATION_OFFSET, .values = {static_cast<uint64_t>(offset)}};
+  return true;
+}
+
+const DwarfCfaInfo::Info DwarfCfaInfo::kTable[64] = {
+    {
+        // 0x00 DW_CFA_nop
+        "DW_CFA_nop",
+        2,
+        0,
+        {},
+        {},
+    },
+    {
+        "DW_CFA_set_loc",  // 0x01 DW_CFA_set_loc
+        2,
+        1,
+        {DW_EH_PE_absptr},
+        {DWARF_DISPLAY_SET_LOC},
+    },
+    {
+        "DW_CFA_advance_loc1",  // 0x02 DW_CFA_advance_loc1
+        2,
+        1,
+        {DW_EH_PE_udata1},
+        {DWARF_DISPLAY_ADVANCE_LOC},
+    },
+    {
+        "DW_CFA_advance_loc2",  // 0x03 DW_CFA_advance_loc2
+        2,
+        1,
+        {DW_EH_PE_udata2},
+        {DWARF_DISPLAY_ADVANCE_LOC},
+    },
+    {
+        "DW_CFA_advance_loc4",  // 0x04 DW_CFA_advance_loc4
+        2,
+        1,
+        {DW_EH_PE_udata4},
+        {DWARF_DISPLAY_ADVANCE_LOC},
+    },
+    {
+        "DW_CFA_offset_extended",  // 0x05 DW_CFA_offset_extended
+        2,
+        2,
+        {DW_EH_PE_uleb128, DW_EH_PE_uleb128},
+        {DWARF_DISPLAY_REGISTER, DWARF_DISPLAY_NUMBER},
+    },
+    {
+        "DW_CFA_restore_extended",  // 0x06 DW_CFA_restore_extended
+        2,
+        1,
+        {DW_EH_PE_uleb128},
+        {DWARF_DISPLAY_REGISTER},
+    },
+    {
+        "DW_CFA_undefined",  // 0x07 DW_CFA_undefined
+        2,
+        1,
+        {DW_EH_PE_uleb128},
+        {DWARF_DISPLAY_REGISTER},
+    },
+    {
+        "DW_CFA_same_value",  // 0x08 DW_CFA_same_value
+        2,
+        1,
+        {DW_EH_PE_uleb128},
+        {DWARF_DISPLAY_REGISTER},
+    },
+    {
+        "DW_CFA_register",  // 0x09 DW_CFA_register
+        2,
+        2,
+        {DW_EH_PE_uleb128, DW_EH_PE_uleb128},
+        {DWARF_DISPLAY_REGISTER, DWARF_DISPLAY_REGISTER},
+    },
+    {
+        "DW_CFA_remember_state",  // 0x0a DW_CFA_remember_state
+        2,
+        0,
+        {},
+        {},
+    },
+    {
+        "DW_CFA_restore_state",  // 0x0b DW_CFA_restore_state
+        2,
+        0,
+        {},
+        {},
+    },
+    {
+        "DW_CFA_def_cfa",  // 0x0c DW_CFA_def_cfa
+        2,
+        2,
+        {DW_EH_PE_uleb128, DW_EH_PE_uleb128},
+        {DWARF_DISPLAY_REGISTER, DWARF_DISPLAY_NUMBER},
+    },
+    {
+        "DW_CFA_def_cfa_register",  // 0x0d DW_CFA_def_cfa_register
+        2,
+        1,
+        {DW_EH_PE_uleb128},
+        {DWARF_DISPLAY_REGISTER},
+    },
+    {
+        "DW_CFA_def_cfa_offset",  // 0x0e DW_CFA_def_cfa_offset
+        2,
+        1,
+        {DW_EH_PE_uleb128},
+        {DWARF_DISPLAY_NUMBER},
+    },
+    {
+        "DW_CFA_def_cfa_expression",  // 0x0f DW_CFA_def_cfa_expression
+        2,
+        1,
+        {DW_EH_PE_block},
+        {DWARF_DISPLAY_EVAL_BLOCK},
+    },
+    {
+        "DW_CFA_expression",  // 0x10 DW_CFA_expression
+        2,
+        2,
+        {DW_EH_PE_uleb128, DW_EH_PE_block},
+        {DWARF_DISPLAY_REGISTER, DWARF_DISPLAY_EVAL_BLOCK},
+    },
+    {
+        "DW_CFA_offset_extended_sf",  // 0x11 DW_CFA_offset_extend_sf
+        2,
+        2,
+        {DW_EH_PE_uleb128, DW_EH_PE_sleb128},
+        {DWARF_DISPLAY_REGISTER, DWARF_DISPLAY_SIGNED_NUMBER},
+    },
+    {
+        "DW_CFA_def_cfa_sf",  // 0x12 DW_CFA_def_cfa_sf
+        2,
+        2,
+        {DW_EH_PE_uleb128, DW_EH_PE_sleb128},
+        {DWARF_DISPLAY_REGISTER, DWARF_DISPLAY_SIGNED_NUMBER},
+    },
+    {
+        "DW_CFA_def_cfa_offset_sf",  // 0x13 DW_CFA_def_cfa_offset_sf
+        2,
+        1,
+        {DW_EH_PE_sleb128},
+        {DWARF_DISPLAY_SIGNED_NUMBER},
+    },
+    {
+        "DW_CFA_val_offset",  // 0x14 DW_CFA_val_offset
+        2,
+        2,
+        {DW_EH_PE_uleb128, DW_EH_PE_uleb128},
+        {DWARF_DISPLAY_REGISTER, DWARF_DISPLAY_NUMBER},
+    },
+    {
+        "DW_CFA_val_offset_sf",  // 0x15 DW_CFA_val_offset_sf
+        2,
+        2,
+        {DW_EH_PE_uleb128, DW_EH_PE_sleb128},
+        {DWARF_DISPLAY_REGISTER, DWARF_DISPLAY_SIGNED_NUMBER},
+    },
+    {
+        "DW_CFA_val_expression",  // 0x16 DW_CFA_val_expression
+        2,
+        2,
+        {DW_EH_PE_uleb128, DW_EH_PE_block},
+        {DWARF_DISPLAY_REGISTER, DWARF_DISPLAY_EVAL_BLOCK},
+    },
+    {nullptr, 0, 0, {}, {}},  // 0x17 illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x18 illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x19 illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x1a illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x1b illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x1c DW_CFA_lo_user (Treat as illegal)
+    {nullptr, 0, 0, {}, {}},  // 0x1d illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x1e illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x1f illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x20 illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x21 illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x22 illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x23 illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x24 illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x25 illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x26 illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x27 illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x28 illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x29 illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x2a illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x2b illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x2c illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x2d DW_CFA_GNU_window_save (Treat as illegal)
+    {
+        "DW_CFA_GNU_args_size",  // 0x2e DW_CFA_GNU_args_size
+        2,
+        1,
+        {DW_EH_PE_uleb128},
+        {DWARF_DISPLAY_NUMBER},
+    },
+    {
+        "DW_CFA_GNU_negative_offset_extended",  // 0x2f DW_CFA_GNU_negative_offset_extended
+        2,
+        2,
+        {DW_EH_PE_uleb128, DW_EH_PE_uleb128},
+        {DWARF_DISPLAY_REGISTER, DWARF_DISPLAY_NUMBER},
+    },
+    {nullptr, 0, 0, {}, {}},  // 0x31 illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x32 illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x33 illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x34 illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x35 illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x36 illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x37 illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x38 illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x39 illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x3a illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x3b illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x3c illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x3d illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x3e illegal cfa
+    {nullptr, 0, 0, {}, {}},  // 0x3f DW_CFA_hi_user (Treat as illegal)
+};
+
+// Explicitly instantiate DwarfCfa.
+template class DwarfCfa<uint32_t>;
+template class DwarfCfa<uint64_t>;
diff --git a/libunwindstack/DwarfCfa.h b/libunwindstack/DwarfCfa.h
new file mode 100644
index 0000000..ce7da4a
--- /dev/null
+++ b/libunwindstack/DwarfCfa.h
@@ -0,0 +1,255 @@
+/*
+ * 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 _LIBUNWINDSTACK_DWARF_CFA_H
+#define _LIBUNWINDSTACK_DWARF_CFA_H
+
+#include <stdint.h>
+
+#include <stack>
+#include <string>
+#include <type_traits>
+#include <vector>
+
+#include "DwarfError.h"
+#include "DwarfLocation.h"
+#include "DwarfMemory.h"
+#include "DwarfStructs.h"
+
+// DWARF Standard home: http://dwarfstd.org/
+// This code is based on DWARF 4: http://http://dwarfstd.org/doc/DWARF4.pdf
+// See section 6.4.2.1 for a description of the DW_CFA_xxx values.
+
+class DwarfCfaInfo {
+ public:
+  enum DisplayType : uint8_t {
+    DWARF_DISPLAY_NONE = 0,
+    DWARF_DISPLAY_REGISTER,
+    DWARF_DISPLAY_NUMBER,
+    DWARF_DISPLAY_SIGNED_NUMBER,
+    DWARF_DISPLAY_EVAL_BLOCK,
+    DWARF_DISPLAY_ADDRESS,
+    DWARF_DISPLAY_SET_LOC,
+    DWARF_DISPLAY_ADVANCE_LOC,
+  };
+
+  struct Info {
+    const char* name;
+    uint8_t supported_version;
+    uint8_t num_operands;
+    uint8_t operands[2];
+    uint8_t display_operands[2];
+  };
+
+  const static Info kTable[64];
+};
+
+template <typename AddressType>
+class DwarfCfa {
+  // Signed version of AddressType
+  typedef typename std::make_signed<AddressType>::type SignedType;
+
+ public:
+  DwarfCfa(DwarfMemory* memory, const DwarfFDE* fde) : memory_(memory), fde_(fde) {}
+  virtual ~DwarfCfa() = default;
+
+  bool GetLocationInfo(uint64_t pc, uint64_t start_offset, uint64_t end_offset,
+                       dwarf_loc_regs_t* loc_regs);
+
+  bool Log(uint32_t indent, uint64_t pc, uint64_t load_bias, uint64_t start_offset,
+           uint64_t end_offset);
+
+  DwarfError last_error() { return last_error_; }
+
+  AddressType cur_pc() { return cur_pc_; }
+
+  void set_cie_loc_regs(const dwarf_loc_regs_t* cie_loc_regs) { cie_loc_regs_ = cie_loc_regs; }
+
+ protected:
+  std::string GetOperandString(uint8_t operand, uint64_t value, uint64_t* cur_pc);
+
+  bool LogOffsetRegisterString(uint32_t indent, uint64_t cfa_offset, uint8_t reg);
+
+  bool LogInstruction(uint32_t indent, uint64_t cfa_offset, uint8_t op, uint64_t* cur_pc);
+
+ private:
+  DwarfError last_error_;
+  DwarfMemory* memory_;
+  const DwarfFDE* fde_;
+
+  AddressType cur_pc_;
+  const dwarf_loc_regs_t* cie_loc_regs_ = nullptr;
+  std::vector<AddressType> operands_;
+  std::stack<dwarf_loc_regs_t> loc_reg_state_;
+
+  // CFA processing functions.
+  bool cfa_nop(dwarf_loc_regs_t*);
+  bool cfa_set_loc(dwarf_loc_regs_t*);
+  bool cfa_advance_loc(dwarf_loc_regs_t*);
+  bool cfa_offset(dwarf_loc_regs_t*);
+  bool cfa_restore(dwarf_loc_regs_t*);
+  bool cfa_undefined(dwarf_loc_regs_t*);
+  bool cfa_same_value(dwarf_loc_regs_t*);
+  bool cfa_register(dwarf_loc_regs_t*);
+  bool cfa_remember_state(dwarf_loc_regs_t*);
+  bool cfa_restore_state(dwarf_loc_regs_t*);
+  bool cfa_def_cfa(dwarf_loc_regs_t*);
+  bool cfa_def_cfa_register(dwarf_loc_regs_t*);
+  bool cfa_def_cfa_offset(dwarf_loc_regs_t*);
+  bool cfa_def_cfa_expression(dwarf_loc_regs_t*);
+  bool cfa_expression(dwarf_loc_regs_t*);
+  bool cfa_offset_extended_sf(dwarf_loc_regs_t*);
+  bool cfa_def_cfa_sf(dwarf_loc_regs_t*);
+  bool cfa_def_cfa_offset_sf(dwarf_loc_regs_t*);
+  bool cfa_val_offset(dwarf_loc_regs_t*);
+  bool cfa_val_offset_sf(dwarf_loc_regs_t*);
+  bool cfa_val_expression(dwarf_loc_regs_t*);
+  bool cfa_gnu_negative_offset_extended(dwarf_loc_regs_t*);
+
+  using process_func = bool (DwarfCfa::*)(dwarf_loc_regs_t*);
+  constexpr static process_func kCallbackTable[64] = {
+      // 0x00 DW_CFA_nop
+      &DwarfCfa::cfa_nop,
+      // 0x01 DW_CFA_set_loc
+      &DwarfCfa::cfa_set_loc,
+      // 0x02 DW_CFA_advance_loc1
+      &DwarfCfa::cfa_advance_loc,
+      // 0x03 DW_CFA_advance_loc2
+      &DwarfCfa::cfa_advance_loc,
+      // 0x04 DW_CFA_advance_loc4
+      &DwarfCfa::cfa_advance_loc,
+      // 0x05 DW_CFA_offset_extended
+      &DwarfCfa::cfa_offset,
+      // 0x06 DW_CFA_restore_extended
+      &DwarfCfa::cfa_restore,
+      // 0x07 DW_CFA_undefined
+      &DwarfCfa::cfa_undefined,
+      // 0x08 DW_CFA_same_value
+      &DwarfCfa::cfa_same_value,
+      // 0x09 DW_CFA_register
+      &DwarfCfa::cfa_register,
+      // 0x0a DW_CFA_remember_state
+      &DwarfCfa::cfa_remember_state,
+      // 0x0b DW_CFA_restore_state
+      &DwarfCfa::cfa_restore_state,
+      // 0x0c DW_CFA_def_cfa
+      &DwarfCfa::cfa_def_cfa,
+      // 0x0d DW_CFA_def_cfa_register
+      &DwarfCfa::cfa_def_cfa_register,
+      // 0x0e DW_CFA_def_cfa_offset
+      &DwarfCfa::cfa_def_cfa_offset,
+      // 0x0f DW_CFA_def_cfa_expression
+      &DwarfCfa::cfa_def_cfa_expression,
+      // 0x10 DW_CFA_expression
+      &DwarfCfa::cfa_expression,
+      // 0x11 DW_CFA_offset_extended_sf
+      &DwarfCfa::cfa_offset_extended_sf,
+      // 0x12 DW_CFA_def_cfa_sf
+      &DwarfCfa::cfa_def_cfa_sf,
+      // 0x13 DW_CFA_def_cfa_offset_sf
+      &DwarfCfa::cfa_def_cfa_offset_sf,
+      // 0x14 DW_CFA_val_offset
+      &DwarfCfa::cfa_val_offset,
+      // 0x15 DW_CFA_val_offset_sf
+      &DwarfCfa::cfa_val_offset_sf,
+      // 0x16 DW_CFA_val_expression
+      &DwarfCfa::cfa_val_expression,
+      // 0x17 illegal cfa
+      nullptr,
+      // 0x18 illegal cfa
+      nullptr,
+      // 0x19 illegal cfa
+      nullptr,
+      // 0x1a illegal cfa
+      nullptr,
+      // 0x1b illegal cfa
+      nullptr,
+      // 0x1c DW_CFA_lo_user (Treat this as illegal)
+      nullptr,
+      // 0x1d illegal cfa
+      nullptr,
+      // 0x1e illegal cfa
+      nullptr,
+      // 0x1f illegal cfa
+      nullptr,
+      // 0x20 illegal cfa
+      nullptr,
+      // 0x21 illegal cfa
+      nullptr,
+      // 0x22 illegal cfa
+      nullptr,
+      // 0x23 illegal cfa
+      nullptr,
+      // 0x24 illegal cfa
+      nullptr,
+      // 0x25 illegal cfa
+      nullptr,
+      // 0x26 illegal cfa
+      nullptr,
+      // 0x27 illegal cfa
+      nullptr,
+      // 0x28 illegal cfa
+      nullptr,
+      // 0x29 illegal cfa
+      nullptr,
+      // 0x2a illegal cfa
+      nullptr,
+      // 0x2b illegal cfa
+      nullptr,
+      // 0x2c illegal cfa
+      nullptr,
+      // 0x2d DW_CFA_GNU_window_save (Treat this as illegal)
+      nullptr,
+      // 0x2e DW_CFA_GNU_args_size
+      &DwarfCfa::cfa_nop,
+      // 0x2f DW_CFA_GNU_negative_offset_extended
+      &DwarfCfa::cfa_gnu_negative_offset_extended,
+      // 0x30 illegal cfa
+      nullptr,
+      // 0x31 illegal cfa
+      nullptr,
+      // 0x32 illegal cfa
+      nullptr,
+      // 0x33 illegal cfa
+      nullptr,
+      // 0x34 illegal cfa
+      nullptr,
+      // 0x35 illegal cfa
+      nullptr,
+      // 0x36 illegal cfa
+      nullptr,
+      // 0x37 illegal cfa
+      nullptr,
+      // 0x38 illegal cfa
+      nullptr,
+      // 0x39 illegal cfa
+      nullptr,
+      // 0x3a illegal cfa
+      nullptr,
+      // 0x3b illegal cfa
+      nullptr,
+      // 0x3c illegal cfa
+      nullptr,
+      // 0x3d illegal cfa
+      nullptr,
+      // 0x3e illegal cfa
+      nullptr,
+      // 0x3f DW_CFA_hi_user (Treat this as illegal)
+      nullptr,
+  };
+};
+
+#endif  // _LIBUNWINDSTACK_DWARF_CFA_H
diff --git a/libunwindstack/DwarfEncoding.h b/libunwindstack/DwarfEncoding.h
new file mode 100644
index 0000000..0ff3b8c
--- /dev/null
+++ b/libunwindstack/DwarfEncoding.h
@@ -0,0 +1,47 @@
+/*
+ * 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 _LIBUNWINDSTACK_DWARF_ENCODING_H
+#define _LIBUNWINDSTACK_DWARF_ENCODING_H
+
+#include <stdint.h>
+
+enum DwarfEncoding : uint8_t {
+  DW_EH_PE_omit = 0xff,
+
+  DW_EH_PE_absptr = 0x00,
+  DW_EH_PE_uleb128 = 0x01,
+  DW_EH_PE_udata2 = 0x02,
+  DW_EH_PE_udata4 = 0x03,
+  DW_EH_PE_udata8 = 0x04,
+  DW_EH_PE_sleb128 = 0x09,
+  DW_EH_PE_sdata2 = 0x0a,
+  DW_EH_PE_sdata4 = 0x0b,
+  DW_EH_PE_sdata8 = 0x0c,
+
+  DW_EH_PE_pcrel = 0x10,
+  DW_EH_PE_textrel = 0x20,
+  DW_EH_PE_datarel = 0x30,
+  DW_EH_PE_funcrel = 0x40,
+  DW_EH_PE_aligned = 0x50,
+
+  // The following are special values used to encode CFA and OP operands.
+  DW_EH_PE_udata1 = 0x0d,
+  DW_EH_PE_sdata1 = 0x0e,
+  DW_EH_PE_block = 0x0f,
+};
+
+#endif  // _LIBUNWINDSTACK_DWARF_ENCODING_H
diff --git a/bootstat/uptime_parser.h b/libunwindstack/DwarfError.h
similarity index 61%
copy from bootstat/uptime_parser.h
copy to libunwindstack/DwarfError.h
index 756ae9b..824c307 100644
--- a/bootstat/uptime_parser.h
+++ b/libunwindstack/DwarfError.h
@@ -14,16 +14,19 @@
  * limitations under the License.
  */
 
-#ifndef UPTIME_PARSER_H_
-#define UPTIME_PARSER_H_
+#ifndef _LIBUNWINDSTACK_DWARF_ERROR_H
+#define _LIBUNWINDSTACK_DWARF_ERROR_H
 
-#include <time.h>
+#include <stdint.h>
 
-namespace bootstat {
+enum DwarfError : uint8_t {
+  DWARF_ERROR_NONE,
+  DWARF_ERROR_MEMORY_INVALID,
+  DWARF_ERROR_ILLEGAL_VALUE,
+  DWARF_ERROR_ILLEGAL_STATE,
+  DWARF_ERROR_STACK_INDEX_NOT_VALID,
+  DWARF_ERROR_NOT_IMPLEMENTED,
+  DWARF_ERROR_TOO_MANY_ITERATIONS,
+};
 
-// Returns the number of seconds the system has been on since reboot.
-time_t ParseUptime();
-
-}  // namespace bootstat
-
-#endif  // UPTIME_PARSER_H_
\ No newline at end of file
+#endif  // _LIBUNWINDSTACK_DWARF_ERROR_H
diff --git a/libunwindstack/DwarfLocation.h b/libunwindstack/DwarfLocation.h
new file mode 100644
index 0000000..062d125
--- /dev/null
+++ b/libunwindstack/DwarfLocation.h
@@ -0,0 +1,41 @@
+/*
+ * 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 _LIBUNWINDSTACK_DWARF_LOCATION_H
+#define _LIBUNWINDSTACK_DWARF_LOCATION_H
+
+#include <stdint.h>
+
+#include <unordered_map>
+
+enum DwarfLocationEnum : uint8_t {
+  DWARF_LOCATION_INVALID = 0,
+  DWARF_LOCATION_UNDEFINED,
+  DWARF_LOCATION_OFFSET,
+  DWARF_LOCATION_VAL_OFFSET,
+  DWARF_LOCATION_REGISTER,
+  DWARF_LOCATION_EXPRESSION,
+  DWARF_LOCATION_VAL_EXPRESSION,
+};
+
+struct DwarfLocation {
+  DwarfLocationEnum type;
+  uint64_t values[2];
+};
+
+typedef std::unordered_map<uint16_t, DwarfLocation> dwarf_loc_regs_t;
+
+#endif  // _LIBUNWINDSTACK_DWARF_LOCATION_H
diff --git a/libunwindstack/DwarfMemory.cpp b/libunwindstack/DwarfMemory.cpp
new file mode 100644
index 0000000..11806ea
--- /dev/null
+++ b/libunwindstack/DwarfMemory.cpp
@@ -0,0 +1,248 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <assert.h>
+#include <stdint.h>
+
+#include <string>
+
+#include "DwarfEncoding.h"
+#include "DwarfMemory.h"
+#include "Memory.h"
+
+bool DwarfMemory::ReadBytes(void* dst, size_t num_bytes) {
+  if (!memory_->Read(cur_offset_, dst, num_bytes)) {
+    return false;
+  }
+  cur_offset_ += num_bytes;
+  return true;
+}
+
+template <typename SignedType>
+bool DwarfMemory::ReadSigned(uint64_t* value) {
+  SignedType signed_value;
+  if (!ReadBytes(&signed_value, sizeof(SignedType))) {
+    return false;
+  }
+  *value = static_cast<int64_t>(signed_value);
+  return true;
+}
+
+bool DwarfMemory::ReadULEB128(uint64_t* value) {
+  uint64_t cur_value = 0;
+  uint64_t shift = 0;
+  uint8_t byte;
+  do {
+    if (!ReadBytes(&byte, 1)) {
+      return false;
+    }
+    cur_value += static_cast<uint64_t>(byte & 0x7f) << shift;
+    shift += 7;
+  } while (byte & 0x80);
+  *value = cur_value;
+  return true;
+}
+
+bool DwarfMemory::ReadSLEB128(int64_t* value) {
+  uint64_t cur_value = 0;
+  uint64_t shift = 0;
+  uint8_t byte;
+  do {
+    if (!ReadBytes(&byte, 1)) {
+      return false;
+    }
+    cur_value += static_cast<uint64_t>(byte & 0x7f) << shift;
+    shift += 7;
+  } while (byte & 0x80);
+  if (byte & 0x40) {
+    // Negative value, need to sign extend.
+    cur_value |= static_cast<uint64_t>(-1) << shift;
+  }
+  *value = static_cast<int64_t>(cur_value);
+  return true;
+}
+
+template <typename AddressType>
+size_t DwarfMemory::GetEncodedSize(uint8_t encoding) {
+  switch (encoding & 0x0f) {
+    case DW_EH_PE_absptr:
+      return sizeof(AddressType);
+    case DW_EH_PE_udata1:
+    case DW_EH_PE_sdata1:
+      return 1;
+    case DW_EH_PE_udata2:
+    case DW_EH_PE_sdata2:
+      return 2;
+    case DW_EH_PE_udata4:
+    case DW_EH_PE_sdata4:
+      return 4;
+    case DW_EH_PE_udata8:
+    case DW_EH_PE_sdata8:
+      return 8;
+    case DW_EH_PE_uleb128:
+    case DW_EH_PE_sleb128:
+    default:
+      return 0;
+  }
+}
+
+bool DwarfMemory::AdjustEncodedValue(uint8_t encoding, uint64_t* value) {
+  assert((encoding & 0x0f) == 0);
+  assert(encoding != DW_EH_PE_aligned);
+
+  // Handle the encoding.
+  switch (encoding) {
+    case DW_EH_PE_absptr:
+      // Nothing to do.
+      break;
+    case DW_EH_PE_pcrel:
+      if (pc_offset_ == static_cast<uint64_t>(-1)) {
+        // Unsupported encoding.
+        return false;
+      }
+      *value += pc_offset_;
+      break;
+    case DW_EH_PE_textrel:
+      if (text_offset_ == static_cast<uint64_t>(-1)) {
+        // Unsupported encoding.
+        return false;
+      }
+      *value += text_offset_;
+      break;
+    case DW_EH_PE_datarel:
+      if (data_offset_ == static_cast<uint64_t>(-1)) {
+        // Unsupported encoding.
+        return false;
+      }
+      *value += data_offset_;
+      break;
+    case DW_EH_PE_funcrel:
+      if (func_offset_ == static_cast<uint64_t>(-1)) {
+        // Unsupported encoding.
+        return false;
+      }
+      *value += func_offset_;
+      break;
+    default:
+      return false;
+  }
+
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfMemory::ReadEncodedValue(uint8_t encoding, uint64_t* value) {
+  if (encoding == DW_EH_PE_omit) {
+    *value = 0;
+    return true;
+  } else if (encoding == DW_EH_PE_aligned) {
+    if (__builtin_add_overflow(cur_offset_, sizeof(AddressType) - 1, &cur_offset_)) {
+      return false;
+    }
+    cur_offset_ &= -sizeof(AddressType);
+
+    if (sizeof(AddressType) != sizeof(uint64_t)) {
+      *value = 0;
+    }
+    return ReadBytes(value, sizeof(AddressType));
+  }
+
+  // Get the data.
+  switch (encoding & 0x0f) {
+    case DW_EH_PE_absptr:
+      if (sizeof(AddressType) != sizeof(uint64_t)) {
+        *value = 0;
+      }
+      if (!ReadBytes(value, sizeof(AddressType))) {
+        return false;
+      }
+      break;
+    case DW_EH_PE_uleb128:
+      if (!ReadULEB128(value)) {
+        return false;
+      }
+      break;
+    case DW_EH_PE_sleb128:
+      int64_t signed_value;
+      if (!ReadSLEB128(&signed_value)) {
+        return false;
+      }
+      *value = static_cast<uint64_t>(signed_value);
+      break;
+    case DW_EH_PE_udata1: {
+      uint8_t value8;
+      if (!ReadBytes(&value8, 1)) {
+        return false;
+      }
+      *value = value8;
+    } break;
+    case DW_EH_PE_sdata1:
+      if (!ReadSigned<int8_t>(value)) {
+        return false;
+      }
+      break;
+    case DW_EH_PE_udata2: {
+      uint16_t value16;
+      if (!ReadBytes(&value16, 2)) {
+        return false;
+      }
+      *value = value16;
+    } break;
+    case DW_EH_PE_sdata2:
+      if (!ReadSigned<int16_t>(value)) {
+        return false;
+      }
+      break;
+    case DW_EH_PE_udata4: {
+      uint32_t value32;
+      if (!ReadBytes(&value32, 4)) {
+        return false;
+      }
+      *value = value32;
+    } break;
+    case DW_EH_PE_sdata4:
+      if (!ReadSigned<int32_t>(value)) {
+        return false;
+      }
+      break;
+    case DW_EH_PE_udata8:
+      if (!ReadBytes(value, sizeof(uint64_t))) {
+        return false;
+      }
+      break;
+    case DW_EH_PE_sdata8:
+      if (!ReadSigned<int64_t>(value)) {
+        return false;
+      }
+      break;
+    default:
+      return false;
+  }
+
+  return AdjustEncodedValue(encoding & 0xf0, value);
+}
+
+// Instantiate all of the needed template functions.
+template bool DwarfMemory::ReadSigned<int8_t>(uint64_t*);
+template bool DwarfMemory::ReadSigned<int16_t>(uint64_t*);
+template bool DwarfMemory::ReadSigned<int32_t>(uint64_t*);
+template bool DwarfMemory::ReadSigned<int64_t>(uint64_t*);
+
+template size_t DwarfMemory::GetEncodedSize<uint32_t>(uint8_t);
+template size_t DwarfMemory::GetEncodedSize<uint64_t>(uint8_t);
+
+template bool DwarfMemory::ReadEncodedValue<uint32_t>(uint8_t, uint64_t*);
+template bool DwarfMemory::ReadEncodedValue<uint64_t>(uint8_t, uint64_t*);
diff --git a/libunwindstack/DwarfMemory.h b/libunwindstack/DwarfMemory.h
new file mode 100644
index 0000000..a304dd9
--- /dev/null
+++ b/libunwindstack/DwarfMemory.h
@@ -0,0 +1,72 @@
+/*
+ * 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 _LIBUNWINDSTACK_DWARF_MEMORY_H
+#define _LIBUNWINDSTACK_DWARF_MEMORY_H
+
+#include <stdint.h>
+
+// Forward declarations.
+class Memory;
+
+class DwarfMemory {
+ public:
+  DwarfMemory(Memory* memory) : memory_(memory) {}
+  virtual ~DwarfMemory() = default;
+
+  bool ReadBytes(void* dst, size_t num_bytes);
+
+  template <typename SignedType>
+  bool ReadSigned(uint64_t* value);
+
+  bool ReadULEB128(uint64_t* value);
+
+  bool ReadSLEB128(int64_t* value);
+
+  template <typename AddressType>
+  size_t GetEncodedSize(uint8_t encoding);
+
+  bool AdjustEncodedValue(uint8_t encoding, uint64_t* value);
+
+  template <typename AddressType>
+  bool ReadEncodedValue(uint8_t encoding, uint64_t* value);
+
+  uint64_t cur_offset() { return cur_offset_; }
+  void set_cur_offset(uint64_t cur_offset) { cur_offset_ = cur_offset; }
+
+  void set_pc_offset(uint64_t offset) { pc_offset_ = offset; }
+  void clear_pc_offset() { pc_offset_ = static_cast<uint64_t>(-1); }
+
+  void set_data_offset(uint64_t offset) { data_offset_ = offset; }
+  void clear_data_offset() { data_offset_ = static_cast<uint64_t>(-1); }
+
+  void set_func_offset(uint64_t offset) { func_offset_ = offset; }
+  void clear_func_offset() { func_offset_ = static_cast<uint64_t>(-1); }
+
+  void set_text_offset(uint64_t offset) { text_offset_ = offset; }
+  void clear_text_offset() { text_offset_ = static_cast<uint64_t>(-1); }
+
+ private:
+  Memory* memory_;
+  uint64_t cur_offset_ = 0;
+
+  uint64_t pc_offset_ = static_cast<uint64_t>(-1);
+  uint64_t data_offset_ = static_cast<uint64_t>(-1);
+  uint64_t func_offset_ = static_cast<uint64_t>(-1);
+  uint64_t text_offset_ = static_cast<uint64_t>(-1);
+};
+
+#endif  // _LIBUNWINDSTACK_DWARF_MEMORY_H
diff --git a/libunwindstack/DwarfOp.cpp b/libunwindstack/DwarfOp.cpp
new file mode 100644
index 0000000..507ca08
--- /dev/null
+++ b/libunwindstack/DwarfOp.cpp
@@ -0,0 +1,462 @@
+/*
+ * 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 <deque>
+#include <string>
+#include <vector>
+
+#include <android-base/stringprintf.h>
+
+#include "DwarfError.h"
+#include "DwarfMemory.h"
+#include "DwarfOp.h"
+#include "Log.h"
+#include "Memory.h"
+#include "Regs.h"
+
+template <typename AddressType>
+constexpr typename DwarfOp<AddressType>::OpCallback DwarfOp<AddressType>::kCallbackTable[256];
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::Eval(uint64_t start, uint64_t end, uint8_t dwarf_version) {
+  uint32_t iterations = 0;
+  is_register_ = false;
+  stack_.clear();
+  memory_->set_cur_offset(start);
+  while (memory_->cur_offset() < end) {
+    if (!Decode(dwarf_version)) {
+      return false;
+    }
+    // To protect against a branch that creates an infinite loop,
+    // terminate if the number of iterations gets too high.
+    if (iterations++ == 1000) {
+      last_error_ = DWARF_ERROR_TOO_MANY_ITERATIONS;
+      return false;
+    }
+  }
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::Decode(uint8_t dwarf_version) {
+  last_error_ = DWARF_ERROR_NONE;
+  if (!memory_->ReadBytes(&cur_op_, 1)) {
+    last_error_ = DWARF_ERROR_MEMORY_INVALID;
+    return false;
+  }
+
+  const auto* op = &kCallbackTable[cur_op_];
+  const auto handle_func = op->handle_func;
+  if (handle_func == nullptr) {
+    last_error_ = DWARF_ERROR_ILLEGAL_VALUE;
+    return false;
+  }
+
+  // Check for an unsupported opcode.
+  if (dwarf_version < op->supported_version) {
+    last_error_ = DWARF_ERROR_ILLEGAL_VALUE;
+    return false;
+  }
+
+  // Make sure that the required number of stack elements is available.
+  if (stack_.size() < op->num_required_stack_values) {
+    last_error_ = DWARF_ERROR_STACK_INDEX_NOT_VALID;
+    return false;
+  }
+
+  operands_.clear();
+  for (size_t i = 0; i < op->num_operands; i++) {
+    uint64_t value;
+    if (!memory_->ReadEncodedValue<AddressType>(op->operands[i], &value)) {
+      last_error_ = DWARF_ERROR_MEMORY_INVALID;
+      return false;
+    }
+    operands_.push_back(value);
+  }
+  return (this->*handle_func)();
+}
+
+template <typename AddressType>
+void DwarfOp<AddressType>::GetLogInfo(uint64_t start, uint64_t end,
+                                      std::vector<std::string>* lines) {
+  memory_->set_cur_offset(start);
+  while (memory_->cur_offset() < end) {
+    uint8_t cur_op;
+    if (!memory_->ReadBytes(&cur_op, 1)) {
+      return;
+    }
+
+    std::string raw_string(android::base::StringPrintf("Raw Data: 0x%02x", cur_op));
+    std::string log_string;
+    const auto* op = &kCallbackTable[cur_op];
+    if (op->handle_func == nullptr) {
+      log_string = "Illegal";
+    } else {
+      log_string = op->name;
+      uint64_t start_offset = memory_->cur_offset();
+      for (size_t i = 0; i < op->num_operands; i++) {
+        uint64_t value;
+        if (!memory_->ReadEncodedValue<AddressType>(op->operands[i], &value)) {
+          return;
+        }
+        log_string += ' ' + std::to_string(value);
+      }
+      uint64_t end_offset = memory_->cur_offset();
+
+      memory_->set_cur_offset(start_offset);
+      for (size_t i = start_offset; i < end_offset; i++) {
+        uint8_t byte;
+        if (!memory_->ReadBytes(&byte, 1)) {
+          return;
+        }
+        raw_string += android::base::StringPrintf(" 0x%02x", byte);
+      }
+      memory_->set_cur_offset(end_offset);
+    }
+    lines->push_back(std::move(log_string));
+    lines->push_back(std::move(raw_string));
+  }
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_deref() {
+  // Read the address and dereference it.
+  AddressType addr = StackPop();
+  AddressType value;
+  if (!regular_memory()->Read(addr, &value, sizeof(value))) {
+    last_error_ = DWARF_ERROR_MEMORY_INVALID;
+    return false;
+  }
+  stack_.push_front(value);
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_deref_size() {
+  AddressType bytes_to_read = OperandAt(0);
+  if (bytes_to_read > sizeof(AddressType) || bytes_to_read == 0) {
+    last_error_ = DWARF_ERROR_ILLEGAL_VALUE;
+    return false;
+  }
+  // Read the address and dereference it.
+  AddressType addr = StackPop();
+  AddressType value = 0;
+  if (!regular_memory()->Read(addr, &value, bytes_to_read)) {
+    last_error_ = DWARF_ERROR_MEMORY_INVALID;
+    return false;
+  }
+  stack_.push_front(value);
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_push() {
+  // Push all of the operands.
+  for (auto operand : operands_) {
+    stack_.push_front(operand);
+  }
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_dup() {
+  stack_.push_front(StackAt(0));
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_drop() {
+  StackPop();
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_over() {
+  stack_.push_front(StackAt(1));
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_pick() {
+  AddressType index = OperandAt(0);
+  if (index > StackSize()) {
+    last_error_ = DWARF_ERROR_STACK_INDEX_NOT_VALID;
+    return false;
+  }
+  stack_.push_front(StackAt(index));
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_swap() {
+  AddressType old_value = stack_[0];
+  stack_[0] = stack_[1];
+  stack_[1] = old_value;
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_rot() {
+  AddressType top = stack_[0];
+  stack_[0] = stack_[1];
+  stack_[1] = stack_[2];
+  stack_[2] = top;
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_abs() {
+  SignedType signed_value = static_cast<SignedType>(stack_[0]);
+  if (signed_value < 0) {
+    signed_value = -signed_value;
+  }
+  stack_[0] = static_cast<AddressType>(signed_value);
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_and() {
+  AddressType top = StackPop();
+  stack_[0] &= top;
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_div() {
+  AddressType top = StackPop();
+  if (top == 0) {
+    last_error_ = DWARF_ERROR_ILLEGAL_VALUE;
+    return false;
+  }
+  SignedType signed_divisor = static_cast<SignedType>(top);
+  SignedType signed_dividend = static_cast<SignedType>(stack_[0]);
+  stack_[0] = static_cast<AddressType>(signed_dividend / signed_divisor);
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_minus() {
+  AddressType top = StackPop();
+  stack_[0] -= top;
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_mod() {
+  AddressType top = StackPop();
+  if (top == 0) {
+    last_error_ = DWARF_ERROR_ILLEGAL_VALUE;
+    return false;
+  }
+  stack_[0] %= top;
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_mul() {
+  AddressType top = StackPop();
+  stack_[0] *= top;
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_neg() {
+  SignedType signed_value = static_cast<SignedType>(stack_[0]);
+  stack_[0] = static_cast<AddressType>(-signed_value);
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_not() {
+  stack_[0] = ~stack_[0];
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_or() {
+  AddressType top = StackPop();
+  stack_[0] |= top;
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_plus() {
+  AddressType top = StackPop();
+  stack_[0] += top;
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_plus_uconst() {
+  stack_[0] += OperandAt(0);
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_shl() {
+  AddressType top = StackPop();
+  stack_[0] <<= top;
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_shr() {
+  AddressType top = StackPop();
+  stack_[0] >>= top;
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_shra() {
+  AddressType top = StackPop();
+  SignedType signed_value = static_cast<SignedType>(stack_[0]) >> top;
+  stack_[0] = static_cast<AddressType>(signed_value);
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_xor() {
+  AddressType top = StackPop();
+  stack_[0] ^= top;
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_bra() {
+  // Requires one stack element.
+  AddressType top = StackPop();
+  int16_t offset = static_cast<int16_t>(OperandAt(0));
+  uint64_t cur_offset;
+  if (top != 0) {
+    cur_offset = memory_->cur_offset() + offset;
+  } else {
+    cur_offset = memory_->cur_offset() - offset;
+  }
+  memory_->set_cur_offset(cur_offset);
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_eq() {
+  AddressType top = StackPop();
+  stack_[0] = bool_to_dwarf_bool(stack_[0] == top);
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_ge() {
+  AddressType top = StackPop();
+  stack_[0] = bool_to_dwarf_bool(stack_[0] >= top);
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_gt() {
+  AddressType top = StackPop();
+  stack_[0] = bool_to_dwarf_bool(stack_[0] > top);
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_le() {
+  AddressType top = StackPop();
+  stack_[0] = bool_to_dwarf_bool(stack_[0] <= top);
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_lt() {
+  AddressType top = StackPop();
+  stack_[0] = bool_to_dwarf_bool(stack_[0] < top);
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_ne() {
+  AddressType top = StackPop();
+  stack_[0] = bool_to_dwarf_bool(stack_[0] != top);
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_skip() {
+  int16_t offset = static_cast<int16_t>(OperandAt(0));
+  uint64_t cur_offset = memory_->cur_offset() + offset;
+  memory_->set_cur_offset(cur_offset);
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_lit() {
+  stack_.push_front(cur_op() - 0x30);
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_reg() {
+  is_register_ = true;
+  stack_.push_front(cur_op() - 0x50);
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_regx() {
+  is_register_ = true;
+  stack_.push_front(OperandAt(0));
+  return true;
+}
+
+// It's not clear for breg/bregx, if this op should read the current
+// value of the register, or where we think that register is located.
+// For simplicity, the code will read the value before doing the unwind.
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_breg() {
+  uint16_t reg = cur_op() - 0x70;
+  if (reg >= regs_->total_regs()) {
+    last_error_ = DWARF_ERROR_ILLEGAL_VALUE;
+    return false;
+  }
+  stack_.push_front((*regs_)[reg] + OperandAt(0));
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_bregx() {
+  AddressType reg = OperandAt(0);
+  if (reg >= regs_->total_regs()) {
+    last_error_ = DWARF_ERROR_ILLEGAL_VALUE;
+    return false;
+  }
+  stack_.push_front((*regs_)[reg] + OperandAt(1));
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_nop() {
+  return true;
+}
+
+template <typename AddressType>
+bool DwarfOp<AddressType>::op_not_implemented() {
+  last_error_ = DWARF_ERROR_NOT_IMPLEMENTED;
+  return false;
+}
+
+// Explicitly instantiate DwarfOp.
+template class DwarfOp<uint32_t>;
+template class DwarfOp<uint64_t>;
diff --git a/libunwindstack/DwarfOp.h b/libunwindstack/DwarfOp.h
new file mode 100644
index 0000000..ed6537a
--- /dev/null
+++ b/libunwindstack/DwarfOp.h
@@ -0,0 +1,1636 @@
+/*
+ * 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 _LIBUNWINDSTACK_DWARF_OP_H
+#define _LIBUNWINDSTACK_DWARF_OP_H
+
+#include <stdint.h>
+
+#include <deque>
+#include <string>
+#include <type_traits>
+#include <vector>
+
+#include "DwarfEncoding.h"
+
+enum DwarfVersion : uint8_t {
+  DWARF_VERSION_2 = 2,
+  DWARF_VERSION_3 = 3,
+  DWARF_VERSION_4 = 4,
+  DWARF_VERSION_MAX = DWARF_VERSION_4,
+};
+
+// Forward declarations.
+class DwarfMemory;
+class Memory;
+template <typename AddressType>
+class RegsTmpl;
+
+template <typename AddressType>
+class DwarfOp {
+  // Signed version of AddressType
+  typedef typename std::make_signed<AddressType>::type SignedType;
+
+  struct OpCallback {
+    const char* name;
+    bool (DwarfOp::*handle_func)();
+    uint8_t supported_version;
+    uint8_t num_required_stack_values;
+    uint8_t num_operands;
+    uint8_t operands[2];
+  };
+
+ public:
+  DwarfOp(DwarfMemory* memory, Memory* regular_memory)
+      : memory_(memory), regular_memory_(regular_memory) {}
+  virtual ~DwarfOp() = default;
+
+  bool Decode(uint8_t dwarf_version);
+
+  bool Eval(uint64_t start, uint64_t end, uint8_t dwarf_version);
+
+  void GetLogInfo(uint64_t start, uint64_t end, std::vector<std::string>* lines);
+
+  AddressType StackAt(size_t index) { return stack_[index]; }
+  size_t StackSize() { return stack_.size(); }
+
+  void set_regs(RegsTmpl<AddressType>* regs) { regs_ = regs; }
+
+  DwarfError last_error() { return last_error_; }
+
+  bool is_register() { return is_register_; }
+
+  uint8_t cur_op() { return cur_op_; }
+
+  Memory* regular_memory() { return regular_memory_; }
+
+ protected:
+  AddressType OperandAt(size_t index) { return operands_[index]; }
+  size_t OperandsSize() { return operands_.size(); }
+
+  AddressType StackPop() {
+    AddressType value = stack_.front();
+    stack_.pop_front();
+    return value;
+  }
+
+ private:
+  DwarfMemory* memory_;
+  Memory* regular_memory_;
+
+  RegsTmpl<AddressType>* regs_;
+  bool is_register_ = false;
+  DwarfError last_error_ = DWARF_ERROR_NONE;
+  uint8_t cur_op_;
+  std::vector<AddressType> operands_;
+  std::deque<AddressType> stack_;
+
+  inline AddressType bool_to_dwarf_bool(bool value) { return value ? 1 : 0; }
+
+  // Op processing functions.
+  bool op_deref();
+  bool op_deref_size();
+  bool op_push();
+  bool op_dup();
+  bool op_drop();
+  bool op_over();
+  bool op_pick();
+  bool op_swap();
+  bool op_rot();
+  bool op_abs();
+  bool op_and();
+  bool op_div();
+  bool op_minus();
+  bool op_mod();
+  bool op_mul();
+  bool op_neg();
+  bool op_not();
+  bool op_or();
+  bool op_plus();
+  bool op_plus_uconst();
+  bool op_shl();
+  bool op_shr();
+  bool op_shra();
+  bool op_xor();
+  bool op_bra();
+  bool op_eq();
+  bool op_ge();
+  bool op_gt();
+  bool op_le();
+  bool op_lt();
+  bool op_ne();
+  bool op_skip();
+  bool op_lit();
+  bool op_reg();
+  bool op_regx();
+  bool op_breg();
+  bool op_bregx();
+  bool op_nop();
+  bool op_not_implemented();
+
+  constexpr static OpCallback kCallbackTable[256] = {
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0x00 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0x01 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0x02 illegal op
+      {
+          // 0x03 DW_OP_addr
+          "DW_OP_addr",
+          &DwarfOp::op_push,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_absptr},
+      },
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0x04 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0x05 illegal op
+      {
+          // 0x06 DW_OP_deref
+          "DW_OP_deref",
+          &DwarfOp::op_deref,
+          DWARF_VERSION_2,
+          1,
+          0,
+          {},
+      },
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0x07 illegal op
+      {
+          // 0x08 DW_OP_const1u
+          "DW_OP_const1u",
+          &DwarfOp::op_push,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_udata1},
+      },
+      {
+          // 0x09 DW_OP_const1s
+          "DW_OP_const1s",
+          &DwarfOp::op_push,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sdata1},
+      },
+      {
+          // 0x0a DW_OP_const2u
+          "DW_OP_const2u",
+          &DwarfOp::op_push,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_udata2},
+      },
+      {
+          // 0x0b DW_OP_const2s
+          "DW_OP_const2s",
+          &DwarfOp::op_push,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sdata2},
+      },
+      {
+          // 0x0c DW_OP_const4u
+          "DW_OP_const4u",
+          &DwarfOp::op_push,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_udata4},
+      },
+      {
+          // 0x0d DW_OP_const4s
+          "DW_OP_const4s",
+          &DwarfOp::op_push,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sdata4},
+      },
+      {
+          // 0x0e DW_OP_const8u
+          "DW_OP_const8u",
+          &DwarfOp::op_push,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_udata8},
+      },
+      {
+          // 0x0f DW_OP_const8s
+          "DW_OP_const8s",
+          &DwarfOp::op_push,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sdata8},
+      },
+      {
+          // 0x10 DW_OP_constu
+          "DW_OP_constu",
+          &DwarfOp::op_push,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_uleb128},
+      },
+      {
+          // 0x11 DW_OP_consts
+          "DW_OP_consts",
+          &DwarfOp::op_push,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x12 DW_OP_dup
+          "DW_OP_dup",
+          &DwarfOp::op_dup,
+          DWARF_VERSION_2,
+          1,
+          0,
+          {},
+      },
+      {
+          // 0x13 DW_OP_drop
+          "DW_OP_drop",
+          &DwarfOp::op_drop,
+          DWARF_VERSION_2,
+          1,
+          0,
+          {},
+      },
+      {
+          // 0x14 DW_OP_over
+          "DW_OP_over",
+          &DwarfOp::op_over,
+          DWARF_VERSION_2,
+          2,
+          0,
+          {},
+      },
+      {
+          // 0x15 DW_OP_pick
+          "DW_OP_pick",
+          &DwarfOp::op_pick,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_udata1},
+      },
+      {
+          // 0x16 DW_OP_swap
+          "DW_OP_swap",
+          &DwarfOp::op_swap,
+          DWARF_VERSION_2,
+          2,
+          0,
+          {},
+      },
+      {
+          // 0x17 DW_OP_rot
+          "DW_OP_rot",
+          &DwarfOp::op_rot,
+          DWARF_VERSION_2,
+          3,
+          0,
+          {},
+      },
+      {
+          // 0x18 DW_OP_xderef
+          "DW_OP_xderef",
+          &DwarfOp::op_not_implemented,
+          DWARF_VERSION_2,
+          2,
+          0,
+          {},
+      },
+      {
+          // 0x19 DW_OP_abs
+          "DW_OP_abs",
+          &DwarfOp::op_abs,
+          DWARF_VERSION_2,
+          1,
+          0,
+          {},
+      },
+      {
+          // 0x1a DW_OP_and
+          "DW_OP_and",
+          &DwarfOp::op_and,
+          DWARF_VERSION_2,
+          2,
+          0,
+          {},
+      },
+      {
+          // 0x1b DW_OP_div
+          "DW_OP_div",
+          &DwarfOp::op_div,
+          DWARF_VERSION_2,
+          2,
+          0,
+          {},
+      },
+      {
+          // 0x1c DW_OP_minus
+          "DW_OP_minus",
+          &DwarfOp::op_minus,
+          DWARF_VERSION_2,
+          2,
+          0,
+          {},
+      },
+      {
+          // 0x1d DW_OP_mod
+          "DW_OP_mod",
+          &DwarfOp::op_mod,
+          DWARF_VERSION_2,
+          2,
+          0,
+          {},
+      },
+      {
+          // 0x1e DW_OP_mul
+          "DW_OP_mul",
+          &DwarfOp::op_mul,
+          DWARF_VERSION_2,
+          2,
+          0,
+          {},
+      },
+      {
+          // 0x1f DW_OP_neg
+          "DW_OP_neg",
+          &DwarfOp::op_neg,
+          DWARF_VERSION_2,
+          1,
+          0,
+          {},
+      },
+      {
+          // 0x20 DW_OP_not
+          "DW_OP_not",
+          &DwarfOp::op_not,
+          DWARF_VERSION_2,
+          1,
+          0,
+          {},
+      },
+      {
+          // 0x21 DW_OP_or
+          "DW_OP_or",
+          &DwarfOp::op_or,
+          DWARF_VERSION_2,
+          2,
+          0,
+          {},
+      },
+      {
+          // 0x22 DW_OP_plus
+          "DW_OP_plus",
+          &DwarfOp::op_plus,
+          DWARF_VERSION_2,
+          2,
+          0,
+          {},
+      },
+      {
+          // 0x23 DW_OP_plus_uconst
+          "DW_OP_plus_uconst",
+          &DwarfOp::op_plus_uconst,
+          DWARF_VERSION_2,
+          1,
+          1,
+          {DW_EH_PE_uleb128},
+      },
+      {
+          // 0x24 DW_OP_shl
+          "DW_OP_shl",
+          &DwarfOp::op_shl,
+          DWARF_VERSION_2,
+          2,
+          0,
+          {},
+      },
+      {
+          // 0x25 DW_OP_shr
+          "DW_OP_shr",
+          &DwarfOp::op_shr,
+          DWARF_VERSION_2,
+          2,
+          0,
+          {},
+      },
+      {
+          // 0x26 DW_OP_shra
+          "DW_OP_shra",
+          &DwarfOp::op_shra,
+          DWARF_VERSION_2,
+          2,
+          0,
+          {},
+      },
+      {
+          // 0x27 DW_OP_xor
+          "DW_OP_xor",
+          &DwarfOp::op_xor,
+          DWARF_VERSION_2,
+          2,
+          0,
+          {},
+      },
+      {
+          // 0x28 DW_OP_bra
+          "DW_OP_bra",
+          &DwarfOp::op_bra,
+          DWARF_VERSION_2,
+          1,
+          1,
+          {DW_EH_PE_sdata2},
+      },
+      {
+          // 0x29 DW_OP_eq
+          "DW_OP_eq",
+          &DwarfOp::op_eq,
+          DWARF_VERSION_2,
+          2,
+          0,
+          {},
+      },
+      {
+          // 0x2a DW_OP_ge
+          "DW_OP_ge",
+          &DwarfOp::op_ge,
+          DWARF_VERSION_2,
+          2,
+          0,
+          {},
+      },
+      {
+          // 0x2b DW_OP_gt
+          "DW_OP_gt",
+          &DwarfOp::op_gt,
+          DWARF_VERSION_2,
+          2,
+          0,
+          {},
+      },
+      {
+          // 0x2c DW_OP_le
+          "DW_OP_le",
+          &DwarfOp::op_le,
+          DWARF_VERSION_2,
+          2,
+          0,
+          {},
+      },
+      {
+          // 0x2d DW_OP_lt
+          "DW_OP_lt",
+          &DwarfOp::op_lt,
+          DWARF_VERSION_2,
+          2,
+          0,
+          {},
+      },
+      {
+          // 0x2e DW_OP_ne
+          "DW_OP_ne",
+          &DwarfOp::op_ne,
+          DWARF_VERSION_2,
+          2,
+          0,
+          {},
+      },
+      {
+          // 0x2f DW_OP_skip
+          "DW_OP_skip",
+          &DwarfOp::op_skip,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sdata2},
+      },
+      {
+          // 0x30 DW_OP_lit0
+          "DW_OP_lit0",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x31 DW_OP_lit1
+          "DW_OP_lit1",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x32 DW_OP_lit2
+          "DW_OP_lit2",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x33 DW_OP_lit3
+          "DW_OP_lit3",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x34 DW_OP_lit4
+          "DW_OP_lit4",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x35 DW_OP_lit5
+          "DW_OP_lit5",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x36 DW_OP_lit6
+          "DW_OP_lit6",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x37 DW_OP_lit7
+          "DW_OP_lit7",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x38 DW_OP_lit8
+          "DW_OP_lit8",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x39 DW_OP_lit9
+          "DW_OP_lit9",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x3a DW_OP_lit10
+          "DW_OP_lit10",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x3b DW_OP_lit11
+          "DW_OP_lit11",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x3c DW_OP_lit12
+          "DW_OP_lit12",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x3d DW_OP_lit13
+          "DW_OP_lit13",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x3e DW_OP_lit14
+          "DW_OP_lit14",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x3f DW_OP_lit15
+          "DW_OP_lit15",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x40 DW_OP_lit16
+          "DW_OP_lit16",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x41 DW_OP_lit17
+          "DW_OP_lit17",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x42 DW_OP_lit18
+          "DW_OP_lit18",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x43 DW_OP_lit19
+          "DW_OP_lit19",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x44 DW_OP_lit20
+          "DW_OP_lit20",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x45 DW_OP_lit21
+          "DW_OP_lit21",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x46 DW_OP_lit22
+          "DW_OP_lit22",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x47 DW_OP_lit23
+          "DW_OP_lit23",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x48 DW_OP_lit24
+          "DW_OP_lit24",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x49 DW_OP_lit25
+          "DW_OP_lit25",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x4a DW_OP_lit26
+          "DW_OP_lit26",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x4b DW_OP_lit27
+          "DW_OP_lit27",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x4c DW_OP_lit28
+          "DW_OP_lit28",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x4d DW_OP_lit29
+          "DW_OP_lit29",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x4e DW_OP_lit30
+          "DW_OP_lit30",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x4f DW_OP_lit31
+          "DW_OP_lit31",
+          &DwarfOp::op_lit,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x50 DW_OP_reg0
+          "DW_OP_reg0",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x51 DW_OP_reg1
+          "DW_OP_reg1",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x52 DW_OP_reg2
+          "DW_OP_reg2",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x53 DW_OP_reg3
+          "DW_OP_reg3",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x54 DW_OP_reg4
+          "DW_OP_reg4",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x55 DW_OP_reg5
+          "DW_OP_reg5",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x56 DW_OP_reg6
+          "DW_OP_reg6",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x57 DW_OP_reg7
+          "DW_OP_reg7",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x58 DW_OP_reg8
+          "DW_OP_reg8",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x59 DW_OP_reg9
+          "DW_OP_reg9",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x5a DW_OP_reg10
+          "DW_OP_reg10",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x5b DW_OP_reg11
+          "DW_OP_reg11",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x5c DW_OP_reg12
+          "DW_OP_reg12",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x5d DW_OP_reg13
+          "DW_OP_reg13",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x5e DW_OP_reg14
+          "DW_OP_reg14",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x5f DW_OP_reg15
+          "DW_OP_reg15",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x60 DW_OP_reg16
+          "DW_OP_reg16",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x61 DW_OP_reg17
+          "DW_OP_reg17",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x62 DW_OP_reg18
+          "DW_OP_reg18",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x63 DW_OP_reg19
+          "DW_OP_reg19",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x64 DW_OP_reg20
+          "DW_OP_reg20",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x65 DW_OP_reg21
+          "DW_OP_reg21",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x66 DW_OP_reg22
+          "DW_OP_reg22",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x67 DW_OP_reg23
+          "DW_OP_reg23",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x68 DW_OP_reg24
+          "DW_OP_reg24",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x69 DW_OP_reg25
+          "DW_OP_reg25",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x6a DW_OP_reg26
+          "DW_OP_reg26",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x6b DW_OP_reg27
+          "DW_OP_reg27",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x6c DW_OP_reg28
+          "DW_OP_reg28",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x6d DW_OP_reg29
+          "DW_OP_reg29",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x6e DW_OP_reg30
+          "DW_OP_reg30",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x6f DW_OP_reg31
+          "DW_OP_reg31",
+          &DwarfOp::op_reg,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x70 DW_OP_breg0
+          "DW_OP_breg0",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x71 DW_OP_breg1
+          "DW_OP_breg1",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x72 DW_OP_breg2
+          "DW_OP_breg2",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x73 DW_OP_breg3
+          "DW_OP_breg3",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x74 DW_OP_breg4
+          "DW_OP_breg4",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x75 DW_OP_breg5
+          "DW_OP_breg5",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x76 DW_OP_breg6
+          "DW_OP_breg6",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x77 DW_OP_breg7
+          "DW_OP_breg7",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x78 DW_OP_breg8
+          "DW_OP_breg8",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x79 DW_OP_breg9
+          "DW_OP_breg9",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x7a DW_OP_breg10
+          "DW_OP_breg10",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x7b DW_OP_breg11
+          "DW_OP_breg11",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x7c DW_OP_breg12
+          "DW_OP_breg12",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x7d DW_OP_breg13
+          "DW_OP_breg13",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x7e DW_OP_breg14
+          "DW_OP_breg14",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x7f DW_OP_breg15
+          "DW_OP_breg15",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x80 DW_OP_breg16
+          "DW_OP_breg16",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x81 DW_OP_breg17
+          "DW_OP_breg17",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x82 DW_OP_breg18
+          "DW_OP_breg18",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x83 DW_OP_breg19
+          "DW_OP_breg19",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x84 DW_OP_breg20
+          "DW_OP_breg20",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x85 DW_OP_breg21
+          "DW_OP_breg21",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x86 DW_OP_breg22
+          "DW_OP_breg22",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x87 DW_OP_breg23
+          "DW_OP_breg23",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x88 DW_OP_breg24
+          "DW_OP_breg24",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x89 DW_OP_breg25
+          "DW_OP_breg25",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x8a DW_OP_breg26
+          "DW_OP_breg26",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x8b DW_OP_breg27
+          "DW_OP_breg27",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x8c DW_OP_breg28
+          "DW_OP_breg28",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x8d DW_OP_breg29
+          "DW_OP_breg29",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x8e DW_OP_breg30
+          "DW_OP_breg30",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x8f DW_OP_breg31
+          "DW_OP_breg31",
+          &DwarfOp::op_breg,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x90 DW_OP_regx
+          "DW_OP_regx",
+          &DwarfOp::op_regx,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_uleb128},
+      },
+      {
+          // 0x91 DW_OP_fbreg
+          "DW_OP_fbreg",
+          &DwarfOp::op_not_implemented,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_sleb128},
+      },
+      {
+          // 0x92 DW_OP_bregx
+          "DW_OP_bregx",
+          &DwarfOp::op_bregx,
+          DWARF_VERSION_2,
+          0,
+          2,
+          {DW_EH_PE_uleb128, DW_EH_PE_sleb128},
+      },
+      {
+          // 0x93 DW_OP_piece
+          "DW_OP_piece",
+          &DwarfOp::op_not_implemented,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_uleb128},
+      },
+      {
+          // 0x94 DW_OP_deref_size
+          "DW_OP_deref_size",
+          &DwarfOp::op_deref_size,
+          DWARF_VERSION_2,
+          1,
+          1,
+          {DW_EH_PE_udata1},
+      },
+      {
+          // 0x95 DW_OP_xderef_size
+          "DW_OP_xderef_size",
+          &DwarfOp::op_not_implemented,
+          DWARF_VERSION_2,
+          0,
+          1,
+          {DW_EH_PE_udata1},
+      },
+      {
+          // 0x96 DW_OP_nop
+          "DW_OP_nop",
+          &DwarfOp::op_nop,
+          DWARF_VERSION_2,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x97 DW_OP_push_object_address
+          "DW_OP_push_object_address",
+          &DwarfOp::op_not_implemented,
+          DWARF_VERSION_3,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x98 DW_OP_call2
+          "DW_OP_call2",
+          &DwarfOp::op_not_implemented,
+          DWARF_VERSION_3,
+          0,
+          1,
+          {DW_EH_PE_udata2},
+      },
+      {
+          // 0x99 DW_OP_call4
+          "DW_OP_call4",
+          &DwarfOp::op_not_implemented,
+          DWARF_VERSION_3,
+          0,
+          1,
+          {DW_EH_PE_udata4},
+      },
+      {
+          // 0x9a DW_OP_call_ref
+          "DW_OP_call_ref",
+          &DwarfOp::op_not_implemented,
+          DWARF_VERSION_3,
+          0,
+          0,  // Has a different sized operand (4 bytes or 8 bytes).
+          {},
+      },
+      {
+          // 0x9b DW_OP_form_tls_address
+          "DW_OP_form_tls_address",
+          &DwarfOp::op_not_implemented,
+          DWARF_VERSION_3,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x9c DW_OP_call_frame_cfa
+          "DW_OP_call_frame_cfa",
+          &DwarfOp::op_not_implemented,
+          DWARF_VERSION_3,
+          0,
+          0,
+          {},
+      },
+      {
+          // 0x9d DW_OP_bit_piece
+          "DW_OP_bit_piece",
+          &DwarfOp::op_not_implemented,
+          DWARF_VERSION_3,
+          0,
+          2,
+          {DW_EH_PE_uleb128, DW_EH_PE_uleb128},
+      },
+      {
+          // 0x9e DW_OP_implicit_value
+          "DW_OP_implicit_value",
+          &DwarfOp::op_not_implemented,
+          DWARF_VERSION_4,
+          0,
+          1,
+          {DW_EH_PE_uleb128},
+      },
+      {
+          // 0x9f DW_OP_stack_value
+          "DW_OP_stack_value",
+          &DwarfOp::op_not_implemented,
+          DWARF_VERSION_4,
+          1,
+          0,
+          {},
+      },
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xa0 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xa1 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xa2 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xa3 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xa4 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xa5 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xa6 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xa7 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xa8 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xa9 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xaa illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xab illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xac illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xad illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xae illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xaf illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xb0 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xb1 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xb2 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xb3 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xb4 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xb5 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xb6 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xb7 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xb8 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xb9 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xba illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xbb illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xbc illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xbd illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xbe illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xbf illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xc0 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xc1 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xc2 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xc3 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xc4 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xc5 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xc6 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xc7 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xc8 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xc9 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xca illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xcb illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xcc illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xcd illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xce illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xcf illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xd0 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xd1 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xd2 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xd3 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xd4 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xd5 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xd6 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xd7 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xd8 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xd9 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xda illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xdb illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xdc illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xdd illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xde illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xdf illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xe0 DW_OP_lo_user
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xe1 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xe2 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xe3 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xe4 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xe5 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xe6 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xe7 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xe8 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xe9 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xea illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xeb illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xec illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xed illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xee illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xef illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xf0 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xf1 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xf2 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xf3 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xf4 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xf5 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xf6 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xf7 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xf8 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xf9 illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xfa illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xfb illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xfc illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xfd illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xfe illegal op
+      {nullptr, nullptr, 0, 0, 0, {}},  // 0xff DW_OP_hi_user
+  };
+};
+
+#endif  // _LIBUNWINDSTACK_DWARF_OP_H
diff --git a/libunwindstack/DwarfStructs.h b/libunwindstack/DwarfStructs.h
new file mode 100644
index 0000000..57aac88
--- /dev/null
+++ b/libunwindstack/DwarfStructs.h
@@ -0,0 +1,52 @@
+/*
+ * 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 _LIBUNWINDSTACK_DWARF_STRUCTS_H
+#define _LIBUNWINDSTACK_DWARF_STRUCTS_H
+
+#include <stdint.h>
+
+#include <vector>
+
+#include "DwarfEncoding.h"
+
+struct DwarfCIE {
+  uint8_t version = 0;
+  uint8_t fde_address_encoding = DW_EH_PE_absptr;
+  uint8_t lsda_encoding = DW_EH_PE_omit;
+  uint8_t segment_size = 0;
+  std::vector<char> augmentation_string;
+  uint64_t personality_handler = 0;
+  uint64_t cfa_instructions_offset = 0;
+  uint64_t cfa_instructions_end = 0;
+  uint64_t code_alignment_factor = 0;
+  int64_t data_alignment_factor = 0;
+  uint64_t return_address_register = 0;
+};
+
+struct DwarfFDE {
+  uint64_t cie_offset = 0;
+  uint64_t cfa_instructions_offset = 0;
+  uint64_t cfa_instructions_end = 0;
+  uint64_t pc_start = 0;
+  uint64_t pc_end = 0;
+  uint64_t lsda_address = 0;
+  const DwarfCIE* cie = nullptr;
+};
+
+constexpr uint16_t CFA_REG = static_cast<uint16_t>(-1);
+
+#endif  // _LIBUNWINDSTACK_DWARF_STRUCTS_H
diff --git a/libunwindstack/ElfInterface.cpp b/libunwindstack/ElfInterface.cpp
index d59e9d8..087457c 100644
--- a/libunwindstack/ElfInterface.cpp
+++ b/libunwindstack/ElfInterface.cpp
@@ -42,7 +42,7 @@
   uint64_t offset = ehdr.e_phoff;
   for (size_t i = 0; i < ehdr.e_phnum; i++, offset += ehdr.e_phentsize) {
     PhdrType phdr;
-    if (!memory_->Read(offset, &phdr, &phdr.p_type, sizeof(phdr.p_type))) {
+    if (!memory_->ReadField(offset, &phdr, &phdr.p_type, sizeof(phdr.p_type))) {
       return false;
     }
 
@@ -54,20 +54,20 @@
     case PT_LOAD:
     {
       // Get the flags first, if this isn't an executable header, ignore it.
-      if (!memory_->Read(offset, &phdr, &phdr.p_flags, sizeof(phdr.p_flags))) {
+      if (!memory_->ReadField(offset, &phdr, &phdr.p_flags, sizeof(phdr.p_flags))) {
         return false;
       }
       if ((phdr.p_flags & PF_X) == 0) {
         continue;
       }
 
-      if (!memory_->Read(offset, &phdr, &phdr.p_vaddr, sizeof(phdr.p_vaddr))) {
+      if (!memory_->ReadField(offset, &phdr, &phdr.p_vaddr, sizeof(phdr.p_vaddr))) {
         return false;
       }
-      if (!memory_->Read(offset, &phdr, &phdr.p_offset, sizeof(phdr.p_offset))) {
+      if (!memory_->ReadField(offset, &phdr, &phdr.p_offset, sizeof(phdr.p_offset))) {
         return false;
       }
-      if (!memory_->Read(offset, &phdr, &phdr.p_memsz, sizeof(phdr.p_memsz))) {
+      if (!memory_->ReadField(offset, &phdr, &phdr.p_memsz, sizeof(phdr.p_memsz))) {
         return false;
       }
       pt_loads_[phdr.p_offset] = LoadInfo{phdr.p_offset, phdr.p_vaddr,
@@ -79,22 +79,22 @@
     }
 
     case PT_GNU_EH_FRAME:
-      if (!memory_->Read(offset, &phdr, &phdr.p_offset, sizeof(phdr.p_offset))) {
+      if (!memory_->ReadField(offset, &phdr, &phdr.p_offset, sizeof(phdr.p_offset))) {
         return false;
       }
       eh_frame_offset_ = phdr.p_offset;
-      if (!memory_->Read(offset, &phdr, &phdr.p_memsz, sizeof(phdr.p_memsz))) {
+      if (!memory_->ReadField(offset, &phdr, &phdr.p_memsz, sizeof(phdr.p_memsz))) {
         return false;
       }
       eh_frame_size_ = phdr.p_memsz;
       break;
 
     case PT_DYNAMIC:
-      if (!memory_->Read(offset, &phdr, &phdr.p_offset, sizeof(phdr.p_offset))) {
+      if (!memory_->ReadField(offset, &phdr, &phdr.p_offset, sizeof(phdr.p_offset))) {
         return false;
       }
       dynamic_offset_ = phdr.p_offset;
-      if (!memory_->Read(offset, &phdr, &phdr.p_memsz, sizeof(phdr.p_memsz))) {
+      if (!memory_->ReadField(offset, &phdr, &phdr.p_memsz, sizeof(phdr.p_memsz))) {
         return false;
       }
       dynamic_size_ = phdr.p_memsz;
@@ -116,8 +116,8 @@
   ShdrType shdr;
   if (ehdr.e_shstrndx < ehdr.e_shnum) {
     uint64_t sh_offset = offset + ehdr.e_shstrndx * ehdr.e_shentsize;
-    if (memory_->Read(sh_offset, &shdr, &shdr.sh_offset, sizeof(shdr.sh_offset))
-        && memory_->Read(sh_offset, &shdr, &shdr.sh_size, sizeof(shdr.sh_size))) {
+    if (memory_->ReadField(sh_offset, &shdr, &shdr.sh_offset, sizeof(shdr.sh_offset)) &&
+        memory_->ReadField(sh_offset, &shdr, &shdr.sh_size, sizeof(shdr.sh_size))) {
       sec_offset = shdr.sh_offset;
       sec_size = shdr.sh_size;
     }
@@ -125,27 +125,27 @@
 
   // Skip the first header, it's always going to be NULL.
   for (size_t i = 1; i < ehdr.e_shnum; i++, offset += ehdr.e_shentsize) {
-    if (!memory_->Read(offset, &shdr, &shdr.sh_type, sizeof(shdr.sh_type))) {
+    if (!memory_->ReadField(offset, &shdr, &shdr.sh_type, sizeof(shdr.sh_type))) {
       return false;
     }
 
     if (shdr.sh_type == SHT_PROGBITS) {
       // Look for the .debug_frame and .gnu_debugdata.
-      if (!memory_->Read(offset, &shdr, &shdr.sh_name, sizeof(shdr.sh_name))) {
+      if (!memory_->ReadField(offset, &shdr, &shdr.sh_name, sizeof(shdr.sh_name))) {
         return false;
       }
       if (shdr.sh_name < sec_size) {
         std::string name;
         if (memory_->ReadString(sec_offset + shdr.sh_name, &name)) {
           if (name == ".debug_frame") {
-            if (memory_->Read(offset, &shdr, &shdr.sh_offset, sizeof(shdr.sh_offset))
-                && memory_->Read(offset, &shdr, &shdr.sh_size, sizeof(shdr.sh_size))) {
+            if (memory_->ReadField(offset, &shdr, &shdr.sh_offset, sizeof(shdr.sh_offset)) &&
+                memory_->ReadField(offset, &shdr, &shdr.sh_size, sizeof(shdr.sh_size))) {
               debug_frame_offset_ = shdr.sh_offset;
               debug_frame_size_ = shdr.sh_size;
             }
           } else if (name == ".gnu_debugdata") {
-            if (memory_->Read(offset, &shdr, &shdr.sh_offset, sizeof(shdr.sh_offset))
-                && memory_->Read(offset, &shdr, &shdr.sh_size, sizeof(shdr.sh_size))) {
+            if (memory_->ReadField(offset, &shdr, &shdr.sh_offset, sizeof(shdr.sh_offset)) &&
+                memory_->ReadField(offset, &shdr, &shdr.sh_size, sizeof(shdr.sh_size))) {
               gnu_debugdata_offset_ = shdr.sh_offset;
               gnu_debugdata_size_ = shdr.sh_size;
             }
diff --git a/libunwindstack/ElfInterfaceArm.cpp b/libunwindstack/ElfInterfaceArm.cpp
index e157320..bab84cc 100644
--- a/libunwindstack/ElfInterfaceArm.cpp
+++ b/libunwindstack/ElfInterfaceArm.cpp
@@ -85,10 +85,10 @@
   }
 
   Elf32_Phdr phdr;
-  if (!memory_->Read(offset, &phdr, &phdr.p_vaddr, sizeof(phdr.p_vaddr))) {
+  if (!memory_->ReadField(offset, &phdr, &phdr.p_vaddr, sizeof(phdr.p_vaddr))) {
     return true;
   }
-  if (!memory_->Read(offset, &phdr, &phdr.p_memsz, sizeof(phdr.p_memsz))) {
+  if (!memory_->ReadField(offset, &phdr, &phdr.p_memsz, sizeof(phdr.p_memsz))) {
     return true;
   }
   // The load_bias_ should always be set by this time.
@@ -98,13 +98,15 @@
 }
 
 bool ElfInterfaceArm::Step(uint64_t pc, Regs* regs, Memory* process_memory) {
-  return StepExidx(pc, regs, process_memory) ||
-      ElfInterface32::Step(pc, regs, process_memory);
+  // 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) || StepExidx(pc, regs, process_memory);
 }
 
 bool ElfInterfaceArm::StepExidx(uint64_t pc, Regs* regs, Memory* process_memory) {
   RegsArm* regs_arm = reinterpret_cast<RegsArm*>(regs);
-  // First try arm, then try dwarf.
   uint64_t entry_offset;
   if (!FindEntry(pc, &entry_offset)) {
     return false;
diff --git a/libunwindstack/MapInfo.cpp b/libunwindstack/MapInfo.cpp
new file mode 100644
index 0000000..051f700
--- /dev/null
+++ b/libunwindstack/MapInfo.cpp
@@ -0,0 +1,86 @@
+/*
+ * 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 <sys/types.h>
+#include <unistd.h>
+
+#include <memory>
+#include <string>
+
+#include "Elf.h"
+#include "MapInfo.h"
+#include "Maps.h"
+#include "Memory.h"
+
+Memory* MapInfo::CreateMemory(pid_t pid) {
+  if (end <= start) {
+    return nullptr;
+  }
+
+  elf_offset = 0;
+
+  // First try and use the file associated with the info.
+  if (!name.empty()) {
+    // Fail on device maps.
+    if (flags & MAPS_FLAGS_DEVICE_MAP) {
+      return nullptr;
+    }
+
+    std::unique_ptr<MemoryFileAtOffset> file_memory(new MemoryFileAtOffset);
+    uint64_t map_size;
+    if (offset != 0) {
+      // Only map in a piece of the file.
+      map_size = end - start;
+    } else {
+      map_size = UINT64_MAX;
+    }
+    if (file_memory->Init(name, offset, map_size)) {
+      // It's possible that a non-zero offset might not be pointing to
+      // valid elf data. Check if this is a valid elf, and if not assume
+      // that this was meant to incorporate the entire file.
+      if (offset != 0 && !Elf::IsValidElf(file_memory.get())) {
+        // Don't bother checking the validity that will happen on the elf init.
+        if (file_memory->Init(name, 0)) {
+          elf_offset = offset;
+          return file_memory.release();
+        }
+        // Fall through if the init fails.
+      } else {
+        return file_memory.release();
+      }
+    }
+  }
+
+  Memory* memory = nullptr;
+  if (pid == getpid()) {
+    memory = new MemoryLocal();
+  } else {
+    memory = new MemoryRemote(pid);
+  }
+  return new MemoryRange(memory, start, end);
+}
+
+Elf* MapInfo::GetElf(pid_t pid, bool) {
+  if (elf) {
+    return elf;
+  }
+
+  elf = new Elf(CreateMemory(pid));
+  elf->Init();
+  // If the init fails, keep the elf around as an invalid object so we
+  // don't try to reinit the object.
+  return elf;
+}
diff --git a/libunwindstack/MapInfo.h b/libunwindstack/MapInfo.h
index 8342904..79a2ada 100644
--- a/libunwindstack/MapInfo.h
+++ b/libunwindstack/MapInfo.h
@@ -39,6 +39,7 @@
   uint64_t elf_offset;
 
   Memory* CreateMemory(pid_t pid);
+  Elf* GetElf(pid_t pid, bool init_gnu_debugdata = false);
 };
 
 #endif  // _LIBUNWINDSTACK_MAP_INFO_H
diff --git a/libunwindstack/Maps.cpp b/libunwindstack/Maps.cpp
new file mode 100644
index 0000000..b369c43
--- /dev/null
+++ b/libunwindstack/Maps.cpp
@@ -0,0 +1,196 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <errno.h>
+#include <fcntl.h>
+#include <inttypes.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <sys/mman.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <android-base/unique_fd.h>
+
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "Maps.h"
+
+MapInfo* Maps::Find(uint64_t pc) {
+  if (maps_.empty()) {
+    return nullptr;
+  }
+  size_t first = 0;
+  size_t last = maps_.size();
+  while (first < last) {
+    size_t index = (first + last) / 2;
+    MapInfo* cur = &maps_[index];
+    if (pc >= cur->start && pc < cur->end) {
+      return cur;
+    } else if (pc < cur->start) {
+      last = index;
+    } else {
+      first = index + 1;
+    }
+  }
+  return nullptr;
+}
+
+bool Maps::ParseLine(const char* line, MapInfo* map_info) {
+  char permissions[5];
+  int name_pos;
+  // Linux /proc/<pid>/maps lines:
+  // 6f000000-6f01e000 rwxp 00000000 00:0c 16389419   /system/lib/libcomposer.so
+  if (sscanf(line, "%" SCNx64 "-%" SCNx64 " %4s %" SCNx64 " %*x:%*x %*d %n", &map_info->start,
+             &map_info->end, permissions, &map_info->offset, &name_pos) != 4) {
+    return false;
+  }
+  map_info->flags = PROT_NONE;
+  if (permissions[0] == 'r') {
+    map_info->flags |= PROT_READ;
+  }
+  if (permissions[1] == 'w') {
+    map_info->flags |= PROT_WRITE;
+  }
+  if (permissions[2] == 'x') {
+    map_info->flags |= PROT_EXEC;
+  }
+
+  map_info->name = &line[name_pos];
+  size_t length = map_info->name.length() - 1;
+  if (map_info->name[length] == '\n') {
+    map_info->name.erase(length);
+  }
+  // Mark a device map in /dev/and not in /dev/ashmem/ specially.
+  if (!map_info->name.empty() && map_info->name.substr(0, 5) == "/dev/" &&
+      map_info->name.substr(5, 7) != "ashmem/") {
+    map_info->flags |= MAPS_FLAGS_DEVICE_MAP;
+  }
+
+  return true;
+}
+
+bool Maps::Parse() {
+  std::unique_ptr<FILE, decltype(&fclose)> fp(fopen(GetMapsFile().c_str(), "re"), fclose);
+  if (!fp) {
+    return false;
+  }
+
+  bool valid = true;
+  char* line = nullptr;
+  size_t line_len;
+  while (getline(&line, &line_len, fp.get()) > 0) {
+    MapInfo map_info;
+    if (!ParseLine(line, &map_info)) {
+      valid = false;
+      break;
+    }
+
+    maps_.push_back(map_info);
+  }
+  free(line);
+
+  return valid;
+}
+
+Maps::~Maps() {
+  for (auto& map : maps_) {
+    delete map.elf;
+    map.elf = nullptr;
+  }
+}
+
+bool BufferMaps::Parse() {
+  const char* start_of_line = buffer_;
+  do {
+    std::string line;
+    const char* end_of_line = strchr(start_of_line, '\n');
+    if (end_of_line == nullptr) {
+      line = start_of_line;
+    } else {
+      end_of_line++;
+      line = std::string(start_of_line, end_of_line - start_of_line);
+    }
+
+    MapInfo map_info;
+    if (!ParseLine(line.c_str(), &map_info)) {
+      return false;
+    }
+    maps_.push_back(map_info);
+
+    start_of_line = end_of_line;
+  } while (start_of_line != nullptr && *start_of_line != '\0');
+  return true;
+}
+
+const std::string RemoteMaps::GetMapsFile() const {
+  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) {
+    MapInfo map_info;
+    ssize_t bytes = TEMP_FAILURE_RETRY(read(fd, &map_info.start, sizeof(map_info.start)));
+    if (bytes == 0) {
+      break;
+    }
+    if (bytes == -1 || bytes != sizeof(map_info.start)) {
+      return false;
+    }
+    bytes = TEMP_FAILURE_RETRY(read(fd, &map_info.end, sizeof(map_info.end)));
+    if (bytes == -1 || bytes != sizeof(map_info.end)) {
+      return false;
+    }
+    bytes = TEMP_FAILURE_RETRY(read(fd, &map_info.offset, sizeof(map_info.offset)));
+    if (bytes == -1 || bytes != sizeof(map_info.offset)) {
+      return false;
+    }
+    bytes = TEMP_FAILURE_RETRY(read(fd, &map_info.flags, sizeof(map_info.flags)));
+    if (bytes == -1 || bytes != sizeof(map_info.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;
+      }
+      map_info.name = std::string(name.data(), len);
+    }
+    maps_.push_back(map_info);
+  }
+  return true;
+}
diff --git a/libunwindstack/Maps.h b/libunwindstack/Maps.h
new file mode 100644
index 0000000..239b64a
--- /dev/null
+++ b/libunwindstack/Maps.h
@@ -0,0 +1,107 @@
+/*
+ * 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 _LIBUNWINDSTACK_MAPS_H
+#define _LIBUNWINDSTACK_MAPS_H
+
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <string>
+#include <vector>
+
+#include "Elf.h"
+#include "MapInfo.h"
+
+// Special flag to indicate a map is in /dev/. However, a map in
+// /dev/ashmem/... does not set this flag.
+static constexpr int MAPS_FLAGS_DEVICE_MAP = 0x8000;
+
+class Maps {
+ public:
+  Maps() = default;
+  virtual ~Maps();
+
+  MapInfo* Find(uint64_t pc);
+
+  bool ParseLine(const char* line, MapInfo* map_info);
+
+  virtual bool Parse();
+
+  virtual const std::string GetMapsFile() const { return ""; }
+
+  typedef std::vector<MapInfo>::iterator iterator;
+  iterator begin() { return maps_.begin(); }
+  iterator end() { return maps_.end(); }
+
+  typedef std::vector<MapInfo>::const_iterator const_iterator;
+  const_iterator begin() const { return maps_.begin(); }
+  const_iterator end() const { return maps_.end(); }
+
+  size_t Total() { return maps_.size(); }
+
+ protected:
+  std::vector<MapInfo> maps_;
+};
+
+class RemoteMaps : public Maps {
+ public:
+  RemoteMaps(pid_t pid) : pid_(pid) {}
+  virtual ~RemoteMaps() = default;
+
+  virtual const std::string GetMapsFile() const override;
+
+ private:
+  pid_t pid_;
+};
+
+class LocalMaps : public RemoteMaps {
+ public:
+  LocalMaps() : RemoteMaps(getpid()) {}
+  virtual ~LocalMaps() = default;
+};
+
+class BufferMaps : public Maps {
+ public:
+  BufferMaps(const char* buffer) : buffer_(buffer) {}
+  virtual ~BufferMaps() = default;
+
+  bool Parse() override;
+
+ private:
+  const char* buffer_;
+};
+
+class FileMaps : public Maps {
+ public:
+  FileMaps(const std::string& file) : file_(file) {}
+  virtual ~FileMaps() = default;
+
+  const std::string GetMapsFile() const override { return file_; }
+
+ protected:
+  const std::string file_;
+};
+
+class OfflineMaps : public FileMaps {
+ public:
+  OfflineMaps(const std::string& file) : FileMaps(file) {}
+  virtual ~OfflineMaps() = default;
+
+  bool Parse() override;
+};
+
+#endif  // _LIBUNWINDSTACK_MAPS_H
diff --git a/libunwindstack/Memory.cpp b/libunwindstack/Memory.cpp
index 1fcf842..9e46509 100644
--- a/libunwindstack/Memory.cpp
+++ b/libunwindstack/Memory.cpp
@@ -96,10 +96,16 @@
 
   offset_ = offset & (getpagesize() - 1);
   uint64_t aligned_offset = offset & ~(getpagesize() - 1);
+  if (aligned_offset > static_cast<uint64_t>(buf.st_size) ||
+      offset > static_cast<uint64_t>(buf.st_size)) {
+    return false;
+  }
+
   size_ = buf.st_size - aligned_offset;
-  if (size < (UINT64_MAX - offset_) && size + offset_ < size_) {
+  uint64_t max_size;
+  if (!__builtin_add_overflow(size, offset_, &max_size) && max_size < size_) {
     // Truncate the mapped size.
-    size_ = size + offset_;
+    size_ = max_size;
   }
   void* map = mmap(nullptr, size_, PROT_READ, MAP_PRIVATE, fd, aligned_offset);
   if (map == MAP_FAILED) {
@@ -113,14 +119,15 @@
 }
 
 bool MemoryFileAtOffset::Read(uint64_t addr, void* dst, size_t size) {
-  if (addr + size > size_) {
+  uint64_t max_size;
+  if (__builtin_add_overflow(addr, size, &max_size) || max_size > size_) {
     return false;
   }
   memcpy(dst, &data_[addr], size);
   return true;
 }
 
-static bool PtraceRead(pid_t pid, uint64_t addr, long* value) {
+bool MemoryRemote::PtraceRead(uint64_t addr, long* value) {
 #if !defined(__LP64__)
   // Cannot read an address greater than 32 bits.
   if (addr > UINT32_MAX) {
@@ -130,7 +137,7 @@
   // ptrace() returns -1 and sets errno when the operation fails.
   // To disambiguate -1 from a valid result, we clear errno beforehand.
   errno = 0;
-  *value = ptrace(PTRACE_PEEKTEXT, pid, reinterpret_cast<void*>(addr), nullptr);
+  *value = ptrace(PTRACE_PEEKTEXT, pid_, reinterpret_cast<void*>(addr), nullptr);
   if (*value == -1 && errno) {
     return false;
   }
@@ -138,11 +145,17 @@
 }
 
 bool MemoryRemote::Read(uint64_t addr, void* dst, size_t bytes) {
+  // Make sure that there is no overflow.
+  uint64_t max_size;
+  if (__builtin_add_overflow(addr, bytes, &max_size)) {
+    return false;
+  }
+
   size_t bytes_read = 0;
   long data;
   size_t align_bytes = addr & (sizeof(long) - 1);
   if (align_bytes != 0) {
-    if (!PtraceRead(pid_, addr & ~(sizeof(long) - 1), &data)) {
+    if (!PtraceRead(addr & ~(sizeof(long) - 1), &data)) {
       return false;
     }
     size_t copy_bytes = std::min(sizeof(long) - align_bytes, bytes);
@@ -154,7 +167,7 @@
   }
 
   for (size_t i = 0; i < bytes / sizeof(long); i++) {
-    if (!PtraceRead(pid_, addr, &data)) {
+    if (!PtraceRead(addr, &data)) {
       return false;
     }
     memcpy(dst, &data, sizeof(long));
@@ -165,7 +178,7 @@
 
   size_t left_over = bytes & (sizeof(long) - 1);
   if (left_over) {
-    if (!PtraceRead(pid_, addr, &data)) {
+    if (!PtraceRead(addr, &data)) {
       return false;
     }
     memcpy(dst, &data, left_over);
@@ -175,7 +188,13 @@
 }
 
 bool MemoryLocal::Read(uint64_t addr, void* dst, size_t size) {
-  // The process_vm_readv call does will not always work on remote
+  // Make sure that there is no overflow.
+  uint64_t max_size;
+  if (__builtin_add_overflow(addr, size, &max_size)) {
+    return false;
+  }
+
+  // The process_vm_readv call will not always work on remote
   // processes, so only use it for reads from the current pid.
   // Use this method to avoid crashes if an address is invalid since
   // unwind data could try to access any part of the address space.
@@ -208,9 +227,29 @@
 }
 
 bool MemoryOffline::Read(uint64_t addr, void* dst, size_t size) {
-  if (addr < start_ || addr + size > start_ + offset_ + size_) {
+  uint64_t max_size;
+  if (__builtin_add_overflow(addr, size, &max_size)) {
+    return false;
+  }
+
+  uint64_t real_size;
+  if (__builtin_add_overflow(start_, offset_, &real_size) ||
+      __builtin_add_overflow(real_size, size_, &real_size)) {
+    return false;
+  }
+
+  if (addr < start_ || max_size > real_size) {
     return false;
   }
   memcpy(dst, &data_[addr + offset_ - start_ + sizeof(start_)], size);
   return true;
 }
+
+bool MemoryRange::Read(uint64_t addr, void* dst, size_t size) {
+  uint64_t max_read;
+  if (__builtin_add_overflow(addr, size, &max_read) || max_read > length_) {
+    return false;
+  }
+  // The check above guarantees that addr + begin_ will not overflow.
+  return memory_->Read(addr + begin_, dst, size);
+}
diff --git a/libunwindstack/Memory.h b/libunwindstack/Memory.h
index c5316a1..f9f6d56 100644
--- a/libunwindstack/Memory.h
+++ b/libunwindstack/Memory.h
@@ -17,6 +17,7 @@
 #ifndef _LIBUNWINDSTACK_MEMORY_H
 #define _LIBUNWINDSTACK_MEMORY_H
 
+#include <assert.h>
 #include <stdint.h>
 #include <sys/types.h>
 #include <unistd.h>
@@ -33,9 +34,16 @@
 
   virtual bool Read(uint64_t addr, void* dst, size_t size) = 0;
 
-  inline bool Read(uint64_t addr, void* start, void* field, size_t size) {
-    return Read(addr + reinterpret_cast<uintptr_t>(field) - reinterpret_cast<uintptr_t>(start),
-                field, size);
+  inline bool ReadField(uint64_t addr, void* start, void* field, size_t size) {
+    if (reinterpret_cast<uintptr_t>(field) < reinterpret_cast<uintptr_t>(start)) {
+      return false;
+    }
+    uint64_t offset = reinterpret_cast<uintptr_t>(field) - reinterpret_cast<uintptr_t>(start);
+    if (__builtin_add_overflow(addr, offset, &offset)) {
+      return false;
+    }
+    // The read will check if offset + size overflows.
+    return Read(offset, field, size);
   }
 
   inline bool Read32(uint64_t addr, uint32_t* dst) {
@@ -103,6 +111,9 @@
 
   pid_t pid() { return pid_; }
 
+ protected:
+  virtual bool PtraceRead(uint64_t addr, long* value);
+
  private:
   pid_t pid_;
 };
@@ -118,15 +129,12 @@
 class MemoryRange : public Memory {
  public:
   MemoryRange(Memory* memory, uint64_t begin, uint64_t end)
-      : memory_(memory), begin_(begin), length_(end - begin_) {}
+      : memory_(memory), begin_(begin), length_(end - begin) {
+    assert(end > begin);
+  }
   virtual ~MemoryRange() { delete memory_; }
 
-  inline bool Read(uint64_t addr, void* dst, size_t size) override {
-    if (addr + size <= length_) {
-      return memory_->Read(addr + begin_, dst, size);
-    }
-    return false;
-  }
+  bool Read(uint64_t addr, void* dst, size_t size) override;
 
  private:
   Memory* memory_;
diff --git a/libunwindstack/Symbols.cpp b/libunwindstack/Symbols.cpp
new file mode 100644
index 0000000..86c1233
--- /dev/null
+++ b/libunwindstack/Symbols.cpp
@@ -0,0 +1,110 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <assert.h>
+#include <elf.h>
+#include <stdint.h>
+
+#include <string>
+
+#include "Memory.h"
+#include "Symbols.h"
+
+Symbols::Symbols(uint64_t offset, uint64_t size, uint64_t entry_size, uint64_t str_offset,
+                 uint64_t str_size)
+    : cur_offset_(offset),
+      offset_(offset),
+      end_(offset + size),
+      entry_size_(entry_size),
+      str_offset_(str_offset),
+      str_end_(str_offset_ + str_size) {}
+
+const Symbols::Info* Symbols::GetInfoFromCache(uint64_t addr) {
+  // Binary search the table.
+  size_t first = 0;
+  size_t last = symbols_.size();
+  while (first < last) {
+    size_t current = first + (last - first) / 2;
+    const Info* info = &symbols_[current];
+    if (addr < info->start_offset) {
+      last = current;
+    } else if (addr < info->end_offset) {
+      return info;
+    } else {
+      first = current + 1;
+    }
+  }
+  return nullptr;
+}
+
+template <typename SymType>
+bool Symbols::GetName(uint64_t addr, uint64_t load_bias, Memory* elf_memory, std::string* name,
+                      uint64_t* func_offset) {
+  addr += load_bias;
+
+  if (symbols_.size() != 0) {
+    const Info* info = GetInfoFromCache(addr);
+    if (info) {
+      assert(addr >= info->start_offset && addr <= info->end_offset);
+      *func_offset = addr - info->start_offset;
+      return elf_memory->ReadString(info->str_offset, name, str_end_ - info->str_offset);
+    }
+  }
+
+  bool symbol_added = false;
+  bool return_value = false;
+  while (cur_offset_ + entry_size_ <= end_) {
+    SymType entry;
+    if (!elf_memory->Read(cur_offset_, &entry, sizeof(entry))) {
+      // Stop all processing, something looks like it is corrupted.
+      cur_offset_ = UINT64_MAX;
+      return false;
+    }
+    cur_offset_ += entry_size_;
+
+    if (entry.st_shndx != SHN_UNDEF && ELF32_ST_TYPE(entry.st_info) == STT_FUNC) {
+      // Treat st_value as virtual address.
+      uint64_t start_offset = entry.st_value;
+      if (entry.st_shndx != SHN_ABS) {
+        start_offset += load_bias;
+      }
+      uint64_t end_offset = start_offset + entry.st_size;
+
+      // Cache the value.
+      symbols_.emplace_back(start_offset, end_offset, str_offset_ + entry.st_name);
+      symbol_added = true;
+
+      if (addr >= start_offset && addr < end_offset) {
+        *func_offset = addr - start_offset;
+        uint64_t offset = str_offset_ + entry.st_name;
+        if (offset < str_end_) {
+          return_value = elf_memory->ReadString(offset, name, str_end_ - offset);
+        }
+        break;
+      }
+    }
+  }
+
+  if (symbol_added) {
+    std::sort(symbols_.begin(), symbols_.end(),
+              [](const Info& a, const Info& b) { return a.start_offset < b.start_offset; });
+  }
+  return return_value;
+}
+
+// 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*);
diff --git a/libunwindstack/Symbols.h b/libunwindstack/Symbols.h
new file mode 100644
index 0000000..3c0d033
--- /dev/null
+++ b/libunwindstack/Symbols.h
@@ -0,0 +1,64 @@
+/*
+ * 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 _LIBUNWINDSTACK_SYMBOLS_H
+#define _LIBUNWINDSTACK_SYMBOLS_H
+
+#include <stdint.h>
+
+#include <string>
+#include <vector>
+
+// Forward declaration.
+class Memory;
+
+class Symbols {
+  struct Info {
+    Info(uint64_t start_offset, uint64_t end_offset, uint64_t str_offset)
+        : start_offset(start_offset), end_offset(end_offset), str_offset(str_offset) {}
+    uint64_t start_offset;
+    uint64_t end_offset;
+    uint64_t str_offset;
+  };
+
+ public:
+  Symbols(uint64_t offset, uint64_t size, uint64_t entry_size, uint64_t str_offset,
+          uint64_t str_size);
+  virtual ~Symbols() = default;
+
+  const Info* GetInfoFromCache(uint64_t addr);
+
+  template <typename SymType>
+  bool GetName(uint64_t addr, uint64_t load_bias, Memory* elf_memory, std::string* name,
+               uint64_t* func_offset);
+
+  void ClearCache() {
+    symbols_.clear();
+    cur_offset_ = offset_;
+  }
+
+ private:
+  uint64_t cur_offset_;
+  uint64_t offset_;
+  uint64_t end_;
+  uint64_t entry_size_;
+  uint64_t str_offset_;
+  uint64_t str_end_;
+
+  std::vector<Info> symbols_;
+};
+
+#endif  // _LIBUNWINDSTACK_SYMBOLS_H
diff --git a/libunwindstack/tests/DwarfCfaLogTest.cpp b/libunwindstack/tests/DwarfCfaLogTest.cpp
new file mode 100644
index 0000000..3185bc3
--- /dev/null
+++ b/libunwindstack/tests/DwarfCfaLogTest.cpp
@@ -0,0 +1,814 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdint.h>
+
+#include <memory>
+#include <type_traits>
+#include <unordered_map>
+
+#include <android-base/stringprintf.h>
+#include <gtest/gtest.h>
+
+#include "DwarfCfa.h"
+#include "DwarfLocation.h"
+#include "DwarfMemory.h"
+#include "DwarfStructs.h"
+#include "Log.h"
+
+#include "LogFake.h"
+#include "MemoryFake.h"
+
+template <typename TypeParam>
+class DwarfCfaLogTest : public ::testing::Test {
+ protected:
+  void SetUp() override {
+    ResetLogs();
+    memory_.Clear();
+
+    dmem_.reset(new DwarfMemory(&memory_));
+
+    cie_.cfa_instructions_offset = 0x1000;
+    cie_.cfa_instructions_end = 0x1030;
+    // These two values should be different to distinguish between
+    // operations that deal with code versus data.
+    cie_.code_alignment_factor = 4;
+    cie_.data_alignment_factor = 8;
+
+    fde_.cfa_instructions_offset = 0x2000;
+    fde_.cfa_instructions_end = 0x2030;
+    fde_.pc_start = 0x2000;
+    fde_.pc_end = 0x2000;
+    fde_.pc_end = 0x10000;
+    fde_.cie = &cie_;
+    cfa_.reset(new DwarfCfa<TypeParam>(dmem_.get(), &fde_));
+  }
+
+  MemoryFake memory_;
+  std::unique_ptr<DwarfMemory> dmem_;
+  std::unique_ptr<DwarfCfa<TypeParam>> cfa_;
+  DwarfCIE cie_;
+  DwarfFDE fde_;
+};
+TYPED_TEST_CASE_P(DwarfCfaLogTest);
+
+// NOTE: All class variable references have to be prefaced with this->.
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_illegal) {
+  for (uint8_t i = 0x17; i < 0x3f; i++) {
+    if (i == 0x2e || i == 0x2f) {
+      // Skip gnu extension ops.
+      continue;
+    }
+    this->memory_.SetMemory(0x2000, std::vector<uint8_t>{i});
+
+    ResetLogs();
+    ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x2000, 0x2001));
+    std::string expected = "4 unwind Illegal\n";
+    expected += android::base::StringPrintf("4 unwind Raw Data: 0x%02x\n", i);
+    ASSERT_EQ(expected, GetFakeLogPrint());
+    ASSERT_EQ("", GetFakeLogBuf());
+  }
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_nop) {
+  this->memory_.SetMemory(0x2000, std::vector<uint8_t>{0x00});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x2000, 0x2001));
+  std::string expected =
+      "4 unwind DW_CFA_nop\n"
+      "4 unwind Raw Data: 0x00\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_offset) {
+  this->memory_.SetMemory(0x2000, std::vector<uint8_t>{0x83, 0x04});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x2000, 0x2002));
+  std::string expected =
+      "4 unwind DW_CFA_offset register(3) 4\n"
+      "4 unwind Raw Data: 0x83 0x04\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  this->memory_.SetMemory(0x2100, std::vector<uint8_t>{0x83, 0x84, 0x01});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x2100, 0x2103));
+  expected =
+      "4 unwind DW_CFA_offset register(3) 132\n"
+      "4 unwind Raw Data: 0x83 0x84 0x01\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_offset_extended) {
+  this->memory_.SetMemory(0x500, std::vector<uint8_t>{0x05, 0x03, 0x02});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x500, 0x503));
+  std::string expected =
+      "4 unwind DW_CFA_offset_extended register(3) 2\n"
+      "4 unwind Raw Data: 0x05 0x03 0x02\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  this->memory_.SetMemory(0x1500, std::vector<uint8_t>{0x05, 0x81, 0x01, 0x82, 0x12});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x1500, 0x1505));
+  expected =
+      "4 unwind DW_CFA_offset_extended register(129) 2306\n"
+      "4 unwind Raw Data: 0x05 0x81 0x01 0x82 0x12\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_offset_extended_sf) {
+  this->memory_.SetMemory(0x500, std::vector<uint8_t>{0x11, 0x05, 0x10});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x500, 0x503));
+  std::string expected =
+      "4 unwind DW_CFA_offset_extended_sf register(5) 16\n"
+      "4 unwind Raw Data: 0x11 0x05 0x10\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  // Check a negative value for the offset.
+  ResetLogs();
+  this->memory_.SetMemory(0x1500, std::vector<uint8_t>{0x11, 0x86, 0x01, 0xff, 0x7f});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x1500, 0x1505));
+  expected =
+      "4 unwind DW_CFA_offset_extended_sf register(134) -1\n"
+      "4 unwind Raw Data: 0x11 0x86 0x01 0xff 0x7f\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_restore) {
+  this->memory_.SetMemory(0x2000, std::vector<uint8_t>{0xc2});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x2000, 0x2001));
+  std::string expected =
+      "4 unwind DW_CFA_restore register(2)\n"
+      "4 unwind Raw Data: 0xc2\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  this->memory_.SetMemory(0x3000, std::vector<uint8_t>{0x82, 0x04, 0xc2});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x3000, 0x3003));
+  expected =
+      "4 unwind DW_CFA_offset register(2) 4\n"
+      "4 unwind Raw Data: 0x82 0x04\n"
+      "4 unwind DW_CFA_restore register(2)\n"
+      "4 unwind Raw Data: 0xc2\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_restore_extended) {
+  this->memory_.SetMemory(0x4000, std::vector<uint8_t>{0x06, 0x08});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x4000, 0x4002));
+  std::string expected =
+      "4 unwind DW_CFA_restore_extended register(8)\n"
+      "4 unwind Raw Data: 0x06 0x08\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  this->memory_.SetMemory(0x5000, std::vector<uint8_t>{0x05, 0x82, 0x02, 0x04, 0x06, 0x82, 0x02});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x5000, 0x5007));
+  expected =
+      "4 unwind DW_CFA_offset_extended register(258) 4\n"
+      "4 unwind Raw Data: 0x05 0x82 0x02 0x04\n"
+      "4 unwind DW_CFA_restore_extended register(258)\n"
+      "4 unwind Raw Data: 0x06 0x82 0x02\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_set_loc) {
+  uint8_t buffer[1 + sizeof(TypeParam)];
+  buffer[0] = 0x1;
+  TypeParam address;
+  std::string raw_data("Raw Data: 0x01 ");
+  std::string address_str;
+  if (std::is_same<TypeParam, uint32_t>::value) {
+    address = 0x81234578U;
+    address_str = "0x81234578";
+    raw_data += "0x78 0x45 0x23 0x81";
+  } else {
+    address = 0x8123456712345678ULL;
+    address_str = "0x8123456712345678";
+    raw_data += "0x78 0x56 0x34 0x12 0x67 0x45 0x23 0x81";
+  }
+  memcpy(&buffer[1], &address, sizeof(address));
+
+  this->memory_.SetMemory(0x50, buffer, sizeof(buffer));
+  ResetLogs();
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x50, 0x51 + sizeof(TypeParam)));
+  std::string expected = "4 unwind DW_CFA_set_loc " + address_str + "\n";
+  expected += "4 unwind " + raw_data + "\n";
+  expected += "4 unwind \n";
+  expected += "4 unwind PC " + address_str + "\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  // Check for a set going back.
+  ResetLogs();
+  this->fde_.pc_start = address + 0x10;
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x50, 0x51 + sizeof(TypeParam)));
+  expected = "4 unwind DW_CFA_set_loc " + address_str + "\n";
+  expected += "4 unwind " + raw_data + "\n";
+  expected += "4 unwind \n";
+  expected += "4 unwind PC " + address_str + "\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_advance_loc) {
+  this->memory_.SetMemory(0x200, std::vector<uint8_t>{0x44});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x200, 0x201));
+  std::string expected =
+      "4 unwind DW_CFA_advance_loc 4\n"
+      "4 unwind Raw Data: 0x44\n"
+      "4 unwind \n"
+      "4 unwind PC 0x2010\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0x100, 0x200, 0x201));
+  expected =
+      "4 unwind DW_CFA_advance_loc 4\n"
+      "4 unwind Raw Data: 0x44\n"
+      "4 unwind \n"
+      "4 unwind PC 0x2110\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_advance_loc1) {
+  this->memory_.SetMemory(0x200, std::vector<uint8_t>{0x02, 0x04});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x200, 0x202));
+  std::string expected =
+      "4 unwind DW_CFA_advance_loc1 4\n"
+      "4 unwind Raw Data: 0x02 0x04\n"
+      "4 unwind \n"
+      "4 unwind PC 0x2004\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0x10, 0x200, 0x202));
+  expected =
+      "4 unwind DW_CFA_advance_loc1 4\n"
+      "4 unwind Raw Data: 0x02 0x04\n"
+      "4 unwind \n"
+      "4 unwind PC 0x2014\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_advance_loc2) {
+  this->memory_.SetMemory(0x600, std::vector<uint8_t>{0x03, 0x04, 0x03});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x600, 0x603));
+  std::string expected =
+      "4 unwind DW_CFA_advance_loc2 772\n"
+      "4 unwind Raw Data: 0x03 0x04 0x03\n"
+      "4 unwind \n"
+      "4 unwind PC 0x2304\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0x1000, 0x600, 0x603));
+  expected =
+      "4 unwind DW_CFA_advance_loc2 772\n"
+      "4 unwind Raw Data: 0x03 0x04 0x03\n"
+      "4 unwind \n"
+      "4 unwind PC 0x3304\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_advance_loc4) {
+  this->memory_.SetMemory(0x500, std::vector<uint8_t>{0x04, 0x04, 0x03, 0x02, 0x01});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x500, 0x505));
+  std::string expected =
+      "4 unwind DW_CFA_advance_loc4 16909060\n"
+      "4 unwind Raw Data: 0x04 0x04 0x03 0x02 0x01\n"
+      "4 unwind \n"
+      "4 unwind PC 0x1022304\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0x2000, 0x500, 0x505));
+  expected =
+      "4 unwind DW_CFA_advance_loc4 16909060\n"
+      "4 unwind Raw Data: 0x04 0x04 0x03 0x02 0x01\n"
+      "4 unwind \n"
+      "4 unwind PC 0x1024304\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_undefined) {
+  this->memory_.SetMemory(0xa00, std::vector<uint8_t>{0x07, 0x09});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0xa00, 0xa02));
+  std::string expected =
+      "4 unwind DW_CFA_undefined register(9)\n"
+      "4 unwind Raw Data: 0x07 0x09\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  dwarf_loc_regs_t cie_loc_regs;
+  this->memory_.SetMemory(0x1a00, std::vector<uint8_t>{0x07, 0x81, 0x01});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x1a00, 0x1a03));
+  expected =
+      "4 unwind DW_CFA_undefined register(129)\n"
+      "4 unwind Raw Data: 0x07 0x81 0x01\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_same) {
+  this->memory_.SetMemory(0x100, std::vector<uint8_t>{0x08, 0x7f});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x100, 0x102));
+  std::string expected =
+      "4 unwind DW_CFA_same_value register(127)\n"
+      "4 unwind Raw Data: 0x08 0x7f\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  this->memory_.SetMemory(0x2100, std::vector<uint8_t>{0x08, 0xff, 0x01});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x2100, 0x2103));
+  expected =
+      "4 unwind DW_CFA_same_value register(255)\n"
+      "4 unwind Raw Data: 0x08 0xff 0x01\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_register) {
+  this->memory_.SetMemory(0x300, std::vector<uint8_t>{0x09, 0x02, 0x01});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x300, 0x303));
+  std::string expected =
+      "4 unwind DW_CFA_register register(2) register(1)\n"
+      "4 unwind Raw Data: 0x09 0x02 0x01\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  this->memory_.SetMemory(0x4300, std::vector<uint8_t>{0x09, 0xff, 0x01, 0xff, 0x03});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x4300, 0x4305));
+  expected =
+      "4 unwind DW_CFA_register register(255) register(511)\n"
+      "4 unwind Raw Data: 0x09 0xff 0x01 0xff 0x03\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_state) {
+  this->memory_.SetMemory(0x300, std::vector<uint8_t>{0x0a});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x300, 0x301));
+
+  std::string expected =
+      "4 unwind DW_CFA_remember_state\n"
+      "4 unwind Raw Data: 0x0a\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  this->memory_.SetMemory(0x4300, std::vector<uint8_t>{0x0b});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x4300, 0x4301));
+
+  expected =
+      "4 unwind DW_CFA_restore_state\n"
+      "4 unwind Raw Data: 0x0b\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_state_cfa_offset_restore) {
+  this->memory_.SetMemory(0x3000, std::vector<uint8_t>{0x0a, 0x0e, 0x40, 0x0b});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x3000, 0x3004));
+
+  std::string expected =
+      "4 unwind DW_CFA_remember_state\n"
+      "4 unwind Raw Data: 0x0a\n"
+      "4 unwind DW_CFA_def_cfa_offset 64\n"
+      "4 unwind Raw Data: 0x0e 0x40\n"
+      "4 unwind DW_CFA_restore_state\n"
+      "4 unwind Raw Data: 0x0b\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_def_cfa) {
+  this->memory_.SetMemory(0x100, std::vector<uint8_t>{0x0c, 0x7f, 0x74});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x100, 0x103));
+
+  std::string expected =
+      "4 unwind DW_CFA_def_cfa register(127) 116\n"
+      "4 unwind Raw Data: 0x0c 0x7f 0x74\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  this->memory_.SetMemory(0x200, std::vector<uint8_t>{0x0c, 0xff, 0x02, 0xf4, 0x04});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x200, 0x205));
+
+  expected =
+      "4 unwind DW_CFA_def_cfa register(383) 628\n"
+      "4 unwind Raw Data: 0x0c 0xff 0x02 0xf4 0x04\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_def_cfa_sf) {
+  this->memory_.SetMemory(0x100, std::vector<uint8_t>{0x12, 0x30, 0x25});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x100, 0x103));
+
+  std::string expected =
+      "4 unwind DW_CFA_def_cfa_sf register(48) 37\n"
+      "4 unwind Raw Data: 0x12 0x30 0x25\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  // Test a negative value.
+  ResetLogs();
+  this->memory_.SetMemory(0x200, std::vector<uint8_t>{0x12, 0xa3, 0x01, 0xfa, 0x7f});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x200, 0x205));
+
+  expected =
+      "4 unwind DW_CFA_def_cfa_sf register(163) -6\n"
+      "4 unwind Raw Data: 0x12 0xa3 0x01 0xfa 0x7f\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_def_cfa_register) {
+  this->memory_.SetMemory(0x100, std::vector<uint8_t>{0x0d, 0x72});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x100, 0x102));
+
+  std::string expected =
+      "4 unwind DW_CFA_def_cfa_register register(114)\n"
+      "4 unwind Raw Data: 0x0d 0x72\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  this->memory_.SetMemory(0x200, std::vector<uint8_t>{0x0d, 0xf9, 0x20});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x200, 0x203));
+
+  expected =
+      "4 unwind DW_CFA_def_cfa_register register(4217)\n"
+      "4 unwind Raw Data: 0x0d 0xf9 0x20\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_def_cfa_offset) {
+  this->memory_.SetMemory(0x100, std::vector<uint8_t>{0x0e, 0x59});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x100, 0x102));
+
+  std::string expected =
+      "4 unwind DW_CFA_def_cfa_offset 89\n"
+      "4 unwind Raw Data: 0x0e 0x59\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x100, 0x102));
+
+  expected =
+      "4 unwind DW_CFA_def_cfa_offset 89\n"
+      "4 unwind Raw Data: 0x0e 0x59\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  this->memory_.SetMemory(0x200, std::vector<uint8_t>{0x0e, 0xd4, 0x0a});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x200, 0x203));
+
+  expected =
+      "4 unwind DW_CFA_def_cfa_offset 1364\n"
+      "4 unwind Raw Data: 0x0e 0xd4 0x0a\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_def_cfa_offset_sf) {
+  this->memory_.SetMemory(0x100, std::vector<uint8_t>{0x13, 0x23});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x100, 0x102));
+
+  std::string expected =
+      "4 unwind DW_CFA_def_cfa_offset_sf 35\n"
+      "4 unwind Raw Data: 0x13 0x23\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x100, 0x102));
+
+  expected =
+      "4 unwind DW_CFA_def_cfa_offset_sf 35\n"
+      "4 unwind Raw Data: 0x13 0x23\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  // Negative offset.
+  ResetLogs();
+  this->memory_.SetMemory(0x200, std::vector<uint8_t>{0x13, 0xf6, 0x7f});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x200, 0x203));
+
+  expected =
+      "4 unwind DW_CFA_def_cfa_offset_sf -10\n"
+      "4 unwind Raw Data: 0x13 0xf6 0x7f\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_def_cfa_expression) {
+  this->memory_.SetMemory(0x100, std::vector<uint8_t>{0x0f, 0x04, 0x01, 0x02, 0x04, 0x05});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x100, 0x106));
+
+  std::string expected =
+      "4 unwind DW_CFA_def_cfa_expression 4\n"
+      "4 unwind Raw Data: 0x0f 0x04 0x01 0x02 0x04 0x05\n"
+      "4 unwind   Illegal\n"
+      "4 unwind   Raw Data: 0x01\n"
+      "4 unwind   Illegal\n"
+      "4 unwind   Raw Data: 0x02\n"
+      "4 unwind   Illegal\n"
+      "4 unwind   Raw Data: 0x04\n"
+      "4 unwind   Illegal\n"
+      "4 unwind   Raw Data: 0x05\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  std::vector<uint8_t> ops{0x0f, 0x81, 0x01};
+  expected = "4 unwind Raw Data: 0x0f 0x81 0x01";
+  std::string op_string;
+  for (uint8_t i = 3; i < 132; i++) {
+    ops.push_back(0x05);
+    op_string +=
+        "4 unwind   Illegal\n"
+        "4 unwind   Raw Data: 0x05\n";
+    expected += " 0x05";
+    if (((i + 1) % 10) == 0) {
+      expected += "\n4 unwind Raw Data:";
+    }
+  }
+  expected += '\n';
+  this->memory_.SetMemory(0x200, ops);
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x200, 0x284));
+
+  expected = "4 unwind DW_CFA_def_cfa_expression 129\n" + expected;
+  ASSERT_EQ(expected + op_string, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_expression) {
+  this->memory_.SetMemory(0x100, std::vector<uint8_t>{0x10, 0x04, 0x02, 0xc0, 0xc1});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x100, 0x105));
+
+  std::string expected =
+      "4 unwind DW_CFA_expression register(4) 2\n"
+      "4 unwind Raw Data: 0x10 0x04 0x02 0xc0 0xc1\n"
+      "4 unwind   Illegal\n"
+      "4 unwind   Raw Data: 0xc0\n"
+      "4 unwind   Illegal\n"
+      "4 unwind   Raw Data: 0xc1\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  std::vector<uint8_t> ops{0x10, 0xff, 0x01, 0x82, 0x01};
+  expected = "4 unwind Raw Data: 0x10 0xff 0x01 0x82 0x01";
+  std::string op_string;
+  for (uint8_t i = 5; i < 135; i++) {
+    ops.push_back(0xa0 + (i - 5) % 96);
+    op_string += "4 unwind   Illegal\n";
+    op_string += android::base::StringPrintf("4 unwind   Raw Data: 0x%02x\n", ops.back());
+    expected += android::base::StringPrintf(" 0x%02x", ops.back());
+    if (((i + 1) % 10) == 0) {
+      expected += "\n4 unwind Raw Data:";
+    }
+  }
+  expected = "4 unwind DW_CFA_expression register(255) 130\n" + expected + "\n";
+
+  this->memory_.SetMemory(0x200, ops);
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x200, 0x287));
+
+  ASSERT_EQ(expected + op_string, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_val_offset) {
+  this->memory_.SetMemory(0x100, std::vector<uint8_t>{0x14, 0x45, 0x54});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x100, 0x103));
+
+  std::string expected =
+      "4 unwind DW_CFA_val_offset register(69) 84\n"
+      "4 unwind Raw Data: 0x14 0x45 0x54\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  this->memory_.SetMemory(0x400, std::vector<uint8_t>{0x14, 0xa2, 0x02, 0xb4, 0x05});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x400, 0x405));
+
+  expected =
+      "4 unwind DW_CFA_val_offset register(290) 692\n"
+      "4 unwind Raw Data: 0x14 0xa2 0x02 0xb4 0x05\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_val_offset_sf) {
+  this->memory_.SetMemory(0x100, std::vector<uint8_t>{0x15, 0x56, 0x12});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x100, 0x103));
+
+  std::string expected =
+      "4 unwind DW_CFA_val_offset_sf register(86) 18\n"
+      "4 unwind Raw Data: 0x15 0x56 0x12\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  // Negative value.
+  ResetLogs();
+  this->memory_.SetMemory(0xa00, std::vector<uint8_t>{0x15, 0xff, 0x01, 0xc0, 0x7f});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0xa00, 0xa05));
+
+  expected =
+      "4 unwind DW_CFA_val_offset_sf register(255) -64\n"
+      "4 unwind Raw Data: 0x15 0xff 0x01 0xc0 0x7f\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_val_expression) {
+  this->memory_.SetMemory(0x100, std::vector<uint8_t>{0x16, 0x05, 0x02, 0xb0, 0xb1});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x100, 0x105));
+
+  std::string expected =
+      "4 unwind DW_CFA_val_expression register(5) 2\n"
+      "4 unwind Raw Data: 0x16 0x05 0x02 0xb0 0xb1\n"
+      "4 unwind   Illegal\n"
+      "4 unwind   Raw Data: 0xb0\n"
+      "4 unwind   Illegal\n"
+      "4 unwind   Raw Data: 0xb1\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  std::vector<uint8_t> ops{0x16, 0x83, 0x10, 0xa8, 0x01};
+  expected = "4 unwind Raw Data: 0x16 0x83 0x10 0xa8 0x01";
+  std::string op_string;
+  for (uint8_t i = 0; i < 168; i++) {
+    ops.push_back(0xa0 + (i % 96));
+    op_string += "4 unwind   Illegal\n";
+    op_string += android::base::StringPrintf("4 unwind   Raw Data: 0x%02x\n", ops.back());
+    expected += android::base::StringPrintf(" 0x%02x", ops.back());
+    if (((i + 6) % 10) == 0) {
+      expected += "\n4 unwind Raw Data:";
+    }
+  }
+  expected = "4 unwind DW_CFA_val_expression register(2051) 168\n" + expected + "\n";
+
+  this->memory_.SetMemory(0xa00, ops);
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0xa00, 0xaad));
+
+  ASSERT_EQ(expected + op_string, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_gnu_args_size) {
+  this->memory_.SetMemory(0x2000, std::vector<uint8_t>{0x2e, 0x04});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x2000, 0x2002));
+
+  std::string expected =
+      "4 unwind DW_CFA_GNU_args_size 4\n"
+      "4 unwind Raw Data: 0x2e 0x04\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  this->memory_.SetMemory(0x5000, std::vector<uint8_t>{0x2e, 0xa4, 0x80, 0x04});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x5000, 0x5004));
+
+  expected =
+      "4 unwind DW_CFA_GNU_args_size 65572\n"
+      "4 unwind Raw Data: 0x2e 0xa4 0x80 0x04\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_gnu_negative_offset_extended) {
+  this->memory_.SetMemory(0x500, std::vector<uint8_t>{0x2f, 0x08, 0x10});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x500, 0x503));
+
+  std::string expected =
+      "4 unwind DW_CFA_GNU_negative_offset_extended register(8) 16\n"
+      "4 unwind Raw Data: 0x2f 0x08 0x10\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  this->memory_.SetMemory(0x1500, std::vector<uint8_t>{0x2f, 0x81, 0x02, 0xff, 0x01});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x1500, 0x1505));
+
+  expected =
+      "4 unwind DW_CFA_GNU_negative_offset_extended register(257) 255\n"
+      "4 unwind Raw Data: 0x2f 0x81 0x02 0xff 0x01\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaLogTest, cfa_register_override) {
+  this->memory_.SetMemory(0x300, std::vector<uint8_t>{0x09, 0x02, 0x01, 0x09, 0x02, 0x04});
+
+  ASSERT_TRUE(this->cfa_->Log(0, this->fde_.pc_start, 0, 0x300, 0x306));
+
+  std::string expected =
+      "4 unwind DW_CFA_register register(2) register(1)\n"
+      "4 unwind Raw Data: 0x09 0x02 0x01\n"
+      "4 unwind DW_CFA_register register(2) register(4)\n"
+      "4 unwind Raw Data: 0x09 0x02 0x04\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+REGISTER_TYPED_TEST_CASE_P(DwarfCfaLogTest, cfa_illegal, cfa_nop, cfa_offset, cfa_offset_extended,
+                           cfa_offset_extended_sf, cfa_restore, cfa_restore_extended, cfa_set_loc,
+                           cfa_advance_loc, cfa_advance_loc1, cfa_advance_loc2, cfa_advance_loc4,
+                           cfa_undefined, cfa_same, cfa_register, cfa_state,
+                           cfa_state_cfa_offset_restore, cfa_def_cfa, cfa_def_cfa_sf,
+                           cfa_def_cfa_register, cfa_def_cfa_offset, cfa_def_cfa_offset_sf,
+                           cfa_def_cfa_expression, cfa_expression, cfa_val_offset,
+                           cfa_val_offset_sf, cfa_val_expression, cfa_gnu_args_size,
+                           cfa_gnu_negative_offset_extended, cfa_register_override);
+
+typedef ::testing::Types<uint32_t, uint64_t> DwarfCfaLogTestTypes;
+INSTANTIATE_TYPED_TEST_CASE_P(, DwarfCfaLogTest, DwarfCfaLogTestTypes);
diff --git a/libunwindstack/tests/DwarfCfaTest.cpp b/libunwindstack/tests/DwarfCfaTest.cpp
new file mode 100644
index 0000000..6cf028a
--- /dev/null
+++ b/libunwindstack/tests/DwarfCfaTest.cpp
@@ -0,0 +1,959 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdint.h>
+
+#include <memory>
+#include <unordered_map>
+
+#include <gtest/gtest.h>
+
+#include "DwarfCfa.h"
+#include "DwarfLocation.h"
+#include "DwarfMemory.h"
+#include "DwarfStructs.h"
+#include "Log.h"
+
+#include "LogFake.h"
+#include "MemoryFake.h"
+
+template <typename TypeParam>
+class DwarfCfaTest : public ::testing::Test {
+ protected:
+  void SetUp() override {
+    ResetLogs();
+    memory_.Clear();
+
+    dmem_.reset(new DwarfMemory(&memory_));
+
+    cie_.cfa_instructions_offset = 0x1000;
+    cie_.cfa_instructions_end = 0x1030;
+    // These two values should be different to distinguish between
+    // operations that deal with code versus data.
+    cie_.code_alignment_factor = 4;
+    cie_.data_alignment_factor = 8;
+
+    fde_.cfa_instructions_offset = 0x2000;
+    fde_.cfa_instructions_end = 0x2030;
+    fde_.pc_start = 0x2000;
+    fde_.cie = &cie_;
+
+    cfa_.reset(new DwarfCfa<TypeParam>(dmem_.get(), &fde_));
+  }
+
+  MemoryFake memory_;
+  std::unique_ptr<DwarfMemory> dmem_;
+  std::unique_ptr<DwarfCfa<TypeParam>> cfa_;
+  DwarfCIE cie_;
+  DwarfFDE fde_;
+};
+TYPED_TEST_CASE_P(DwarfCfaTest);
+
+// NOTE: All test class variables need to be referenced as this->.
+
+TYPED_TEST_P(DwarfCfaTest, cfa_illegal) {
+  for (uint8_t i = 0x17; i < 0x3f; i++) {
+    if (i == 0x2e || i == 0x2f) {
+      // Skip gnu extension ops.
+      continue;
+    }
+    this->memory_.SetMemory(0x2000, std::vector<uint8_t>{i});
+    dwarf_loc_regs_t loc_regs;
+
+    ASSERT_FALSE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x2000, 0x2001, &loc_regs));
+    ASSERT_EQ(DWARF_ERROR_ILLEGAL_VALUE, this->cfa_->last_error());
+    ASSERT_EQ(0x2001U, this->dmem_->cur_offset());
+
+    ASSERT_EQ("", GetFakeLogPrint());
+    ASSERT_EQ("", GetFakeLogBuf());
+  }
+}
+
+TYPED_TEST_P(DwarfCfaTest, cfa_nop) {
+  this->memory_.SetMemory(0x2000, std::vector<uint8_t>{0x00});
+  dwarf_loc_regs_t loc_regs;
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x2000, 0x2001, &loc_regs));
+  ASSERT_EQ(0x2001U, this->dmem_->cur_offset());
+  ASSERT_EQ(0U, loc_regs.size());
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+// This test needs to be examined.
+TYPED_TEST_P(DwarfCfaTest, cfa_offset) {
+  this->memory_.SetMemory(0x2000, std::vector<uint8_t>{0x83, 0x04});
+  dwarf_loc_regs_t loc_regs;
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x2000, 0x2002, &loc_regs));
+  ASSERT_EQ(0x2002U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  auto location = loc_regs.find(3);
+  ASSERT_NE(loc_regs.end(), location);
+  ASSERT_EQ(DWARF_LOCATION_OFFSET, location->second.type);
+  ASSERT_EQ(32U, location->second.values[0]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  this->memory_.SetMemory(0x2100, std::vector<uint8_t>{0x83, 0x84, 0x01});
+  loc_regs.clear();
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x2100, 0x2103, &loc_regs));
+  ASSERT_EQ(0x2103U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  location = loc_regs.find(3);
+  ASSERT_NE(loc_regs.end(), location);
+  ASSERT_EQ(DWARF_LOCATION_OFFSET, location->second.type);
+  ASSERT_EQ(1056U, location->second.values[0]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaTest, cfa_offset_extended) {
+  this->memory_.SetMemory(0x500, std::vector<uint8_t>{0x05, 0x03, 0x02});
+  dwarf_loc_regs_t loc_regs;
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x500, 0x503, &loc_regs));
+  ASSERT_EQ(0x503U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  auto location = loc_regs.find(3);
+  ASSERT_NE(loc_regs.end(), location);
+  ASSERT_EQ(DWARF_LOCATION_OFFSET, location->second.type);
+  ASSERT_EQ(2U, location->second.values[0]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  loc_regs.clear();
+  this->memory_.SetMemory(0x1500, std::vector<uint8_t>{0x05, 0x81, 0x01, 0x82, 0x12});
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x1500, 0x1505, &loc_regs));
+  ASSERT_EQ(0x1505U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  location = loc_regs.find(129);
+  ASSERT_NE(loc_regs.end(), location);
+  ASSERT_EQ(DWARF_LOCATION_OFFSET, location->second.type);
+  ASSERT_EQ(2306U, location->second.values[0]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaTest, cfa_offset_extended_sf) {
+  this->memory_.SetMemory(0x500, std::vector<uint8_t>{0x11, 0x05, 0x10});
+  dwarf_loc_regs_t loc_regs;
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x500, 0x503, &loc_regs));
+  ASSERT_EQ(0x503U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  auto location = loc_regs.find(5);
+  ASSERT_NE(loc_regs.end(), location);
+  ASSERT_EQ(DWARF_LOCATION_OFFSET, location->second.type);
+  ASSERT_EQ(0x80U, location->second.values[0]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  // Check a negative value for the offset.
+  ResetLogs();
+  loc_regs.clear();
+  this->memory_.SetMemory(0x1500, std::vector<uint8_t>{0x11, 0x86, 0x01, 0xff, 0x7f});
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x1500, 0x1505, &loc_regs));
+  ASSERT_EQ(0x1505U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  location = loc_regs.find(134);
+  ASSERT_NE(loc_regs.end(), location);
+  ASSERT_EQ(DWARF_LOCATION_OFFSET, location->second.type);
+  ASSERT_EQ(static_cast<uint64_t>(-8), location->second.values[0]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaTest, cfa_restore) {
+  this->memory_.SetMemory(0x2000, std::vector<uint8_t>{0xc2});
+  dwarf_loc_regs_t loc_regs;
+
+  ASSERT_FALSE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x2000, 0x2001, &loc_regs));
+  ASSERT_EQ(DWARF_ERROR_ILLEGAL_STATE, this->cfa_->last_error());
+  ASSERT_EQ(0x2001U, this->dmem_->cur_offset());
+  ASSERT_EQ(0U, loc_regs.size());
+
+  ASSERT_EQ("4 unwind restore while processing cie\n", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  dwarf_loc_regs_t cie_loc_regs;
+  cie_loc_regs[2] = {.type = DWARF_LOCATION_REGISTER, .values = {0, 0}};
+  this->cfa_->set_cie_loc_regs(&cie_loc_regs);
+  this->memory_.SetMemory(0x3000, std::vector<uint8_t>{0x82, 0x04, 0xc2});
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x3000, 0x3003, &loc_regs));
+  ASSERT_EQ(0x3003U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  auto location = loc_regs.find(2);
+  ASSERT_NE(loc_regs.end(), location);
+  ASSERT_EQ(DWARF_LOCATION_REGISTER, location->second.type);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaTest, cfa_restore_extended) {
+  this->memory_.SetMemory(0x4000, std::vector<uint8_t>{0x06, 0x08});
+  dwarf_loc_regs_t loc_regs;
+
+  ASSERT_FALSE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x4000, 0x4002, &loc_regs));
+  ASSERT_EQ(DWARF_ERROR_ILLEGAL_STATE, this->cfa_->last_error());
+  ASSERT_EQ(0x4002U, this->dmem_->cur_offset());
+  ASSERT_EQ(0U, loc_regs.size());
+
+  ASSERT_EQ("4 unwind restore while processing cie\n", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  loc_regs.clear();
+  this->memory_.SetMemory(0x5000, std::vector<uint8_t>{0x05, 0x82, 0x02, 0x04, 0x06, 0x82, 0x02});
+  dwarf_loc_regs_t cie_loc_regs;
+  cie_loc_regs[258] = {.type = DWARF_LOCATION_REGISTER, .values = {0, 0}};
+  this->cfa_->set_cie_loc_regs(&cie_loc_regs);
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x5000, 0x5007, &loc_regs));
+  ASSERT_EQ(0x5007U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  auto location = loc_regs.find(258);
+  ASSERT_NE(loc_regs.end(), location);
+  ASSERT_EQ(DWARF_LOCATION_REGISTER, location->second.type);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaTest, cfa_set_loc) {
+  uint8_t buffer[1 + sizeof(TypeParam)];
+  buffer[0] = 0x1;
+  TypeParam address;
+  std::string raw_data("Raw Data: 0x01 ");
+  std::string address_str;
+  if (sizeof(TypeParam) == 4) {
+    address = 0x81234578U;
+    address_str = "0x81234578";
+    raw_data += "0x78 0x45 0x23 0x81";
+  } else {
+    address = 0x8123456712345678ULL;
+    address_str = "0x8123456712345678";
+    raw_data += "0x78 0x56 0x34 0x12 0x67 0x45 0x23 0x81";
+  }
+  memcpy(&buffer[1], &address, sizeof(address));
+
+  this->memory_.SetMemory(0x50, buffer, sizeof(buffer));
+  ResetLogs();
+  dwarf_loc_regs_t loc_regs;
+  ASSERT_TRUE(
+      this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x50, 0x51 + sizeof(TypeParam), &loc_regs));
+  ASSERT_EQ(0x51 + sizeof(TypeParam), this->dmem_->cur_offset());
+  ASSERT_EQ(address, this->cfa_->cur_pc());
+  ASSERT_EQ(0U, loc_regs.size());
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  // Check for a set going back.
+  ResetLogs();
+  loc_regs.clear();
+  this->fde_.pc_start = address + 0x10;
+  ASSERT_TRUE(
+      this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x50, 0x51 + sizeof(TypeParam), &loc_regs));
+  ASSERT_EQ(0x51 + sizeof(TypeParam), this->dmem_->cur_offset());
+  ASSERT_EQ(address, this->cfa_->cur_pc());
+  ASSERT_EQ(0U, loc_regs.size());
+
+  std::string cur_address_str(address_str);
+  cur_address_str[cur_address_str.size() - 2] = '8';
+  std::string expected = "4 unwind Warning: PC is moving backwards: old " + cur_address_str +
+                         " new " + address_str + "\n";
+  ASSERT_EQ(expected, GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaTest, cfa_advance_loc1) {
+  this->memory_.SetMemory(0x200, std::vector<uint8_t>{0x02, 0x04});
+  dwarf_loc_regs_t loc_regs;
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x200, 0x202, &loc_regs));
+  ASSERT_EQ(0x202U, this->dmem_->cur_offset());
+  ASSERT_EQ(this->fde_.pc_start + 0x10, this->cfa_->cur_pc());
+  ASSERT_EQ(0U, loc_regs.size());
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaTest, cfa_advance_loc2) {
+  this->memory_.SetMemory(0x600, std::vector<uint8_t>{0x03, 0x04, 0x03});
+  dwarf_loc_regs_t loc_regs;
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x600, 0x603, &loc_regs));
+  ASSERT_EQ(0x603U, this->dmem_->cur_offset());
+  ASSERT_EQ(this->fde_.pc_start + 0xc10U, this->cfa_->cur_pc());
+  ASSERT_EQ(0U, loc_regs.size());
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaTest, cfa_advance_loc4) {
+  this->memory_.SetMemory(0x500, std::vector<uint8_t>{0x04, 0x04, 0x03, 0x02, 0x01});
+  dwarf_loc_regs_t loc_regs;
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x500, 0x505, &loc_regs));
+  ASSERT_EQ(0x505U, this->dmem_->cur_offset());
+  ASSERT_EQ(this->fde_.pc_start + 0x4080c10, this->cfa_->cur_pc());
+  ASSERT_EQ(0U, loc_regs.size());
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaTest, cfa_undefined) {
+  this->memory_.SetMemory(0xa00, std::vector<uint8_t>{0x07, 0x09});
+  dwarf_loc_regs_t loc_regs;
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0xa00, 0xa02, &loc_regs));
+  ASSERT_EQ(0xa02U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  auto location = loc_regs.find(9);
+  ASSERT_NE(loc_regs.end(), location);
+  ASSERT_EQ(DWARF_LOCATION_UNDEFINED, location->second.type);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  loc_regs.clear();
+  this->memory_.SetMemory(0x1a00, std::vector<uint8_t>{0x07, 0x81, 0x01});
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x1a00, 0x1a03, &loc_regs));
+  ASSERT_EQ(0x1a03U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  location = loc_regs.find(129);
+  ASSERT_NE(loc_regs.end(), location);
+  ASSERT_EQ(DWARF_LOCATION_UNDEFINED, location->second.type);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaTest, cfa_same) {
+  this->memory_.SetMemory(0x100, std::vector<uint8_t>{0x08, 0x7f});
+  dwarf_loc_regs_t loc_regs;
+
+  loc_regs[127] = {.type = DWARF_LOCATION_REGISTER, .values = {0, 0}};
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x100, 0x102, &loc_regs));
+  ASSERT_EQ(0x102U, this->dmem_->cur_offset());
+  ASSERT_EQ(0U, loc_regs.size());
+  ASSERT_EQ(0U, loc_regs.count(127));
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  loc_regs.clear();
+  this->memory_.SetMemory(0x2100, std::vector<uint8_t>{0x08, 0xff, 0x01});
+
+  loc_regs[255] = {.type = DWARF_LOCATION_REGISTER, .values = {0, 0}};
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x2100, 0x2103, &loc_regs));
+  ASSERT_EQ(0x2103U, this->dmem_->cur_offset());
+  ASSERT_EQ(0U, loc_regs.size());
+  ASSERT_EQ(0U, loc_regs.count(255));
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaTest, cfa_register) {
+  this->memory_.SetMemory(0x300, std::vector<uint8_t>{0x09, 0x02, 0x01});
+  dwarf_loc_regs_t loc_regs;
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x300, 0x303, &loc_regs));
+  ASSERT_EQ(0x303U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  auto location = loc_regs.find(2);
+  ASSERT_NE(loc_regs.end(), location);
+  ASSERT_EQ(DWARF_LOCATION_REGISTER, location->second.type);
+  ASSERT_EQ(1U, location->second.values[0]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  loc_regs.clear();
+  this->memory_.SetMemory(0x4300, std::vector<uint8_t>{0x09, 0xff, 0x01, 0xff, 0x03});
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x4300, 0x4305, &loc_regs));
+  ASSERT_EQ(0x4305U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  location = loc_regs.find(255);
+  ASSERT_NE(loc_regs.end(), location);
+  ASSERT_EQ(DWARF_LOCATION_REGISTER, location->second.type);
+  ASSERT_EQ(511U, location->second.values[0]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaTest, cfa_state) {
+  this->memory_.SetMemory(0x300, std::vector<uint8_t>{0x0a});
+  dwarf_loc_regs_t loc_regs;
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x300, 0x301, &loc_regs));
+  ASSERT_EQ(0x301U, this->dmem_->cur_offset());
+  ASSERT_EQ(0U, loc_regs.size());
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  this->memory_.SetMemory(0x4300, std::vector<uint8_t>{0x0b});
+
+  loc_regs.clear();
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x4300, 0x4301, &loc_regs));
+  ASSERT_EQ(0x4301U, this->dmem_->cur_offset());
+  ASSERT_EQ(0U, loc_regs.size());
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  this->memory_.SetMemory(0x2000, std::vector<uint8_t>{0x85, 0x02, 0x0a, 0x86, 0x04, 0x0b});
+
+  loc_regs.clear();
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x2000, 0x2005, &loc_regs));
+  ASSERT_EQ(0x2005U, this->dmem_->cur_offset());
+  ASSERT_EQ(2U, loc_regs.size());
+  ASSERT_NE(loc_regs.end(), loc_regs.find(5));
+  ASSERT_NE(loc_regs.end(), loc_regs.find(6));
+
+  loc_regs.clear();
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x2000, 0x2006, &loc_regs));
+  ASSERT_EQ(0x2006U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  ASSERT_NE(loc_regs.end(), loc_regs.find(5));
+
+  ResetLogs();
+  this->memory_.SetMemory(
+      0x6000, std::vector<uint8_t>{0x0a, 0x85, 0x02, 0x0a, 0x86, 0x04, 0x0a, 0x87, 0x01, 0x0a, 0x89,
+                                   0x05, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b});
+
+  loc_regs.clear();
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x6000, 0x600c, &loc_regs));
+  ASSERT_EQ(0x600cU, this->dmem_->cur_offset());
+  ASSERT_EQ(4U, loc_regs.size());
+  ASSERT_NE(loc_regs.end(), loc_regs.find(5));
+  ASSERT_NE(loc_regs.end(), loc_regs.find(6));
+  ASSERT_NE(loc_regs.end(), loc_regs.find(7));
+  ASSERT_NE(loc_regs.end(), loc_regs.find(9));
+
+  loc_regs.clear();
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x6000, 0x600d, &loc_regs));
+  ASSERT_EQ(0x600dU, this->dmem_->cur_offset());
+  ASSERT_EQ(3U, loc_regs.size());
+  ASSERT_NE(loc_regs.end(), loc_regs.find(5));
+  ASSERT_NE(loc_regs.end(), loc_regs.find(6));
+  ASSERT_NE(loc_regs.end(), loc_regs.find(7));
+
+  loc_regs.clear();
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x6000, 0x600e, &loc_regs));
+  ASSERT_EQ(0x600eU, this->dmem_->cur_offset());
+  ASSERT_EQ(2U, loc_regs.size());
+  ASSERT_NE(loc_regs.end(), loc_regs.find(5));
+  ASSERT_NE(loc_regs.end(), loc_regs.find(6));
+
+  loc_regs.clear();
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x6000, 0x600f, &loc_regs));
+  ASSERT_EQ(0x600fU, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  ASSERT_NE(loc_regs.end(), loc_regs.find(5));
+
+  loc_regs.clear();
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x6000, 0x6010, &loc_regs));
+  ASSERT_EQ(0x6010U, this->dmem_->cur_offset());
+  ASSERT_EQ(0U, loc_regs.size());
+
+  loc_regs.clear();
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x6000, 0x6011, &loc_regs));
+  ASSERT_EQ(0x6011U, this->dmem_->cur_offset());
+  ASSERT_EQ(0U, loc_regs.size());
+}
+
+// This test verifies that the cfa offset is saved and restored properly.
+// Even though the spec is not clear about whether the offset is also
+// restored, the gcc unwinder does, and libunwind does too.
+TYPED_TEST_P(DwarfCfaTest, cfa_state_cfa_offset_restore) {
+  this->memory_.SetMemory(0x3000, std::vector<uint8_t>{0x0a, 0x0e, 0x40, 0x0b});
+  dwarf_loc_regs_t loc_regs;
+  loc_regs[CFA_REG] = {.type = DWARF_LOCATION_REGISTER, .values = {5, 100}};
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x3000, 0x3004, &loc_regs));
+  ASSERT_EQ(0x3004U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  ASSERT_EQ(DWARF_LOCATION_REGISTER, loc_regs[CFA_REG].type);
+  ASSERT_EQ(5U, loc_regs[CFA_REG].values[0]);
+  ASSERT_EQ(100U, loc_regs[CFA_REG].values[1]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaTest, cfa_def_cfa) {
+  this->memory_.SetMemory(0x100, std::vector<uint8_t>{0x0c, 0x7f, 0x74});
+  dwarf_loc_regs_t loc_regs;
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x100, 0x103, &loc_regs));
+  ASSERT_EQ(0x103U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  ASSERT_EQ(DWARF_LOCATION_REGISTER, loc_regs[CFA_REG].type);
+  ASSERT_EQ(0x7fU, loc_regs[CFA_REG].values[0]);
+  ASSERT_EQ(0x74U, loc_regs[CFA_REG].values[1]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  loc_regs.clear();
+  this->memory_.SetMemory(0x200, std::vector<uint8_t>{0x0c, 0xff, 0x02, 0xf4, 0x04});
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x200, 0x205, &loc_regs));
+  ASSERT_EQ(0x205U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  ASSERT_EQ(DWARF_LOCATION_REGISTER, loc_regs[CFA_REG].type);
+  ASSERT_EQ(0x17fU, loc_regs[CFA_REG].values[0]);
+  ASSERT_EQ(0x274U, loc_regs[CFA_REG].values[1]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaTest, cfa_def_cfa_sf) {
+  this->memory_.SetMemory(0x100, std::vector<uint8_t>{0x12, 0x30, 0x25});
+  dwarf_loc_regs_t loc_regs;
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x100, 0x103, &loc_regs));
+  ASSERT_EQ(0x103U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  ASSERT_EQ(DWARF_LOCATION_REGISTER, loc_regs[CFA_REG].type);
+  ASSERT_EQ(0x30U, loc_regs[CFA_REG].values[0]);
+  ASSERT_EQ(0x128U, loc_regs[CFA_REG].values[1]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  // Test a negative value.
+  ResetLogs();
+  loc_regs.clear();
+  this->memory_.SetMemory(0x200, std::vector<uint8_t>{0x12, 0xa3, 0x01, 0xfa, 0x7f});
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x200, 0x205, &loc_regs));
+  ASSERT_EQ(0x205U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  ASSERT_EQ(DWARF_LOCATION_REGISTER, loc_regs[CFA_REG].type);
+  ASSERT_EQ(0xa3U, loc_regs[CFA_REG].values[0]);
+  ASSERT_EQ(static_cast<uint64_t>(-48), loc_regs[CFA_REG].values[1]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaTest, cfa_def_cfa_register) {
+  this->memory_.SetMemory(0x100, std::vector<uint8_t>{0x0d, 0x72});
+  dwarf_loc_regs_t loc_regs;
+
+  // This fails because the cfa is not defined as a register.
+  ASSERT_FALSE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x100, 0x102, &loc_regs));
+  ASSERT_EQ(0U, loc_regs.size());
+  ASSERT_EQ(DWARF_ERROR_ILLEGAL_STATE, this->cfa_->last_error());
+
+  ASSERT_EQ("4 unwind Attempt to set new register, but cfa is not already set to a register.\n",
+            GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  loc_regs.clear();
+  loc_regs[CFA_REG] = {.type = DWARF_LOCATION_REGISTER, .values = {3, 20}};
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x100, 0x102, &loc_regs));
+  ASSERT_EQ(0x102U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  ASSERT_EQ(DWARF_LOCATION_REGISTER, loc_regs[CFA_REG].type);
+  ASSERT_EQ(0x72U, loc_regs[CFA_REG].values[0]);
+  ASSERT_EQ(20U, loc_regs[CFA_REG].values[1]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  this->memory_.SetMemory(0x200, std::vector<uint8_t>{0x0d, 0xf9, 0x20});
+  loc_regs.clear();
+  loc_regs[CFA_REG] = {.type = DWARF_LOCATION_REGISTER, .values = {3, 60}};
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x200, 0x203, &loc_regs));
+  ASSERT_EQ(0x203U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  ASSERT_EQ(DWARF_LOCATION_REGISTER, loc_regs[CFA_REG].type);
+  ASSERT_EQ(0x1079U, loc_regs[CFA_REG].values[0]);
+  ASSERT_EQ(60U, loc_regs[CFA_REG].values[1]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaTest, cfa_def_cfa_offset) {
+  this->memory_.SetMemory(0x100, std::vector<uint8_t>{0x0e, 0x59});
+  dwarf_loc_regs_t loc_regs;
+
+  // This fails because the cfa is not defined as a register.
+  ASSERT_FALSE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x100, 0x102, &loc_regs));
+  ASSERT_EQ(0U, loc_regs.size());
+  ASSERT_EQ(DWARF_ERROR_ILLEGAL_STATE, this->cfa_->last_error());
+
+  ASSERT_EQ("4 unwind Attempt to set offset, but cfa is not set to a register.\n",
+            GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  loc_regs.clear();
+  loc_regs[CFA_REG] = {.type = DWARF_LOCATION_REGISTER, .values = {3}};
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x100, 0x102, &loc_regs));
+  ASSERT_EQ(0x102U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  ASSERT_EQ(DWARF_LOCATION_REGISTER, loc_regs[CFA_REG].type);
+  ASSERT_EQ(3U, loc_regs[CFA_REG].values[0]);
+  ASSERT_EQ(0x59U, loc_regs[CFA_REG].values[1]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  this->memory_.SetMemory(0x200, std::vector<uint8_t>{0x0e, 0xd4, 0x0a});
+  loc_regs.clear();
+  loc_regs[CFA_REG] = {.type = DWARF_LOCATION_REGISTER, .values = {3}};
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x200, 0x203, &loc_regs));
+  ASSERT_EQ(0x203U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  ASSERT_EQ(DWARF_LOCATION_REGISTER, loc_regs[CFA_REG].type);
+  ASSERT_EQ(3U, loc_regs[CFA_REG].values[0]);
+  ASSERT_EQ(0x554U, loc_regs[CFA_REG].values[1]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaTest, cfa_def_cfa_offset_sf) {
+  this->memory_.SetMemory(0x100, std::vector<uint8_t>{0x13, 0x23});
+  dwarf_loc_regs_t loc_regs;
+
+  // This fails because the cfa is not defined as a register.
+  ASSERT_FALSE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x100, 0x102, &loc_regs));
+  ASSERT_EQ(DWARF_ERROR_ILLEGAL_STATE, this->cfa_->last_error());
+
+  ASSERT_EQ("4 unwind Attempt to set offset, but cfa is not set to a register.\n",
+            GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  loc_regs.clear();
+  loc_regs[CFA_REG] = {.type = DWARF_LOCATION_REGISTER, .values = {3}};
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x100, 0x102, &loc_regs));
+  ASSERT_EQ(0x102U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  ASSERT_EQ(DWARF_LOCATION_REGISTER, loc_regs[CFA_REG].type);
+  ASSERT_EQ(3U, loc_regs[CFA_REG].values[0]);
+  ASSERT_EQ(0x118U, loc_regs[CFA_REG].values[1]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  // Negative offset.
+  ResetLogs();
+  this->memory_.SetMemory(0x200, std::vector<uint8_t>{0x13, 0xf6, 0x7f});
+  loc_regs.clear();
+  loc_regs[CFA_REG] = {.type = DWARF_LOCATION_REGISTER, .values = {3}};
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x200, 0x203, &loc_regs));
+  ASSERT_EQ(0x203U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  ASSERT_EQ(DWARF_LOCATION_REGISTER, loc_regs[CFA_REG].type);
+  ASSERT_EQ(3U, loc_regs[CFA_REG].values[0]);
+  ASSERT_EQ(static_cast<TypeParam>(-80), static_cast<TypeParam>(loc_regs[CFA_REG].values[1]));
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaTest, cfa_def_cfa_expression) {
+  this->memory_.SetMemory(0x100, std::vector<uint8_t>{0x0f, 0x04, 0x01, 0x02, 0x03, 0x04});
+  dwarf_loc_regs_t loc_regs;
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x100, 0x106, &loc_regs));
+  ASSERT_EQ(0x106U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  std::vector<uint8_t> ops{0x0f, 0x81, 0x01};
+  for (uint8_t i = 3; i < 132; i++) {
+    ops.push_back(i - 1);
+  }
+  this->memory_.SetMemory(0x200, ops);
+  loc_regs.clear();
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x200, 0x284, &loc_regs));
+  ASSERT_EQ(0x284U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaTest, cfa_expression) {
+  this->memory_.SetMemory(0x100, std::vector<uint8_t>{0x10, 0x04, 0x02, 0x40, 0x20});
+  dwarf_loc_regs_t loc_regs;
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x100, 0x105, &loc_regs));
+  ASSERT_EQ(0x105U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  auto location = loc_regs.find(4);
+  ASSERT_NE(loc_regs.end(), location);
+  ASSERT_EQ(DWARF_LOCATION_EXPRESSION, location->second.type);
+  ASSERT_EQ(2U, location->second.values[0]);
+  ASSERT_EQ(0x105U, location->second.values[1]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  std::vector<uint8_t> ops{0x10, 0xff, 0x01, 0x82, 0x01};
+  for (uint8_t i = 5; i < 135; i++) {
+    ops.push_back(i - 4);
+  }
+
+  this->memory_.SetMemory(0x200, ops);
+  loc_regs.clear();
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x200, 0x287, &loc_regs));
+  ASSERT_EQ(0x287U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  location = loc_regs.find(255);
+  ASSERT_NE(loc_regs.end(), location);
+  ASSERT_EQ(DWARF_LOCATION_EXPRESSION, location->second.type);
+  ASSERT_EQ(130U, location->second.values[0]);
+  ASSERT_EQ(0x287U, location->second.values[1]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaTest, cfa_val_offset) {
+  this->memory_.SetMemory(0x100, std::vector<uint8_t>{0x14, 0x45, 0x54});
+  dwarf_loc_regs_t loc_regs;
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x100, 0x103, &loc_regs));
+  ASSERT_EQ(0x103U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  auto location = loc_regs.find(69);
+  ASSERT_NE(loc_regs.end(), location);
+  ASSERT_EQ(DWARF_LOCATION_VAL_OFFSET, location->second.type);
+  ASSERT_EQ(0x2a0U, location->second.values[0]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  loc_regs.clear();
+  this->memory_.SetMemory(0x400, std::vector<uint8_t>{0x14, 0xa2, 0x02, 0xb4, 0x05});
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x400, 0x405, &loc_regs));
+  ASSERT_EQ(0x405U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  location = loc_regs.find(290);
+  ASSERT_NE(loc_regs.end(), location);
+  ASSERT_EQ(DWARF_LOCATION_VAL_OFFSET, location->second.type);
+  ASSERT_EQ(0x15a0U, location->second.values[0]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaTest, cfa_val_offset_sf) {
+  this->memory_.SetMemory(0x100, std::vector<uint8_t>{0x15, 0x56, 0x12});
+  dwarf_loc_regs_t loc_regs;
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x100, 0x103, &loc_regs));
+  ASSERT_EQ(0x103U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  auto location = loc_regs.find(86);
+  ASSERT_NE(loc_regs.end(), location);
+  ASSERT_EQ(DWARF_LOCATION_VAL_OFFSET, location->second.type);
+  ASSERT_EQ(0x90U, location->second.values[0]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  // Negative value.
+  ResetLogs();
+  loc_regs.clear();
+  this->memory_.SetMemory(0xa00, std::vector<uint8_t>{0x15, 0xff, 0x01, 0xc0, 0x7f});
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0xa00, 0xa05, &loc_regs));
+  ASSERT_EQ(0xa05U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  location = loc_regs.find(255);
+  ASSERT_NE(loc_regs.end(), location);
+  ASSERT_EQ(DWARF_LOCATION_VAL_OFFSET, location->second.type);
+  ASSERT_EQ(static_cast<uint64_t>(-512), location->second.values[0]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaTest, cfa_val_expression) {
+  this->memory_.SetMemory(0x100, std::vector<uint8_t>{0x16, 0x05, 0x02, 0x10, 0x20});
+  dwarf_loc_regs_t loc_regs;
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x100, 0x105, &loc_regs));
+  ASSERT_EQ(0x105U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  auto location = loc_regs.find(5);
+  ASSERT_NE(loc_regs.end(), location);
+  ASSERT_EQ(DWARF_LOCATION_VAL_EXPRESSION, location->second.type);
+  ASSERT_EQ(2U, location->second.values[0]);
+  ASSERT_EQ(0x105U, location->second.values[1]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  std::vector<uint8_t> ops{0x16, 0x83, 0x10, 0xa8, 0x01};
+  for (uint8_t i = 0; i < 168; i++) {
+    ops.push_back(i);
+  }
+
+  this->memory_.SetMemory(0xa00, ops);
+  loc_regs.clear();
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0xa00, 0xaad, &loc_regs));
+  ASSERT_EQ(0xaadU, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  location = loc_regs.find(2051);
+  ASSERT_NE(loc_regs.end(), location);
+  ASSERT_EQ(DWARF_LOCATION_VAL_EXPRESSION, location->second.type);
+  ASSERT_EQ(168U, location->second.values[0]);
+  ASSERT_EQ(0xaadU, location->second.values[1]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaTest, cfa_gnu_args_size) {
+  this->memory_.SetMemory(0x2000, std::vector<uint8_t>{0x2e, 0x04});
+  dwarf_loc_regs_t loc_regs;
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x2000, 0x2002, &loc_regs));
+  ASSERT_EQ(0x2002U, this->dmem_->cur_offset());
+  ASSERT_EQ(0U, loc_regs.size());
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  loc_regs.clear();
+  this->memory_.SetMemory(0x5000, std::vector<uint8_t>{0x2e, 0xa4, 0x80, 0x04});
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x5000, 0x5004, &loc_regs));
+  ASSERT_EQ(0x5004U, this->dmem_->cur_offset());
+  ASSERT_EQ(0U, loc_regs.size());
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaTest, cfa_gnu_negative_offset_extended) {
+  this->memory_.SetMemory(0x500, std::vector<uint8_t>{0x2f, 0x08, 0x10});
+  dwarf_loc_regs_t loc_regs;
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x500, 0x503, &loc_regs));
+  ASSERT_EQ(0x503U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  auto location = loc_regs.find(8);
+  ASSERT_NE(loc_regs.end(), location);
+  ASSERT_EQ(DWARF_LOCATION_OFFSET, location->second.type);
+  ASSERT_EQ(static_cast<uint64_t>(-16), location->second.values[0]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+
+  ResetLogs();
+  loc_regs.clear();
+  this->memory_.SetMemory(0x1500, std::vector<uint8_t>{0x2f, 0x81, 0x02, 0xff, 0x01});
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x1500, 0x1505, &loc_regs));
+  ASSERT_EQ(0x1505U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  location = loc_regs.find(257);
+  ASSERT_NE(loc_regs.end(), location);
+  ASSERT_EQ(DWARF_LOCATION_OFFSET, location->second.type);
+  ASSERT_EQ(static_cast<uint64_t>(-255), location->second.values[0]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+TYPED_TEST_P(DwarfCfaTest, cfa_register_override) {
+  this->memory_.SetMemory(0x300, std::vector<uint8_t>{0x09, 0x02, 0x01, 0x09, 0x02, 0x04});
+  dwarf_loc_regs_t loc_regs;
+
+  ASSERT_TRUE(this->cfa_->GetLocationInfo(this->fde_.pc_start, 0x300, 0x306, &loc_regs));
+  ASSERT_EQ(0x306U, this->dmem_->cur_offset());
+  ASSERT_EQ(1U, loc_regs.size());
+  auto location = loc_regs.find(2);
+  ASSERT_NE(loc_regs.end(), location);
+  ASSERT_EQ(DWARF_LOCATION_REGISTER, location->second.type);
+  ASSERT_EQ(4U, location->second.values[0]);
+
+  ASSERT_EQ("", GetFakeLogPrint());
+  ASSERT_EQ("", GetFakeLogBuf());
+}
+
+REGISTER_TYPED_TEST_CASE_P(DwarfCfaTest, cfa_illegal, cfa_nop, cfa_offset, cfa_offset_extended,
+                           cfa_offset_extended_sf, cfa_restore, cfa_restore_extended, cfa_set_loc,
+                           cfa_advance_loc1, cfa_advance_loc2, cfa_advance_loc4, cfa_undefined,
+                           cfa_same, cfa_register, cfa_state, cfa_state_cfa_offset_restore,
+                           cfa_def_cfa, cfa_def_cfa_sf, cfa_def_cfa_register, cfa_def_cfa_offset,
+                           cfa_def_cfa_offset_sf, cfa_def_cfa_expression, cfa_expression,
+                           cfa_val_offset, cfa_val_offset_sf, cfa_val_expression, cfa_gnu_args_size,
+                           cfa_gnu_negative_offset_extended, cfa_register_override);
+
+typedef ::testing::Types<uint32_t, uint64_t> DwarfCfaTestTypes;
+INSTANTIATE_TYPED_TEST_CASE_P(, DwarfCfaTest, DwarfCfaTestTypes);
diff --git a/libunwindstack/tests/DwarfMemoryTest.cpp b/libunwindstack/tests/DwarfMemoryTest.cpp
new file mode 100644
index 0000000..4877f36
--- /dev/null
+++ b/libunwindstack/tests/DwarfMemoryTest.cpp
@@ -0,0 +1,472 @@
+/*
+ * 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 <ios>
+#include <vector>
+
+#include <gtest/gtest.h>
+
+#include "DwarfMemory.h"
+
+#include "MemoryFake.h"
+
+class DwarfMemoryTest : public ::testing::Test {
+ protected:
+  void SetUp() override {
+    memory_.Clear();
+    dwarf_mem_.reset(new DwarfMemory(&memory_));
+  }
+
+  template <typename AddressType>
+  void GetEncodedSizeTest(uint8_t value, size_t expected);
+  template <typename AddressType>
+  void ReadEncodedValue_omit();
+  template <typename AddressType>
+  void ReadEncodedValue_leb128();
+  template <typename AddressType>
+  void ReadEncodedValue_data1();
+  template <typename AddressType>
+  void ReadEncodedValue_data2();
+  template <typename AddressType>
+  void ReadEncodedValue_data4();
+  template <typename AddressType>
+  void ReadEncodedValue_data8();
+  template <typename AddressType>
+  void ReadEncodedValue_non_zero_adjust();
+  template <typename AddressType>
+  void ReadEncodedValue_overflow();
+
+  MemoryFake memory_;
+  std::unique_ptr<DwarfMemory> dwarf_mem_;
+};
+
+TEST_F(DwarfMemoryTest, ReadBytes) {
+  memory_.SetMemory(0, std::vector<uint8_t>{0x10, 0x18, 0xff, 0xfe});
+
+  uint8_t byte;
+  ASSERT_TRUE(dwarf_mem_->ReadBytes(&byte, 1));
+  ASSERT_EQ(0x10U, byte);
+  ASSERT_TRUE(dwarf_mem_->ReadBytes(&byte, 1));
+  ASSERT_EQ(0x18U, byte);
+  ASSERT_TRUE(dwarf_mem_->ReadBytes(&byte, 1));
+  ASSERT_EQ(0xffU, byte);
+  ASSERT_TRUE(dwarf_mem_->ReadBytes(&byte, 1));
+  ASSERT_EQ(0xfeU, byte);
+  ASSERT_EQ(4U, dwarf_mem_->cur_offset());
+
+  dwarf_mem_->set_cur_offset(2);
+  ASSERT_TRUE(dwarf_mem_->ReadBytes(&byte, 1));
+  ASSERT_EQ(0xffU, byte);
+  ASSERT_EQ(3U, dwarf_mem_->cur_offset());
+}
+
+TEST_F(DwarfMemoryTest, ReadSigned_check) {
+  uint64_t value;
+
+  // Signed 8 byte reads.
+  memory_.SetData8(0, static_cast<uint8_t>(-10));
+  memory_.SetData8(1, 200);
+  ASSERT_TRUE(dwarf_mem_->ReadSigned<int8_t>(&value));
+  ASSERT_EQ(static_cast<int8_t>(-10), static_cast<int8_t>(value));
+  ASSERT_TRUE(dwarf_mem_->ReadSigned<int8_t>(&value));
+  ASSERT_EQ(static_cast<int8_t>(200), static_cast<int8_t>(value));
+
+  // Signed 16 byte reads.
+  memory_.SetData16(0x10, static_cast<uint16_t>(-1000));
+  memory_.SetData16(0x12, 50100);
+  dwarf_mem_->set_cur_offset(0x10);
+  ASSERT_TRUE(dwarf_mem_->ReadSigned<int16_t>(&value));
+  ASSERT_EQ(static_cast<int16_t>(-1000), static_cast<int16_t>(value));
+  ASSERT_TRUE(dwarf_mem_->ReadSigned<int16_t>(&value));
+  ASSERT_EQ(static_cast<int16_t>(50100), static_cast<int16_t>(value));
+
+  // Signed 32 byte reads.
+  memory_.SetData32(0x100, static_cast<uint32_t>(-1000000000));
+  memory_.SetData32(0x104, 3000000000);
+  dwarf_mem_->set_cur_offset(0x100);
+  ASSERT_TRUE(dwarf_mem_->ReadSigned<int32_t>(&value));
+  ASSERT_EQ(static_cast<int32_t>(-1000000000), static_cast<int32_t>(value));
+  ASSERT_TRUE(dwarf_mem_->ReadSigned<int32_t>(&value));
+  ASSERT_EQ(static_cast<int32_t>(3000000000), static_cast<int32_t>(value));
+
+  // Signed 64 byte reads.
+  memory_.SetData64(0x200, static_cast<uint64_t>(-2000000000000LL));
+  memory_.SetData64(0x208, 5000000000000LL);
+  dwarf_mem_->set_cur_offset(0x200);
+  ASSERT_TRUE(dwarf_mem_->ReadSigned<int64_t>(&value));
+  ASSERT_EQ(static_cast<int64_t>(-2000000000000), static_cast<int64_t>(value));
+  ASSERT_TRUE(dwarf_mem_->ReadSigned<int64_t>(&value));
+  ASSERT_EQ(static_cast<int64_t>(5000000000000), static_cast<int64_t>(value));
+}
+
+TEST_F(DwarfMemoryTest, ReadULEB128) {
+  memory_.SetMemory(0, std::vector<uint8_t>{0x01, 0x80, 0x24, 0xff, 0xc3, 0xff, 0x7f});
+
+  uint64_t value;
+  ASSERT_TRUE(dwarf_mem_->ReadULEB128(&value));
+  ASSERT_EQ(1U, dwarf_mem_->cur_offset());
+  ASSERT_EQ(1U, value);
+
+  ASSERT_TRUE(dwarf_mem_->ReadULEB128(&value));
+  ASSERT_EQ(3U, dwarf_mem_->cur_offset());
+  ASSERT_EQ(0x1200U, value);
+
+  ASSERT_TRUE(dwarf_mem_->ReadULEB128(&value));
+  ASSERT_EQ(7U, dwarf_mem_->cur_offset());
+  ASSERT_EQ(0xfffe1ffU, value);
+}
+
+TEST_F(DwarfMemoryTest, ReadSLEB128) {
+  memory_.SetMemory(0, std::vector<uint8_t>{0x06, 0x40, 0x82, 0x34, 0x89, 0x64, 0xf9, 0xc3, 0x8f,
+                                            0x2f, 0xbf, 0xc3, 0xf7, 0x5f});
+
+  int64_t value;
+  ASSERT_TRUE(dwarf_mem_->ReadSLEB128(&value));
+  ASSERT_EQ(1U, dwarf_mem_->cur_offset());
+  ASSERT_EQ(6U, value);
+
+  ASSERT_TRUE(dwarf_mem_->ReadSLEB128(&value));
+  ASSERT_EQ(2U, dwarf_mem_->cur_offset());
+  ASSERT_EQ(0xffffffffffffffc0ULL, static_cast<uint64_t>(value));
+
+  ASSERT_TRUE(dwarf_mem_->ReadSLEB128(&value));
+  ASSERT_EQ(4U, dwarf_mem_->cur_offset());
+  ASSERT_EQ(0x1a02U, value);
+
+  ASSERT_TRUE(dwarf_mem_->ReadSLEB128(&value));
+  ASSERT_EQ(6U, dwarf_mem_->cur_offset());
+  ASSERT_EQ(0xfffffffffffff209ULL, static_cast<uint64_t>(value));
+
+  ASSERT_TRUE(dwarf_mem_->ReadSLEB128(&value));
+  ASSERT_EQ(10U, dwarf_mem_->cur_offset());
+  ASSERT_EQ(0x5e3e1f9U, value);
+
+  ASSERT_TRUE(dwarf_mem_->ReadSLEB128(&value));
+  ASSERT_EQ(14U, dwarf_mem_->cur_offset());
+  ASSERT_EQ(0xfffffffffbfde1bfULL, static_cast<uint64_t>(value));
+}
+
+template <typename AddressType>
+void DwarfMemoryTest::GetEncodedSizeTest(uint8_t value, size_t expected) {
+  for (size_t i = 0; i < 16; i++) {
+    uint8_t encoding = (i << 4) | value;
+    ASSERT_EQ(expected, dwarf_mem_->GetEncodedSize<AddressType>(encoding))
+        << "encoding 0x" << std::hex << static_cast<uint32_t>(encoding) << " test value 0x"
+        << static_cast<size_t>(value);
+  }
+}
+
+TEST_F(DwarfMemoryTest, GetEncodedSize_absptr_uint32_t) {
+  GetEncodedSizeTest<uint32_t>(0, sizeof(uint32_t));
+}
+
+TEST_F(DwarfMemoryTest, GetEncodedSize_absptr_uint64_t) {
+  GetEncodedSizeTest<uint64_t>(0, sizeof(uint64_t));
+}
+
+TEST_F(DwarfMemoryTest, GetEncodedSize_data1) {
+  // udata1
+  GetEncodedSizeTest<uint32_t>(0x0d, 1);
+  GetEncodedSizeTest<uint64_t>(0x0d, 1);
+
+  // sdata1
+  GetEncodedSizeTest<uint32_t>(0x0e, 1);
+  GetEncodedSizeTest<uint64_t>(0x0e, 1);
+}
+
+TEST_F(DwarfMemoryTest, GetEncodedSize_data2) {
+  // udata2
+  GetEncodedSizeTest<uint32_t>(0x02, 2);
+  GetEncodedSizeTest<uint64_t>(0x02, 2);
+
+  // sdata2
+  GetEncodedSizeTest<uint32_t>(0x0a, 2);
+  GetEncodedSizeTest<uint64_t>(0x0a, 2);
+}
+
+TEST_F(DwarfMemoryTest, GetEncodedSize_data4) {
+  // udata4
+  GetEncodedSizeTest<uint32_t>(0x03, 4);
+  GetEncodedSizeTest<uint64_t>(0x03, 4);
+
+  // sdata4
+  GetEncodedSizeTest<uint32_t>(0x0b, 4);
+  GetEncodedSizeTest<uint64_t>(0x0b, 4);
+}
+
+TEST_F(DwarfMemoryTest, GetEncodedSize_data8) {
+  // udata8
+  GetEncodedSizeTest<uint32_t>(0x04, 8);
+  GetEncodedSizeTest<uint64_t>(0x04, 8);
+
+  // sdata8
+  GetEncodedSizeTest<uint32_t>(0x0c, 8);
+  GetEncodedSizeTest<uint64_t>(0x0c, 8);
+}
+
+TEST_F(DwarfMemoryTest, GetEncodedSize_unknown) {
+  GetEncodedSizeTest<uint32_t>(0x01, 0);
+  GetEncodedSizeTest<uint64_t>(0x01, 0);
+
+  GetEncodedSizeTest<uint32_t>(0x09, 0);
+  GetEncodedSizeTest<uint64_t>(0x09, 0);
+
+  GetEncodedSizeTest<uint32_t>(0x0f, 0);
+  GetEncodedSizeTest<uint64_t>(0x0f, 0);
+}
+
+template <typename AddressType>
+void DwarfMemoryTest::ReadEncodedValue_omit() {
+  uint64_t value = 123;
+  ASSERT_TRUE(dwarf_mem_->ReadEncodedValue<AddressType>(0xff, &value));
+  ASSERT_EQ(0U, value);
+}
+
+TEST_F(DwarfMemoryTest, ReadEncodedValue_omit_uint32_t) { ReadEncodedValue_omit<uint32_t>(); }
+
+TEST_F(DwarfMemoryTest, ReadEncodedValue_omit_uint64_t) { ReadEncodedValue_omit<uint64_t>(); }
+
+TEST_F(DwarfMemoryTest, ReadEncodedValue_absptr_uint32_t) {
+  uint64_t value = 100;
+  ASSERT_FALSE(dwarf_mem_->ReadEncodedValue<uint32_t>(0x00, &value));
+
+  memory_.SetData32(0, 0x12345678);
+
+  ASSERT_TRUE(dwarf_mem_->ReadEncodedValue<uint32_t>(0x00, &value));
+  ASSERT_EQ(4U, dwarf_mem_->cur_offset());
+  ASSERT_EQ(0x12345678U, value);
+}
+
+TEST_F(DwarfMemoryTest, ReadEncodedValue_absptr_uint64_t) {
+  uint64_t value = 100;
+  ASSERT_FALSE(dwarf_mem_->ReadEncodedValue<uint64_t>(0x00, &value));
+
+  memory_.SetData64(0, 0x12345678f1f2f3f4ULL);
+
+  ASSERT_TRUE(dwarf_mem_->ReadEncodedValue<uint64_t>(0x00, &value));
+  ASSERT_EQ(8U, dwarf_mem_->cur_offset());
+  ASSERT_EQ(0x12345678f1f2f3f4ULL, value);
+}
+
+TEST_F(DwarfMemoryTest, ReadEncodedValue_aligned_uint32_t) {
+  uint64_t value = 100;
+  dwarf_mem_->set_cur_offset(1);
+  ASSERT_FALSE(dwarf_mem_->ReadEncodedValue<uint32_t>(0x50, &value));
+
+  memory_.SetData32(4, 0x12345678);
+
+  ASSERT_TRUE(dwarf_mem_->ReadEncodedValue<uint32_t>(0x50, &value));
+  ASSERT_EQ(8U, dwarf_mem_->cur_offset());
+  ASSERT_EQ(0x12345678U, value);
+}
+
+TEST_F(DwarfMemoryTest, ReadEncodedValue_aligned_uint64_t) {
+  uint64_t value = 100;
+  dwarf_mem_->set_cur_offset(1);
+  ASSERT_FALSE(dwarf_mem_->ReadEncodedValue<uint64_t>(0x50, &value));
+
+  memory_.SetData64(8, 0x12345678f1f2f3f4ULL);
+
+  ASSERT_TRUE(dwarf_mem_->ReadEncodedValue<uint64_t>(0x50, &value));
+  ASSERT_EQ(16U, dwarf_mem_->cur_offset());
+  ASSERT_EQ(0x12345678f1f2f3f4ULL, value);
+}
+
+template <typename AddressType>
+void DwarfMemoryTest::ReadEncodedValue_leb128() {
+  memory_.SetMemory(0, std::vector<uint8_t>{0x80, 0x42});
+
+  uint64_t value = 100;
+  // uleb128
+  ASSERT_TRUE(dwarf_mem_->ReadEncodedValue<AddressType>(0x01, &value));
+  ASSERT_EQ(0x2100U, value);
+
+  dwarf_mem_->set_cur_offset(0);
+  // sleb128
+  ASSERT_TRUE(dwarf_mem_->ReadEncodedValue<AddressType>(0x09, &value));
+  ASSERT_EQ(0xffffffffffffe100ULL, value);
+}
+
+TEST_F(DwarfMemoryTest, ReadEncodedValue_leb128_uint32_t) { ReadEncodedValue_leb128<uint32_t>(); }
+
+TEST_F(DwarfMemoryTest, ReadEncodedValue_leb128_uint64_t) { ReadEncodedValue_leb128<uint64_t>(); }
+
+template <typename AddressType>
+void DwarfMemoryTest::ReadEncodedValue_data1() {
+  memory_.SetData8(0, 0xe0);
+
+  uint64_t value = 0;
+  ASSERT_TRUE(dwarf_mem_->ReadEncodedValue<AddressType>(0x0d, &value));
+  ASSERT_EQ(0xe0U, value);
+
+  dwarf_mem_->set_cur_offset(0);
+  ASSERT_TRUE(dwarf_mem_->ReadEncodedValue<AddressType>(0x0e, &value));
+  ASSERT_EQ(0xffffffffffffffe0ULL, value);
+}
+
+TEST_F(DwarfMemoryTest, ReadEncodedValue_data1_uint32_t) { ReadEncodedValue_data1<uint32_t>(); }
+
+TEST_F(DwarfMemoryTest, ReadEncodedValue_data1_uint64_t) { ReadEncodedValue_data1<uint64_t>(); }
+
+template <typename AddressType>
+void DwarfMemoryTest::ReadEncodedValue_data2() {
+  memory_.SetData16(0, 0xe000);
+
+  uint64_t value = 0;
+  ASSERT_TRUE(dwarf_mem_->ReadEncodedValue<AddressType>(0x02, &value));
+  ASSERT_EQ(0xe000U, value);
+
+  dwarf_mem_->set_cur_offset(0);
+  ASSERT_TRUE(dwarf_mem_->ReadEncodedValue<AddressType>(0x0a, &value));
+  ASSERT_EQ(0xffffffffffffe000ULL, value);
+}
+
+TEST_F(DwarfMemoryTest, ReadEncodedValue_data2_uint32_t) { ReadEncodedValue_data2<uint32_t>(); }
+
+TEST_F(DwarfMemoryTest, ReadEncodedValue_data2_uint64_t) { ReadEncodedValue_data2<uint64_t>(); }
+
+template <typename AddressType>
+void DwarfMemoryTest::ReadEncodedValue_data4() {
+  memory_.SetData32(0, 0xe0000000);
+
+  uint64_t value = 0;
+  ASSERT_TRUE(dwarf_mem_->ReadEncodedValue<AddressType>(0x03, &value));
+  ASSERT_EQ(0xe0000000U, value);
+
+  dwarf_mem_->set_cur_offset(0);
+  ASSERT_TRUE(dwarf_mem_->ReadEncodedValue<AddressType>(0x0b, &value));
+  ASSERT_EQ(0xffffffffe0000000ULL, value);
+}
+
+TEST_F(DwarfMemoryTest, ReadEncodedValue_data4_uint32_t) { ReadEncodedValue_data4<uint32_t>(); }
+
+TEST_F(DwarfMemoryTest, ReadEncodedValue_data4_uint64_t) { ReadEncodedValue_data4<uint64_t>(); }
+
+template <typename AddressType>
+void DwarfMemoryTest::ReadEncodedValue_data8() {
+  memory_.SetData64(0, 0xe000000000000000ULL);
+
+  uint64_t value = 0;
+  ASSERT_TRUE(dwarf_mem_->ReadEncodedValue<AddressType>(0x04, &value));
+  ASSERT_EQ(0xe000000000000000ULL, value);
+
+  dwarf_mem_->set_cur_offset(0);
+  ASSERT_TRUE(dwarf_mem_->ReadEncodedValue<AddressType>(0x0c, &value));
+  ASSERT_EQ(0xe000000000000000ULL, value);
+}
+
+TEST_F(DwarfMemoryTest, ReadEncodedValue_data8_uint32_t) { ReadEncodedValue_data8<uint32_t>(); }
+
+TEST_F(DwarfMemoryTest, ReadEncodedValue_data8_uint64_t) { ReadEncodedValue_data8<uint64_t>(); }
+
+template <typename AddressType>
+void DwarfMemoryTest::ReadEncodedValue_non_zero_adjust() {
+  memory_.SetData64(0, 0xe000000000000000ULL);
+
+  uint64_t value = 0;
+  dwarf_mem_->set_pc_offset(0x2000);
+  ASSERT_TRUE(dwarf_mem_->ReadEncodedValue<AddressType>(0x14, &value));
+  ASSERT_EQ(0xe000000000002000ULL, value);
+}
+
+TEST_F(DwarfMemoryTest, ReadEncodedValue_non_zero_adjust_uint32_t) {
+  ReadEncodedValue_non_zero_adjust<uint32_t>();
+}
+
+TEST_F(DwarfMemoryTest, ReadEncodedValue_non_zero_adjust_uint64_t) {
+  ReadEncodedValue_non_zero_adjust<uint64_t>();
+}
+
+template <typename AddressType>
+void DwarfMemoryTest::ReadEncodedValue_overflow() {
+  memory_.SetData64(0, 0);
+
+  uint64_t value = 0;
+  dwarf_mem_->set_cur_offset(UINT64_MAX);
+  ASSERT_FALSE(dwarf_mem_->ReadEncodedValue<AddressType>(0x50, &value));
+}
+
+TEST_F(DwarfMemoryTest, ReadEncodedValue_overflow_uint32_t) {
+  ReadEncodedValue_overflow<uint32_t>();
+}
+
+TEST_F(DwarfMemoryTest, ReadEncodedValue_overflow_uint64_t) {
+  ReadEncodedValue_overflow<uint64_t>();
+}
+
+TEST_F(DwarfMemoryTest, AdjustEncodedValue_absptr) {
+  uint64_t value = 0x1234;
+  ASSERT_TRUE(dwarf_mem_->AdjustEncodedValue(0x00, &value));
+  ASSERT_EQ(0x1234U, value);
+}
+
+TEST_F(DwarfMemoryTest, AdjustEncodedValue_pcrel) {
+  uint64_t value = 0x1234;
+  ASSERT_FALSE(dwarf_mem_->AdjustEncodedValue(0x10, &value));
+
+  dwarf_mem_->set_pc_offset(0x2000);
+  ASSERT_TRUE(dwarf_mem_->AdjustEncodedValue(0x10, &value));
+  ASSERT_EQ(0x3234U, value);
+
+  dwarf_mem_->set_pc_offset(static_cast<uint64_t>(-4));
+  value = 0x1234;
+  ASSERT_TRUE(dwarf_mem_->AdjustEncodedValue(0x10, &value));
+  ASSERT_EQ(0x1230U, value);
+}
+
+TEST_F(DwarfMemoryTest, AdjustEncodedValue_textrel) {
+  uint64_t value = 0x8234;
+  ASSERT_FALSE(dwarf_mem_->AdjustEncodedValue(0x20, &value));
+
+  dwarf_mem_->set_text_offset(0x1000);
+  ASSERT_TRUE(dwarf_mem_->AdjustEncodedValue(0x20, &value));
+  ASSERT_EQ(0x9234U, value);
+
+  dwarf_mem_->set_text_offset(static_cast<uint64_t>(-16));
+  value = 0x8234;
+  ASSERT_TRUE(dwarf_mem_->AdjustEncodedValue(0x20, &value));
+  ASSERT_EQ(0x8224U, value);
+}
+
+TEST_F(DwarfMemoryTest, AdjustEncodedValue_datarel) {
+  uint64_t value = 0xb234;
+  ASSERT_FALSE(dwarf_mem_->AdjustEncodedValue(0x30, &value));
+
+  dwarf_mem_->set_data_offset(0x1200);
+  ASSERT_TRUE(dwarf_mem_->AdjustEncodedValue(0x30, &value));
+  ASSERT_EQ(0xc434U, value);
+
+  dwarf_mem_->set_data_offset(static_cast<uint64_t>(-256));
+  value = 0xb234;
+  ASSERT_TRUE(dwarf_mem_->AdjustEncodedValue(0x30, &value));
+  ASSERT_EQ(0xb134U, value);
+}
+
+TEST_F(DwarfMemoryTest, AdjustEncodedValue_funcrel) {
+  uint64_t value = 0x15234;
+  ASSERT_FALSE(dwarf_mem_->AdjustEncodedValue(0x40, &value));
+
+  dwarf_mem_->set_func_offset(0x60000);
+  ASSERT_TRUE(dwarf_mem_->AdjustEncodedValue(0x40, &value));
+  ASSERT_EQ(0x75234U, value);
+
+  dwarf_mem_->set_func_offset(static_cast<uint64_t>(-4096));
+  value = 0x15234;
+  ASSERT_TRUE(dwarf_mem_->AdjustEncodedValue(0x40, &value));
+  ASSERT_EQ(0x14234U, value);
+}
diff --git a/libunwindstack/tests/DwarfOpLogTest.cpp b/libunwindstack/tests/DwarfOpLogTest.cpp
new file mode 100644
index 0000000..d18aad0
--- /dev/null
+++ b/libunwindstack/tests/DwarfOpLogTest.cpp
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdint.h>
+
+#include <ios>
+#include <vector>
+
+#include <gtest/gtest.h>
+
+#include "DwarfError.h"
+#include "DwarfMemory.h"
+#include "DwarfOp.h"
+#include "Log.h"
+#include "Regs.h"
+
+#include "MemoryFake.h"
+
+template <typename TypeParam>
+class DwarfOpLogTest : public ::testing::Test {
+ protected:
+  void SetUp() override {
+    op_memory_.Clear();
+    regular_memory_.Clear();
+    mem_.reset(new DwarfMemory(&op_memory_));
+    op_.reset(new DwarfOp<TypeParam>(mem_.get(), &regular_memory_));
+  }
+
+  MemoryFake op_memory_;
+  MemoryFake regular_memory_;
+
+  std::unique_ptr<DwarfMemory> mem_;
+  std::unique_ptr<DwarfOp<TypeParam>> op_;
+};
+TYPED_TEST_CASE_P(DwarfOpLogTest);
+
+TYPED_TEST_P(DwarfOpLogTest, multiple_ops) {
+  // Multi operation opcodes.
+  std::vector<uint8_t> opcode_buffer = {
+      0x0a, 0x20, 0x10, 0x08, 0x03, 0x12, 0x27,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  std::vector<std::string> lines;
+  this->op_->GetLogInfo(0, opcode_buffer.size(), &lines);
+  std::vector<std::string> expected{
+      "DW_OP_const2u 4128", "Raw Data: 0x0a 0x20 0x10", "DW_OP_const1u 3", "Raw Data: 0x08 0x03",
+      "DW_OP_dup",          "Raw Data: 0x12",           "DW_OP_xor",       "Raw Data: 0x27"};
+  ASSERT_EQ(expected, lines);
+}
+
+REGISTER_TYPED_TEST_CASE_P(DwarfOpLogTest, multiple_ops);
+
+typedef ::testing::Types<uint32_t, uint64_t> DwarfOpLogTestTypes;
+INSTANTIATE_TYPED_TEST_CASE_P(, DwarfOpLogTest, DwarfOpLogTestTypes);
diff --git a/libunwindstack/tests/DwarfOpTest.cpp b/libunwindstack/tests/DwarfOpTest.cpp
new file mode 100644
index 0000000..520c545
--- /dev/null
+++ b/libunwindstack/tests/DwarfOpTest.cpp
@@ -0,0 +1,1593 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdint.h>
+
+#include <ios>
+#include <vector>
+
+#include <gtest/gtest.h>
+
+#include "DwarfError.h"
+#include "DwarfMemory.h"
+#include "DwarfOp.h"
+#include "Log.h"
+#include "Regs.h"
+
+#include "MemoryFake.h"
+
+template <typename TypeParam>
+class RegsFake : public RegsTmpl<TypeParam> {
+ public:
+  RegsFake(uint16_t total_regs, uint16_t sp_reg)
+      : RegsTmpl<TypeParam>(total_regs, sp_reg, Regs::Location(Regs::LOCATION_UNKNOWN, 0)) {}
+  virtual ~RegsFake() = default;
+
+  uint64_t GetRelPc(Elf*, const MapInfo*) override { return 0; }
+  uint64_t GetAdjustedPc(uint64_t, Elf*) override { return 0; }
+  bool GetReturnAddressFromDefault(Memory*, uint64_t*) { return false; }
+};
+
+template <typename TypeParam>
+class DwarfOpTest : public ::testing::Test {
+ protected:
+  void SetUp() override {
+    op_memory_.Clear();
+    regular_memory_.Clear();
+    mem_.reset(new DwarfMemory(&op_memory_));
+    op_.reset(new DwarfOp<TypeParam>(mem_.get(), &regular_memory_));
+  }
+
+  MemoryFake op_memory_;
+  MemoryFake regular_memory_;
+
+  std::unique_ptr<DwarfMemory> mem_;
+  std::unique_ptr<DwarfOp<TypeParam>> op_;
+};
+TYPED_TEST_CASE_P(DwarfOpTest);
+
+TYPED_TEST_P(DwarfOpTest, decode) {
+  // Memory error.
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_MEMORY_INVALID, this->op_->last_error());
+
+  // No error.
+  this->op_memory_.SetMemory(0, std::vector<uint8_t>{0x96});
+  this->mem_->set_cur_offset(0);
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_NONE, this->op_->last_error());
+  ASSERT_EQ(0x96U, this->op_->cur_op());
+  ASSERT_EQ(1U, this->mem_->cur_offset());
+}
+
+TYPED_TEST_P(DwarfOpTest, eval) {
+  // Memory error.
+  ASSERT_FALSE(this->op_->Eval(0, 2, DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_MEMORY_INVALID, this->op_->last_error());
+
+  // Register set.
+  // Do this first, to verify that subsequent calls reset the value.
+  this->op_memory_.SetMemory(0, std::vector<uint8_t>{0x50});
+  ASSERT_TRUE(this->op_->Eval(0, 1, DWARF_VERSION_MAX));
+  ASSERT_TRUE(this->op_->is_register());
+  ASSERT_EQ(1U, this->mem_->cur_offset());
+  ASSERT_EQ(1U, this->op_->StackSize());
+
+  // Multi operation opcodes.
+  std::vector<uint8_t> opcode_buffer = {
+      0x08, 0x04, 0x08, 0x03, 0x08, 0x02, 0x08, 0x01,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  ASSERT_TRUE(this->op_->Eval(0, 8, DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_NONE, this->op_->last_error());
+  ASSERT_FALSE(this->op_->is_register());
+  ASSERT_EQ(8U, this->mem_->cur_offset());
+  ASSERT_EQ(4U, this->op_->StackSize());
+  ASSERT_EQ(1U, this->op_->StackAt(0));
+  ASSERT_EQ(2U, this->op_->StackAt(1));
+  ASSERT_EQ(3U, this->op_->StackAt(2));
+  ASSERT_EQ(4U, this->op_->StackAt(3));
+
+  // Infinite loop.
+  this->op_memory_.SetMemory(0, std::vector<uint8_t>{0x2f, 0xfd, 0xff});
+  ASSERT_FALSE(this->op_->Eval(0, 4, DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_TOO_MANY_ITERATIONS, this->op_->last_error());
+  ASSERT_FALSE(this->op_->is_register());
+  ASSERT_EQ(0U, this->op_->StackSize());
+}
+
+TYPED_TEST_P(DwarfOpTest, illegal_opcode) {
+  // Fill the buffer with all of the illegal opcodes.
+  std::vector<uint8_t> opcode_buffer = {0x00, 0x01, 0x02, 0x04, 0x05, 0x07};
+  for (size_t opcode = 0xa0; opcode < 256; opcode++) {
+    opcode_buffer.push_back(opcode);
+  }
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  for (size_t i = 0; i < opcode_buffer.size(); i++) {
+    ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+    ASSERT_EQ(DWARF_ERROR_ILLEGAL_VALUE, this->op_->last_error());
+    ASSERT_EQ(opcode_buffer[i], this->op_->cur_op());
+  }
+}
+
+TYPED_TEST_P(DwarfOpTest, illegal_in_version3) {
+  std::vector<uint8_t> opcode_buffer = {0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d};
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  for (size_t i = 0; i < opcode_buffer.size(); i++) {
+    ASSERT_FALSE(this->op_->Decode(2));
+    ASSERT_EQ(DWARF_ERROR_ILLEGAL_VALUE, this->op_->last_error());
+    ASSERT_EQ(opcode_buffer[i], this->op_->cur_op());
+  }
+}
+
+TYPED_TEST_P(DwarfOpTest, illegal_in_version4) {
+  std::vector<uint8_t> opcode_buffer = {0x9e, 0x9f};
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  for (size_t i = 0; i < opcode_buffer.size(); i++) {
+    ASSERT_FALSE(this->op_->Decode(3));
+    ASSERT_EQ(DWARF_ERROR_ILLEGAL_VALUE, this->op_->last_error());
+    ASSERT_EQ(opcode_buffer[i], this->op_->cur_op());
+  }
+}
+
+TYPED_TEST_P(DwarfOpTest, not_implemented) {
+  std::vector<uint8_t> opcode_buffer = {
+      // Push values so that any not implemented ops will return the right error.
+      0x08, 0x03, 0x08, 0x02, 0x08, 0x01,
+      // xderef
+      0x18,
+      // fbreg
+      0x91, 0x01,
+      // piece
+      0x93, 0x01,
+      // xderef_size
+      0x95, 0x01,
+      // push_object_address
+      0x97,
+      // call2
+      0x98, 0x01, 0x02,
+      // call4
+      0x99, 0x01, 0x02, 0x03, 0x04,
+      // call_ref
+      0x9a,
+      // form_tls_address
+      0x9b,
+      // call_frame_cfa
+      0x9c,
+      // bit_piece
+      0x9d, 0x01, 0x01,
+      // implicit_value
+      0x9e, 0x01,
+      // stack_value
+      0x9f,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  // Push the stack values.
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+
+  while (this->mem_->cur_offset() < opcode_buffer.size()) {
+    ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+    ASSERT_EQ(DWARF_ERROR_NOT_IMPLEMENTED, this->op_->last_error());
+  }
+}
+
+TYPED_TEST_P(DwarfOpTest, op_addr) {
+  std::vector<uint8_t> opcode_buffer = {0x03, 0x12, 0x23, 0x34, 0x45};
+  if (sizeof(TypeParam) == 8) {
+    opcode_buffer.push_back(0x56);
+    opcode_buffer.push_back(0x67);
+    opcode_buffer.push_back(0x78);
+    opcode_buffer.push_back(0x89);
+  }
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x03, this->op_->cur_op());
+  ASSERT_EQ(1U, this->op_->StackSize());
+  if (sizeof(TypeParam) == 4) {
+    ASSERT_EQ(0x45342312U, this->op_->StackAt(0));
+  } else {
+    ASSERT_EQ(0x8978675645342312UL, this->op_->StackAt(0));
+  }
+}
+
+TYPED_TEST_P(DwarfOpTest, op_deref) {
+  std::vector<uint8_t> opcode_buffer = {
+      // Try a dereference with nothing on the stack.
+      0x06,
+      // Add an address, then dereference.
+      0x0a, 0x10, 0x20, 0x06,
+      // Now do another dereference that should fail in memory.
+      0x06,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+  TypeParam value = 0x12345678;
+  this->regular_memory_.SetMemory(0x2010, &value, sizeof(value));
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x06, this->op_->cur_op());
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_EQ(value, this->op_->StackAt(0));
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_MEMORY_INVALID, this->op_->last_error());
+}
+
+TYPED_TEST_P(DwarfOpTest, op_deref_size) {
+  this->op_memory_.SetMemory(0, std::vector<uint8_t>{0x94});
+  TypeParam value = 0x12345678;
+  this->regular_memory_.SetMemory(0x2010, &value, sizeof(value));
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  // Read all byte sizes up to the sizeof the type.
+  for (size_t i = 1; i < sizeof(TypeParam); i++) {
+    this->op_memory_.SetMemory(
+        0, std::vector<uint8_t>{0x0a, 0x10, 0x20, 0x94, static_cast<uint8_t>(i)});
+    ASSERT_TRUE(this->op_->Eval(0, 5, DWARF_VERSION_MAX)) << "Failed at size " << i;
+    ASSERT_EQ(1U, this->op_->StackSize()) << "Failed at size " << i;
+    ASSERT_EQ(0x94, this->op_->cur_op()) << "Failed at size " << i;
+    TypeParam expected_value = 0;
+    memcpy(&expected_value, &value, i);
+    ASSERT_EQ(expected_value, this->op_->StackAt(0)) << "Failed at size " << i;
+  }
+
+  // Zero byte read.
+  this->op_memory_.SetMemory(0, std::vector<uint8_t>{0x0a, 0x10, 0x20, 0x94, 0x00});
+  ASSERT_FALSE(this->op_->Eval(0, 5, DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_ILLEGAL_VALUE, this->op_->last_error());
+
+  // Read too many bytes.
+  this->op_memory_.SetMemory(0, std::vector<uint8_t>{0x0a, 0x10, 0x20, 0x94, sizeof(TypeParam) + 1});
+  ASSERT_FALSE(this->op_->Eval(0, 5, DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_ILLEGAL_VALUE, this->op_->last_error());
+
+  // Force bad memory read.
+  this->op_memory_.SetMemory(0, std::vector<uint8_t>{0x0a, 0x10, 0x40, 0x94, 0x01});
+  ASSERT_FALSE(this->op_->Eval(0, 5, DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_MEMORY_INVALID, this->op_->last_error());
+}
+
+TYPED_TEST_P(DwarfOpTest, const_unsigned) {
+  std::vector<uint8_t> opcode_buffer = {
+      // const1u
+      0x08, 0x12, 0x08, 0xff,
+      // const2u
+      0x0a, 0x45, 0x12, 0x0a, 0x00, 0xff,
+      // const4u
+      0x0c, 0x12, 0x23, 0x34, 0x45, 0x0c, 0x03, 0x02, 0x01, 0xff,
+      // const8u
+      0x0e, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x0e, 0x87, 0x98, 0xa9, 0xba, 0xcb,
+      0xdc, 0xed, 0xfe,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  // const1u
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x08, this->op_->cur_op());
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_EQ(0x12U, this->op_->StackAt(0));
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x08, this->op_->cur_op());
+  ASSERT_EQ(2U, this->op_->StackSize());
+  ASSERT_EQ(0xffU, this->op_->StackAt(0));
+
+  // const2u
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x0a, this->op_->cur_op());
+  ASSERT_EQ(3U, this->op_->StackSize());
+  ASSERT_EQ(0x1245U, this->op_->StackAt(0));
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x0a, this->op_->cur_op());
+  ASSERT_EQ(4U, this->op_->StackSize());
+  ASSERT_EQ(0xff00U, this->op_->StackAt(0));
+
+  // const4u
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x0c, this->op_->cur_op());
+  ASSERT_EQ(5U, this->op_->StackSize());
+  ASSERT_EQ(0x45342312U, this->op_->StackAt(0));
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x0c, this->op_->cur_op());
+  ASSERT_EQ(6U, this->op_->StackSize());
+  ASSERT_EQ(0xff010203U, this->op_->StackAt(0));
+
+  // const8u
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x0e, this->op_->cur_op());
+  ASSERT_EQ(7U, this->op_->StackSize());
+  if (sizeof(TypeParam) == 4) {
+    ASSERT_EQ(0x05060708U, this->op_->StackAt(0));
+  } else {
+    ASSERT_EQ(0x0102030405060708ULL, this->op_->StackAt(0));
+  }
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x0e, this->op_->cur_op());
+  ASSERT_EQ(8U, this->op_->StackSize());
+  if (sizeof(TypeParam) == 4) {
+    ASSERT_EQ(0xbaa99887UL, this->op_->StackAt(0));
+  } else {
+    ASSERT_EQ(0xfeeddccbbaa99887ULL, this->op_->StackAt(0));
+  }
+}
+
+TYPED_TEST_P(DwarfOpTest, const_signed) {
+  std::vector<uint8_t> opcode_buffer = {
+      // const1s
+      0x09, 0x12, 0x09, 0xff,
+      // const2s
+      0x0b, 0x21, 0x32, 0x0b, 0x08, 0xff,
+      // const4s
+      0x0d, 0x45, 0x34, 0x23, 0x12, 0x0d, 0x01, 0x02, 0x03, 0xff,
+      // const8s
+      0x0f, 0x89, 0x78, 0x67, 0x56, 0x45, 0x34, 0x23, 0x12, 0x0f, 0x04, 0x03, 0x02, 0x01, 0xef,
+      0xef, 0xef, 0xff,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  // const1s
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x09, this->op_->cur_op());
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_EQ(0x12U, this->op_->StackAt(0));
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x09, this->op_->cur_op());
+  ASSERT_EQ(2U, this->op_->StackSize());
+  ASSERT_EQ(static_cast<TypeParam>(-1), this->op_->StackAt(0));
+
+  // const2s
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x0b, this->op_->cur_op());
+  ASSERT_EQ(3U, this->op_->StackSize());
+  ASSERT_EQ(0x3221U, this->op_->StackAt(0));
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x0b, this->op_->cur_op());
+  ASSERT_EQ(4U, this->op_->StackSize());
+  ASSERT_EQ(static_cast<TypeParam>(-248), this->op_->StackAt(0));
+
+  // const4s
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x0d, this->op_->cur_op());
+  ASSERT_EQ(5U, this->op_->StackSize());
+  ASSERT_EQ(0x12233445U, this->op_->StackAt(0));
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x0d, this->op_->cur_op());
+  ASSERT_EQ(6U, this->op_->StackSize());
+  ASSERT_EQ(static_cast<TypeParam>(-16580095), this->op_->StackAt(0));
+
+  // const8s
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x0f, this->op_->cur_op());
+  ASSERT_EQ(7U, this->op_->StackSize());
+  if (sizeof(TypeParam) == 4) {
+    ASSERT_EQ(0x56677889ULL, this->op_->StackAt(0));
+  } else {
+    ASSERT_EQ(0x1223344556677889ULL, this->op_->StackAt(0));
+  }
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x0f, this->op_->cur_op());
+  ASSERT_EQ(8U, this->op_->StackSize());
+  if (sizeof(TypeParam) == 4) {
+    ASSERT_EQ(0x01020304U, this->op_->StackAt(0));
+  } else {
+    ASSERT_EQ(static_cast<TypeParam>(-4521264810949884LL), this->op_->StackAt(0));
+  }
+}
+
+TYPED_TEST_P(DwarfOpTest, const_uleb) {
+  std::vector<uint8_t> opcode_buffer = {
+      // Single byte ULEB128
+      0x10, 0x22, 0x10, 0x7f,
+      // Multi byte ULEB128
+      0x10, 0xa2, 0x22, 0x10, 0xa2, 0x74, 0x10, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88,
+      0x09, 0x10, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x79,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  // Single byte ULEB128
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x10, this->op_->cur_op());
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_EQ(0x22U, this->op_->StackAt(0));
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x10, this->op_->cur_op());
+  ASSERT_EQ(2U, this->op_->StackSize());
+  ASSERT_EQ(0x7fU, this->op_->StackAt(0));
+
+  // Multi byte ULEB128
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x10, this->op_->cur_op());
+  ASSERT_EQ(3U, this->op_->StackSize());
+  ASSERT_EQ(0x1122U, this->op_->StackAt(0));
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x10, this->op_->cur_op());
+  ASSERT_EQ(4U, this->op_->StackSize());
+  ASSERT_EQ(0x3a22U, this->op_->StackAt(0));
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x10, this->op_->cur_op());
+  ASSERT_EQ(5U, this->op_->StackSize());
+  if (sizeof(TypeParam) == 4) {
+    ASSERT_EQ(0x5080c101U, this->op_->StackAt(0));
+  } else {
+    ASSERT_EQ(0x9101c305080c101ULL, this->op_->StackAt(0));
+  }
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x10, this->op_->cur_op());
+  ASSERT_EQ(6U, this->op_->StackSize());
+  if (sizeof(TypeParam) == 4) {
+    ASSERT_EQ(0x5080c101U, this->op_->StackAt(0));
+  } else {
+    ASSERT_EQ(0x79101c305080c101ULL, this->op_->StackAt(0));
+  }
+}
+
+TYPED_TEST_P(DwarfOpTest, const_sleb) {
+  std::vector<uint8_t> opcode_buffer = {
+      // Single byte SLEB128
+      0x11, 0x22, 0x11, 0x7f,
+      // Multi byte SLEB128
+      0x11, 0xa2, 0x22, 0x11, 0xa2, 0x74, 0x11, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88,
+      0x09, 0x11,
+  };
+  if (sizeof(TypeParam) == 4) {
+    opcode_buffer.push_back(0xb8);
+    opcode_buffer.push_back(0xd3);
+    opcode_buffer.push_back(0x63);
+  } else {
+    opcode_buffer.push_back(0x81);
+    opcode_buffer.push_back(0x82);
+    opcode_buffer.push_back(0x83);
+    opcode_buffer.push_back(0x84);
+    opcode_buffer.push_back(0x85);
+    opcode_buffer.push_back(0x86);
+    opcode_buffer.push_back(0x87);
+    opcode_buffer.push_back(0x88);
+    opcode_buffer.push_back(0x79);
+  }
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  // Single byte SLEB128
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x11, this->op_->cur_op());
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_EQ(0x22U, this->op_->StackAt(0));
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x11, this->op_->cur_op());
+  ASSERT_EQ(2U, this->op_->StackSize());
+  ASSERT_EQ(static_cast<TypeParam>(-1), this->op_->StackAt(0));
+
+  // Multi byte SLEB128
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x11, this->op_->cur_op());
+  ASSERT_EQ(3U, this->op_->StackSize());
+  ASSERT_EQ(0x1122U, this->op_->StackAt(0));
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x11, this->op_->cur_op());
+  ASSERT_EQ(4U, this->op_->StackSize());
+  ASSERT_EQ(static_cast<TypeParam>(-1502), this->op_->StackAt(0));
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x11, this->op_->cur_op());
+  ASSERT_EQ(5U, this->op_->StackSize());
+  if (sizeof(TypeParam) == 4) {
+    ASSERT_EQ(0x5080c101U, this->op_->StackAt(0));
+  } else {
+    ASSERT_EQ(0x9101c305080c101ULL, this->op_->StackAt(0));
+  }
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x11, this->op_->cur_op());
+  ASSERT_EQ(6U, this->op_->StackSize());
+  if (sizeof(TypeParam) == 4) {
+    ASSERT_EQ(static_cast<TypeParam>(-464456), this->op_->StackAt(0));
+  } else {
+    ASSERT_EQ(static_cast<TypeParam>(-499868564803501823LL), this->op_->StackAt(0));
+  }
+}
+
+TYPED_TEST_P(DwarfOpTest, op_dup) {
+  std::vector<uint8_t> opcode_buffer = {
+      // Should fail since nothing is on the stack.
+      0x12,
+      // Push on a value and dup.
+      0x08, 0x15, 0x12,
+      // Do it again.
+      0x08, 0x23, 0x12,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x12, this->op_->cur_op());
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x12, this->op_->cur_op());
+  ASSERT_EQ(2U, this->op_->StackSize());
+  ASSERT_EQ(0x15U, this->op_->StackAt(0));
+  ASSERT_EQ(0x15U, this->op_->StackAt(1));
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(3U, this->op_->StackSize());
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x12, this->op_->cur_op());
+  ASSERT_EQ(4U, this->op_->StackSize());
+  ASSERT_EQ(0x23U, this->op_->StackAt(0));
+  ASSERT_EQ(0x23U, this->op_->StackAt(1));
+  ASSERT_EQ(0x15U, this->op_->StackAt(2));
+  ASSERT_EQ(0x15U, this->op_->StackAt(3));
+}
+
+TYPED_TEST_P(DwarfOpTest, op_drop) {
+  std::vector<uint8_t> opcode_buffer = {
+      // Push a couple of values.
+      0x08, 0x10, 0x08, 0x20,
+      // Drop the values.
+      0x13, 0x13,
+      // Attempt to drop empty stack.
+      0x13,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(2U, this->op_->StackSize());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x13, this->op_->cur_op());
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_EQ(0x10U, this->op_->StackAt(0));
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x13, this->op_->cur_op());
+  ASSERT_EQ(0U, this->op_->StackSize());
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x13, this->op_->cur_op());
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+}
+
+TYPED_TEST_P(DwarfOpTest, op_over) {
+  std::vector<uint8_t> opcode_buffer = {
+      // Push a couple of values.
+      0x08, 0x1a, 0x08, 0xed,
+      // Copy a value.
+      0x14,
+      // Remove all but one element.
+      0x13, 0x13,
+      // Provoke a failure with this opcode.
+      0x14,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(2U, this->op_->StackSize());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x14, this->op_->cur_op());
+  ASSERT_EQ(3U, this->op_->StackSize());
+  ASSERT_EQ(0x1aU, this->op_->StackAt(0));
+  ASSERT_EQ(0xedU, this->op_->StackAt(1));
+  ASSERT_EQ(0x1aU, this->op_->StackAt(2));
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(2U, this->op_->StackSize());
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x14, this->op_->cur_op());
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+}
+
+TYPED_TEST_P(DwarfOpTest, op_pick) {
+  std::vector<uint8_t> opcode_buffer = {
+      // Push a few values.
+      0x08, 0x1a, 0x08, 0xed, 0x08, 0x34,
+      // Copy the value at offset 2.
+      0x15, 0x01,
+      // Copy the last value in the stack.
+      0x15, 0x03,
+      // Choose an invalid index.
+      0x15, 0x10,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(2U, this->op_->StackSize());
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(3U, this->op_->StackSize());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x15, this->op_->cur_op());
+  ASSERT_EQ(4U, this->op_->StackSize());
+  ASSERT_EQ(0xedU, this->op_->StackAt(0));
+  ASSERT_EQ(0x34U, this->op_->StackAt(1));
+  ASSERT_EQ(0xedU, this->op_->StackAt(2));
+  ASSERT_EQ(0x1aU, this->op_->StackAt(3));
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x15, this->op_->cur_op());
+  ASSERT_EQ(5U, this->op_->StackSize());
+  ASSERT_EQ(0x1aU, this->op_->StackAt(0));
+  ASSERT_EQ(0xedU, this->op_->StackAt(1));
+  ASSERT_EQ(0x34U, this->op_->StackAt(2));
+  ASSERT_EQ(0xedU, this->op_->StackAt(3));
+  ASSERT_EQ(0x1aU, this->op_->StackAt(4));
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x15, this->op_->cur_op());
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+}
+
+TYPED_TEST_P(DwarfOpTest, op_swap) {
+  std::vector<uint8_t> opcode_buffer = {
+      // Push a couple of values.
+      0x08, 0x26, 0x08, 0xab,
+      // Swap values.
+      0x16,
+      // Pop a value to cause a failure.
+      0x13, 0x16,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(2U, this->op_->StackSize());
+  ASSERT_EQ(0xabU, this->op_->StackAt(0));
+  ASSERT_EQ(0x26U, this->op_->StackAt(1));
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x16, this->op_->cur_op());
+  ASSERT_EQ(2U, this->op_->StackSize());
+  ASSERT_EQ(0x26U, this->op_->StackAt(0));
+  ASSERT_EQ(0xabU, this->op_->StackAt(1));
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x16, this->op_->cur_op());
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+}
+
+TYPED_TEST_P(DwarfOpTest, op_rot) {
+  std::vector<uint8_t> opcode_buffer = {
+      // Rotate that should cause a failure.
+      0x17, 0x08, 0x10,
+      // Only 1 value on stack, should fail.
+      0x17, 0x08, 0x20,
+      // Only 2 values on stack, should fail.
+      0x17, 0x08, 0x30,
+      // Should rotate properly.
+      0x17,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(2U, this->op_->StackSize());
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(3U, this->op_->StackSize());
+  ASSERT_EQ(0x30U, this->op_->StackAt(0));
+  ASSERT_EQ(0x20U, this->op_->StackAt(1));
+  ASSERT_EQ(0x10U, this->op_->StackAt(2));
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x17, this->op_->cur_op());
+  ASSERT_EQ(3U, this->op_->StackSize());
+  ASSERT_EQ(0x20U, this->op_->StackAt(0));
+  ASSERT_EQ(0x10U, this->op_->StackAt(1));
+  ASSERT_EQ(0x30U, this->op_->StackAt(2));
+}
+
+TYPED_TEST_P(DwarfOpTest, op_abs) {
+  std::vector<uint8_t> opcode_buffer = {
+      // Abs that should fail.
+      0x19,
+      // A value that is already positive.
+      0x08, 0x10, 0x19,
+      // A value that is negative.
+      0x11, 0x7f, 0x19,
+      // A value that is large and negative.
+      0x11, 0x81, 0x80, 0x80, 0x80,
+  };
+  if (sizeof(TypeParam) == 4) {
+    opcode_buffer.push_back(0x08);
+  } else {
+    opcode_buffer.push_back(0x80);
+    opcode_buffer.push_back(0x80);
+    opcode_buffer.push_back(0x01);
+  }
+  opcode_buffer.push_back(0x19);
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_EQ(0x10U, this->op_->StackAt(0));
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x19, this->op_->cur_op());
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_EQ(0x10U, this->op_->StackAt(0));
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(2U, this->op_->StackSize());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x19, this->op_->cur_op());
+  ASSERT_EQ(2U, this->op_->StackSize());
+  ASSERT_EQ(0x1U, this->op_->StackAt(0));
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(3U, this->op_->StackSize());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x19, this->op_->cur_op());
+  ASSERT_EQ(3U, this->op_->StackSize());
+  if (sizeof(TypeParam) == 4) {
+    ASSERT_EQ(2147483647U, this->op_->StackAt(0));
+  } else {
+    ASSERT_EQ(4398046511105UL, this->op_->StackAt(0));
+  }
+}
+
+TYPED_TEST_P(DwarfOpTest, op_and) {
+  std::vector<uint8_t> opcode_buffer = {
+      // No stack, and op will fail.
+      0x1b,
+      // Push a single value.
+      0x08, 0x20,
+      // One element stack, and op will fail.
+      0x1b,
+      // Push another value.
+      0x08, 0x02, 0x1b,
+      // Push on two negative values.
+      0x11, 0x7c, 0x11, 0x7f, 0x1b,
+      // Push one negative, one positive.
+      0x11, 0x10, 0x11, 0x7c, 0x1b,
+      // Divide by zero.
+      0x11, 0x10, 0x11, 0x00, 0x1b,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  // Two positive values.
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(2U, this->op_->StackSize());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x1b, this->op_->cur_op());
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_EQ(0x10U, this->op_->StackAt(0));
+
+  // Two negative values.
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(2U, this->op_->StackSize());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(3U, this->op_->StackSize());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x1b, this->op_->cur_op());
+  ASSERT_EQ(2U, this->op_->StackSize());
+  ASSERT_EQ(0x04U, this->op_->StackAt(0));
+
+  // One negative value, one positive value.
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(3U, this->op_->StackSize());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(4U, this->op_->StackSize());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x1b, this->op_->cur_op());
+  ASSERT_EQ(3U, this->op_->StackSize());
+  ASSERT_EQ(static_cast<TypeParam>(-4), this->op_->StackAt(0));
+
+  // Divide by zero.
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(4U, this->op_->StackSize());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(5U, this->op_->StackSize());
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_ILLEGAL_VALUE, this->op_->last_error());
+}
+
+TYPED_TEST_P(DwarfOpTest, op_div) {
+  std::vector<uint8_t> opcode_buffer = {
+      // No stack, and op will fail.
+      0x1a,
+      // Push a single value.
+      0x08, 0x48,
+      // One element stack, and op will fail.
+      0x1a,
+      // Push another value.
+      0x08, 0xf0, 0x1a,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(2U, this->op_->StackSize());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x1a, this->op_->cur_op());
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_EQ(0x40U, this->op_->StackAt(0));
+}
+
+TYPED_TEST_P(DwarfOpTest, op_minus) {
+  std::vector<uint8_t> opcode_buffer = {
+      // No stack, and op will fail.
+      0x1c,
+      // Push a single value.
+      0x08, 0x48,
+      // One element stack, and op will fail.
+      0x1c,
+      // Push another value.
+      0x08, 0x04, 0x1c,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(2U, this->op_->StackSize());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x1c, this->op_->cur_op());
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_EQ(0x44U, this->op_->StackAt(0));
+}
+
+TYPED_TEST_P(DwarfOpTest, op_mod) {
+  std::vector<uint8_t> opcode_buffer = {
+      // No stack, and op will fail.
+      0x1d,
+      // Push a single value.
+      0x08, 0x47,
+      // One element stack, and op will fail.
+      0x1d,
+      // Push another value.
+      0x08, 0x04, 0x1d,
+      // Try a mod of zero.
+      0x08, 0x01, 0x08, 0x00, 0x1d,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(2U, this->op_->StackSize());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x1d, this->op_->cur_op());
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_EQ(0x03U, this->op_->StackAt(0));
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(2U, this->op_->StackSize());
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(3U, this->op_->StackSize());
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_ILLEGAL_VALUE, this->op_->last_error());
+}
+
+TYPED_TEST_P(DwarfOpTest, op_mul) {
+  std::vector<uint8_t> opcode_buffer = {
+      // No stack, and op will fail.
+      0x1e,
+      // Push a single value.
+      0x08, 0x48,
+      // One element stack, and op will fail.
+      0x1e,
+      // Push another value.
+      0x08, 0x04, 0x1e,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(2U, this->op_->StackSize());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x1e, this->op_->cur_op());
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_EQ(0x120U, this->op_->StackAt(0));
+}
+
+TYPED_TEST_P(DwarfOpTest, op_neg) {
+  std::vector<uint8_t> opcode_buffer = {
+      // No stack, and op will fail.
+      0x1f,
+      // Push a single value.
+      0x08, 0x48, 0x1f,
+      // Push a negative value.
+      0x11, 0x7f, 0x1f,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x1f, this->op_->cur_op());
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_EQ(static_cast<TypeParam>(-72), this->op_->StackAt(0));
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(2U, this->op_->StackSize());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x1f, this->op_->cur_op());
+  ASSERT_EQ(2U, this->op_->StackSize());
+  ASSERT_EQ(0x01U, this->op_->StackAt(0));
+}
+
+TYPED_TEST_P(DwarfOpTest, op_not) {
+  std::vector<uint8_t> opcode_buffer = {
+      // No stack, and op will fail.
+      0x20,
+      // Push a single value.
+      0x08, 0x4, 0x20,
+      // Push a negative value.
+      0x11, 0x7c, 0x20,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x20, this->op_->cur_op());
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_EQ(static_cast<TypeParam>(-5), this->op_->StackAt(0));
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(2U, this->op_->StackSize());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x20, this->op_->cur_op());
+  ASSERT_EQ(2U, this->op_->StackSize());
+  ASSERT_EQ(0x03U, this->op_->StackAt(0));
+}
+
+TYPED_TEST_P(DwarfOpTest, op_or) {
+  std::vector<uint8_t> opcode_buffer = {
+      // No stack, and op will fail.
+      0x21,
+      // Push a single value.
+      0x08, 0x48,
+      // One element stack, and op will fail.
+      0x21,
+      // Push another value.
+      0x08, 0xf4, 0x21,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(2U, this->op_->StackSize());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x21, this->op_->cur_op());
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_EQ(0xfcU, this->op_->StackAt(0));
+}
+
+TYPED_TEST_P(DwarfOpTest, op_plus) {
+  std::vector<uint8_t> opcode_buffer = {
+      // No stack, and op will fail.
+      0x22,
+      // Push a single value.
+      0x08, 0xff,
+      // One element stack, and op will fail.
+      0x22,
+      // Push another value.
+      0x08, 0xf2, 0x22,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(2U, this->op_->StackSize());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x22, this->op_->cur_op());
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_EQ(0x1f1U, this->op_->StackAt(0));
+}
+
+TYPED_TEST_P(DwarfOpTest, op_plus_uconst) {
+  std::vector<uint8_t> opcode_buffer = {
+      // No stack, and op will fail.
+      0x23,
+      // Push a single value.
+      0x08, 0x50, 0x23, 0x80, 0x51,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x23, this->op_->cur_op());
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_EQ(0x28d0U, this->op_->StackAt(0));
+}
+
+TYPED_TEST_P(DwarfOpTest, op_shl) {
+  std::vector<uint8_t> opcode_buffer = {
+      // No stack, and op will fail.
+      0x24,
+      // Push a single value.
+      0x08, 0x67,
+      // One element stack, and op will fail.
+      0x24,
+      // Push another value.
+      0x08, 0x03, 0x24,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(2U, this->op_->StackSize());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x24, this->op_->cur_op());
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_EQ(0x338U, this->op_->StackAt(0));
+}
+
+TYPED_TEST_P(DwarfOpTest, op_shr) {
+  std::vector<uint8_t> opcode_buffer = {
+      // No stack, and op will fail.
+      0x25,
+      // Push a single value.
+      0x11, 0x70,
+      // One element stack, and op will fail.
+      0x25,
+      // Push another value.
+      0x08, 0x03, 0x25,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(2U, this->op_->StackSize());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x25, this->op_->cur_op());
+  ASSERT_EQ(1U, this->op_->StackSize());
+  if (sizeof(TypeParam) == 4) {
+    ASSERT_EQ(0x1ffffffeU, this->op_->StackAt(0));
+  } else {
+    ASSERT_EQ(0x1ffffffffffffffeULL, this->op_->StackAt(0));
+  }
+}
+
+TYPED_TEST_P(DwarfOpTest, op_shra) {
+  std::vector<uint8_t> opcode_buffer = {
+      // No stack, and op will fail.
+      0x26,
+      // Push a single value.
+      0x11, 0x70,
+      // One element stack, and op will fail.
+      0x26,
+      // Push another value.
+      0x08, 0x03, 0x26,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(2U, this->op_->StackSize());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x26, this->op_->cur_op());
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_EQ(static_cast<TypeParam>(-2), this->op_->StackAt(0));
+}
+
+TYPED_TEST_P(DwarfOpTest, op_xor) {
+  std::vector<uint8_t> opcode_buffer = {
+      // No stack, and op will fail.
+      0x27,
+      // Push a single value.
+      0x08, 0x11,
+      // One element stack, and op will fail.
+      0x27,
+      // Push another value.
+      0x08, 0x41, 0x27,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(2U, this->op_->StackSize());
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x27, this->op_->cur_op());
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_EQ(0x50U, this->op_->StackAt(0));
+}
+
+TYPED_TEST_P(DwarfOpTest, op_bra) {
+  std::vector<uint8_t> opcode_buffer = {
+      // No stack, and op will fail.
+      0x28,
+      // Push on a non-zero value with a positive branch.
+      0x08, 0x11, 0x28, 0x02, 0x01,
+      // Push on a zero value with a positive branch.
+      0x08, 0x00, 0x28, 0x05, 0x00,
+      // Push on a non-zero value with a negative branch.
+      0x08, 0x11, 0x28, 0xfc, 0xff,
+      // Push on a zero value with a negative branch.
+      0x08, 0x00, 0x28, 0xf0, 0xff,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  ASSERT_FALSE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+  // Push on a non-zero value with a positive branch.
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+
+  uint64_t offset = this->mem_->cur_offset() + 3;
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x28, this->op_->cur_op());
+  ASSERT_EQ(0U, this->op_->StackSize());
+  ASSERT_EQ(offset + 0x102, this->mem_->cur_offset());
+
+  // Push on a zero value with a positive branch.
+  this->mem_->set_cur_offset(offset);
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+
+  offset = this->mem_->cur_offset() + 3;
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x28, this->op_->cur_op());
+  ASSERT_EQ(0U, this->op_->StackSize());
+  ASSERT_EQ(offset - 5, this->mem_->cur_offset());
+
+  // Push on a non-zero value with a negative branch.
+  this->mem_->set_cur_offset(offset);
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+
+  offset = this->mem_->cur_offset() + 3;
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x28, this->op_->cur_op());
+  ASSERT_EQ(0U, this->op_->StackSize());
+  ASSERT_EQ(offset - 4, this->mem_->cur_offset());
+
+  // Push on a zero value with a negative branch.
+  this->mem_->set_cur_offset(offset);
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(1U, this->op_->StackSize());
+
+  offset = this->mem_->cur_offset() + 3;
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x28, this->op_->cur_op());
+  ASSERT_EQ(0U, this->op_->StackSize());
+  ASSERT_EQ(offset + 16, this->mem_->cur_offset());
+}
+
+TYPED_TEST_P(DwarfOpTest, compare_opcode_stack_error) {
+  // All of the ops require two stack elements. Loop through all of these
+  // ops with potential errors.
+  std::vector<uint8_t> opcode_buffer = {
+      0xff,  // Place holder for compare op.
+      0x08, 0x11,
+      0xff,  // Place holder for compare op.
+  };
+
+  for (uint8_t opcode = 0x29; opcode <= 0x2e; opcode++) {
+    opcode_buffer[0] = opcode;
+    opcode_buffer[3] = opcode;
+    this->op_memory_.SetMemory(0, opcode_buffer);
+
+    ASSERT_FALSE(this->op_->Eval(0, 1, DWARF_VERSION_MAX));
+    ASSERT_EQ(opcode, this->op_->cur_op());
+    ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+
+    ASSERT_FALSE(this->op_->Eval(1, 4, DWARF_VERSION_MAX));
+    ASSERT_EQ(opcode, this->op_->cur_op());
+    ASSERT_EQ(1U, this->op_->StackSize());
+    ASSERT_EQ(DWARF_ERROR_STACK_INDEX_NOT_VALID, this->op_->last_error());
+  }
+}
+
+TYPED_TEST_P(DwarfOpTest, compare_opcodes) {
+  // Have three different checks for each compare op:
+  //   - Both values the same.
+  //   - The first value larger than the second.
+  //   - The second value larger than the first.
+  std::vector<uint8_t> opcode_buffer = {
+      // Values the same.
+      0x08, 0x11, 0x08, 0x11,
+      0xff,  // Placeholder.
+      // First value larger.
+      0x08, 0x12, 0x08, 0x10,
+      0xff,  // Placeholder.
+      // Second value larger.
+      0x08, 0x10, 0x08, 0x12,
+      0xff,  // Placeholder.
+  };
+
+  // Opcode followed by the expected values on the stack.
+  std::vector<uint8_t> expected = {
+      0x29, 1, 0, 0,  // eq
+      0x2a, 1, 1, 0,  // ge
+      0x2b, 0, 1, 0,  // gt
+      0x2c, 1, 0, 1,  // le
+      0x2d, 0, 0, 1,  // lt
+      0x2e, 0, 1, 1,  // ne
+  };
+  for (size_t i = 0; i < expected.size(); i += 4) {
+    opcode_buffer[4] = expected[i];
+    opcode_buffer[9] = expected[i];
+    opcode_buffer[14] = expected[i];
+    this->op_memory_.SetMemory(0, opcode_buffer);
+
+    ASSERT_TRUE(this->op_->Eval(0, 15, DWARF_VERSION_MAX))
+        << "Op: 0x" << std::hex << static_cast<uint32_t>(expected[i]) << " failed";
+
+    ASSERT_EQ(3U, this->op_->StackSize());
+    ASSERT_EQ(expected[i + 1], this->op_->StackAt(2));
+    ASSERT_EQ(expected[i + 2], this->op_->StackAt(1));
+    ASSERT_EQ(expected[i + 3], this->op_->StackAt(0));
+  }
+}
+
+TYPED_TEST_P(DwarfOpTest, op_skip) {
+  std::vector<uint8_t> opcode_buffer = {
+      // Positive value.
+      0x2f, 0x10, 0x20,
+      // Negative value.
+      0x2f, 0xfd, 0xff,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  uint64_t offset = this->mem_->cur_offset() + 3;
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x2f, this->op_->cur_op());
+  ASSERT_EQ(0U, this->op_->StackSize());
+  ASSERT_EQ(offset + 0x2010, this->mem_->cur_offset());
+
+  this->mem_->set_cur_offset(offset);
+  offset = this->mem_->cur_offset() + 3;
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x2f, this->op_->cur_op());
+  ASSERT_EQ(0U, this->op_->StackSize());
+  ASSERT_EQ(offset - 3, this->mem_->cur_offset());
+}
+
+TYPED_TEST_P(DwarfOpTest, op_lit) {
+  std::vector<uint8_t> opcode_buffer;
+
+  // Verify every lit opcode.
+  for (uint8_t op = 0x30; op <= 0x4f; op++) {
+    opcode_buffer.push_back(op);
+  }
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  for (size_t i = 0; i < opcode_buffer.size(); i++) {
+    uint32_t op = opcode_buffer[i];
+    ASSERT_TRUE(this->op_->Eval(i, i + 1, DWARF_VERSION_MAX)) << "Failed op: 0x" << std::hex << op;
+    ASSERT_EQ(op, this->op_->cur_op());
+    ASSERT_EQ(1U, this->op_->StackSize()) << "Failed op: 0x" << std::hex << op;
+    ASSERT_EQ(op - 0x30U, this->op_->StackAt(0)) << "Failed op: 0x" << std::hex << op;
+  }
+}
+
+TYPED_TEST_P(DwarfOpTest, op_reg) {
+  std::vector<uint8_t> opcode_buffer;
+
+  // Verify every reg opcode.
+  for (uint8_t op = 0x50; op <= 0x6f; op++) {
+    opcode_buffer.push_back(op);
+  }
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  for (size_t i = 0; i < opcode_buffer.size(); i++) {
+    uint32_t op = opcode_buffer[i];
+    ASSERT_TRUE(this->op_->Eval(i, i + 1, DWARF_VERSION_MAX)) << "Failed op: 0x" << std::hex << op;
+    ASSERT_EQ(op, this->op_->cur_op());
+    ASSERT_TRUE(this->op_->is_register()) << "Failed op: 0x" << std::hex << op;
+    ASSERT_EQ(1U, this->op_->StackSize()) << "Failed op: 0x" << std::hex << op;
+    ASSERT_EQ(op - 0x50U, this->op_->StackAt(0)) << "Failed op: 0x" << std::hex << op;
+  }
+}
+
+TYPED_TEST_P(DwarfOpTest, op_regx) {
+  std::vector<uint8_t> opcode_buffer = {
+      0x90, 0x02, 0x90, 0x80, 0x15,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  ASSERT_TRUE(this->op_->Eval(0, 2, DWARF_VERSION_MAX));
+  ASSERT_EQ(0x90, this->op_->cur_op());
+  ASSERT_TRUE(this->op_->is_register());
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_EQ(0x02U, this->op_->StackAt(0));
+
+  ASSERT_TRUE(this->op_->Eval(2, 5, DWARF_VERSION_MAX));
+  ASSERT_EQ(0x90, this->op_->cur_op());
+  ASSERT_TRUE(this->op_->is_register());
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_EQ(0xa80U, this->op_->StackAt(0));
+}
+
+TYPED_TEST_P(DwarfOpTest, op_breg) {
+  std::vector<uint8_t> opcode_buffer;
+
+  // Verify every reg opcode.
+  for (uint8_t op = 0x70; op <= 0x8f; op++) {
+    // Positive value added to register.
+    opcode_buffer.push_back(op);
+    opcode_buffer.push_back(0x12);
+    // Negative value added to register.
+    opcode_buffer.push_back(op);
+    opcode_buffer.push_back(0x7e);
+  }
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  RegsFake<TypeParam> regs(32, 10);
+  for (size_t i = 0; i < 32; i++) {
+    regs[i] = i + 10;
+  }
+  this->op_->set_regs(&regs);
+
+  uint64_t offset = 0;
+  for (uint32_t op = 0x70; op <= 0x8f; op++) {
+    // Positive value added to register.
+    ASSERT_TRUE(this->op_->Eval(offset, offset + 2, DWARF_VERSION_MAX)) << "Failed op: 0x"
+                                                                        << std::hex << op;
+    ASSERT_EQ(op, this->op_->cur_op());
+    ASSERT_EQ(1U, this->op_->StackSize()) << "Failed op: 0x" << std::hex << op;
+    ASSERT_EQ(op - 0x70 + 10 + 0x12, this->op_->StackAt(0)) << "Failed op: 0x" << std::hex << op;
+    offset += 2;
+
+    // Negative value added to register.
+    ASSERT_TRUE(this->op_->Eval(offset, offset + 2, DWARF_VERSION_MAX)) << "Failed op: 0x"
+                                                                        << std::hex << op;
+    ASSERT_EQ(op, this->op_->cur_op());
+    ASSERT_EQ(1U, this->op_->StackSize()) << "Failed op: 0x" << std::hex << op;
+    ASSERT_EQ(op - 0x70 + 10 - 2, this->op_->StackAt(0)) << "Failed op: 0x" << std::hex << op;
+    offset += 2;
+  }
+}
+
+TYPED_TEST_P(DwarfOpTest, op_breg_invalid_register) {
+  std::vector<uint8_t> opcode_buffer = {
+      0x7f, 0x12, 0x80, 0x12,
+  };
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  RegsFake<TypeParam> regs(16, 10);
+  for (size_t i = 0; i < 16; i++) {
+    regs[i] = i + 10;
+  }
+  this->op_->set_regs(&regs);
+
+  // Should pass since this references the last regsister.
+  ASSERT_TRUE(this->op_->Eval(0, 2, DWARF_VERSION_MAX));
+  ASSERT_EQ(0x7fU, this->op_->cur_op());
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_EQ(0x2bU, this->op_->StackAt(0));
+
+  // Should fail since this references a non-existent register.
+  ASSERT_FALSE(this->op_->Eval(2, 4, DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_ILLEGAL_VALUE, this->op_->last_error());
+}
+
+TYPED_TEST_P(DwarfOpTest, op_bregx) {
+  std::vector<uint8_t> opcode_buffer = {// Positive value added to register.
+                                        0x92, 0x05, 0x20,
+                                        // Negative value added to register.
+                                        0x92, 0x06, 0x80, 0x7e,
+                                        // Illegal register.
+                                        0x92, 0x80, 0x15, 0x80, 0x02};
+  this->op_memory_.SetMemory(0, opcode_buffer);
+
+  RegsFake<TypeParam> regs(10, 10);
+  regs[5] = 0x45;
+  regs[6] = 0x190;
+  this->op_->set_regs(&regs);
+
+  ASSERT_TRUE(this->op_->Eval(0, 3, DWARF_VERSION_MAX));
+  ASSERT_EQ(0x92, this->op_->cur_op());
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_EQ(0x65U, this->op_->StackAt(0));
+
+  ASSERT_TRUE(this->op_->Eval(3, 7, DWARF_VERSION_MAX));
+  ASSERT_EQ(0x92, this->op_->cur_op());
+  ASSERT_EQ(1U, this->op_->StackSize());
+  ASSERT_EQ(0x90U, this->op_->StackAt(0));
+
+  ASSERT_FALSE(this->op_->Eval(7, 12, DWARF_VERSION_MAX));
+  ASSERT_EQ(DWARF_ERROR_ILLEGAL_VALUE, this->op_->last_error());
+}
+
+TYPED_TEST_P(DwarfOpTest, op_nop) {
+  this->op_memory_.SetMemory(0, std::vector<uint8_t>{0x96});
+
+  ASSERT_TRUE(this->op_->Decode(DWARF_VERSION_MAX));
+  ASSERT_EQ(0x96, this->op_->cur_op());
+  ASSERT_EQ(0U, this->op_->StackSize());
+}
+
+REGISTER_TYPED_TEST_CASE_P(DwarfOpTest, decode, eval, illegal_opcode, illegal_in_version3,
+                           illegal_in_version4, not_implemented, op_addr, op_deref, op_deref_size,
+                           const_unsigned, const_signed, const_uleb, const_sleb, op_dup, op_drop,
+                           op_over, op_pick, op_swap, op_rot, op_abs, op_and, op_div, op_minus,
+                           op_mod, op_mul, op_neg, op_not, op_or, op_plus, op_plus_uconst, op_shl,
+                           op_shr, op_shra, op_xor, op_bra, compare_opcode_stack_error,
+                           compare_opcodes, op_skip, op_lit, op_reg, op_regx, op_breg,
+                           op_breg_invalid_register, op_bregx, op_nop);
+
+typedef ::testing::Types<uint32_t, uint64_t> DwarfOpTestTypes;
+INSTANTIATE_TYPED_TEST_CASE_P(, DwarfOpTest, DwarfOpTestTypes);
diff --git a/libunwindstack/tests/MapInfoTest.cpp b/libunwindstack/tests/MapInfoTest.cpp
new file mode 100644
index 0000000..c846ad7
--- /dev/null
+++ b/libunwindstack/tests/MapInfoTest.cpp
@@ -0,0 +1,220 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <elf.h>
+#include <errno.h>
+#include <signal.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/ptrace.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <memory>
+#include <vector>
+
+#include <android-base/file.h>
+#include <android-base/test_utils.h>
+#include <gtest/gtest.h>
+
+#include "Elf.h"
+#include "MapInfo.h"
+#include "Memory.h"
+
+class MapInfoTest : public ::testing::Test {
+ protected:
+  static void SetUpTestCase() {
+    std::vector<uint8_t> buffer(1024);
+    memcpy(buffer.data(), ELFMAG, SELFMAG);
+    for (size_t i = SELFMAG; i < buffer.size(); i++) {
+      buffer[i] = i / 256 + 1;
+    }
+    ASSERT_TRUE(android::base::WriteFully(elf_.fd, buffer.data(), buffer.size()));
+
+    for (size_t i = 0; i < 0x100; i++) {
+      buffer[i] = i / 256 + 1;
+    }
+    memcpy(&buffer[0x100], ELFMAG, SELFMAG);
+    for (size_t i = 0x100 + SELFMAG; i < buffer.size(); i++) {
+      buffer[i] = i / 256 + 1;
+    }
+    ASSERT_TRUE(android::base::WriteFully(elf_at_100_.fd, buffer.data(), buffer.size()));
+  }
+
+  static TemporaryFile elf_;
+
+  static TemporaryFile elf_at_100_;
+};
+TemporaryFile MapInfoTest::elf_;
+TemporaryFile MapInfoTest::elf_at_100_;
+
+TEST_F(MapInfoTest, end_le_start) {
+  MapInfo info{.start = 0x100, .end = 0x100, .offset = 0, .name = elf_.path};
+
+  std::unique_ptr<Memory> memory;
+  memory.reset(info.CreateMemory(getpid()));
+  ASSERT_TRUE(memory.get() == nullptr);
+
+  info.end = 0xff;
+  memory.reset(info.CreateMemory(getpid()));
+  ASSERT_TRUE(memory.get() == nullptr);
+
+  // Make sure this test is valid.
+  info.end = 0x101;
+  memory.reset(info.CreateMemory(getpid()));
+  ASSERT_FALSE(info.CreateMemory(getpid()) == nullptr);
+}
+
+// Verify that if the offset is non-zero but there is no elf at the offset,
+// that the full file is used.
+TEST_F(MapInfoTest, create_memory_file_backed_non_zero_offset_full_file) {
+  MapInfo info{.start = 0x100, .end = 0x200, .offset = 0x100, .name = elf_.path};
+
+  std::unique_ptr<Memory> memory(info.CreateMemory(getpid()));
+  ASSERT_TRUE(memory.get() != nullptr);
+  ASSERT_EQ(0x100U, info.elf_offset);
+
+  // Read the entire file.
+  std::vector<uint8_t> buffer(1024);
+  ASSERT_TRUE(memory->Read(0, buffer.data(), 1024));
+  ASSERT_TRUE(memcmp(buffer.data(), ELFMAG, SELFMAG) == 0);
+  for (size_t i = SELFMAG; i < buffer.size(); i++) {
+    ASSERT_EQ(i / 256 + 1, buffer[i]) << "Failed at byte " << i;
+  }
+
+  ASSERT_FALSE(memory->Read(1024, buffer.data(), 1));
+}
+
+// Verify that if the offset is non-zero and there is an elf at that
+// offset, that only part of the file is used.
+TEST_F(MapInfoTest, create_memory_file_backed_non_zero_offset_partial_file) {
+  MapInfo info{.start = 0x100, .end = 0x200, .offset = 0x100, .name = elf_at_100_.path};
+
+  std::unique_ptr<Memory> memory(info.CreateMemory(getpid()));
+  ASSERT_TRUE(memory.get() != nullptr);
+  ASSERT_EQ(0U, info.elf_offset);
+
+  // Read the valid part of the file.
+  std::vector<uint8_t> buffer(0x100);
+  ASSERT_TRUE(memory->Read(0, buffer.data(), 0x100));
+  ASSERT_TRUE(memcmp(buffer.data(), ELFMAG, SELFMAG) == 0);
+  for (size_t i = SELFMAG; i < buffer.size(); i++) {
+    ASSERT_EQ(2, buffer[i]) << "Failed at byte " << i;
+  }
+
+  ASSERT_FALSE(memory->Read(0x100, buffer.data(), 1));
+}
+
+// Verify that device file names will never result in Memory object creation.
+TEST_F(MapInfoTest, create_memory_check_device_maps) {
+  // Set up some memory so that a valid local memory object would
+  // be returned if the file mapping fails, but the device check is incorrect.
+  std::vector<uint8_t> buffer(1024);
+  MapInfo info;
+  info.start = reinterpret_cast<uint64_t>(buffer.data());
+  info.end = info.start + buffer.size();
+  info.offset = 0;
+  std::unique_ptr<Memory> memory;
+
+  info.flags = 0x8000;
+  info.name = "/dev/something";
+  memory.reset(info.CreateMemory(getpid()));
+  ASSERT_TRUE(memory.get() == nullptr);
+}
+
+TEST_F(MapInfoTest, create_memory_local_memory) {
+  // Set up some memory for a valid local memory object.
+  std::vector<uint8_t> buffer(1024);
+  for (size_t i = 0; i < buffer.size(); i++) {
+    buffer[i] = i % 256;
+  }
+
+  MapInfo info;
+  info.start = reinterpret_cast<uint64_t>(buffer.data());
+  info.end = info.start + buffer.size();
+  info.offset = 0;
+
+  std::unique_ptr<Memory> memory;
+  memory.reset(info.CreateMemory(getpid()));
+  ASSERT_TRUE(memory.get() != nullptr);
+
+  std::vector<uint8_t> read_buffer(1024);
+  ASSERT_TRUE(memory->Read(0, read_buffer.data(), read_buffer.size()));
+  for (size_t i = 0; i < read_buffer.size(); i++) {
+    ASSERT_EQ(i % 256, read_buffer[i]) << "Failed at byte " << i;
+  }
+
+  ASSERT_FALSE(memory->Read(read_buffer.size(), read_buffer.data(), 1));
+}
+
+TEST_F(MapInfoTest, create_memory_remote_memory) {
+  std::vector<uint8_t> buffer(1024);
+  memset(buffer.data(), 0xa, buffer.size());
+
+  pid_t pid;
+  if ((pid = fork()) == 0) {
+    while (true)
+      ;
+    exit(1);
+  }
+  ASSERT_LT(0, pid);
+
+  ASSERT_TRUE(ptrace(PTRACE_ATTACH, pid, 0, 0) != -1);
+  uint64_t iterations = 0;
+  siginfo_t si;
+  while (TEMP_FAILURE_RETRY(ptrace(PTRACE_GETSIGINFO, pid, 0, &si)) < 0 && errno == ESRCH) {
+    usleep(30);
+    iterations++;
+    ASSERT_LT(iterations, 500000000ULL);
+  }
+
+  MapInfo info;
+  info.start = reinterpret_cast<uint64_t>(buffer.data());
+  info.end = info.start + buffer.size();
+  info.offset = 0;
+
+  std::unique_ptr<Memory> memory;
+  memory.reset(info.CreateMemory(pid));
+  ASSERT_TRUE(memory.get() != nullptr);
+  // Set the local memory to a different value to guarantee we are reading
+  // from the remote process.
+  memset(buffer.data(), 0x1, buffer.size());
+  std::vector<uint8_t> read_buffer(1024);
+  ASSERT_TRUE(memory->Read(0, read_buffer.data(), read_buffer.size()));
+  for (size_t i = 0; i < read_buffer.size(); i++) {
+    ASSERT_EQ(0xaU, read_buffer[i]) << "Failed at byte " << i;
+  }
+
+  ASSERT_TRUE(ptrace(PTRACE_DETACH, pid, 0, 0) == 0);
+
+  kill(pid, SIGKILL);
+}
+
+TEST_F(MapInfoTest, get_elf) {
+  // Create a map to use as initialization data.
+  void* map = mmap(nullptr, 1024, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+  ASSERT_NE(MAP_FAILED, map);
+
+  uint64_t start = reinterpret_cast<uint64_t>(map);
+  MapInfo info{.start = start, .end = start + 1024, .offset = 0, .name = ""};
+
+  // The map contains garbage, but this should still produce an elf object.
+  Elf* elf = info.GetElf(getpid(), false);
+  ASSERT_TRUE(elf != nullptr);
+  ASSERT_FALSE(elf->valid());
+
+  ASSERT_EQ(0, munmap(map, 1024));
+}
diff --git a/libunwindstack/tests/MapsTest.cpp b/libunwindstack/tests/MapsTest.cpp
new file mode 100644
index 0000000..7eb9bae
--- /dev/null
+++ b/libunwindstack/tests/MapsTest.cpp
@@ -0,0 +1,237 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <sys/mman.h>
+
+#include <android-base/file.h>
+#include <android-base/test_utils.h>
+#include <gtest/gtest.h>
+
+#include "Maps.h"
+
+TEST(MapsTest, parse_permissions) {
+  BufferMaps maps(
+      "1000-2000 ---- 00000000 00:00 0\n"
+      "2000-3000 r--- 00000000 00:00 0\n"
+      "3000-4000 -w-- 00000000 00:00 0\n"
+      "4000-5000 --x- 00000000 00:00 0\n"
+      "5000-6000 rwx- 00000000 00:00 0\n");
+
+  ASSERT_TRUE(maps.Parse());
+  ASSERT_EQ(5U, maps.Total());
+  auto it = maps.begin();
+  ASSERT_EQ(PROT_NONE, it->flags);
+  ASSERT_EQ(0x1000U, it->start);
+  ASSERT_EQ(0x2000U, it->end);
+  ASSERT_EQ(0U, it->offset);
+  ASSERT_EQ("", it->name);
+  ++it;
+  ASSERT_EQ(PROT_READ, it->flags);
+  ASSERT_EQ(0x2000U, it->start);
+  ASSERT_EQ(0x3000U, it->end);
+  ASSERT_EQ(0U, it->offset);
+  ASSERT_EQ("", it->name);
+  ++it;
+  ASSERT_EQ(PROT_WRITE, it->flags);
+  ASSERT_EQ(0x3000U, it->start);
+  ASSERT_EQ(0x4000U, it->end);
+  ASSERT_EQ(0U, it->offset);
+  ASSERT_EQ("", it->name);
+  ++it;
+  ASSERT_EQ(PROT_EXEC, it->flags);
+  ASSERT_EQ(0x4000U, it->start);
+  ASSERT_EQ(0x5000U, it->end);
+  ASSERT_EQ(0U, it->offset);
+  ASSERT_EQ("", it->name);
+  ++it;
+  ASSERT_EQ(PROT_READ | PROT_WRITE | PROT_EXEC, it->flags);
+  ASSERT_EQ(0x5000U, it->start);
+  ASSERT_EQ(0x6000U, it->end);
+  ASSERT_EQ(0U, it->offset);
+  ASSERT_EQ("", it->name);
+  ++it;
+  ASSERT_EQ(it, maps.end());
+}
+
+TEST(MapsTest, parse_name) {
+  BufferMaps maps(
+      "720b29b000-720b29e000 rw-p 00000000 00:00 0\n"
+      "720b29e000-720b29f000 rw-p 00000000 00:00 0 /system/lib/fake.so\n"
+      "720b29f000-720b2a0000 rw-p 00000000 00:00 0");
+
+  ASSERT_TRUE(maps.Parse());
+  ASSERT_EQ(3U, maps.Total());
+  auto it = maps.begin();
+  ASSERT_EQ("", it->name);
+  ASSERT_EQ(0x720b29b000U, it->start);
+  ASSERT_EQ(0x720b29e000U, it->end);
+  ASSERT_EQ(0U, it->offset);
+  ASSERT_EQ(PROT_READ | PROT_WRITE, it->flags);
+  ++it;
+  ASSERT_EQ("/system/lib/fake.so", it->name);
+  ASSERT_EQ(0x720b29e000U, it->start);
+  ASSERT_EQ(0x720b29f000U, it->end);
+  ASSERT_EQ(0U, it->offset);
+  ASSERT_EQ(PROT_READ | PROT_WRITE, it->flags);
+  ++it;
+  ASSERT_EQ("", it->name);
+  ASSERT_EQ(0x720b29f000U, it->start);
+  ASSERT_EQ(0x720b2a0000U, it->end);
+  ASSERT_EQ(0U, it->offset);
+  ASSERT_EQ(PROT_READ | PROT_WRITE, it->flags);
+  ++it;
+  ASSERT_EQ(it, maps.end());
+}
+
+TEST(MapsTest, parse_offset) {
+  BufferMaps maps(
+      "a000-e000 rw-p 00000000 00:00 0 /system/lib/fake.so\n"
+      "e000-f000 rw-p 00a12345 00:00 0 /system/lib/fake.so\n");
+
+  ASSERT_TRUE(maps.Parse());
+  ASSERT_EQ(2U, maps.Total());
+  auto it = maps.begin();
+  ASSERT_EQ(0U, it->offset);
+  ASSERT_EQ(0xa000U, it->start);
+  ASSERT_EQ(0xe000U, it->end);
+  ASSERT_EQ(PROT_READ | PROT_WRITE, it->flags);
+  ASSERT_EQ("/system/lib/fake.so", it->name);
+  ++it;
+  ASSERT_EQ(0xa12345U, it->offset);
+  ASSERT_EQ(0xe000U, it->start);
+  ASSERT_EQ(0xf000U, it->end);
+  ASSERT_EQ(PROT_READ | PROT_WRITE, it->flags);
+  ASSERT_EQ("/system/lib/fake.so", it->name);
+  ++it;
+  ASSERT_EQ(maps.end(), it);
+}
+
+TEST(MapsTest, device) {
+  BufferMaps maps(
+      "a000-e000 rw-p 00000000 00:00 0 /dev/\n"
+      "f000-f100 rw-p 00000000 00:00 0 /dev/does_not_exist\n"
+      "f100-f200 rw-p 00000000 00:00 0 /dev/ashmem/does_not_exist\n"
+      "f200-f300 rw-p 00000000 00:00 0 /devsomething/does_not_exist\n");
+
+  ASSERT_TRUE(maps.Parse());
+  ASSERT_EQ(4U, maps.Total());
+  auto it = maps.begin();
+  ASSERT_TRUE(it->flags & 0x8000);
+  ASSERT_EQ("/dev/", it->name);
+  ++it;
+  ASSERT_TRUE(it->flags & 0x8000);
+  ASSERT_EQ("/dev/does_not_exist", it->name);
+  ++it;
+  ASSERT_FALSE(it->flags & 0x8000);
+  ASSERT_EQ("/dev/ashmem/does_not_exist", it->name);
+  ++it;
+  ASSERT_FALSE(it->flags & 0x8000);
+  ASSERT_EQ("/devsomething/does_not_exist", it->name);
+}
+
+TEST(MapsTest, file_smoke) {
+  TemporaryFile tf;
+  ASSERT_TRUE(tf.fd != -1);
+
+  ASSERT_TRUE(
+      android::base::WriteStringToFile("720b29b000-720b29e000 r-xp a0000000 00:00 0   /fake.so\n"
+                                       "720b2b0000-720b2e0000 r-xp b0000000 00:00 0   /fake2.so\n"
+                                       "720b2e0000-720b2f0000 r-xp c0000000 00:00 0   /fake3.so\n",
+                                       tf.path, 0660, getuid(), getgid()));
+
+  FileMaps maps(tf.path);
+
+  ASSERT_TRUE(maps.Parse());
+  ASSERT_EQ(3U, maps.Total());
+  auto it = maps.begin();
+  ASSERT_EQ(0x720b29b000U, it->start);
+  ASSERT_EQ(0x720b29e000U, it->end);
+  ASSERT_EQ(0xa0000000U, it->offset);
+  ASSERT_EQ(PROT_READ | PROT_EXEC, it->flags);
+  ASSERT_EQ("/fake.so", it->name);
+  ++it;
+  ASSERT_EQ(0x720b2b0000U, it->start);
+  ASSERT_EQ(0x720b2e0000U, it->end);
+  ASSERT_EQ(0xb0000000U, it->offset);
+  ASSERT_EQ(PROT_READ | PROT_EXEC, it->flags);
+  ASSERT_EQ("/fake2.so", it->name);
+  ++it;
+  ASSERT_EQ(0x720b2e0000U, it->start);
+  ASSERT_EQ(0x720b2f0000U, it->end);
+  ASSERT_EQ(0xc0000000U, it->offset);
+  ASSERT_EQ(PROT_READ | PROT_EXEC, it->flags);
+  ASSERT_EQ("/fake3.so", it->name);
+  ++it;
+  ASSERT_EQ(it, maps.end());
+}
+
+TEST(MapsTest, find) {
+  BufferMaps maps(
+      "1000-2000 r--p 00000010 00:00 0 /system/lib/fake1.so\n"
+      "3000-4000 -w-p 00000020 00:00 0 /system/lib/fake2.so\n"
+      "6000-8000 --xp 00000030 00:00 0 /system/lib/fake3.so\n"
+      "a000-b000 rw-p 00000040 00:00 0 /system/lib/fake4.so\n"
+      "e000-f000 rwxp 00000050 00:00 0 /system/lib/fake5.so\n");
+  ASSERT_TRUE(maps.Parse());
+  ASSERT_EQ(5U, maps.Total());
+
+  ASSERT_TRUE(maps.Find(0x500) == nullptr);
+  ASSERT_TRUE(maps.Find(0x2000) == nullptr);
+  ASSERT_TRUE(maps.Find(0x5010) == nullptr);
+  ASSERT_TRUE(maps.Find(0x9a00) == nullptr);
+  ASSERT_TRUE(maps.Find(0xf000) == nullptr);
+  ASSERT_TRUE(maps.Find(0xf010) == nullptr);
+
+  MapInfo* info = maps.Find(0x1000);
+  ASSERT_TRUE(info != nullptr);
+  ASSERT_EQ(0x1000U, info->start);
+  ASSERT_EQ(0x2000U, info->end);
+  ASSERT_EQ(0x10U, info->offset);
+  ASSERT_EQ(PROT_READ, info->flags);
+  ASSERT_EQ("/system/lib/fake1.so", info->name);
+
+  info = maps.Find(0x3020);
+  ASSERT_TRUE(info != nullptr);
+  ASSERT_EQ(0x3000U, info->start);
+  ASSERT_EQ(0x4000U, info->end);
+  ASSERT_EQ(0x20U, info->offset);
+  ASSERT_EQ(PROT_WRITE, info->flags);
+  ASSERT_EQ("/system/lib/fake2.so", info->name);
+
+  info = maps.Find(0x6020);
+  ASSERT_TRUE(info != nullptr);
+  ASSERT_EQ(0x6000U, info->start);
+  ASSERT_EQ(0x8000U, info->end);
+  ASSERT_EQ(0x30U, info->offset);
+  ASSERT_EQ(PROT_EXEC, info->flags);
+  ASSERT_EQ("/system/lib/fake3.so", info->name);
+
+  info = maps.Find(0xafff);
+  ASSERT_TRUE(info != nullptr);
+  ASSERT_EQ(0xa000U, info->start);
+  ASSERT_EQ(0xb000U, info->end);
+  ASSERT_EQ(0x40U, info->offset);
+  ASSERT_EQ(PROT_READ | PROT_WRITE, info->flags);
+  ASSERT_EQ("/system/lib/fake4.so", info->name);
+
+  info = maps.Find(0xe500);
+  ASSERT_TRUE(info != nullptr);
+  ASSERT_EQ(0xe000U, info->start);
+  ASSERT_EQ(0xf000U, info->end);
+  ASSERT_EQ(0x50U, info->offset);
+  ASSERT_EQ(PROT_READ | PROT_WRITE | PROT_EXEC, info->flags);
+  ASSERT_EQ("/system/lib/fake5.so", info->name);
+}
diff --git a/libunwindstack/tests/MemoryBuffer.cpp b/libunwindstack/tests/MemoryBuffer.cpp
new file mode 100644
index 0000000..af3d6b9
--- /dev/null
+++ b/libunwindstack/tests/MemoryBuffer.cpp
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <vector>
+
+#include <gtest/gtest.h>
+
+#include "Memory.h"
+
+#include "LogFake.h"
+
+class MemoryBufferTest : public ::testing::Test {
+ protected:
+  void SetUp() override {
+    ResetLogs();
+    memory_.reset(new MemoryBuffer);
+  }
+  std::unique_ptr<MemoryBuffer> memory_;
+};
+
+TEST_F(MemoryBufferTest, empty) {
+  ASSERT_EQ(0U, memory_->Size());
+  std::vector<uint8_t> buffer(1024);
+  ASSERT_FALSE(memory_->Read(0, buffer.data(), 1));
+  ASSERT_EQ(nullptr, memory_->GetPtr(0));
+  ASSERT_EQ(nullptr, memory_->GetPtr(1));
+}
+
+TEST_F(MemoryBufferTest, write_read) {
+  memory_->Resize(256);
+  ASSERT_EQ(256U, memory_->Size());
+  ASSERT_TRUE(memory_->GetPtr(0) != nullptr);
+  ASSERT_TRUE(memory_->GetPtr(1) != nullptr);
+  ASSERT_TRUE(memory_->GetPtr(255) != nullptr);
+  ASSERT_TRUE(memory_->GetPtr(256) == nullptr);
+
+  uint8_t* data = memory_->GetPtr(0);
+  for (size_t i = 0; i < memory_->Size(); i++) {
+    data[i] = i;
+  }
+
+  std::vector<uint8_t> buffer(memory_->Size());
+  ASSERT_TRUE(memory_->Read(0, buffer.data(), buffer.size()));
+  for (size_t i = 0; i < buffer.size(); i++) {
+    ASSERT_EQ(i, buffer[i]) << "Failed at byte " << i;
+  }
+}
+
+TEST_F(MemoryBufferTest, read_failures) {
+  memory_->Resize(100);
+  std::vector<uint8_t> buffer(200);
+  ASSERT_FALSE(memory_->Read(0, buffer.data(), 101));
+  ASSERT_FALSE(memory_->Read(100, buffer.data(), 1));
+  ASSERT_FALSE(memory_->Read(101, buffer.data(), 2));
+  ASSERT_FALSE(memory_->Read(99, buffer.data(), 2));
+  ASSERT_TRUE(memory_->Read(99, buffer.data(), 1));
+}
+
+TEST_F(MemoryBufferTest, read_failure_overflow) {
+  memory_->Resize(100);
+  std::vector<uint8_t> buffer(200);
+
+  ASSERT_FALSE(memory_->Read(UINT64_MAX - 100, buffer.data(), 200));
+}
diff --git a/libunwindstack/tests/MemoryFake.h b/libunwindstack/tests/MemoryFake.h
index e05736b..70ef30a 100644
--- a/libunwindstack/tests/MemoryFake.h
+++ b/libunwindstack/tests/MemoryFake.h
@@ -75,4 +75,16 @@
   }
 };
 
+class MemoryFakeRemote : public MemoryRemote {
+ public:
+  MemoryFakeRemote() : MemoryRemote(0) {}
+  virtual ~MemoryFakeRemote() = default;
+
+ protected:
+  bool PtraceRead(uint64_t, long* value) override {
+    *value = 0;
+    return true;
+  }
+};
+
 #endif  // _LIBUNWINDSTACK_TESTS_MEMORY_FAKE_H
diff --git a/libunwindstack/tests/MemoryFileTest.cpp b/libunwindstack/tests/MemoryFileTest.cpp
index 870ca19..aa7a23a 100644
--- a/libunwindstack/tests/MemoryFileTest.cpp
+++ b/libunwindstack/tests/MemoryFileTest.cpp
@@ -14,6 +14,9 @@
  * limitations under the License.
  */
 
+#include <string>
+#include <vector>
+
 #include <android-base/test_utils.h>
 #include <android-base/file.h>
 #include <gtest/gtest.h>
@@ -39,7 +42,7 @@
   TemporaryFile* tf_ = nullptr;
 };
 
-TEST_F(MemoryFileTest, offset_0) {
+TEST_F(MemoryFileTest, init_offset_0) {
   WriteTestData();
 
   ASSERT_TRUE(memory_.Init(tf_->path, 0));
@@ -49,7 +52,7 @@
   ASSERT_STREQ("0123456789", buffer.data());
 }
 
-TEST_F(MemoryFileTest, offset_non_zero) {
+TEST_F(MemoryFileTest, init_offset_non_zero) {
   WriteTestData();
 
   ASSERT_TRUE(memory_.Init(tf_->path, 10));
@@ -59,7 +62,7 @@
   ASSERT_STREQ("abcdefghij", buffer.data());
 }
 
-TEST_F(MemoryFileTest, offset_non_zero_larger_than_pagesize) {
+TEST_F(MemoryFileTest, init_offset_non_zero_larger_than_pagesize) {
   size_t pagesize = getpagesize();
   std::string large_string;
   for (size_t i = 0; i < pagesize; i++) {
@@ -75,7 +78,7 @@
   ASSERT_STREQ("abcdefgh", buffer.data());
 }
 
-TEST_F(MemoryFileTest, offset_pagesize_aligned) {
+TEST_F(MemoryFileTest, init_offset_pagesize_aligned) {
   size_t pagesize = getpagesize();
   std::string data;
   for (size_t i = 0; i < 2 * pagesize; i++) {
@@ -96,7 +99,7 @@
   ASSERT_STREQ(expected_str.c_str(), buffer.data());
 }
 
-TEST_F(MemoryFileTest, offset_pagesize_aligned_plus_extra) {
+TEST_F(MemoryFileTest, init_offset_pagesize_aligned_plus_extra) {
   size_t pagesize = getpagesize();
   std::string data;
   for (size_t i = 0; i < 2 * pagesize; i++) {
@@ -117,6 +120,23 @@
   ASSERT_STREQ(expected_str.c_str(), buffer.data());
 }
 
+TEST_F(MemoryFileTest, init_offset_greater_than_filesize) {
+  size_t pagesize = getpagesize();
+  std::string data;
+  uint64_t file_size = 2 * pagesize + pagesize / 2;
+  for (size_t i = 0; i < file_size; i++) {
+    data += static_cast<char>((i / pagesize) + '0');
+  }
+  ASSERT_TRUE(android::base::WriteStringToFd(data, tf_->fd));
+
+  // Check offset > file size fails and aligned_offset > file size.
+  ASSERT_FALSE(memory_.Init(tf_->path, file_size + 2 * pagesize));
+  // Check offset == filesize fails.
+  ASSERT_FALSE(memory_.Init(tf_->path, file_size));
+  // Check aligned_offset < filesize, but offset > filesize fails.
+  ASSERT_FALSE(memory_.Init(tf_->path, 2 * pagesize + pagesize / 2 + pagesize / 4));
+}
+
 TEST_F(MemoryFileTest, read_error) {
   std::string data;
   for (size_t i = 0; i < 5000; i++) {
@@ -137,32 +157,9 @@
   ASSERT_TRUE(memory_.Read(4990, buffer.data(), 10));
   ASSERT_FALSE(memory_.Read(4999, buffer.data(), 2));
   ASSERT_TRUE(memory_.Read(4999, buffer.data(), 1));
-}
 
-TEST_F(MemoryFileTest, read_string) {
-  std::string value("name_in_file");
-  ASSERT_TRUE(android::base::WriteFully(tf_->fd, value.c_str(), value.size() + 1));
-
-  std::string name;
-  ASSERT_TRUE(memory_.Init(tf_->path, 0));
-  ASSERT_TRUE(memory_.ReadString(0, &name));
-  ASSERT_EQ("name_in_file", name);
-  ASSERT_TRUE(memory_.ReadString(5, &name));
-  ASSERT_EQ("in_file", name);
-}
-
-TEST_F(MemoryFileTest, read_string_error) {
-  std::vector<uint8_t> buffer = { 0x23, 0x32, 0x45 };
-  ASSERT_TRUE(android::base::WriteFully(tf_->fd, buffer.data(), buffer.size()));
-
-  std::string name;
-  ASSERT_TRUE(memory_.Init(tf_->path, 0));
-
-  // Read from a non-existant address.
-  ASSERT_FALSE(memory_.ReadString(100, &name));
-
-  // This should fail because there is no terminating \0
-  ASSERT_FALSE(memory_.ReadString(0, &name));
+  // Check that overflow fails properly.
+  ASSERT_FALSE(memory_.Read(UINT64_MAX - 100, buffer.data(), 200));
 }
 
 TEST_F(MemoryFileTest, read_past_file_within_mapping) {
diff --git a/libunwindstack/tests/MemoryLocalTest.cpp b/libunwindstack/tests/MemoryLocalTest.cpp
index 0ba5f1c..ab999da 100644
--- a/libunwindstack/tests/MemoryLocalTest.cpp
+++ b/libunwindstack/tests/MemoryLocalTest.cpp
@@ -47,25 +47,6 @@
   }
 }
 
-TEST(MemoryLocalTest, read_string) {
-  std::string name("string_in_memory");
-
-  MemoryLocal local;
-
-  std::vector<uint8_t> dst(1024);
-  std::string dst_name;
-  ASSERT_TRUE(local.ReadString(reinterpret_cast<uint64_t>(name.c_str()), &dst_name));
-  ASSERT_EQ("string_in_memory", dst_name);
-
-  ASSERT_TRUE(local.ReadString(reinterpret_cast<uint64_t>(&name[7]), &dst_name));
-  ASSERT_EQ("in_memory", dst_name);
-
-  ASSERT_TRUE(local.ReadString(reinterpret_cast<uint64_t>(&name[7]), &dst_name, 10));
-  ASSERT_EQ("in_memory", dst_name);
-
-  ASSERT_FALSE(local.ReadString(reinterpret_cast<uint64_t>(&name[7]), &dst_name, 9));
-}
-
 TEST(MemoryLocalTest, read_illegal) {
   MemoryLocal local;
 
@@ -73,3 +54,13 @@
   ASSERT_FALSE(local.Read(0, dst.data(), 1));
   ASSERT_FALSE(local.Read(0, dst.data(), 100));
 }
+
+TEST(MemoryLocalTest, read_overflow) {
+  MemoryLocal local;
+
+  // On 32 bit this test doesn't necessarily cause an overflow. The 64 bit
+  // version will always go through the overflow check.
+  std::vector<uint8_t> dst(100);
+  uint64_t value;
+  ASSERT_FALSE(local.Read(reinterpret_cast<uint64_t>(&value), dst.data(), SIZE_MAX));
+}
diff --git a/libunwindstack/tests/MemoryRangeTest.cpp b/libunwindstack/tests/MemoryRangeTest.cpp
index d636ec4..ee5ba01 100644
--- a/libunwindstack/tests/MemoryRangeTest.cpp
+++ b/libunwindstack/tests/MemoryRangeTest.cpp
@@ -17,6 +17,7 @@
 #include <stdint.h>
 #include <string.h>
 
+#include <memory>
 #include <vector>
 
 #include <gtest/gtest.h>
@@ -65,35 +66,14 @@
   ASSERT_FALSE(range.Read(1020, dst.data(), 5));
   ASSERT_FALSE(range.Read(1024, dst.data(), 1));
   ASSERT_FALSE(range.Read(1024, dst.data(), 1024));
+
+  // Verify that reading up to the end works.
+  ASSERT_TRUE(range.Read(1020, dst.data(), 4));
 }
 
-TEST_F(MemoryRangeTest, read_string_past_end) {
-  std::string name("0123456789");
-  memory_->SetMemory(0, name);
+TEST_F(MemoryRangeTest, read_overflow) {
+  std::vector<uint8_t> buffer(100);
 
-  // Verify a read past the range fails.
-  MemoryRange range(memory_, 0, 5);
-  std::string dst_name;
-  ASSERT_FALSE(range.ReadString(0, &dst_name));
-}
-
-TEST_F(MemoryRangeTest, read_string_to_end) {
-  std::string name("0123456789");
-  memory_->SetMemory(30, name);
-
-  // Verify the range going to the end of the string works.
-  MemoryRange range(memory_, 30, 30 + name.size() + 1);
-  std::string dst_name;
-  ASSERT_TRUE(range.ReadString(0, &dst_name));
-  ASSERT_EQ("0123456789", dst_name);
-}
-
-TEST_F(MemoryRangeTest, read_string_fencepost) {
-  std::string name("0123456789");
-  memory_->SetMemory(10, name);
-
-  // Verify the range set to one byte less than the end of the string fails.
-  MemoryRange range(memory_, 10, 10 + name.size());
-  std::string dst_name;
-  ASSERT_FALSE(range.ReadString(0, &dst_name));
+  std::unique_ptr<MemoryRange> overflow(new MemoryRange(new MemoryFakeAlwaysReadZero, 100, 200));
+  ASSERT_FALSE(overflow->Read(UINT64_MAX - 10, buffer.data(), 100));
 }
diff --git a/libunwindstack/tests/MemoryRemoteTest.cpp b/libunwindstack/tests/MemoryRemoteTest.cpp
index 7664c3e..e48edf7 100644
--- a/libunwindstack/tests/MemoryRemoteTest.cpp
+++ b/libunwindstack/tests/MemoryRemoteTest.cpp
@@ -33,6 +33,8 @@
 
 #include "Memory.h"
 
+#include "MemoryFake.h"
+
 class MemoryRemoteTest : public ::testing::Test {
  protected:
   static uint64_t NanoTime() {
@@ -121,6 +123,9 @@
   ASSERT_TRUE(remote.Read(reinterpret_cast<uint64_t>(src) + pagesize - 1, dst.data(), 1));
   ASSERT_FALSE(remote.Read(reinterpret_cast<uint64_t>(src) + pagesize - 4, dst.data(), 8));
 
+  // Check overflow condition is caught properly.
+  ASSERT_FALSE(remote.Read(UINT64_MAX - 100, dst.data(), 200));
+
   ASSERT_EQ(0, munmap(src, pagesize));
 
   ASSERT_TRUE(Detach(pid));
@@ -128,6 +133,14 @@
   kill(pid, SIGKILL);
 }
 
+TEST_F(MemoryRemoteTest, read_overflow) {
+  MemoryFakeRemote remote;
+
+  // Check overflow condition is caught properly.
+  std::vector<uint8_t> dst(200);
+  ASSERT_FALSE(remote.Read(UINT64_MAX - 100, dst.data(), 200));
+}
+
 TEST_F(MemoryRemoteTest, read_illegal) {
   pid_t pid;
   if ((pid = fork()) == 0) {
diff --git a/libunwindstack/tests/MemoryTest.cpp b/libunwindstack/tests/MemoryTest.cpp
new file mode 100644
index 0000000..51b5d7d
--- /dev/null
+++ b/libunwindstack/tests/MemoryTest.cpp
@@ -0,0 +1,126 @@
+/*
+ * 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 <string.h>
+
+#include <string>
+#include <vector>
+
+#include <gtest/gtest.h>
+
+#include "Memory.h"
+
+#include "MemoryFake.h"
+
+TEST(MemoryTest, read32) {
+  MemoryFakeAlwaysReadZero memory;
+
+  uint32_t data = 0xffffffff;
+  ASSERT_TRUE(memory.Read32(0, &data));
+  ASSERT_EQ(0U, data);
+}
+
+TEST(MemoryTest, read64) {
+  MemoryFakeAlwaysReadZero memory;
+
+  uint64_t data = 0xffffffffffffffffULL;
+  ASSERT_TRUE(memory.Read64(0, &data));
+  ASSERT_EQ(0U, data);
+}
+
+struct FakeStruct {
+  int one;
+  bool two;
+  uint32_t three;
+  uint64_t four;
+};
+
+TEST(MemoryTest, read_field) {
+  MemoryFakeAlwaysReadZero memory;
+
+  FakeStruct data;
+  memset(&data, 0xff, sizeof(data));
+  ASSERT_TRUE(memory.ReadField(0, &data, &data.one, sizeof(data.one)));
+  ASSERT_EQ(0, data.one);
+
+  memset(&data, 0xff, sizeof(data));
+  ASSERT_TRUE(memory.ReadField(0, &data, &data.two, sizeof(data.two)));
+  ASSERT_FALSE(data.two);
+
+  memset(&data, 0xff, sizeof(data));
+  ASSERT_TRUE(memory.ReadField(0, &data, &data.three, sizeof(data.three)));
+  ASSERT_EQ(0U, data.three);
+
+  memset(&data, 0xff, sizeof(data));
+  ASSERT_TRUE(memory.ReadField(0, &data, &data.four, sizeof(data.four)));
+  ASSERT_EQ(0U, data.four);
+}
+
+TEST(MemoryTest, read_field_fails) {
+  MemoryFakeAlwaysReadZero memory;
+
+  FakeStruct data;
+  memset(&data, 0xff, sizeof(data));
+
+  ASSERT_FALSE(memory.ReadField(UINT64_MAX, &data, &data.three, sizeof(data.three)));
+
+  // Field and start reversed, should fail.
+  ASSERT_FALSE(memory.ReadField(100, &data.two, &data, sizeof(data.two)));
+  ASSERT_FALSE(memory.ReadField(0, &data.two, &data, sizeof(data.two)));
+}
+
+TEST(MemoryTest, read_string) {
+  std::string name("string_in_memory");
+
+  MemoryFake memory;
+
+  memory.SetMemory(100, name.c_str(), name.size() + 1);
+
+  std::string dst_name;
+  ASSERT_TRUE(memory.ReadString(100, &dst_name));
+  ASSERT_EQ("string_in_memory", dst_name);
+
+  ASSERT_TRUE(memory.ReadString(107, &dst_name));
+  ASSERT_EQ("in_memory", dst_name);
+
+  // Set size greater than string.
+  ASSERT_TRUE(memory.ReadString(107, &dst_name, 10));
+  ASSERT_EQ("in_memory", dst_name);
+
+  ASSERT_FALSE(memory.ReadString(107, &dst_name, 9));
+}
+
+TEST(MemoryTest, read_string_error) {
+  std::string name("short");
+
+  MemoryFake memory;
+
+  // Save everything except the terminating '\0'.
+  memory.SetMemory(0, name.c_str(), name.size());
+
+  std::string dst_name;
+  // Read from a non-existant address.
+  ASSERT_FALSE(memory.ReadString(100, &dst_name));
+
+  // This should fail because there is no terminating '\0'.
+  ASSERT_FALSE(memory.ReadString(0, &dst_name));
+
+  // This should pass because there is a terminating '\0'.
+  memory.SetData8(name.size(), '\0');
+  ASSERT_TRUE(memory.ReadString(0, &dst_name));
+  ASSERT_EQ("short", dst_name);
+}
diff --git a/libunwindstack/tests/SymbolsTest.cpp b/libunwindstack/tests/SymbolsTest.cpp
new file mode 100644
index 0000000..a0a21e6
--- /dev/null
+++ b/libunwindstack/tests/SymbolsTest.cpp
@@ -0,0 +1,335 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <elf.h>
+#include <errno.h>
+#include <signal.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/ptrace.h>
+#include <sys/types.h>
+#include <time.h>
+#include <unistd.h>
+
+#include <vector>
+
+#include <android-base/file.h>
+#include <android-base/test_utils.h>
+#include <gtest/gtest.h>
+
+#include "Memory.h"
+#include "MemoryFake.h"
+#include "Symbols.h"
+
+template <typename TypeParam>
+class SymbolsTest : public ::testing::Test {
+ protected:
+  void SetUp() override { memory_.Clear(); }
+
+  void InitSym(TypeParam* sym, uint32_t st_value, uint32_t st_size, uint32_t st_name) {
+    memset(sym, 0, sizeof(*sym));
+    sym->st_info = STT_FUNC;
+    sym->st_value = st_value;
+    sym->st_size = st_size;
+    sym->st_name = st_name;
+    sym->st_shndx = SHN_COMMON;
+  }
+
+  MemoryFake memory_;
+};
+TYPED_TEST_CASE_P(SymbolsTest);
+
+TYPED_TEST_P(SymbolsTest, function_bounds_check) {
+  Symbols symbols(0x1000, sizeof(TypeParam), sizeof(TypeParam), 0x2000, 0x100);
+
+  TypeParam sym;
+  this->InitSym(&sym, 0x5000, 0x10, 0x40);
+  uint64_t offset = 0x1000;
+  this->memory_.SetMemory(offset, &sym, sizeof(sym));
+
+  std::string fake_name("fake_function");
+  this->memory_.SetMemory(0x2040, fake_name.c_str(), fake_name.size() + 1);
+
+  std::string name;
+  uint64_t func_offset;
+  ASSERT_TRUE(symbols.GetName<TypeParam>(0x5000, 0, &this->memory_, &name, &func_offset));
+  ASSERT_EQ("fake_function", name);
+  ASSERT_EQ(0U, func_offset);
+
+  name.clear();
+  ASSERT_TRUE(symbols.GetName<TypeParam>(0x500f, 0, &this->memory_, &name, &func_offset));
+  ASSERT_EQ("fake_function", name);
+  ASSERT_EQ(0xfU, func_offset);
+
+  // Check one before and one after the function.
+  ASSERT_FALSE(symbols.GetName<TypeParam>(0x4fff, 0, &this->memory_, &name, &func_offset));
+  ASSERT_FALSE(symbols.GetName<TypeParam>(0x5010, 0, &this->memory_, &name, &func_offset));
+}
+
+TYPED_TEST_P(SymbolsTest, no_symbol) {
+  Symbols symbols(0x1000, sizeof(TypeParam), sizeof(TypeParam), 0x2000, 0x100);
+
+  TypeParam sym;
+  this->InitSym(&sym, 0x5000, 0x10, 0x40);
+  uint64_t offset = 0x1000;
+  this->memory_.SetMemory(offset, &sym, sizeof(sym));
+
+  std::string fake_name("fake_function");
+  this->memory_.SetMemory(0x2040, fake_name.c_str(), fake_name.size() + 1);
+
+  // First verify that we can get the name.
+  std::string name;
+  uint64_t func_offset;
+  ASSERT_TRUE(symbols.GetName<TypeParam>(0x5000, 0, &this->memory_, &name, &func_offset));
+  ASSERT_EQ("fake_function", name);
+  ASSERT_EQ(0U, func_offset);
+
+  // Now modify the info field so it's no longer a function.
+  sym.st_info = 0;
+  this->memory_.SetMemory(offset, &sym, sizeof(sym));
+  // Clear the cache to force the symbol data to be re-read.
+  symbols.ClearCache();
+  ASSERT_FALSE(symbols.GetName<TypeParam>(0x5000, 0, &this->memory_, &name, &func_offset));
+
+  // Set the function back, and set the shndx to UNDEF.
+  sym.st_info = STT_FUNC;
+  sym.st_shndx = SHN_UNDEF;
+  this->memory_.SetMemory(offset, &sym, sizeof(sym));
+  // Clear the cache to force the symbol data to be re-read.
+  symbols.ClearCache();
+  ASSERT_FALSE(symbols.GetName<TypeParam>(0x5000, 0, &this->memory_, &name, &func_offset));
+}
+
+TYPED_TEST_P(SymbolsTest, multiple_entries) {
+  Symbols symbols(0x1000, sizeof(TypeParam) * 3, sizeof(TypeParam), 0x2000, 0x500);
+
+  TypeParam sym;
+  uint64_t offset = 0x1000;
+  std::string fake_name;
+
+  this->InitSym(&sym, 0x5000, 0x10, 0x40);
+  this->memory_.SetMemory(offset, &sym, sizeof(sym));
+  fake_name = "function_one";
+  this->memory_.SetMemory(0x2040, fake_name.c_str(), fake_name.size() + 1);
+  offset += sizeof(sym);
+
+  this->InitSym(&sym, 0x3004, 0x200, 0x100);
+  this->memory_.SetMemory(offset, &sym, sizeof(sym));
+  fake_name = "function_two";
+  this->memory_.SetMemory(0x2100, fake_name.c_str(), fake_name.size() + 1);
+  offset += sizeof(sym);
+
+  this->InitSym(&sym, 0xa010, 0x20, 0x230);
+  this->memory_.SetMemory(offset, &sym, sizeof(sym));
+  fake_name = "function_three";
+  this->memory_.SetMemory(0x2230, fake_name.c_str(), fake_name.size() + 1);
+
+  std::string name;
+  uint64_t func_offset;
+  ASSERT_TRUE(symbols.GetName<TypeParam>(0x3005, 0, &this->memory_, &name, &func_offset));
+  ASSERT_EQ("function_two", name);
+  ASSERT_EQ(1U, func_offset);
+
+  name.clear();
+  ASSERT_TRUE(symbols.GetName<TypeParam>(0x5004, 0, &this->memory_, &name, &func_offset));
+  ASSERT_EQ("function_one", name);
+  ASSERT_EQ(4U, func_offset);
+
+  name.clear();
+  ASSERT_TRUE(symbols.GetName<TypeParam>(0xa011, 0, &this->memory_, &name, &func_offset));
+  ASSERT_EQ("function_three", name);
+  ASSERT_EQ(1U, func_offset);
+
+  // Reget some of the others to verify getting one function name doesn't
+  // affect any of the next calls.
+  name.clear();
+  ASSERT_TRUE(symbols.GetName<TypeParam>(0x5008, 0, &this->memory_, &name, &func_offset));
+  ASSERT_EQ("function_one", name);
+  ASSERT_EQ(8U, func_offset);
+
+  name.clear();
+  ASSERT_TRUE(symbols.GetName<TypeParam>(0x3008, 0, &this->memory_, &name, &func_offset));
+  ASSERT_EQ("function_two", name);
+  ASSERT_EQ(4U, func_offset);
+
+  name.clear();
+  ASSERT_TRUE(symbols.GetName<TypeParam>(0xa01a, 0, &this->memory_, &name, &func_offset));
+  ASSERT_EQ("function_three", name);
+  ASSERT_EQ(0xaU, func_offset);
+}
+
+TYPED_TEST_P(SymbolsTest, multiple_entries_nonstandard_size) {
+  uint64_t entry_size = sizeof(TypeParam) + 5;
+  Symbols symbols(0x1000, entry_size * 3, entry_size, 0x2000, 0x500);
+
+  TypeParam sym;
+  uint64_t offset = 0x1000;
+  std::string fake_name;
+
+  this->InitSym(&sym, 0x5000, 0x10, 0x40);
+  this->memory_.SetMemory(offset, &sym, sizeof(sym));
+  fake_name = "function_one";
+  this->memory_.SetMemory(0x2040, fake_name.c_str(), fake_name.size() + 1);
+  offset += entry_size;
+
+  this->InitSym(&sym, 0x3004, 0x200, 0x100);
+  this->memory_.SetMemory(offset, &sym, sizeof(sym));
+  fake_name = "function_two";
+  this->memory_.SetMemory(0x2100, fake_name.c_str(), fake_name.size() + 1);
+  offset += entry_size;
+
+  this->InitSym(&sym, 0xa010, 0x20, 0x230);
+  this->memory_.SetMemory(offset, &sym, sizeof(sym));
+  fake_name = "function_three";
+  this->memory_.SetMemory(0x2230, fake_name.c_str(), fake_name.size() + 1);
+
+  std::string name;
+  uint64_t func_offset;
+  ASSERT_TRUE(symbols.GetName<TypeParam>(0x3005, 0, &this->memory_, &name, &func_offset));
+  ASSERT_EQ("function_two", name);
+  ASSERT_EQ(1U, func_offset);
+
+  name.clear();
+  ASSERT_TRUE(symbols.GetName<TypeParam>(0x5004, 0, &this->memory_, &name, &func_offset));
+  ASSERT_EQ("function_one", name);
+  ASSERT_EQ(4U, func_offset);
+
+  name.clear();
+  ASSERT_TRUE(symbols.GetName<TypeParam>(0xa011, 0, &this->memory_, &name, &func_offset));
+  ASSERT_EQ("function_three", name);
+  ASSERT_EQ(1U, func_offset);
+}
+
+TYPED_TEST_P(SymbolsTest, load_bias) {
+  Symbols symbols(0x1000, sizeof(TypeParam), sizeof(TypeParam), 0x2000, 0x100);
+
+  TypeParam sym;
+  this->InitSym(&sym, 0x5000, 0x10, 0x40);
+  uint64_t offset = 0x1000;
+  this->memory_.SetMemory(offset, &sym, sizeof(sym));
+
+  std::string fake_name("fake_function");
+  this->memory_.SetMemory(0x2040, fake_name.c_str(), fake_name.size() + 1);
+
+  // Set a non-zero load_bias that should be a valid function offset.
+  std::string name;
+  uint64_t func_offset;
+  ASSERT_TRUE(symbols.GetName<TypeParam>(0x5004, 0x1000, &this->memory_, &name, &func_offset));
+  ASSERT_EQ("fake_function", name);
+  ASSERT_EQ(4U, func_offset);
+
+  // Set a flag that should cause the load_bias to be ignored.
+  sym.st_shndx = SHN_ABS;
+  this->memory_.SetMemory(offset, &sym, sizeof(sym));
+  // Clear the cache to force the symbol data to be re-read.
+  symbols.ClearCache();
+  ASSERT_FALSE(symbols.GetName<TypeParam>(0x5004, 0x1000, &this->memory_, &name, &func_offset));
+}
+
+TYPED_TEST_P(SymbolsTest, symtab_value_out_of_bounds) {
+  Symbols symbols_end_at_100(0x1000, sizeof(TypeParam) * 2, sizeof(TypeParam), 0x2000, 0x100);
+  Symbols symbols_end_at_200(0x1000, sizeof(TypeParam) * 2, sizeof(TypeParam), 0x2000, 0x200);
+
+  TypeParam sym;
+  uint64_t offset = 0x1000;
+
+  this->InitSym(&sym, 0x5000, 0x10, 0xfb);
+  this->memory_.SetMemory(offset, &sym, sizeof(sym));
+  offset += sizeof(sym);
+
+  this->InitSym(&sym, 0x3000, 0x10, 0x100);
+  this->memory_.SetMemory(offset, &sym, sizeof(sym));
+
+  // Put the name across the end of the tab.
+  std::string fake_name("fake_function");
+  this->memory_.SetMemory(0x20fb, fake_name.c_str(), fake_name.size() + 1);
+
+  std::string name;
+  uint64_t func_offset;
+  // Verify that we can get the function name properly for both entries.
+  ASSERT_TRUE(symbols_end_at_200.GetName<TypeParam>(0x5000, 0, &this->memory_, &name, &func_offset));
+  ASSERT_EQ("fake_function", name);
+  ASSERT_EQ(0U, func_offset);
+  ASSERT_TRUE(symbols_end_at_200.GetName<TypeParam>(0x3000, 0, &this->memory_, &name, &func_offset));
+  ASSERT_EQ("function", name);
+  ASSERT_EQ(0U, func_offset);
+
+  // Now use the symbol table that ends at 0x100.
+  ASSERT_FALSE(
+      symbols_end_at_100.GetName<TypeParam>(0x5000, 0, &this->memory_, &name, &func_offset));
+  ASSERT_FALSE(
+      symbols_end_at_100.GetName<TypeParam>(0x3000, 0, &this->memory_, &name, &func_offset));
+}
+
+// Verify the entire func table is cached.
+TYPED_TEST_P(SymbolsTest, symtab_read_cached) {
+  Symbols symbols(0x1000, 3 * sizeof(TypeParam), sizeof(TypeParam), 0xa000, 0x1000);
+
+  TypeParam sym;
+  uint64_t offset = 0x1000;
+
+  // Make sure that these entries are not in ascending order.
+  this->InitSym(&sym, 0x5000, 0x10, 0x100);
+  this->memory_.SetMemory(offset, &sym, sizeof(sym));
+  offset += sizeof(sym);
+
+  this->InitSym(&sym, 0x2000, 0x300, 0x200);
+  this->memory_.SetMemory(offset, &sym, sizeof(sym));
+  offset += sizeof(sym);
+
+  this->InitSym(&sym, 0x1000, 0x100, 0x300);
+  this->memory_.SetMemory(offset, &sym, sizeof(sym));
+  offset += sizeof(sym);
+
+  // Do call that should cache all of the entries (except the string data).
+  std::string name;
+  uint64_t func_offset;
+  ASSERT_FALSE(symbols.GetName<TypeParam>(0x6000, 0, &this->memory_, &name, &func_offset));
+  this->memory_.Clear();
+  ASSERT_FALSE(symbols.GetName<TypeParam>(0x6000, 0, &this->memory_, &name, &func_offset));
+
+  // Clear the memory and only put the symbol data string data in memory.
+  this->memory_.Clear();
+
+  std::string fake_name;
+  fake_name = "first_entry";
+  this->memory_.SetMemory(0xa100, fake_name.c_str(), fake_name.size() + 1);
+  fake_name = "second_entry";
+  this->memory_.SetMemory(0xa200, fake_name.c_str(), fake_name.size() + 1);
+  fake_name = "third_entry";
+  this->memory_.SetMemory(0xa300, fake_name.c_str(), fake_name.size() + 1);
+
+  ASSERT_TRUE(symbols.GetName<TypeParam>(0x5001, 0, &this->memory_, &name, &func_offset));
+  ASSERT_EQ("first_entry", name);
+  ASSERT_EQ(1U, func_offset);
+
+  ASSERT_TRUE(symbols.GetName<TypeParam>(0x2002, 0, &this->memory_, &name, &func_offset));
+  ASSERT_EQ("second_entry", name);
+  ASSERT_EQ(2U, func_offset);
+
+  ASSERT_TRUE(symbols.GetName<TypeParam>(0x1003, 0, &this->memory_, &name, &func_offset));
+  ASSERT_EQ("third_entry", name);
+  ASSERT_EQ(3U, func_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);
+
+typedef ::testing::Types<Elf32_Sym, Elf64_Sym> SymbolsTestTypes;
+INSTANTIATE_TYPED_TEST_CASE_P(, SymbolsTest, SymbolsTestTypes);
diff --git a/libusbhost/Android.bp b/libusbhost/Android.bp
new file mode 100644
index 0000000..a0d6b9b
--- /dev/null
+++ b/libusbhost/Android.bp
@@ -0,0 +1,35 @@
+//
+// 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.
+//
+
+cc_library {
+    name: "libusbhost",
+    host_supported: true,
+    srcs: ["usbhost.c"],
+    cflags: ["-Werror"],
+    export_include_dirs: ["include"],
+    target: {
+        android: {
+            cflags: [
+                "-g",
+                "-DUSE_LIBLOG",
+            ],
+            shared_libs: ["liblog"],
+        },
+        darwin: {
+            enabled: false,
+        },
+    },
+}
diff --git a/libusbhost/Android.mk b/libusbhost/Android.mk
deleted file mode 100644
index 9439846..0000000
--- a/libusbhost/Android.mk
+++ /dev/null
@@ -1,56 +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.
-#
-
-LOCAL_PATH := $(call my-dir)
-
-# Static library for Linux host
-# ========================================================
-
-ifeq ($(HOST_OS),linux)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := libusbhost
-LOCAL_SRC_FILES := usbhost.c
-LOCAL_CFLAGS := -Werror
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-include $(BUILD_HOST_STATIC_LIBRARY)
-
-endif
-
-# Shared library for target
-# ========================================================
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := libusbhost
-LOCAL_SRC_FILES := usbhost.c
-LOCAL_CFLAGS := -g -DUSE_LIBLOG -Werror
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-# needed for logcat
-LOCAL_SHARED_LIBRARIES := libcutils
-include $(BUILD_SHARED_LIBRARY)
-
-# Static library for target
-# ========================================================
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := libusbhost
-LOCAL_SRC_FILES := usbhost.c
-LOCAL_CFLAGS := -Werror
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-include $(BUILD_STATIC_LIBRARY)
diff --git a/libusbhost/usbhost.c b/libusbhost/usbhost.c
index 68aca17..050fc2f 100644
--- a/libusbhost/usbhost.c
+++ b/libusbhost/usbhost.c
@@ -19,7 +19,7 @@
 
 #ifdef USE_LIBLOG
 #define LOG_TAG "usbhost"
-#include "utils/Log.h"
+#include "log/log.h"
 #define D ALOGD
 #else
 #define D printf
diff --git a/libutils/Android.bp b/libutils/Android.bp
index 2b7412b..33770ba 100644
--- a/libutils/Android.bp
+++ b/libutils/Android.bp
@@ -14,9 +14,24 @@
 
 cc_library_headers {
     name: "libutils_headers",
+    vendor_available: true,
     host_supported: true,
+
+    header_libs: [
+        "libsystem_headers",
+        "libcutils_headers"
+    ],
+    export_header_lib_headers: [
+        "libsystem_headers",
+        "libcutils_headers"
+    ],
     export_include_dirs: ["include"],
+
     target: {
+        android: {
+            header_libs: ["libbacktrace_headers"],
+            export_header_lib_headers: ["libbacktrace_headers"],
+        },
         linux_bionic: {
             enabled: true,
         },
@@ -28,6 +43,7 @@
 
 cc_library {
     name: "libutils",
+    vendor_available: true,
     host_supported: true,
 
     srcs: [
diff --git a/libutils/ProcessCallStack.cpp b/libutils/ProcessCallStack.cpp
index 73ed4eb..983847c 100644
--- a/libutils/ProcessCallStack.cpp
+++ b/libutils/ProcessCallStack.cpp
@@ -21,6 +21,7 @@
 #include <errno.h>
 #include <stdio.h>
 #include <string.h>
+#include <unistd.h>
 #include <memory>
 
 #include <utils/Log.h>
diff --git a/libutils/include/utils/Compat.h b/libutils/include/utils/Compat.h
index 2709e3b..dee577e 100644
--- a/libutils/include/utils/Compat.h
+++ b/libutils/include/utils/Compat.h
@@ -37,6 +37,10 @@
     return pwrite(fd, buf, nbytes, offset);
 }
 
+static inline int ftruncate64(int fd, off64_t length) {
+    return ftruncate(fd, length);
+}
+
 #endif /* __APPLE__ */
 
 #if defined(_WIN32)
diff --git a/libutils/include/utils/FastStrcmp.h b/libutils/include/utils/FastStrcmp.h
index 3844e7d..5cadc94 100644
--- a/libutils/include/utils/FastStrcmp.h
+++ b/libutils/include/utils/FastStrcmp.h
@@ -17,6 +17,13 @@
 #ifndef _ANDROID_UTILS_FASTSTRCMP_H__
 #define _ANDROID_UTILS_FASTSTRCMP_H__
 
+#include <ctype.h>
+#include <string.h>
+
+#ifndef __predict_true
+#define __predict_true(exp) __builtin_expect((exp) != 0, 1)
+#endif
+
 #ifdef __cplusplus
 
 // Optimized for instruction cache locality
@@ -28,25 +35,41 @@
 //
 //  fastcmp<strncmp>(str1, str2, len)
 //
-// NB: Does not work for the case insensitive str*cmp functions.
+// NB: use fasticmp for the case insensitive str*cmp functions.
 // NB: Returns boolean, do not use if expecting to check negative value.
 //     Thus not semantically identical to the expected function behavior.
 
-template <int (*cmp)(const char *l, const char *r, const size_t s)>
-static inline int fastcmp(const char *l, const char *r, const size_t s) {
-    return (*l != *r) || cmp(l + 1, r + 1, s - 1);
+template <int (*cmp)(const char* l, const char* r, const size_t s)>
+static inline int fastcmp(const char* l, const char* r, const size_t s) {
+    const ssize_t n = s;  // To help reject negative sizes, treat like zero
+    return __predict_true(n > 0) &&
+           ((*l != *r) || (__predict_true(n > 1) && cmp(l + 1, r + 1, n - 1)));
 }
 
-template <int (*cmp)(const void *l, const void *r, const size_t s)>
-static inline int fastcmp(const void *lv, const void *rv, const size_t s) {
-    const char *l = static_cast<const char *>(lv);
-    const char *r = static_cast<const char *>(rv);
-    return (*l != *r) || cmp(l + 1, r + 1, s - 1);
+template <int (*cmp)(const char* l, const char* r, const size_t s)>
+static inline int fasticmp(const char* l, const char* r, const size_t s) {
+    const ssize_t n = s;  // To help reject negative sizes, treat like zero
+    return __predict_true(n > 0) &&
+           ((tolower(*l) != tolower(*r)) || (__predict_true(n > 1) && cmp(l + 1, r + 1, n - 1)));
 }
 
-template <int (*cmp)(const char *l, const char *r)>
-static inline int fastcmp(const char *l, const char *r) {
-    return (*l != *r) || cmp(l + 1, r + 1);
+template <int (*cmp)(const void* l, const void* r, const size_t s)>
+static inline int fastcmp(const void* lv, const void* rv, const size_t s) {
+    const char* l = static_cast<const char*>(lv);
+    const char* r = static_cast<const char*>(rv);
+    const ssize_t n = s;  // To help reject negative sizes, treat like zero
+    return __predict_true(n > 0) &&
+           ((*l != *r) || (__predict_true(n > 1) && cmp(l + 1, r + 1, n - 1)));
+}
+
+template <int (*cmp)(const char* l, const char* r)>
+static inline int fastcmp(const char* l, const char* r) {
+    return (*l != *r) || (__predict_true(*l) && cmp(l + 1, r + 1));
+}
+
+template <int (*cmp)(const char* l, const char* r)>
+static inline int fasticmp(const char* l, const char* r) {
+    return (tolower(*l) != tolower(*r)) || (__predict_true(*l) && cmp(l + 1, r + 1));
 }
 
 #endif
diff --git a/libziparchive/zip_archive.cc b/libziparchive/zip_archive.cc
index 0ac6f2c..246575f 100644
--- a/libziparchive/zip_archive.cc
+++ b/libziparchive/zip_archive.cc
@@ -563,6 +563,17 @@
 
   // Paranoia: Match the values specified in the local file header
   // to those specified in the central directory.
+
+  // Verify that the central directory and local file header agree on the use of a trailing
+  // Data Descriptor.
+  if ((lfh->gpb_flags & kGPBDDFlagMask) != (cdr->gpb_flags & kGPBDDFlagMask)) {
+    ALOGW("Zip: gpb flag mismatch. expected {%04" PRIx16 "}, was {%04" PRIx16 "}",
+          cdr->gpb_flags, lfh->gpb_flags);
+    return kInconsistentInformation;
+  }
+
+  // If there is no trailing data descriptor, verify that the central directory and local file
+  // header agree on the crc, compressed, and uncompressed sizes of the entry.
   if ((lfh->gpb_flags & kGPBDDFlagMask) == 0) {
     data->has_data_descriptor = 0;
     if (data->compressed_length != lfh->compressed_size
diff --git a/libziparchive/zip_writer.cc b/libziparchive/zip_writer.cc
index b72ed7f..6d28bdb 100644
--- a/libziparchive/zip_writer.cc
+++ b/libziparchive/zip_writer.cc
@@ -14,21 +14,24 @@
  * limitations under the License.
  */
 
-#include "entry_name_utils-inl.h"
-#include "zip_archive_common.h"
 #include "ziparchive/zip_writer.h"
 
-#include <utils/Log.h>
-
-#include <sys/param.h>
-
-#include <cassert>
 #include <cstdio>
-#include <memory>
-#include <vector>
+#include <sys/param.h>
+#include <sys/stat.h>
 #include <zlib.h>
 #define DEF_MEM_LEVEL 8                // normally in zutil.h?
 
+#include <memory>
+#include <vector>
+
+#include "android-base/logging.h"
+#include "utils/Compat.h"
+#include "utils/Log.h"
+
+#include "entry_name_utils-inl.h"
+#include "zip_archive_common.h"
+
 #if !defined(powerof2)
 #define powerof2(x) ((((x)-1)&(x))==0)
 #endif
@@ -82,11 +85,19 @@
   delete stream;
 }
 
-ZipWriter::ZipWriter(FILE* f) : file_(f), current_offset_(0), state_(State::kWritingZip),
-                                z_stream_(nullptr, DeleteZStream), buffer_(kBufSize) {
+ZipWriter::ZipWriter(FILE* f) : file_(f), seekable_(false), current_offset_(0),
+                                state_(State::kWritingZip), z_stream_(nullptr, DeleteZStream),
+                                buffer_(kBufSize) {
+  // Check if the file is seekable (regular file). If fstat fails, that's fine, subsequent calls
+  // will fail as well.
+  struct stat file_stats;
+  if (fstat(fileno(f), &file_stats) == 0) {
+    seekable_ = S_ISREG(file_stats.st_mode);
+  }
 }
 
 ZipWriter::ZipWriter(ZipWriter&& writer) : file_(writer.file_),
+                                           seekable_(writer.seekable_),
                                            current_offset_(writer.current_offset_),
                                            state_(writer.state_),
                                            files_(std::move(writer.files_)),
@@ -98,6 +109,7 @@
 
 ZipWriter& ZipWriter::operator=(ZipWriter&& writer) {
   file_ = writer.file_;
+  seekable_ = writer.seekable_;
   current_offset_ = writer.current_offset_;
   state_ = writer.state_;
   files_ = std::move(writer.files_);
@@ -157,6 +169,30 @@
   *out_time = ptm->tm_hour << 11 | ptm->tm_min << 5 | ptm->tm_sec >> 1;
 }
 
+static void CopyFromFileEntry(const ZipWriter::FileEntry& src, bool use_data_descriptor,
+                              LocalFileHeader* dst) {
+  dst->lfh_signature = LocalFileHeader::kSignature;
+  if (use_data_descriptor) {
+    // Set this flag to denote that a DataDescriptor struct will appear after the data,
+    // containing the crc and size fields.
+    dst->gpb_flags |= kGPBDDFlagMask;
+
+    // The size and crc fields must be 0.
+    dst->compressed_size = 0u;
+    dst->uncompressed_size = 0u;
+    dst->crc32 = 0u;
+  } else {
+    dst->compressed_size = src.compressed_size;
+    dst->uncompressed_size = src.uncompressed_size;
+    dst->crc32 = src.crc32;
+  }
+  dst->compression_method = src.compression_method;
+  dst->last_mod_time = src.last_mod_time;
+  dst->last_mod_date = src.last_mod_date;
+  dst->file_name_length = src.path.size();
+  dst->extra_field_length = src.padding_length;
+}
+
 int32_t ZipWriter::StartAlignedEntryWithTime(const char* path, size_t flags,
                                              time_t time, uint32_t alignment) {
   if (state_ != State::kWritingZip) {
@@ -171,74 +207,89 @@
     return kInvalidAlignment;
   }
 
-  FileInfo fileInfo = {};
-  fileInfo.path = std::string(path);
-  fileInfo.local_file_header_offset = current_offset_;
+  FileEntry file_entry = {};
+  file_entry.local_file_header_offset = current_offset_;
+  file_entry.path = path;
 
-  if (!IsValidEntryName(reinterpret_cast<const uint8_t*>(fileInfo.path.data()),
-                       fileInfo.path.size())) {
+  if (!IsValidEntryName(reinterpret_cast<const uint8_t*>(file_entry.path.data()),
+                        file_entry.path.size())) {
     return kInvalidEntryName;
   }
 
-  LocalFileHeader header = {};
-  header.lfh_signature = LocalFileHeader::kSignature;
-
-  // Set this flag to denote that a DataDescriptor struct will appear after the data,
-  // containing the crc and size fields.
-  header.gpb_flags |= kGPBDDFlagMask;
-
   if (flags & ZipWriter::kCompress) {
-    fileInfo.compression_method = kCompressDeflated;
+    file_entry.compression_method = kCompressDeflated;
 
     int32_t result = PrepareDeflate();
     if (result != kNoError) {
       return result;
     }
   } else {
-    fileInfo.compression_method = kCompressStored;
+    file_entry.compression_method = kCompressStored;
   }
-  header.compression_method = fileInfo.compression_method;
 
-  ExtractTimeAndDate(time, &fileInfo.last_mod_time, &fileInfo.last_mod_date);
-  header.last_mod_time = fileInfo.last_mod_time;
-  header.last_mod_date = fileInfo.last_mod_date;
+  ExtractTimeAndDate(time, &file_entry.last_mod_time, &file_entry.last_mod_date);
 
-  header.file_name_length = fileInfo.path.size();
-
-  off64_t offset = current_offset_ + sizeof(header) + fileInfo.path.size();
+  off_t offset = current_offset_ + sizeof(LocalFileHeader) + file_entry.path.size();
   std::vector<char> zero_padding;
   if (alignment != 0 && (offset & (alignment - 1))) {
     // Pad the extra field so the data will be aligned.
     uint16_t padding = alignment - (offset % alignment);
-    header.extra_field_length = padding;
+    file_entry.padding_length = padding;
     offset += padding;
-    zero_padding.resize(padding);
-    memset(zero_padding.data(), 0, zero_padding.size());
+    zero_padding.resize(padding, 0);
   }
 
+  LocalFileHeader header = {};
+  // Always start expecting a data descriptor. When the data has finished being written,
+  // if it is possible to seek back, the GPB flag will reset and the sizes written.
+  CopyFromFileEntry(file_entry, true /*use_data_descriptor*/, &header);
+
   if (fwrite(&header, sizeof(header), 1, file_) != 1) {
     return HandleError(kIoError);
   }
 
-  if (fwrite(path, sizeof(*path), fileInfo.path.size(), file_) != fileInfo.path.size()) {
+  if (fwrite(path, sizeof(*path), file_entry.path.size(), file_) != file_entry.path.size()) {
     return HandleError(kIoError);
   }
 
-  if (header.extra_field_length != 0 &&
-      fwrite(zero_padding.data(), 1, header.extra_field_length, file_)
-      != header.extra_field_length) {
+  if (file_entry.padding_length != 0 &&
+      fwrite(zero_padding.data(), 1, file_entry.padding_length, file_)
+      != file_entry.padding_length) {
     return HandleError(kIoError);
   }
 
-  files_.emplace_back(std::move(fileInfo));
-
+  current_file_entry_ = std::move(file_entry);
   current_offset_ = offset;
   state_ = State::kWritingEntry;
   return kNoError;
 }
 
+int32_t ZipWriter::DiscardLastEntry() {
+  if (state_ != State::kWritingZip || files_.empty()) {
+    return kInvalidState;
+  }
+
+  FileEntry& last_entry = files_.back();
+  current_offset_ = last_entry.local_file_header_offset;
+  if (fseeko(file_, current_offset_, SEEK_SET) != 0) {
+    return HandleError(kIoError);
+  }
+  files_.pop_back();
+  return kNoError;
+}
+
+int32_t ZipWriter::GetLastEntry(FileEntry* out_entry) {
+  CHECK(out_entry != nullptr);
+
+  if (files_.empty()) {
+    return kInvalidState;
+  }
+  *out_entry = files_.back();
+  return kNoError;
+}
+
 int32_t ZipWriter::PrepareDeflate() {
-  assert(state_ == State::kWritingZip);
+  CHECK(state_ == State::kWritingZip);
 
   // Initialize the z_stream for compression.
   z_stream_ = std::unique_ptr<z_stream, void(*)(z_stream*)>(new z_stream(), DeleteZStream);
@@ -269,25 +320,25 @@
     return HandleError(kInvalidState);
   }
 
-  FileInfo& currentFile = files_.back();
   int32_t result = kNoError;
-  if (currentFile.compression_method & kCompressDeflated) {
-    result = CompressBytes(&currentFile, data, len);
+  if (current_file_entry_.compression_method & kCompressDeflated) {
+    result = CompressBytes(&current_file_entry_, data, len);
   } else {
-    result = StoreBytes(&currentFile, data, len);
+    result = StoreBytes(&current_file_entry_, data, len);
   }
 
   if (result != kNoError) {
     return result;
   }
 
-  currentFile.crc32 = crc32(currentFile.crc32, reinterpret_cast<const Bytef*>(data), len);
-  currentFile.uncompressed_size += len;
+  current_file_entry_.crc32 = crc32(current_file_entry_.crc32,
+                                    reinterpret_cast<const Bytef*>(data), len);
+  current_file_entry_.uncompressed_size += len;
   return kNoError;
 }
 
-int32_t ZipWriter::StoreBytes(FileInfo* file, const void* data, size_t len) {
-  assert(state_ == State::kWritingEntry);
+int32_t ZipWriter::StoreBytes(FileEntry* file, const void* data, size_t len) {
+  CHECK(state_ == State::kWritingEntry);
 
   if (fwrite(data, 1, len, file_) != len) {
     return HandleError(kIoError);
@@ -297,11 +348,11 @@
   return kNoError;
 }
 
-int32_t ZipWriter::CompressBytes(FileInfo* file, const void* data, size_t len) {
-  assert(state_ == State::kWritingEntry);
-  assert(z_stream_);
-  assert(z_stream_->next_out != nullptr);
-  assert(z_stream_->avail_out != 0);
+int32_t ZipWriter::CompressBytes(FileEntry* file, const void* data, size_t len) {
+  CHECK(state_ == State::kWritingEntry);
+  CHECK(z_stream_);
+  CHECK(z_stream_->next_out != nullptr);
+  CHECK(z_stream_->avail_out != 0);
 
   // Prepare the input.
   z_stream_->next_in = reinterpret_cast<const uint8_t*>(data);
@@ -331,17 +382,17 @@
   return kNoError;
 }
 
-int32_t ZipWriter::FlushCompressedBytes(FileInfo* file) {
-  assert(state_ == State::kWritingEntry);
-  assert(z_stream_);
-  assert(z_stream_->next_out != nullptr);
-  assert(z_stream_->avail_out != 0);
+int32_t ZipWriter::FlushCompressedBytes(FileEntry* file) {
+  CHECK(state_ == State::kWritingEntry);
+  CHECK(z_stream_);
+  CHECK(z_stream_->next_out != nullptr);
+  CHECK(z_stream_->avail_out != 0);
 
   // Keep deflating while there isn't enough space in the buffer to
   // to complete the compress.
   int zerr;
   while ((zerr = deflate(z_stream_.get(), Z_FINISH)) == Z_OK) {
-    assert(z_stream_->avail_out == 0);
+    CHECK(z_stream_->avail_out == 0);
     size_t write_bytes = z_stream_->next_out - buffer_.data();
     if (fwrite(buffer_.data(), 1, write_bytes, file_) != write_bytes) {
       return HandleError(kIoError);
@@ -373,29 +424,48 @@
     return kInvalidState;
   }
 
-  FileInfo& currentFile = files_.back();
-  if (currentFile.compression_method & kCompressDeflated) {
-    int32_t result = FlushCompressedBytes(&currentFile);
+  if (current_file_entry_.compression_method & kCompressDeflated) {
+    int32_t result = FlushCompressedBytes(&current_file_entry_);
     if (result != kNoError) {
       return result;
     }
   }
 
-  const uint32_t sig = DataDescriptor::kOptSignature;
-  if (fwrite(&sig, sizeof(sig), 1, file_) != 1) {
-    state_ = State::kError;
-    return kIoError;
+  if ((current_file_entry_.compression_method & kCompressDeflated) || !seekable_) {
+    // Some versions of ZIP don't allow STORED data to have a trailing DataDescriptor.
+    // If this file is not seekable, or if the data is compressed, write a DataDescriptor.
+    const uint32_t sig = DataDescriptor::kOptSignature;
+    if (fwrite(&sig, sizeof(sig), 1, file_) != 1) {
+      return HandleError(kIoError);
+    }
+
+    DataDescriptor dd = {};
+    dd.crc32 = current_file_entry_.crc32;
+    dd.compressed_size = current_file_entry_.compressed_size;
+    dd.uncompressed_size = current_file_entry_.uncompressed_size;
+    if (fwrite(&dd, sizeof(dd), 1, file_) != 1) {
+      return HandleError(kIoError);
+    }
+    current_offset_ += sizeof(DataDescriptor::kOptSignature) + sizeof(dd);
+  } else {
+    // Seek back to the header and rewrite to include the size.
+    if (fseeko(file_, current_file_entry_.local_file_header_offset, SEEK_SET) != 0) {
+      return HandleError(kIoError);
+    }
+
+    LocalFileHeader header = {};
+    CopyFromFileEntry(current_file_entry_, false /*use_data_descriptor*/, &header);
+
+    if (fwrite(&header, sizeof(header), 1, file_) != 1) {
+      return HandleError(kIoError);
+    }
+
+    if (fseeko(file_, current_offset_, SEEK_SET) != 0) {
+      return HandleError(kIoError);
+    }
   }
 
-  DataDescriptor dd = {};
-  dd.crc32 = currentFile.crc32;
-  dd.compressed_size = currentFile.compressed_size;
-  dd.uncompressed_size = currentFile.uncompressed_size;
-  if (fwrite(&dd, sizeof(dd), 1, file_) != 1) {
-    return HandleError(kIoError);
-  }
-
-  current_offset_ += sizeof(DataDescriptor::kOptSignature) + sizeof(dd);
+  files_.emplace_back(std::move(current_file_entry_));
   state_ = State::kWritingZip;
   return kNoError;
 }
@@ -405,11 +475,13 @@
     return kInvalidState;
   }
 
-  off64_t startOfCdr = current_offset_;
-  for (FileInfo& file : files_) {
+  off_t startOfCdr = current_offset_;
+  for (FileEntry& file : files_) {
     CentralDirectoryRecord cdr = {};
     cdr.record_signature = CentralDirectoryRecord::kSignature;
-    cdr.gpb_flags |= kGPBDDFlagMask;
+    if ((file.compression_method & kCompressDeflated) || !seekable_) {
+      cdr.gpb_flags |= kGPBDDFlagMask;
+    }
     cdr.compression_method = file.compression_method;
     cdr.last_mod_time = file.last_mod_time;
     cdr.last_mod_date = file.last_mod_date;
@@ -417,7 +489,7 @@
     cdr.compressed_size = file.compressed_size;
     cdr.uncompressed_size = file.uncompressed_size;
     cdr.file_name_length = file.path.size();
-    cdr.local_file_header_offset = file.local_file_header_offset;
+    cdr.local_file_header_offset = static_cast<uint32_t>(file.local_file_header_offset);
     if (fwrite(&cdr, sizeof(cdr), 1, file_) != 1) {
       return HandleError(kIoError);
     }
@@ -442,11 +514,19 @@
     return HandleError(kIoError);
   }
 
+  current_offset_ += sizeof(er);
+
+  // Since we can BackUp() and potentially finish writing at an offset less than one we had
+  // already written at, we must truncate the file.
+
+  if (ftruncate(fileno(file_), current_offset_) != 0) {
+    return HandleError(kIoError);
+  }
+
   if (fflush(file_) != 0) {
     return HandleError(kIoError);
   }
 
-  current_offset_ += sizeof(er);
   state_ = State::kDone;
   return kNoError;
 }
diff --git a/libziparchive/zip_writer_test.cc b/libziparchive/zip_writer_test.cc
index 16a574d..5b526a4 100644
--- a/libziparchive/zip_writer_test.cc
+++ b/libziparchive/zip_writer_test.cc
@@ -23,6 +23,10 @@
 #include <memory>
 #include <vector>
 
+static ::testing::AssertionResult AssertFileEntryContentsEq(const std::string& expected,
+                                                            ZipArchiveHandle handle,
+                                                            ZipEntry* zip_entry);
+
 struct zipwriter : public ::testing::Test {
   TemporaryFile* temp_file_;
   int fd_;
@@ -59,16 +63,11 @@
 
   ZipEntry data;
   ASSERT_EQ(0, FindEntry(handle, ZipString("file.txt"), &data));
-  EXPECT_EQ(strlen(expected), data.compressed_length);
-  EXPECT_EQ(strlen(expected), data.uncompressed_length);
   EXPECT_EQ(kCompressStored, data.method);
-
-  char buffer[6];
-  EXPECT_EQ(0,
-            ExtractToMemory(handle, &data, reinterpret_cast<uint8_t*>(&buffer), sizeof(buffer)));
-  buffer[5] = 0;
-
-  EXPECT_STREQ(expected, buffer);
+  EXPECT_EQ(0u, data.has_data_descriptor);
+  EXPECT_EQ(strlen(expected), data.compressed_length);
+  ASSERT_EQ(strlen(expected), data.uncompressed_length);
+  ASSERT_TRUE(AssertFileEntryContentsEq(expected, handle, &data));
 
   CloseArchive(handle);
 }
@@ -94,26 +93,19 @@
   ZipArchiveHandle handle;
   ASSERT_EQ(0, OpenArchiveFd(fd_, "temp", &handle, false));
 
-  char buffer[4];
   ZipEntry data;
 
   ASSERT_EQ(0, FindEntry(handle, ZipString("file.txt"), &data));
   EXPECT_EQ(kCompressStored, data.method);
   EXPECT_EQ(2u, data.compressed_length);
-  EXPECT_EQ(2u, data.uncompressed_length);
-  ASSERT_EQ(0,
-            ExtractToMemory(handle, &data, reinterpret_cast<uint8_t*>(buffer), arraysize(buffer)));
-  buffer[2] = 0;
-  EXPECT_STREQ("he", buffer);
+  ASSERT_EQ(2u, data.uncompressed_length);
+  ASSERT_TRUE(AssertFileEntryContentsEq("he", handle, &data));
 
   ASSERT_EQ(0, FindEntry(handle, ZipString("file/file.txt"), &data));
   EXPECT_EQ(kCompressStored, data.method);
   EXPECT_EQ(3u, data.compressed_length);
-  EXPECT_EQ(3u, data.uncompressed_length);
-  ASSERT_EQ(0,
-            ExtractToMemory(handle, &data, reinterpret_cast<uint8_t*>(buffer), arraysize(buffer)));
-  buffer[3] = 0;
-  EXPECT_STREQ("llo", buffer);
+  ASSERT_EQ(3u, data.uncompressed_length);
+  ASSERT_TRUE(AssertFileEntryContentsEq("llo", handle, &data));
 
   ASSERT_EQ(0, FindEntry(handle, ZipString("file/file2.txt"), &data));
   EXPECT_EQ(kCompressStored, data.method);
@@ -143,7 +135,7 @@
   CloseArchive(handle);
 }
 
-void ConvertZipTimeToTm(uint32_t& zip_time, struct tm* tm) {
+static void ConvertZipTimeToTm(uint32_t& zip_time, struct tm* tm) {
   memset(tm, 0, sizeof(struct tm));
   tm->tm_hour = (zip_time >> 11) & 0x1f;
   tm->tm_min = (zip_time >> 5) & 0x3f;
@@ -264,14 +256,8 @@
   ZipEntry data;
   ASSERT_EQ(0, FindEntry(handle, ZipString("file.txt"), &data));
   EXPECT_EQ(kCompressDeflated, data.method);
-  EXPECT_EQ(4u, data.uncompressed_length);
-
-  char buffer[5];
-  ASSERT_EQ(0,
-            ExtractToMemory(handle, &data, reinterpret_cast<uint8_t*>(buffer), arraysize(buffer)));
-  buffer[4] = 0;
-
-  EXPECT_STREQ("helo", buffer);
+  ASSERT_EQ(4u, data.uncompressed_length);
+  ASSERT_TRUE(AssertFileEntryContentsEq("helo", handle, &data));
 
   CloseArchive(handle);
 }
@@ -319,3 +305,111 @@
   ASSERT_EQ(-5, writer.StartAlignedEntry("align.txt", ZipWriter::kAlign32, 4096));
   ASSERT_EQ(-6, writer.StartAlignedEntry("align.txt", 0, 3));
 }
+
+TEST_F(zipwriter, BackupRemovesTheLastFile) {
+  ZipWriter writer(file_);
+
+  const char* kKeepThis = "keep this";
+  const char* kDropThis = "drop this";
+  const char* kReplaceWithThis = "replace with this";
+
+  ZipWriter::FileEntry entry;
+  EXPECT_LT(writer.GetLastEntry(&entry), 0);
+
+  ASSERT_EQ(0, writer.StartEntry("keep.txt", 0));
+  ASSERT_EQ(0, writer.WriteBytes(kKeepThis, strlen(kKeepThis)));
+  ASSERT_EQ(0, writer.FinishEntry());
+
+  ASSERT_EQ(0, writer.GetLastEntry(&entry));
+  EXPECT_EQ("keep.txt", entry.path);
+
+  ASSERT_EQ(0, writer.StartEntry("drop.txt", 0));
+  ASSERT_EQ(0, writer.WriteBytes(kDropThis, strlen(kDropThis)));
+  ASSERT_EQ(0, writer.FinishEntry());
+
+  ASSERT_EQ(0, writer.GetLastEntry(&entry));
+  EXPECT_EQ("drop.txt", entry.path);
+
+  ASSERT_EQ(0, writer.DiscardLastEntry());
+
+  ASSERT_EQ(0, writer.GetLastEntry(&entry));
+  EXPECT_EQ("keep.txt", entry.path);
+
+  ASSERT_EQ(0, writer.StartEntry("replace.txt", 0));
+  ASSERT_EQ(0, writer.WriteBytes(kReplaceWithThis, strlen(kReplaceWithThis)));
+  ASSERT_EQ(0, writer.FinishEntry());
+
+  ASSERT_EQ(0, writer.GetLastEntry(&entry));
+  EXPECT_EQ("replace.txt", entry.path);
+
+  ASSERT_EQ(0, writer.Finish());
+
+  // Verify that "drop.txt" does not exist.
+
+  ASSERT_GE(0, lseek(fd_, 0, SEEK_SET));
+
+  ZipArchiveHandle handle;
+  ASSERT_EQ(0, OpenArchiveFd(fd_, "temp", &handle, false));
+
+  ZipEntry data;
+  ASSERT_EQ(0, FindEntry(handle, ZipString("keep.txt"), &data));
+  ASSERT_TRUE(AssertFileEntryContentsEq(kKeepThis, handle, &data));
+
+  ASSERT_NE(0, FindEntry(handle, ZipString("drop.txt"), &data));
+
+  ASSERT_EQ(0, FindEntry(handle, ZipString("replace.txt"), &data));
+  ASSERT_TRUE(AssertFileEntryContentsEq(kReplaceWithThis, handle, &data));
+
+  CloseArchive(handle);
+}
+
+TEST_F(zipwriter, TruncateFileAfterBackup) {
+  ZipWriter writer(file_);
+
+  const char* kSmall = "small";
+
+  ASSERT_EQ(0, writer.StartEntry("small.txt", 0));
+  ASSERT_EQ(0, writer.WriteBytes(kSmall, strlen(kSmall)));
+  ASSERT_EQ(0, writer.FinishEntry());
+
+  ASSERT_EQ(0, writer.StartEntry("large.txt", 0));
+  std::vector<uint8_t> data;
+  data.resize(1024*1024, 0xef);
+  ASSERT_EQ(0, writer.WriteBytes(data.data(), data.size()));
+  ASSERT_EQ(0, writer.FinishEntry());
+
+  off_t before_len = ftello(file_);
+
+  ZipWriter::FileEntry entry;
+  ASSERT_EQ(0, writer.GetLastEntry(&entry));
+  ASSERT_EQ(0, writer.DiscardLastEntry());
+
+  ASSERT_EQ(0, writer.Finish());
+
+  off_t after_len = ftello(file_);
+
+  ASSERT_GT(before_len, after_len);
+}
+
+static ::testing::AssertionResult AssertFileEntryContentsEq(const std::string& expected,
+                                                            ZipArchiveHandle handle,
+                                                            ZipEntry* zip_entry) {
+  if (expected.size() != zip_entry->uncompressed_length) {
+    return ::testing::AssertionFailure() << "uncompressed entry size "
+        << zip_entry->uncompressed_length << " does not match expected size " << expected.size();
+  }
+
+  std::string actual;
+  actual.resize(expected.size());
+
+  uint8_t* buffer = reinterpret_cast<uint8_t*>(&*actual.begin());
+  if (ExtractToMemory(handle, zip_entry, buffer, actual.size()) != 0) {
+    return ::testing::AssertionFailure() << "failed to extract entry";
+  }
+
+  if (expected != actual) {
+    return ::testing::AssertionFailure() << "actual zip_entry data '" << actual
+        << "' does not match expected '" << expected << "'";
+  }
+  return ::testing::AssertionSuccess();
+}
diff --git a/lmkd/Android.bp b/lmkd/Android.bp
new file mode 100644
index 0000000..3f8a503
--- /dev/null
+++ b/lmkd/Android.bp
@@ -0,0 +1,13 @@
+cc_binary {
+    name: "lmkd",
+
+    srcs: ["lmkd.c"],
+    shared_libs: [
+        "liblog",
+        "libprocessgroup",
+        "libcutils",
+    ],
+    cflags: ["-Werror"],
+
+    init_rc: ["lmkd.rc"],
+}
diff --git a/lmkd/Android.mk b/lmkd/Android.mk
deleted file mode 100644
index 8980d1c..0000000
--- a/lmkd/Android.mk
+++ /dev/null
@@ -1,12 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := lmkd.c
-LOCAL_SHARED_LIBRARIES := liblog libm libc libprocessgroup libcutils
-LOCAL_CFLAGS := -Werror
-
-LOCAL_MODULE := lmkd
-
-LOCAL_INIT_RC := lmkd.rc
-
-include $(BUILD_EXECUTABLE)
diff --git a/logcat/Android.mk b/logcat/Android.mk
index f564f0f..4e11ca9 100644
--- a/logcat/Android.mk
+++ b/logcat/Android.mk
@@ -15,6 +15,16 @@
 
 include $(CLEAR_VARS)
 
+LOCAL_MODULE := logcatd
+LOCAL_MODULE_TAGS := debug
+LOCAL_SRC_FILES := logcatd_main.cpp event.logtags
+LOCAL_SHARED_LIBRARIES := liblogcat $(logcatLibs)
+LOCAL_CFLAGS := -Werror
+
+include $(BUILD_EXECUTABLE)
+
+include $(CLEAR_VARS)
+
 LOCAL_MODULE := liblogcat
 LOCAL_SRC_FILES := logcat.cpp getopt_long.cpp logcat_system.cpp
 LOCAL_SHARED_LIBRARIES := $(logcatLibs)
diff --git a/logcat/event.logtags b/logcat/event.logtags
index 909f8e2..efcc817 100644
--- a/logcat/event.logtags
+++ b/logcat/event.logtags
@@ -30,12 +30,15 @@
 # 4: Number of allocations
 # 5: Id
 # 6: Percent
+# s: Number of seconds (monotonic time)
 # Default value for data of type int/long is 2 (bytes).
 #
 # TODO: generate ".java" and ".h" files with integer constants from this file.
 
 # These are used for testing, do not modify without updating
 # tests/framework-tests/src/android/util/EventLogFunctionalTest.java.
+# system/core/liblog/tests/liblog_benchmark.cpp
+# system/core/liblog/tests/liblog_test.cpp
 42    answer (to life the universe etc|3)
 314   pi
 2718  e
diff --git a/logcat/logcat.cpp b/logcat/logcat.cpp
index 8134936..64d1d2f 100644
--- a/logcat/logcat.cpp
+++ b/logcat/logcat.cpp
@@ -882,6 +882,7 @@
           { "grep",          required_argument, nullptr, 'e' },
           // hidden and undocumented reserved alias for --max-count
           { "head",          required_argument, nullptr, 'm' },
+          { "help",          no_argument,       nullptr, 'h' },
           { id_str,          required_argument, nullptr, 0 },
           { "last",          no_argument,       nullptr, 'L' },
           { "max-count",     required_argument, nullptr, 'm' },
@@ -900,9 +901,8 @@
         };
         // clang-format on
 
-        ret = getopt_long_r(argc, argv,
-                            ":cdDLt:T:gG:sQf:r:n:v:b:BSpP:m:e:", long_options,
-                            &option_index, &optctx);
+        ret = getopt_long_r(argc, argv, ":cdDhLt:T:gG:sQf:r:n:v:b:BSpP:m:e:",
+                            long_options, &option_index, &optctx);
         if (ret < 0) break;
 
         switch (ret) {
@@ -1304,6 +1304,11 @@
                              "Option -%c needs an argument\n", optctx.optopt);
                 goto exit;
 
+            case 'h':
+                show_help(context);
+                show_format_help(context);
+                goto exit;
+
             default:
                 logcat_panic(context, HELP_TRUE, "Unrecognized Option %c\n",
                              optctx.optopt);
diff --git a/logcat/logcatd.rc b/logcat/logcatd.rc
index b082a64..06cc90d 100644
--- a/logcat/logcatd.rc
+++ b/logcat/logcatd.rc
@@ -34,9 +34,6 @@
 on property:logd.logpersistd.enable=true && property:logd.logpersistd=logcatd
     # all exec/services are called with umask(077), so no gain beyond 0700
     mkdir /data/misc/logd 0700 logd log
-    # logd for write to /data/misc/logd, log group for read from pstore (-L)
-    # b/28788401 b/30041146 b/30612424
-    # exec - logd log -- /system/bin/logcat -L -b ${logd.logpersistd.buffer:-all} -v threadtime -v usec -v printable -D -f /data/misc/logd/logcat -r 1024 -n ${logd.logpersistd.size:-256} --id=${ro.build.id}
     start logcatd
 
 # stop logcatd service and clear data
@@ -57,7 +54,7 @@
     stop logcatd
 
 # logcatd service
-service logcatd /system/bin/logcat -b ${logd.logpersistd.buffer:-all} -v threadtime -v usec -v printable -D -f /data/misc/logd/logcat -r 1024 -n ${logd.logpersistd.size:-256} --id=${ro.build.id}
+service logcatd /system/bin/logcatd -L -b ${logd.logpersistd.buffer:-all} -v threadtime -v usec -v printable -D -f /data/misc/logd/logcat -r 1024 -n ${logd.logpersistd.size:-256} --id=${ro.build.id}
     class late_start
     disabled
     # logd for write to /data/misc/logd, log group for read from log daemon
diff --git a/logcat/logcatd_main.cpp b/logcat/logcatd_main.cpp
new file mode 100644
index 0000000..9109eb1
--- /dev/null
+++ b/logcat/logcatd_main.cpp
@@ -0,0 +1,71 @@
+/*
+ * 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 <signal.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <string>
+#include <vector>
+
+#include <log/logcat.h>
+
+int main(int argc, char** argv, char** envp) {
+    android_logcat_context ctx = create_android_logcat();
+    if (!ctx) return -1;
+
+    signal(SIGPIPE, exit);
+
+    // Save and detect presence of -L or --last flag
+    std::vector<std::string> args;
+    bool last = false;
+    for (int i = 0; i < argc; ++i) {
+        if (!argv[i]) continue;
+        args.push_back(std::string(argv[i]));
+        if (!strcmp(argv[i], "-L") || !strcmp(argv[i], "--last")) last = true;
+    }
+
+    // Generate argv from saved content
+    std::vector<const char*> argv_hold;
+    for (auto& str : args) argv_hold.push_back(str.c_str());
+    argv_hold.push_back(nullptr);
+
+    int ret = 0;
+    if (last) {
+        // Run logcat command with -L flag
+        ret = android_logcat_run_command(ctx, -1, -1, argv_hold.size() - 1,
+                                         (char* const*)&argv_hold[0], envp);
+        // Remove -L and --last flags from argument list
+        for (std::vector<const char*>::iterator it = argv_hold.begin();
+             it != argv_hold.end();) {
+            if (!*it || (strcmp(*it, "-L") && strcmp(*it, "--last"))) {
+                ++it;
+            } else {
+                it = argv_hold.erase(it);
+            }
+        }
+        // fall through to re-run the command regardless of the arguments
+        // passed in.  For instance, we expect -h to report help stutter.
+    }
+
+    // Run logcat command without -L flag
+    int retval = android_logcat_run_command(ctx, -1, -1, argv_hold.size() - 1,
+                                            (char* const*)&argv_hold[0], envp);
+    if (!ret) ret = retval;
+    retval = android_logcat_destroy(&ctx);
+    if (!ret) ret = retval;
+    return ret;
+}
diff --git a/logcat/tests/Android.mk b/logcat/tests/Android.mk
index 22aca17..defd3c4 100644
--- a/logcat/tests/Android.mk
+++ b/logcat/tests/Android.mk
@@ -50,6 +50,7 @@
 
 test_src_files := \
     logcat_test.cpp \
+    logcatd_test.cpp \
     liblogcat_test.cpp \
 
 # Build tests for the device (with .so). Run with:
diff --git a/logcat/tests/logcat_test.cpp b/logcat/tests/logcat_test.cpp
index 0895834..9c07472 100644
--- a/logcat/tests/logcat_test.cpp
+++ b/logcat/tests/logcat_test.cpp
@@ -17,9 +17,11 @@
 #include <ctype.h>
 #include <dirent.h>
 #include <signal.h>
+#include <stdint.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <sys/cdefs.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <sys/wait.h>
@@ -30,6 +32,7 @@
 
 #include <android-base/file.h>
 #include <gtest/gtest.h>
+#include <log/event_tag_map.h>
 #include <log/log.h>
 #include <log/log_event_list.h>
 
@@ -39,9 +42,23 @@
 #define logcat_pclose(context, fp) pclose(fp)
 #define logcat_system(command) system(command)
 #endif
+#ifndef logcat_executable
+#define USING_LOGCAT_EXECUTABLE_DEFAULT
+#define logcat_executable "logcat"
+#endif
 
 #define BIG_BUFFER (5 * 1024)
 
+// rest(), let the logs settle.
+//
+// logd is in a background cgroup and under extreme load can take up to
+// 3 seconds to land a log entry. Under moderate load we can do with 200ms.
+static void rest() {
+    static const useconds_t restPeriod = 200000;
+
+    usleep(restPeriod);
+}
+
 // enhanced version of LOG_FAILURE_RETRY to add support for EAGAIN and
 // non-syscall libs. Since we are only using this in the emergency of
 // a signal to stuff a terminating code into the logs, we will spin rather
@@ -64,14 +81,13 @@
 
 #undef LOG_TAG
 #define LOG_TAG "inject"
-    RLOGE("logcat.buckets");
-    sleep(1);
+    RLOGE(logcat_executable ".buckets");
+    rest();
 
-    ASSERT_TRUE(
-        NULL !=
-        (fp = logcat_popen(
-             ctx,
-             "logcat -b radio -b events -b system -b main -d 2>/dev/null")));
+    ASSERT_TRUE(NULL !=
+                (fp = logcat_popen(
+                     ctx, logcat_executable
+                     " -b radio -b events -b system -b main -d 2>/dev/null")));
 
     char buffer[BIG_BUFFER];
 
@@ -101,8 +117,8 @@
     logcat_define(ctx);
 
     ASSERT_TRUE(NULL !=
-                (fp = logcat_popen(ctx,
-                                   "logcat -b events -d -s auditd "
+                (fp = logcat_popen(ctx, logcat_executable
+                                   " -b events -d -s auditd "
                                    "am_proc_start am_pss am_proc_bound "
                                    "dvm_lock_sample am_wtf 2>/dev/null")));
 
@@ -170,10 +186,9 @@
 #endif
         strftime(needle, sizeof(needle), "[ %Y-", ptm);
 
-        ASSERT_TRUE(
-            NULL !=
-            (fp = logcat_popen(
-                 ctx, "logcat -v long -v year -b all -t 3 2>/dev/null")));
+        ASSERT_TRUE(NULL != (fp = logcat_popen(
+                                 ctx, logcat_executable
+                                 " -v long -v year -b all -t 3 2>/dev/null")));
 
         char buffer[BIG_BUFFER];
 
@@ -237,8 +252,8 @@
         logcat_define(ctx);
 
         ASSERT_TRUE(NULL !=
-                    (fp = logcat_popen(ctx,
-                                       "logcat -v long -v America/Los_Angeles "
+                    (fp = logcat_popen(ctx, logcat_executable
+                                       " -v long -v America/Los_Angeles "
                                        "-b all -t 3 2>/dev/null")));
 
         char buffer[BIG_BUFFER];
@@ -264,10 +279,9 @@
     FILE* fp;
     logcat_define(ctx);
 
-    ASSERT_TRUE(NULL !=
-                (fp = logcat_popen(ctx,
-                                   "logcat -v long -v America/Los_Angeles -v "
-                                   "zone -b all -t 3 2>/dev/null")));
+    ASSERT_TRUE(NULL != (fp = logcat_popen(ctx, logcat_executable
+                                           " -v long -v America/Los_Angeles -v "
+                                           "zone -b all -t 3 2>/dev/null")));
 
     char buffer[BIG_BUFFER];
 
@@ -435,11 +449,11 @@
 }
 
 TEST(logcat, tail_time) {
-    do_tail_time("logcat -v long -v nsec -b all");
+    do_tail_time(logcat_executable " -v long -v nsec -b all");
 }
 
 TEST(logcat, tail_time_epoch) {
-    do_tail_time("logcat -v long -v nsec -v epoch -b all");
+    do_tail_time(logcat_executable " -v long -v nsec -v epoch -b all");
 }
 
 TEST(logcat, End_to_End) {
@@ -452,8 +466,8 @@
     FILE* fp;
     logcat_define(ctx);
     ASSERT_TRUE(NULL !=
-                (fp = logcat_popen(
-                     ctx, "logcat -v brief -b events -t 100 2>/dev/null")));
+                (fp = logcat_popen(ctx, logcat_executable
+                                   " -v brief -b events -t 100 2>/dev/null")));
 
     char buffer[BIG_BUFFER];
 
@@ -479,6 +493,56 @@
     ASSERT_EQ(1, count);
 }
 
+TEST(logcat, End_to_End_multitude) {
+    pid_t pid = getpid();
+
+    log_time ts(CLOCK_MONOTONIC);
+
+    ASSERT_LT(0, __android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts)));
+
+    FILE* fp[256];  // does this count as a multitude!
+    memset(fp, 0, sizeof(fp));
+    logcat_define(ctx[sizeof(fp) / sizeof(fp[0])]);
+    size_t num = 0;
+    do {
+        EXPECT_TRUE(NULL !=
+                    (fp[num] = logcat_popen(ctx[num], logcat_executable
+                                            " -v brief -b events -t 100")));
+        if (!fp[num]) {
+            fprintf(stderr,
+                    "WARNING: limiting to %zu simultaneous logcat operations\n",
+                    num);
+            break;
+        }
+    } while (++num < sizeof(fp) / sizeof(fp[0]));
+
+    char buffer[BIG_BUFFER];
+
+    size_t count = 0;
+
+    for (size_t idx = 0; idx < sizeof(fp) / sizeof(fp[0]); ++idx) {
+        if (!fp[idx]) break;
+        while (fgets(buffer, sizeof(buffer), fp[idx])) {
+            int p;
+            unsigned long long t;
+
+            if ((2 != sscanf(buffer, "I/[0]     ( %d): %llu", &p, &t)) ||
+                (p != pid)) {
+                continue;
+            }
+
+            log_time tx((const char*)&t);
+            if (ts == tx) {
+                ++count;
+            }
+        }
+
+        logcat_pclose(ctx[idx], fp[idx]);
+    }
+
+    ASSERT_EQ(num, count);
+}
+
 static int get_groups(const char* cmd) {
     FILE* fp;
     logcat_define(ctx);
@@ -554,22 +618,23 @@
 }
 
 TEST(logcat, get_size) {
-    ASSERT_EQ(4, get_groups("logcat -v brief -b radio -b events -b system -b "
+    ASSERT_EQ(4, get_groups(logcat_executable
+                            " -v brief -b radio -b events -b system -b "
                             "main -g 2>/dev/null"));
 }
 
 // duplicate test for get_size, but use comma-separated list of buffers
 TEST(logcat, multiple_buffer) {
     ASSERT_EQ(
-        4, get_groups(
-               "logcat -v brief -b radio,events,system,main -g 2>/dev/null"));
+        4, get_groups(logcat_executable
+                      " -v brief -b radio,events,system,main -g 2>/dev/null"));
 }
 
 TEST(logcat, bad_buffer) {
-    ASSERT_EQ(
-        0,
-        get_groups(
-            "logcat -v brief -b radio,events,bogo,system,main -g 2>/dev/null"));
+    ASSERT_EQ(0,
+              get_groups(
+                  logcat_executable
+                  " -v brief -b radio,events,bogo,system,main -g 2>/dev/null"));
 }
 
 #ifndef logcat
@@ -724,8 +789,8 @@
     char buf[sizeof(form)];
     ASSERT_TRUE(NULL != mkdtemp(strcpy(buf, form)));
 
-    static const char comm[] =
-        "logcat -b radio -b events -b system -b main"
+    static const char comm[] = logcat_executable
+        " -b radio -b events -b system -b main"
         " -d -f %s/log.txt -n 7 -r 1";
     char command[sizeof(buf) + sizeof(comm)];
     snprintf(command, sizeof(command), comm, buf);
@@ -770,8 +835,8 @@
     char tmp_out_dir[sizeof(tmp_out_dir_form)];
     ASSERT_TRUE(NULL != mkdtemp(strcpy(tmp_out_dir, tmp_out_dir_form)));
 
-    static const char logcat_cmd[] =
-        "logcat -b radio -b events -b system -b main"
+    static const char logcat_cmd[] = logcat_executable
+        " -b radio -b events -b system -b main"
         " -d -f %s/log.txt -n 10 -r 1";
     char command[sizeof(tmp_out_dir) + sizeof(logcat_cmd)];
     snprintf(command, sizeof(command), logcat_cmd, tmp_out_dir);
@@ -830,7 +895,7 @@
 
     static const char log_filename[] = "log.txt";
     static const char logcat_cmd[] =
-        "logcat -b all -v nsec -d -f %s/%s -n 256 -r 1024";
+        logcat_executable " -b all -v nsec -d -f %s/%s -n 256 -r 1024";
     static const char cleanup_cmd[] = "rm -rf %s";
     char command[sizeof(tmp_out_dir) + sizeof(logcat_cmd) + sizeof(log_filename)];
     snprintf(command, sizeof(command), logcat_cmd, tmp_out_dir, log_filename);
@@ -955,7 +1020,8 @@
 
     static const char log_filename[] = "log.txt";
     static const unsigned num_val = 32;
-    static const char logcat_cmd[] = "logcat -b all -d -f %s/%s -n %d -r 1";
+    static const char logcat_cmd[] =
+        logcat_executable " -b all -d -f %s/%s -n %d -r 1";
     static const char clear_cmd[] = " -c";
     static const char cleanup_cmd[] = "rm -rf %s";
     char command[sizeof(tmp_out_dir) + sizeof(logcat_cmd) +
@@ -1059,9 +1125,9 @@
 
 TEST(logcat, logrotate_id) {
     static const char logcat_cmd[] =
-        "logcat -b all -d -f %s/%s -n 32 -r 1 --id=test";
+        logcat_executable " -b all -d -f %s/%s -n 32 -r 1 --id=test";
     static const char logcat_short_cmd[] =
-        "logcat -b all -t 10 -f %s/%s -n 32 -r 1 --id=test";
+        logcat_executable " -b all -t 10 -f %s/%s -n 32 -r 1 --id=test";
     static const char tmp_out_dir_form[] =
         "/data/local/tmp/logcat.logrotate.XXXXXX";
     static const char log_filename[] = "log.txt";
@@ -1105,8 +1171,8 @@
 
 TEST(logcat, logrotate_nodir) {
     // expect logcat to error out on writing content and not exit(0) for nodir
-    static const char command[] =
-        "logcat -b all -d"
+    static const char command[] = logcat_executable
+        " -b all -d"
         " -f /das/nein/gerfingerpoken/logcat/log.txt"
         " -n 256 -r 1024";
     EXPECT_FALSE(IsFalse(0 == logcat_system(command), command));
@@ -1150,7 +1216,12 @@
     signal(SIGALRM, caught_blocking_clear);
     alarm(2);
     while (fgets(buffer, sizeof(buffer), fp)) {
-        if (!strncmp(buffer, "clearLog: ", 10)) {
+        if (!strncmp(buffer, "clearLog: ", strlen("clearLog: "))) {
+            fprintf(stderr, "WARNING: Test lacks permission to run :-(\n");
+            count = signals = 1;
+            break;
+        }
+        if (!strncmp(buffer, "failed to clear", strlen("failed to clear"))) {
             fprintf(stderr, "WARNING: Test lacks permission to run :-(\n");
             count = signals = 1;
             break;
@@ -1242,7 +1313,7 @@
     FILE* fp;
     logcat_define(ctx);
 
-    fp = logcat_popen(ctx, "logcat -p 2>/dev/null");
+    fp = logcat_popen(ctx, logcat_executable " -p 2>/dev/null");
     if (fp == NULL) {
         fprintf(stderr, "ERROR: logcat -p 2>/dev/null\n");
         return false;
@@ -1280,7 +1351,8 @@
 
     char buffer[BIG_BUFFER];
 
-    snprintf(buffer, sizeof(buffer), "logcat -P '%s' 2>&1", list ? list : "");
+    snprintf(buffer, sizeof(buffer), logcat_executable " -P '%s' 2>&1",
+             list ? list : "");
     fp = logcat_popen(ctx, buffer);
     if (fp == NULL) {
         fprintf(stderr, "ERROR: %s\n", buffer);
@@ -1342,15 +1414,11 @@
     int count = 0;
 
     char buffer[BIG_BUFFER];
-// Have to make liblogcat data unique from logcat data injection
-#ifdef logcat
-#define logcat_regex_prefix "lolcat_test"
-#else
-#define logcat_regex_prefix "logcat_test"
-#endif
+#define logcat_regex_prefix ___STRING(logcat) "_test"
 
     snprintf(buffer, sizeof(buffer),
-             "logcat --pid %d -d -e " logcat_regex_prefix "_a+b", getpid());
+             logcat_executable " --pid %d -d -e " logcat_regex_prefix "_a+b",
+             getpid());
 
     LOG_FAILURE_RETRY(__android_log_print(ANDROID_LOG_WARN, logcat_regex_prefix,
                                           logcat_regex_prefix "_ab"));
@@ -1361,7 +1429,7 @@
     LOG_FAILURE_RETRY(__android_log_print(ANDROID_LOG_WARN, logcat_regex_prefix,
                                           logcat_regex_prefix "_aaaa"));
     // Let the logs settle
-    sleep(1);
+    rest();
 
     ASSERT_TRUE(NULL != (fp = logcat_popen(ctx, buffer)));
 
@@ -1387,8 +1455,8 @@
 
     char buffer[BIG_BUFFER];
 
-    snprintf(buffer, sizeof(buffer), "logcat --pid %d -d --max-count 3",
-             getpid());
+    snprintf(buffer, sizeof(buffer),
+             logcat_executable " --pid %d -d --max-count 3", getpid());
 
     LOG_FAILURE_RETRY(
         __android_log_print(ANDROID_LOG_WARN, "logcat_test", "logcat_test"));
@@ -1399,8 +1467,7 @@
     LOG_FAILURE_RETRY(
         __android_log_print(ANDROID_LOG_WARN, "logcat_test", "logcat_test"));
 
-    // Let the logs settle
-    sleep(1);
+    rest();
 
     ASSERT_TRUE(NULL != (fp = logcat_popen(ctx, buffer)));
 
@@ -1425,8 +1492,7 @@
 
 static bool End_to_End(const char* tag, const char* fmt, ...) {
     logcat_define(ctx);
-    FILE* fp = logcat_popen(ctx,
-                            "logcat"
+    FILE* fp = logcat_popen(ctx, logcat_executable
                             " -v brief"
                             " -b events"
                             " -v descriptive"
@@ -1472,13 +1538,12 @@
         // Help us pinpoint where things went wrong ...
         fprintf(stderr, "Closest match for\n    %s\n  is\n    %s",
                 expect.c_str(), lastMatch.c_str());
-    } else if (count > 2) {
+    } else if (count > 3) {
         fprintf(stderr, "Too many matches (%d) for %s\n", count, expect.c_str());
     }
 
-    // Expect one the first time around as either liblogcat.descriptive or
-    // logcat.descriptive.  Expect two the second time as the other.
-    return count == 1 || count == 2;
+    // Three different known tests, we can see pollution from the others
+    return count && (count <= 3);
 }
 
 TEST(logcat, descriptive) {
@@ -1486,24 +1551,28 @@
         uint32_t tagNo;
         const char* tagStr;
     };
+    int ret;
 
     {
         static const struct tag hhgtg = { 42, "answer" };
         android_log_event_list ctx(hhgtg.tagNo);
         static const char theAnswer[] = "what is five by seven";
         ctx << theAnswer;
-        ctx.write();
+        // crafted to rest at least once after, and rest between retries.
+        for (ret = -EBUSY; ret == -EBUSY; rest()) ret = ctx.write();
+        EXPECT_LE(0, ret);
         EXPECT_TRUE(
             End_to_End(hhgtg.tagStr, "to life the universe etc=%s", theAnswer));
     }
 
     {
         static const struct tag sync = { 2720, "sync" };
-        static const char id[] = "logcat.decriptive";
+        static const char id[] = ___STRING(logcat) ".descriptive-sync";
         {
             android_log_event_list ctx(sync.tagNo);
             ctx << id << (int32_t)42 << (int32_t)-1 << (int32_t)0;
-            ctx.write();
+            for (ret = -EBUSY; ret == -EBUSY; rest()) ret = ctx.write();
+            EXPECT_LE(0, ret);
             EXPECT_TRUE(End_to_End(sync.tagStr,
                                    "[id=%s,event=42,source=-1,account=0]", id));
         }
@@ -1512,7 +1581,8 @@
         {
             android_log_event_list ctx(sync.tagNo);
             ctx << id << (int32_t)43 << (int64_t)-1 << (int32_t)0;
-            ctx.write();
+            for (ret = -EBUSY; ret == -EBUSY; rest()) ret = ctx.write();
+            EXPECT_LE(0, ret);
             EXPECT_TRUE(End_to_End(sync.tagStr, "[id=%s,event=43,-1,0]", id));
         }
 
@@ -1520,7 +1590,8 @@
         {
             android_log_event_list ctx(sync.tagNo);
             ctx << id << (int32_t)44 << (int32_t)-1 << (int64_t)0;
-            ctx.write();
+            for (ret = -EBUSY; ret == -EBUSY; rest()) ret = ctx.write();
+            EXPECT_LE(0, ret);
             fprintf(stderr, "Expect a \"Closest match\" message\n");
             EXPECT_FALSE(End_to_End(
                 sync.tagStr, "[id=%s,event=44,source=-1,account=0]", id));
@@ -1532,7 +1603,8 @@
         {
             android_log_event_list ctx(sync.tagNo);
             ctx << (uint64_t)30 << (int32_t)2;
-            ctx.write();
+            for (ret = -EBUSY; ret == -EBUSY; rest()) ret = ctx.write();
+            EXPECT_LE(0, ret);
             EXPECT_TRUE(
                 End_to_End(sync.tagStr, "[aggregation time=30ms,count=2]"));
         }
@@ -1540,7 +1612,8 @@
         {
             android_log_event_list ctx(sync.tagNo);
             ctx << (uint64_t)31570 << (int32_t)911;
-            ctx.write();
+            for (ret = -EBUSY; ret == -EBUSY; rest()) ret = ctx.write();
+            EXPECT_LE(0, ret);
             EXPECT_TRUE(
                 End_to_End(sync.tagStr, "[aggregation time=31.57s,count=911]"));
         }
@@ -1551,42 +1624,48 @@
         {
             android_log_event_list ctx(sync.tagNo);
             ctx << (uint32_t)512;
-            ctx.write();
+            for (ret = -EBUSY; ret == -EBUSY; rest()) ret = ctx.write();
+            EXPECT_LE(0, ret);
             EXPECT_TRUE(End_to_End(sync.tagStr, "current=512B"));
         }
 
         {
             android_log_event_list ctx(sync.tagNo);
             ctx << (uint32_t)3072;
-            ctx.write();
+            for (ret = -EBUSY; ret == -EBUSY; rest()) ret = ctx.write();
+            EXPECT_LE(0, ret);
             EXPECT_TRUE(End_to_End(sync.tagStr, "current=3KB"));
         }
 
         {
             android_log_event_list ctx(sync.tagNo);
             ctx << (uint32_t)2097152;
-            ctx.write();
+            for (ret = -EBUSY; ret == -EBUSY; rest()) ret = ctx.write();
+            EXPECT_LE(0, ret);
             EXPECT_TRUE(End_to_End(sync.tagStr, "current=2MB"));
         }
 
         {
             android_log_event_list ctx(sync.tagNo);
             ctx << (uint32_t)2097153;
-            ctx.write();
+            for (ret = -EBUSY; ret == -EBUSY; rest()) ret = ctx.write();
+            EXPECT_LE(0, ret);
             EXPECT_TRUE(End_to_End(sync.tagStr, "current=2097153B"));
         }
 
         {
             android_log_event_list ctx(sync.tagNo);
             ctx << (uint32_t)1073741824;
-            ctx.write();
+            for (ret = -EBUSY; ret == -EBUSY; rest()) ret = ctx.write();
+            EXPECT_LE(0, ret);
             EXPECT_TRUE(End_to_End(sync.tagStr, "current=1GB"));
         }
 
         {
             android_log_event_list ctx(sync.tagNo);
             ctx << (uint32_t)3221225472;  // 3MB, but on purpose overflowed
-            ctx.write();
+            for (ret = -EBUSY; ret == -EBUSY; rest()) ret = ctx.write();
+            EXPECT_LE(0, ret);
             EXPECT_TRUE(End_to_End(sync.tagStr, "current=-1GB"));
         }
     }
@@ -1594,9 +1673,52 @@
     {
         static const struct tag sync = { 27501, "notification_panel_hidden" };
         android_log_event_list ctx(sync.tagNo);
-        ctx.write();
+        for (ret = -EBUSY; ret == -EBUSY; rest()) ret = ctx.write();
+        EXPECT_LE(0, ret);
         EXPECT_TRUE(End_to_End(sync.tagStr, ""));
     }
+
+    {
+        // Invent new entries because existing can not serve
+        EventTagMap* map = android_openEventTagMap(nullptr);
+        ASSERT_TRUE(nullptr != map);
+        static const char name[] = ___STRING(logcat) ".descriptive-monotonic";
+        int myTag = android_lookupEventTagNum(map, name, "(new|1|s)",
+                                              ANDROID_LOG_UNKNOWN);
+        android_closeEventTagMap(map);
+        ASSERT_NE(-1, myTag);
+
+        const struct tag sync = { (uint32_t)myTag, name };
+
+        {
+            android_log_event_list ctx(sync.tagNo);
+            ctx << (uint32_t)7;
+            for (ret = -EBUSY; ret == -EBUSY; rest()) ret = ctx.write();
+            EXPECT_LE(0, ret);
+            EXPECT_TRUE(End_to_End(sync.tagStr, "new=7s"));
+        }
+        {
+            android_log_event_list ctx(sync.tagNo);
+            ctx << (uint32_t)62;
+            for (ret = -EBUSY; ret == -EBUSY; rest()) ret = ctx.write();
+            EXPECT_LE(0, ret);
+            EXPECT_TRUE(End_to_End(sync.tagStr, "new=1:02"));
+        }
+        {
+            android_log_event_list ctx(sync.tagNo);
+            ctx << (uint32_t)3673;
+            for (ret = -EBUSY; ret == -EBUSY; rest()) ret = ctx.write();
+            EXPECT_LE(0, ret);
+            EXPECT_TRUE(End_to_End(sync.tagStr, "new=1:01:13"));
+        }
+        {
+            android_log_event_list ctx(sync.tagNo);
+            ctx << (uint32_t)(86400 + 7200 + 180 + 58);
+            for (ret = -EBUSY; ret == -EBUSY; rest()) ret = ctx.write();
+            EXPECT_LE(0, ret);
+            EXPECT_TRUE(End_to_End(sync.tagStr, "new=1d 2:03:58"));
+        }
+    }
 }
 
 static bool reportedSecurity(const char* command) {
@@ -1613,8 +1735,34 @@
 }
 
 TEST(logcat, security) {
-    EXPECT_FALSE(reportedSecurity("logcat -b all -g 2>&1"));
-    EXPECT_TRUE(reportedSecurity("logcat -b security -g 2>&1"));
-    EXPECT_TRUE(reportedSecurity("logcat -b security -c 2>&1"));
-    EXPECT_TRUE(reportedSecurity("logcat -b security -G 256K 2>&1"));
+    EXPECT_FALSE(reportedSecurity(logcat_executable " -b all -g 2>&1"));
+    EXPECT_TRUE(reportedSecurity(logcat_executable " -b security -g 2>&1"));
+    EXPECT_TRUE(reportedSecurity(logcat_executable " -b security -c 2>&1"));
+    EXPECT_TRUE(
+        reportedSecurity(logcat_executable " -b security -G 256K 2>&1"));
+}
+
+static size_t commandOutputSize(const char* command) {
+    logcat_define(ctx);
+    FILE* fp = logcat_popen(ctx, command);
+    if (!fp) return 0;
+
+    std::string ret;
+    if (!android::base::ReadFdToString(fileno(fp), &ret)) return 0;
+    if (logcat_pclose(ctx, fp) != 0) return 0;
+
+    return ret.size();
+}
+
+TEST(logcat, help) {
+    size_t logcatHelpTextSize = commandOutputSize(logcat_executable " -h 2>&1");
+    EXPECT_LT(4096UL, logcatHelpTextSize);
+    size_t logcatLastHelpTextSize =
+        commandOutputSize(logcat_executable " -L -h 2>&1");
+#ifdef USING_LOGCAT_EXECUTABLE_DEFAULT  // logcat and liblogcat
+    EXPECT_EQ(logcatHelpTextSize, logcatLastHelpTextSize);
+#else
+    // logcatd -L -h prints the help twice, as designed.
+    EXPECT_EQ(logcatHelpTextSize * 2, logcatLastHelpTextSize);
+#endif
 }
diff --git a/bootstat/uptime_parser.h b/logcat/tests/logcatd_test.cpp
similarity index 65%
rename from bootstat/uptime_parser.h
rename to logcat/tests/logcatd_test.cpp
index 756ae9b..bb7534e 100644
--- a/bootstat/uptime_parser.h
+++ b/logcat/tests/logcatd_test.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2016 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,16 +14,7 @@
  * limitations under the License.
  */
 
-#ifndef UPTIME_PARSER_H_
-#define UPTIME_PARSER_H_
+#define logcat logcatd
+#define logcat_executable "logcatd"
 
-#include <time.h>
-
-namespace bootstat {
-
-// Returns the number of seconds the system has been on since reboot.
-time_t ParseUptime();
-
-}  // namespace bootstat
-
-#endif  // UPTIME_PARSER_H_
\ No newline at end of file
+#include "logcat_test.cpp"
diff --git a/logd/Android.mk b/logd/Android.mk
index 9211037..fb51992 100644
--- a/logd/Android.mk
+++ b/logd/Android.mk
@@ -2,12 +2,9 @@
 
 include $(CLEAR_VARS)
 
-LOCAL_MODULE:= logd
-
-LOCAL_INIT_RC := logd.rc
+LOCAL_MODULE:= liblogd
 
 LOCAL_SRC_FILES := \
-    main.cpp \
     LogCommand.cpp \
     CommandListener.cpp \
     LogListener.cpp \
@@ -15,6 +12,7 @@
     FlushCommand.cpp \
     LogBuffer.cpp \
     LogBufferElement.cpp \
+    LogBufferInterface.cpp \
     LogTimes.cpp \
     LogStatistics.cpp \
     LogWhiteBlackList.cpp \
@@ -25,12 +23,9 @@
     event.logtags
 
 LOCAL_SHARED_LIBRARIES := \
-    libsysutils \
-    liblog \
-    libcutils \
-    libbase \
-    libpackagelistparser \
-    libcap
+    libbase
+
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)
 
 # This is what we want to do:
 #  event_logtags = $(shell \
@@ -46,6 +41,30 @@
 
 LOCAL_CFLAGS := -Werror $(event_flag)
 
+include $(BUILD_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE:= logd
+
+LOCAL_INIT_RC := logd.rc
+
+LOCAL_SRC_FILES := \
+    main.cpp
+
+LOCAL_STATIC_LIBRARIES := \
+    liblogd
+
+LOCAL_SHARED_LIBRARIES := \
+    libsysutils \
+    liblog \
+    libcutils \
+    libbase \
+    libpackagelistparser \
+    libcap
+
+LOCAL_CFLAGS := -Werror
+
 include $(BUILD_EXECUTABLE)
 
 include $(CLEAR_VARS)
diff --git a/logd/FlushCommand.cpp b/logd/FlushCommand.cpp
index c67d2bf..a9edc3e 100644
--- a/logd/FlushCommand.cpp
+++ b/logd/FlushCommand.cpp
@@ -44,14 +44,14 @@
 // LogTimeEntrys, and spawn a transitory per-client thread to
 // work at filing data to the  socket.
 //
-// global LogTimeEntry::lock() is used to protect access,
+// global LogTimeEntry::wrlock() is used to protect access,
 // reference counts are used to ensure that individual
 // LogTimeEntry lifetime is managed when not protected.
 void FlushCommand::runSocketCommand(SocketClient* client) {
     LogTimeEntry* entry = NULL;
     LastLogTimes& times = mReader.logbuf().mTimes;
 
-    LogTimeEntry::lock();
+    LogTimeEntry::wrlock();
     LastLogTimes::iterator it = times.begin();
     while (it != times.end()) {
         entry = (*it);
diff --git a/logd/LogAudit.cpp b/logd/LogAudit.cpp
index 2d9024a..ee38d1c 100644
--- a/logd/LogAudit.cpp
+++ b/logd/LogAudit.cpp
@@ -277,7 +277,7 @@
             ++cp;
         }
         tid = pid;
-        logbuf->lock();
+        logbuf->wrlock();
         uid = logbuf->pidToUid(pid);
         logbuf->unlock();
         memmove(pidptr, cp, strlen(cp) + 1);
@@ -322,7 +322,7 @@
         pid = tid;
         comm = "auditd";
     } else {
-        logbuf->lock();
+        logbuf->wrlock();
         comm = commfree = logbuf->pidToName(pid);
         logbuf->unlock();
         if (!comm) {
diff --git a/logd/LogBuffer.cpp b/logd/LogBuffer.cpp
index 352fc18..d9ec081 100644
--- a/logd/LogBuffer.cpp
+++ b/logd/LogBuffer.cpp
@@ -43,6 +43,8 @@
 // Default
 #define log_buffer_size(id) mMaxSize[id]
 
+const log_time LogBuffer::pruneMargin(3, 0);
+
 void LogBuffer::init() {
     log_id_for_each(i) {
         mLastSet[i] = false;
@@ -70,7 +72,7 @@
         // as the act of mounting /data would trigger persist.logd.timestamp to
         // be corrected. 1/30 corner case YMMV.
         //
-        pthread_mutex_lock(&mLogElementsLock);
+        rdlock();
         LogBufferElementCollection::iterator it = mLogElements.begin();
         while ((it != mLogElements.end())) {
             LogBufferElement* e = *it;
@@ -85,7 +87,7 @@
             }
             ++it;
         }
-        pthread_mutex_unlock(&mLogElementsLock);
+        unlock();
     }
 
     // We may have been triggered by a SIGHUP. Release any sleeping reader
@@ -93,7 +95,7 @@
     //
     // NB: this is _not_ performed in the context of a SIGHUP, it is
     // performed during startup, and in context of reinit administrative thread
-    LogTimeEntry::lock();
+    LogTimeEntry::wrlock();
 
     LastLogTimes::iterator times = mTimes.begin();
     while (times != mTimes.end()) {
@@ -109,11 +111,11 @@
 
 LogBuffer::LogBuffer(LastLogTimes* times)
     : monotonic(android_log_clockid() == CLOCK_MONOTONIC), mTimes(*times) {
-    pthread_mutex_init(&mLogElementsLock, NULL);
+    pthread_rwlock_init(&mLogElementsLock, nullptr);
 
     log_id_for_each(i) {
-        lastLoggedElements[i] = NULL;
-        droppedElements[i] = NULL;
+        lastLoggedElements[i] = nullptr;
+        droppedElements[i] = nullptr;
     }
 
     init();
@@ -132,11 +134,11 @@
                                  LogBufferElement* last) {
     // is it mostly identical?
     //  if (!elem) return DIFFERENT;
-    unsigned short lenl = elem->getMsgLen();
-    if (!lenl) return DIFFERENT;
+    ssize_t lenl = elem->getMsgLen();
+    if (lenl <= 0) return DIFFERENT;  // value if this represents a chatty elem
     //  if (!last) return DIFFERENT;
-    unsigned short lenr = last->getMsgLen();
-    if (!lenr) return DIFFERENT;
+    ssize_t lenr = last->getMsgLen();
+    if (lenr <= 0) return DIFFERENT;  // value if this represents a chatty elem
     //  if (elem->getLogId() != last->getLogId()) return DIFFERENT;
     if (elem->getUid() != last->getUid()) return DIFFERENT;
     if (elem->getPid() != last->getPid()) return DIFFERENT;
@@ -162,8 +164,6 @@
     }
 
     // audit message (except sequence number) identical?
-    static const char avc[] = "): avc: ";
-
     if (last->isBinary()) {
         if (fastcmp<memcmp>(msgl, msgr, sizeof(android_log_event_string_t) -
                                             sizeof(int32_t)))
@@ -173,6 +173,7 @@
         msgr += sizeof(android_log_event_string_t);
         lenr -= sizeof(android_log_event_string_t);
     }
+    static const char avc[] = "): avc: ";
     const char* avcl = android::strnstr(msgl, lenl, avc);
     if (!avcl) return DIFFERENT;
     lenl -= avcl - msgl;
@@ -180,10 +181,7 @@
     if (!avcr) return DIFFERENT;
     lenr -= avcr - msgr;
     if (lenl != lenr) return DIFFERENT;
-    // TODO: After b/35468874 is addressed, revisit "lenl > strlen(avc)"
-    // condition, it might become superfluous.
-    if (lenl > strlen(avc) &&
-        fastcmp<memcmp>(avcl + strlen(avc), avcr + strlen(avc),
+    if (fastcmp<memcmp>(avcl + strlen(avc), avcr + strlen(avc),
                         lenl - strlen(avc))) {
         return DIFFERENT;
     }
@@ -200,7 +198,7 @@
         new LogBufferElement(log_id, realtime, uid, pid, tid, msg, len);
     if (log_id != LOG_ID_SECURITY) {
         int prio = ANDROID_LOG_INFO;
-        const char* tag = NULL;
+        const char* tag = nullptr;
         if (log_id == LOG_ID_EVENTS) {
             tag = tagToName(elem->getTag());
         } else {
@@ -209,16 +207,15 @@
         }
         if (!__android_log_is_loggable(prio, tag, ANDROID_LOG_VERBOSE)) {
             // Log traffic received to total
-            pthread_mutex_lock(&mLogElementsLock);
-            stats.add(elem);
-            stats.subtract(elem);
-            pthread_mutex_unlock(&mLogElementsLock);
+            wrlock();
+            stats.addTotal(elem);
+            unlock();
             delete elem;
             return -EACCES;
         }
     }
 
-    pthread_mutex_lock(&mLogElementsLock);
+    wrlock();
     LogBufferElement* currentLast = lastLoggedElements[log_id];
     if (currentLast) {
         LogBufferElement* dropped = droppedElements[log_id];
@@ -226,24 +223,24 @@
         //
         // State Init
         //     incoming:
-        //         dropped = NULL
-        //         currentLast = NULL;
+        //         dropped = nullptr
+        //         currentLast = nullptr;
         //         elem = incoming message
         //     outgoing:
-        //         dropped = NULL -> State 0
+        //         dropped = nullptr -> State 0
         //         currentLast = copy of elem
         //         log elem
         // State 0
         //     incoming:
         //         count = 0
-        //         dropped = NULL
+        //         dropped = nullptr
         //         currentLast = copy of last message
         //         elem = incoming message
         //     outgoing: if match != DIFFERENT
         //         dropped = copy of first identical message -> State 1
         //         currentLast = reference to elem
         //     break: if match == DIFFERENT
-        //         dropped = NULL -> State 0
+        //         dropped = nullptr -> State 0
         //         delete copy of last message (incoming currentLast)
         //         currentLast = copy of elem
         //         log elem
@@ -270,7 +267,7 @@
         //             currentLast = reference to elem, sum liblog.
         //     break: if match == DIFFERENT
         //         delete dropped
-        //         dropped = NULL -> State 0
+        //         dropped = nullptr -> State 0
         //         log reference to last held-back (currentLast)
         //         currentLast = copy of elem
         //         log elem
@@ -289,7 +286,7 @@
         //         currentLast = reference to elem
         //     break: if match == DIFFERENT
         //         log dropped (chatty message)
-        //         dropped = NULL -> State 0
+        //         dropped = nullptr -> State 0
         //         log reference to last held-back (currentLast)
         //         currentLast = copy of elem
         //         log elem
@@ -319,15 +316,14 @@
                     // check for overflow
                     if (total >= UINT32_MAX) {
                         log(currentLast);
-                        pthread_mutex_unlock(&mLogElementsLock);
+                        unlock();
                         return len;
                     }
-                    stats.add(currentLast);
-                    stats.subtract(currentLast);
+                    stats.addTotal(currentLast);
                     delete currentLast;
                     swab = total;
                     event->payload.data = htole32(swab);
-                    pthread_mutex_unlock(&mLogElementsLock);
+                    unlock();
                     return len;
                 }
                 if (count == USHRT_MAX) {
@@ -339,13 +335,12 @@
                 }
             }
             if (count) {
-                stats.add(currentLast);
-                stats.subtract(currentLast);
+                stats.addTotal(currentLast);
                 currentLast->setDropped(count);
             }
             droppedElements[log_id] = currentLast;
             lastLoggedElements[log_id] = elem;
-            pthread_mutex_unlock(&mLogElementsLock);
+            unlock();
             return len;
         }
         if (dropped) {         // State 1 or 2
@@ -354,7 +349,7 @@
             } else {           // State 1
                 delete dropped;
             }
-            droppedElements[log_id] = NULL;
+            droppedElements[log_id] = nullptr;
             log(currentLast);  // report last message in the series
         } else {               // State 0
             delete currentLast;
@@ -363,12 +358,12 @@
     lastLoggedElements[log_id] = new LogBufferElement(*elem);
 
     log(elem);
-    pthread_mutex_unlock(&mLogElementsLock);
+    unlock();
 
     return len;
 }
 
-// assumes mLogElementsLock held, owns elem, will look after garbage collection
+// assumes LogBuffer::wrlock() held, owns elem, look after garbage collection
 void LogBuffer::log(LogBufferElement* elem) {
     // cap on how far back we will sort in-place, otherwise append
     static uint32_t too_far_back = 5;  // five seconds
@@ -389,7 +384,7 @@
         bool end_set = false;
         bool end_always = false;
 
-        LogTimeEntry::lock();
+        LogTimeEntry::rdlock();
 
         LastLogTimes::iterator times = mTimes.begin();
         while (times != mTimes.end()) {
@@ -431,7 +426,7 @@
 
 // Prune at most 10% of the log entries or maxPrune, whichever is less.
 //
-// mLogElementsLock must be held when this function is called.
+// LogBuffer::wrlock() must be held when this function is called.
 void LogBuffer::maybePrune(log_id_t id) {
     size_t sizes = stats.sizes(id);
     unsigned long maxSize = log_buffer_size(id);
@@ -655,14 +650,14 @@
 // The third thread is optional, and only gets hit if there was a whitelist
 // and more needs to be pruned against the backstop of the region lock.
 //
-// mLogElementsLock must be held when this function is called.
+// LogBuffer::wrlock() must be held when this function is called.
 //
 bool LogBuffer::prune(log_id_t id, unsigned long pruneRows, uid_t caller_uid) {
-    LogTimeEntry* oldest = NULL;
+    LogTimeEntry* oldest = nullptr;
     bool busy = false;
     bool clearAll = pruneRows == ULONG_MAX;
 
-    LogTimeEntry::lock();
+    LogTimeEntry::rdlock();
 
     // Region locked?
     LastLogTimes::iterator times = mTimes.begin();
@@ -676,6 +671,8 @@
         }
         times++;
     }
+    log_time watermark(log_time::tv_sec_max, log_time::tv_nsec_max);
+    if (oldest) watermark = oldest->mStart - pruneMargin;
 
     LogBufferElementCollection::iterator it;
 
@@ -697,7 +694,7 @@
                 mLastSet[id] = true;
             }
 
-            if (oldest && (oldest->mStart <= element->getRealTime().nsec())) {
+            if (oldest && (watermark <= element->getRealTime())) {
                 busy = true;
                 if (oldest->mTimeout.tv_sec || oldest->mTimeout.tv_nsec) {
                     oldest->triggerReader_Locked();
@@ -789,7 +786,7 @@
         while (it != mLogElements.end()) {
             LogBufferElement* element = *it;
 
-            if (oldest && (oldest->mStart <= element->getRealTime().nsec())) {
+            if (oldest && (watermark <= element->getRealTime())) {
                 busy = true;
                 if (oldest->mTimeout.tv_sec || oldest->mTimeout.tv_nsec) {
                     oldest->triggerReader_Locked();
@@ -943,7 +940,7 @@
             mLastSet[id] = true;
         }
 
-        if (oldest && (oldest->mStart <= element->getRealTime().nsec())) {
+        if (oldest && (watermark <= element->getRealTime())) {
             busy = true;
             if (whitelist) {
                 break;
@@ -987,7 +984,7 @@
                 mLastSet[id] = true;
             }
 
-            if (oldest && (oldest->mStart <= element->getRealTime().nsec())) {
+            if (oldest && (watermark <= element->getRealTime())) {
                 busy = true;
                 if (stats.sizes(id) > (2 * log_buffer_size(id))) {
                     // kick a misbehaving log reader client off the island
@@ -1020,15 +1017,15 @@
             // one entry, not another clear run, so we are looking for
             // the quick side effect of the return value to tell us if
             // we have a _blocked_ reader.
-            pthread_mutex_lock(&mLogElementsLock);
+            wrlock();
             busy = prune(id, 1, uid);
-            pthread_mutex_unlock(&mLogElementsLock);
+            unlock();
             // It is still busy, blocked reader(s), lets kill them all!
             // otherwise, lets be a good citizen and preserve the slow
             // readers and let the clear run (below) deal with determining
             // if we are still blocked and return an error code to caller.
             if (busy) {
-                LogTimeEntry::lock();
+                LogTimeEntry::wrlock();
                 LastLogTimes::iterator times = mTimes.begin();
                 while (times != mTimes.end()) {
                     LogTimeEntry* entry = (*times);
@@ -1041,9 +1038,9 @@
                 LogTimeEntry::unlock();
             }
         }
-        pthread_mutex_lock(&mLogElementsLock);
+        wrlock();
         busy = prune(id, ULONG_MAX, uid);
-        pthread_mutex_unlock(&mLogElementsLock);
+        unlock();
         if (!busy || !--retry) {
             break;
         }
@@ -1054,9 +1051,9 @@
 
 // get the used space associated with "id".
 unsigned long LogBuffer::getSizeUsed(log_id_t id) {
-    pthread_mutex_lock(&mLogElementsLock);
+    rdlock();
     size_t retval = stats.sizes(id);
-    pthread_mutex_unlock(&mLogElementsLock);
+    unlock();
     return retval;
 }
 
@@ -1066,44 +1063,50 @@
     if (!__android_logger_valid_buffer_size(size)) {
         return -1;
     }
-    pthread_mutex_lock(&mLogElementsLock);
+    wrlock();
     log_buffer_size(id) = size;
-    pthread_mutex_unlock(&mLogElementsLock);
+    unlock();
     return 0;
 }
 
 // get the total space allocated to "id"
 unsigned long LogBuffer::getSize(log_id_t id) {
-    pthread_mutex_lock(&mLogElementsLock);
+    rdlock();
     size_t retval = log_buffer_size(id);
-    pthread_mutex_unlock(&mLogElementsLock);
+    unlock();
     return retval;
 }
 
-log_time LogBuffer::flushTo(
-    SocketClient* reader, const log_time& start, bool privileged, bool security,
-    int (*filter)(const LogBufferElement* element, void* arg), void* arg) {
+log_time LogBuffer::flushTo(SocketClient* reader, const log_time& start,
+                            pid_t* lastTid, bool privileged, bool security,
+                            int (*filter)(const LogBufferElement* element,
+                                          void* arg),
+                            void* arg) {
     LogBufferElementCollection::iterator it;
     uid_t uid = reader->getUid();
 
-    pthread_mutex_lock(&mLogElementsLock);
+    rdlock();
 
     if (start == log_time::EPOCH) {
         // client wants to start from the beginning
         it = mLogElements.begin();
     } else {
-        LogBufferElementCollection::iterator last = mLogElements.begin();
-        // 30 second limit to continue search for out-of-order entries.
-        log_time min = start - log_time(30, 0);
+        // 3 second limit to continue search for out-of-order entries.
+        log_time min = start - pruneMargin;
+
+        // Cap to 300 iterations we look back for out-of-order entries.
+        size_t count = 300;
+
         // Client wants to start from some specified time. Chances are
         // we are better off starting from the end of the time sorted list.
-        for (it = mLogElements.end(); it != mLogElements.begin();
+        LogBufferElementCollection::iterator last;
+        for (last = it = mLogElements.end(); it != mLogElements.begin();
              /* do nothing */) {
             --it;
             LogBufferElement* element = *it;
             if (element->getRealTime() > start) {
                 last = it;
-            } else if (element->getRealTime() < min) {
+            } else if (!--count || (element->getRealTime() < min)) {
                 break;
             }
         }
@@ -1111,13 +1114,23 @@
     }
 
     log_time max = start;
-    // Help detect if the valid message before is from the same source so
-    // we can differentiate chatty filter types.
-    pid_t lastTid[LOG_ID_MAX] = { 0 };
 
+    LogBufferElement* lastElement = nullptr;  // iterator corruption paranoia
+    static const size_t maxSkip = 4194304;    // maximum entries to skip
+    size_t skip = maxSkip;
     for (; it != mLogElements.end(); ++it) {
         LogBufferElement* element = *it;
 
+        if (!--skip) {
+            android::prdebug("reader.per: too many elements skipped");
+            break;
+        }
+        if (element == lastElement) {
+            android::prdebug("reader.per: identical elements");
+            break;
+        }
+        lastElement = element;
+
         if (!privileged && (element->getUid() != uid)) {
             continue;
         }
@@ -1130,7 +1143,7 @@
             continue;
         }
 
-        // NB: calling out to another object with mLogElementsLock held (safe)
+        // NB: calling out to another object with wrlock() held (safe)
         if (filter) {
             int ret = (*filter)(element, arg);
             if (ret == false) {
@@ -1141,16 +1154,19 @@
             }
         }
 
-        bool sameTid = lastTid[element->getLogId()] == element->getTid();
-        // Dropped (chatty) immediately following a valid log from the
-        // same source in the same log buffer indicates we have a
-        // multiple identical squash.  chatty that differs source
-        // is due to spam filter.  chatty to chatty of different
-        // source is also due to spam filter.
-        lastTid[element->getLogId()] =
-            (element->getDropped() && !sameTid) ? 0 : element->getTid();
+        bool sameTid = false;
+        if (lastTid) {
+            sameTid = lastTid[element->getLogId()] == element->getTid();
+            // Dropped (chatty) immediately following a valid log from the
+            // same source in the same log buffer indicates we have a
+            // multiple identical squash.  chatty that differs source
+            // is due to spam filter.  chatty to chatty of different
+            // source is also due to spam filter.
+            lastTid[element->getLogId()] =
+                (element->getDropped() && !sameTid) ? 0 : element->getTid();
+        }
 
-        pthread_mutex_unlock(&mLogElementsLock);
+        unlock();
 
         // range locking in LastLogTimes looks after us
         max = element->flushTo(reader, this, privileged, sameTid);
@@ -1159,20 +1175,21 @@
             return max;
         }
 
-        pthread_mutex_lock(&mLogElementsLock);
+        skip = maxSkip;
+        rdlock();
     }
-    pthread_mutex_unlock(&mLogElementsLock);
+    unlock();
 
     return max;
 }
 
 std::string LogBuffer::formatStatistics(uid_t uid, pid_t pid,
                                         unsigned int logMask) {
-    pthread_mutex_lock(&mLogElementsLock);
+    wrlock();
 
     std::string ret = stats.format(uid, pid, logMask);
 
-    pthread_mutex_unlock(&mLogElementsLock);
+    unlock();
 
     return ret;
 }
diff --git a/logd/LogBuffer.h b/logd/LogBuffer.h
index fcf6b9a..e597754 100644
--- a/logd/LogBuffer.h
+++ b/logd/LogBuffer.h
@@ -27,6 +27,7 @@
 #include <sysutils/SocketClient.h>
 
 #include "LogBufferElement.h"
+#include "LogBufferInterface.h"
 #include "LogStatistics.h"
 #include "LogTags.h"
 #include "LogTimes.h"
@@ -74,9 +75,9 @@
 
 typedef std::list<LogBufferElement*> LogBufferElementCollection;
 
-class LogBuffer {
+class LogBuffer : public LogBufferInterface {
     LogBufferElementCollection mLogElements;
-    pthread_mutex_t mLogElementsLock;
+    pthread_rwlock_t mLogElementsLock;
 
     LogStatistics stats;
 
@@ -107,19 +108,23 @@
     LastLogTimes& mTimes;
 
     explicit LogBuffer(LastLogTimes* times);
-    ~LogBuffer();
+    ~LogBuffer() override;
     void init();
     bool isMonotonic() {
         return monotonic;
     }
 
     int log(log_id_t log_id, log_time realtime, uid_t uid, pid_t pid, pid_t tid,
-            const char* msg, unsigned short len);
+            const char* msg, unsigned short len) override;
+    // lastTid is an optional context to help detect if the last previous
+    // valid message was from the same source so we can differentiate chatty
+    // filter types (identical or expired)
     log_time flushTo(SocketClient* writer, const log_time& start,
+                     pid_t* lastTid,  // &lastTid[LOG_ID_MAX] or nullptr
                      bool privileged, bool security,
                      int (*filter)(const LogBufferElement* element,
-                                   void* arg) = NULL,
-                     void* arg = NULL);
+                                   void* arg) = nullptr,
+                     void* arg = nullptr);
 
     bool clear(log_id_t id, uid_t uid = AID_ROOT);
     unsigned long getSize(log_id_t id);
@@ -150,7 +155,7 @@
         return tags.tagToName(tag);
     }
 
-    // helper must be protected directly or implicitly by lock()/unlock()
+    // helper must be protected directly or implicitly by wrlock()/unlock()
     const char* pidToName(pid_t pid) {
         return stats.pidToName(pid);
     }
@@ -160,16 +165,20 @@
     const char* uidToName(uid_t uid) {
         return stats.uidToName(uid);
     }
-    void lock() {
-        pthread_mutex_lock(&mLogElementsLock);
+    void wrlock() {
+        pthread_rwlock_wrlock(&mLogElementsLock);
+    }
+    void rdlock() {
+        pthread_rwlock_rdlock(&mLogElementsLock);
     }
     void unlock() {
-        pthread_mutex_unlock(&mLogElementsLock);
+        pthread_rwlock_unlock(&mLogElementsLock);
     }
 
    private:
     static constexpr size_t minPrune = 4;
     static constexpr size_t maxPrune = 256;
+    static const log_time pruneMargin;
 
     void maybePrune(log_id_t id);
     bool prune(log_id_t id, unsigned long pruneRows, uid_t uid = AID_ROOT);
diff --git a/logd/LogBufferElement.cpp b/logd/LogBufferElement.cpp
index 81356fe..381c974 100644
--- a/logd/LogBufferElement.cpp
+++ b/logd/LogBufferElement.cpp
@@ -121,7 +121,7 @@
     }
 
     static const char format_uid[] = "uid=%u%s%s %s %u line%s";
-    parent->lock();
+    parent->wrlock();
     const char* name = parent->uidToName(mUid);
     parent->unlock();
     const char* commName = android::tidToName(mTid);
@@ -129,7 +129,7 @@
         commName = android::tidToName(mPid);
     }
     if (!commName) {
-        parent->lock();
+        parent->wrlock();
         commName = parent->pidToName(mPid);
         parent->unlock();
     }
@@ -235,7 +235,9 @@
     }
     iovec[1].iov_len = entry.len;
 
-    log_time retval = reader->sendDatav(iovec, 2) ? FLUSH_ERROR : mRealTime;
+    log_time retval = reader->sendDatav(iovec, 1 + (entry.len != 0))
+                          ? FLUSH_ERROR
+                          : mRealTime;
 
     if (buffer) free(buffer);
 
diff --git a/bootstat/uptime_parser.h b/logd/LogBufferInterface.cpp
similarity index 65%
copy from bootstat/uptime_parser.h
copy to logd/LogBufferInterface.cpp
index 756ae9b..3cb2b89 100644
--- a/bootstat/uptime_parser.h
+++ b/logd/LogBufferInterface.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2016 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,16 +14,9 @@
  * limitations under the License.
  */
 
-#ifndef UPTIME_PARSER_H_
-#define UPTIME_PARSER_H_
+#include "LogBufferInterface.h"
 
-#include <time.h>
-
-namespace bootstat {
-
-// Returns the number of seconds the system has been on since reboot.
-time_t ParseUptime();
-
-}  // namespace bootstat
-
-#endif  // UPTIME_PARSER_H_
\ No newline at end of file
+LogBufferInterface::LogBufferInterface() {
+}
+LogBufferInterface::~LogBufferInterface() {
+}
\ No newline at end of file
diff --git a/logd/LogBufferInterface.h b/logd/LogBufferInterface.h
new file mode 100644
index 0000000..7d82b91
--- /dev/null
+++ b/logd/LogBufferInterface.h
@@ -0,0 +1,40 @@
+/*
+ * 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.
+ */
+
+#ifndef _LOGD_LOG_BUFFER_INTERFACE_H__
+#define _LOGD_LOG_BUFFER_INTERFACE_H__
+
+#include <sys/types.h>
+
+#include <android-base/macros.h>
+#include <log/log_id.h>
+#include <log/log_time.h>
+
+// Abstract interface that handles log when log available.
+class LogBufferInterface {
+   public:
+    LogBufferInterface();
+    virtual ~LogBufferInterface();
+    // Handles a log entry when available in LogListener.
+    // Returns the size of the handled log message.
+    virtual int log(log_id_t log_id, log_time realtime, uid_t uid, pid_t pid,
+                    pid_t tid, const char* msg, unsigned short len) = 0;
+
+   private:
+    DISALLOW_COPY_AND_ASSIGN(LogBufferInterface);
+};
+
+#endif  // _LOGD_LOG_BUFFER_INTERFACE_H__
diff --git a/logd/LogKlog.cpp b/logd/LogKlog.cpp
index 9dfa14e..a7e7208 100644
--- a/logd/LogKlog.cpp
+++ b/logd/LogKlog.cpp
@@ -37,46 +37,49 @@
 
 static const char priority_message[] = { KMSG_PRIORITY(LOG_INFO), '\0' };
 
+// List of the _only_ needles we supply here to android::strnstr
+static const char suspendStr[] = "PM: suspend entry ";
+static const char resumeStr[] = "PM: suspend exit ";
+static const char suspendedStr[] = "Suspended for ";
+static const char healthdStr[] = "healthd";
+static const char batteryStr[] = ": battery ";
+static const char auditStr[] = " audit(";
+static const char klogdStr[] = "logd.klogd: ";
+
 // Parsing is hard
 
 // called if we see a '<', s is the next character, returns pointer after '>'
-static char* is_prio(char* s, size_t len) {
-    if (!len || !isdigit(*s++)) {
-        return NULL;
-    }
+static char* is_prio(char* s, ssize_t len) {
+    if ((len <= 0) || !isdigit(*s++)) return nullptr;
     --len;
     static const size_t max_prio_len = (len < 4) ? len : 4;
     size_t priolen = 0;
     char c;
     while (((c = *s++)) && (++priolen <= max_prio_len)) {
-        if (!isdigit(c)) {
-            return ((c == '>') && (*s == '[')) ? s : NULL;
-        }
+        if (!isdigit(c)) return ((c == '>') && (*s == '[')) ? s : nullptr;
     }
-    return NULL;
+    return nullptr;
 }
 
 // called if we see a '[', s is the next character, returns pointer after ']'
-static char* is_timestamp(char* s, size_t len) {
-    while (len && (*s == ' ')) {
+static char* is_timestamp(char* s, ssize_t len) {
+    while ((len > 0) && (*s == ' ')) {
         ++s;
         --len;
     }
-    if (!len || !isdigit(*s++)) {
-        return NULL;
-    }
+    if ((len <= 0) || !isdigit(*s++)) return nullptr;
     --len;
     bool first_period = true;
     char c;
-    while (len && ((c = *s++))) {
+    while ((len > 0) && ((c = *s++))) {
         --len;
         if ((c == '.') && first_period) {
             first_period = false;
         } else if (!isdigit(c)) {
-            return ((c == ']') && !first_period && (*s == ' ')) ? s : NULL;
+            return ((c == ']') && !first_period && (*s == ' ')) ? s : nullptr;
         }
     }
-    return NULL;
+    return nullptr;
 }
 
 // Like strtok_r with "\r\n" except that we look for log signatures (regex)
@@ -93,96 +96,82 @@
 // space is one more than <digit> of 9
 #define OPEN_BRACKET_SPACE ((char)(OPEN_BRACKET_SIG | 10))
 
-char* log_strntok_r(char* s, size_t* len, char** last, size_t* sublen) {
-    *sublen = 0;
-    if (!*len) {
-        return NULL;
-    }
+char* android::log_strntok_r(char* s, ssize_t& len, char*& last,
+                             ssize_t& sublen) {
+    sublen = 0;
+    if (len <= 0) return nullptr;
     if (!s) {
-        if (!(s = *last)) {
-            return NULL;
-        }
+        if (!(s = last)) return nullptr;
         // fixup for log signature split <,
         // LESS_THAN_SIG + <digit>
         if ((*s & SIGNATURE_MASK) == LESS_THAN_SIG) {
             *s = (*s & ~SIGNATURE_MASK) + '0';
             *--s = '<';
-            ++*len;
+            ++len;
         }
         // fixup for log signature split [,
         // OPEN_BRACKET_SPACE is space, OPEN_BRACKET_SIG + <digit>
         if ((*s & SIGNATURE_MASK) == OPEN_BRACKET_SIG) {
-            if (*s == OPEN_BRACKET_SPACE) {
-                *s = ' ';
-            } else {
-                *s = (*s & ~SIGNATURE_MASK) + '0';
-            }
+            *s = (*s == OPEN_BRACKET_SPACE) ? ' ' : (*s & ~SIGNATURE_MASK) + '0';
             *--s = '[';
-            ++*len;
+            ++len;
         }
     }
 
-    while (*len && ((*s == '\r') || (*s == '\n'))) {
+    while ((len > 0) && ((*s == '\r') || (*s == '\n'))) {
         ++s;
-        --*len;
+        --len;
     }
 
-    if (!*len) {
-        *last = NULL;
-        return NULL;
-    }
+    if (len <= 0) return last = nullptr;
     char *peek, *tok = s;
 
     for (;;) {
-        if (*len == 0) {
-            *last = NULL;
+        if (len <= 0) {
+            last = nullptr;
             return tok;
         }
         char c = *s++;
-        --*len;
-        size_t adjust;
+        --len;
+        ssize_t adjust;
         switch (c) {
             case '\r':
             case '\n':
                 s[-1] = '\0';
-                *last = s;
+                last = s;
                 return tok;
 
             case '<':
-                peek = is_prio(s, *len);
-                if (!peek) {
-                    break;
-                }
+                peek = is_prio(s, len);
+                if (!peek) break;
                 if (s != (tok + 1)) {  // not first?
                     s[-1] = '\0';
                     *s &= ~SIGNATURE_MASK;
                     *s |= LESS_THAN_SIG;  // signature for '<'
-                    *last = s;
+                    last = s;
                     return tok;
                 }
                 adjust = peek - s;
-                if (adjust > *len) {
-                    adjust = *len;
+                if (adjust > len) {
+                    adjust = len;
                 }
-                *sublen += adjust;
-                *len -= adjust;
+                sublen += adjust;
+                len -= adjust;
                 s = peek;
-                if ((*s == '[') && ((peek = is_timestamp(s + 1, *len - 1)))) {
+                if ((*s == '[') && ((peek = is_timestamp(s + 1, len - 1)))) {
                     adjust = peek - s;
-                    if (adjust > *len) {
-                        adjust = *len;
+                    if (adjust > len) {
+                        adjust = len;
                     }
-                    *sublen += adjust;
-                    *len -= adjust;
+                    sublen += adjust;
+                    len -= adjust;
                     s = peek;
                 }
                 break;
 
             case '[':
-                peek = is_timestamp(s, *len);
-                if (!peek) {
-                    break;
-                }
+                peek = is_timestamp(s, len);
+                if (!peek) break;
                 if (s != (tok + 1)) {  // not first?
                     s[-1] = '\0';
                     if (*s == ' ') {
@@ -191,19 +180,19 @@
                         *s &= ~SIGNATURE_MASK;
                         *s |= OPEN_BRACKET_SIG;  // signature for '['
                     }
-                    *last = s;
+                    last = s;
                     return tok;
                 }
                 adjust = peek - s;
-                if (adjust > *len) {
-                    adjust = *len;
+                if (adjust > len) {
+                    adjust = len;
                 }
-                *sublen += adjust;
-                *len -= adjust;
+                sublen += adjust;
+                len -= adjust;
                 s = peek;
                 break;
         }
-        ++*sublen;
+        ++sublen;
     }
     // NOTREACHED
 }
@@ -222,9 +211,10 @@
       initialized(false),
       enableLogging(true),
       auditd(auditd) {
-    static const char klogd_message[] = "%slogd.klogd: %" PRIu64 "\n";
-    char buffer[sizeof(priority_message) + sizeof(klogd_message) + 20 - 4];
-    snprintf(buffer, sizeof(buffer), klogd_message, priority_message,
+    static const char klogd_message[] = "%s%s%" PRIu64 "\n";
+    char buffer[strlen(priority_message) + strlen(klogdStr) +
+                strlen(klogd_message) + 20];
+    snprintf(buffer, sizeof(buffer), klogd_message, priority_message, klogdStr,
              signature.nsec());
     write(fdWrite, buffer, strlen(buffer));
 }
@@ -237,15 +227,15 @@
     }
 
     char buffer[LOGGER_ENTRY_MAX_PAYLOAD];
-    size_t len = 0;
+    ssize_t len = 0;
 
     for (;;) {
         ssize_t retval = 0;
-        if ((sizeof(buffer) - 1 - len) > 0) {
+        if (len < (ssize_t)(sizeof(buffer) - 1)) {
             retval =
                 read(cli->getSocket(), buffer + len, sizeof(buffer) - 1 - len);
         }
-        if ((retval == 0) && (len == 0)) {
+        if ((retval == 0) && (len <= 0)) {
             break;
         }
         if (retval < 0) {
@@ -255,15 +245,16 @@
         bool full = len == (sizeof(buffer) - 1);
         char* ep = buffer + len;
         *ep = '\0';
-        size_t sublen;
-        for (char *ptr = NULL, *tok = buffer;
-             ((tok = log_strntok_r(tok, &len, &ptr, &sublen))); tok = NULL) {
+        ssize_t sublen;
+        for (char *ptr = nullptr, *tok = buffer;
+             !!(tok = android::log_strntok_r(tok, len, ptr, sublen));
+             tok = nullptr) {
             if (((tok + sublen) >= ep) && (retval != 0) && full) {
-                memmove(buffer, tok, sublen);
+                if (sublen > 0) memmove(buffer, tok, sublen);
                 len = sublen;
                 break;
             }
-            if (*tok) {
+            if ((sublen > 0) && *tok) {
                 log(tok, sublen);
             }
         }
@@ -273,9 +264,12 @@
 }
 
 void LogKlog::calculateCorrection(const log_time& monotonic,
-                                  const char* real_string, size_t len) {
+                                  const char* real_string, ssize_t len) {
+    static const char real_format[] = "%Y-%m-%d %H:%M:%S.%09q UTC";
+    if (len < (ssize_t)(strlen(real_format) + 5)) return;
+
     log_time real;
-    const char* ep = real.strptime(real_string, "%Y-%m-%d %H:%M:%S.%09q UTC");
+    const char* ep = real.strptime(real_string, real_format);
     if (!ep || (ep > &real_string[len]) || (real > log_time(CLOCK_REALTIME))) {
         return;
     }
@@ -299,73 +293,50 @@
     }
 }
 
-static const char suspendStr[] = "PM: suspend entry ";
-static const char resumeStr[] = "PM: suspend exit ";
-static const char suspendedStr[] = "Suspended for ";
-
-const char* android::strnstr(const char* s, size_t len, const char* needle) {
-    char c;
-
-    if (!len) return NULL;
-    if ((c = *needle++) != 0) {
-        size_t needleLen = strlen(needle);
-        do {
-            do {
-                if (len <= needleLen) return NULL;
-                --len;
-            } while (*s++ != c);
-        } while (fastcmp<memcmp>(s, needle, needleLen));
-        s--;
-    }
-    return s;
-}
-
-void LogKlog::sniffTime(log_time& now, const char** buf, size_t len,
+void LogKlog::sniffTime(log_time& now, const char*& buf, ssize_t len,
                         bool reverse) {
-    const char* cp = now.strptime(*buf, "[ %s.%q]");
-    if (cp && (cp >= &(*buf)[len])) {
-        cp = NULL;
+    if (len <= 0) return;
+
+    const char* cp = nullptr;
+    if ((len > 10) && (*buf == '[')) {
+        cp = now.strptime(buf, "[ %s.%q]");  // can index beyond buffer bounds
+        if (cp && (cp > &buf[len - 1])) cp = nullptr;
     }
     if (cp) {
-        static const char healthd[] = "healthd";
-        static const char battery[] = ": battery ";
-
-        len -= cp - *buf;
-        if (len && isspace(*cp)) {
+        len -= cp - buf;
+        if ((len > 0) && isspace(*cp)) {
             ++cp;
             --len;
         }
-        *buf = cp;
+        buf = cp;
 
-        if (isMonotonic()) {
-            return;
-        }
+        if (isMonotonic()) return;
 
         const char* b;
         if (((b = android::strnstr(cp, len, suspendStr))) &&
-            ((size_t)((b += sizeof(suspendStr) - 1) - cp) < len)) {
+            (((b += strlen(suspendStr)) - cp) < len)) {
             len -= b - cp;
             calculateCorrection(now, b, len);
         } else if (((b = android::strnstr(cp, len, resumeStr))) &&
-                   ((size_t)((b += sizeof(resumeStr) - 1) - cp) < len)) {
+                   (((b += strlen(resumeStr)) - cp) < len)) {
             len -= b - cp;
             calculateCorrection(now, b, len);
-        } else if (((b = android::strnstr(cp, len, healthd))) &&
-                   ((size_t)((b += sizeof(healthd) - 1) - cp) < len) &&
-                   ((b = android::strnstr(b, len -= b - cp, battery))) &&
-                   ((size_t)((b += sizeof(battery) - 1) - cp) < len)) {
+        } else if (((b = android::strnstr(cp, len, healthdStr))) &&
+                   (((b += strlen(healthdStr)) - cp) < len) &&
+                   ((b = android::strnstr(b, len -= b - cp, batteryStr))) &&
+                   (((b += strlen(batteryStr)) - cp) < len)) {
             // NB: healthd is roughly 150us late, so we use it instead to
             //     trigger a check for ntp-induced or hardware clock drift.
             log_time real(CLOCK_REALTIME);
             log_time mono(CLOCK_MONOTONIC);
             correction = (real < mono) ? log_time::EPOCH : (real - mono);
         } else if (((b = android::strnstr(cp, len, suspendedStr))) &&
-                   ((size_t)((b += sizeof(suspendStr) - 1) - cp) < len)) {
+                   (((b += strlen(suspendStr)) - cp) < len)) {
             len -= b - cp;
             log_time real;
             char* endp;
             real.tv_sec = strtol(b, &endp, 10);
-            if ((*endp == '.') && ((size_t)(endp - b) < len)) {
+            if ((*endp == '.') && ((endp - b) < len)) {
                 unsigned long multiplier = NS_PER_SEC;
                 real.tv_nsec = 0;
                 len -= endp - b;
@@ -394,8 +365,15 @@
     }
 }
 
-pid_t LogKlog::sniffPid(const char** buf, size_t len) {
-    const char* cp = *buf;
+pid_t LogKlog::sniffPid(const char*& buf, ssize_t len) {
+    if (len <= 0) return 0;
+
+    const char* cp = buf;
+    // sscanf does a strlen, let's check if the string is not nul terminated.
+    // pseudo out-of-bounds access since we always have an extra char on buffer.
+    if (((ssize_t)strnlen(cp, len) == len) && cp[len]) {
+        return 0;
+    }
     // HTC kernels with modified printk "c0   1648 "
     if ((len > 9) && (cp[0] == 'c') && isdigit(cp[1]) &&
         (isdigit(cp[2]) || (cp[2] == ' ')) && (cp[3] == ' ')) {
@@ -412,7 +390,7 @@
             int pid = 0;
             char dummy;
             if (sscanf(cp + 4, "%d%c", &pid, &dummy) == 2) {
-                *buf = cp + 10;  // skip-it-all
+                buf = cp + 10;  // skip-it-all
                 return pid;
             }
         }
@@ -434,28 +412,28 @@
 }
 
 // kernel log prefix, convert to a kernel log priority number
-static int parseKernelPrio(const char** buf, size_t len) {
+static int parseKernelPrio(const char*& buf, ssize_t len) {
     int pri = LOG_USER | LOG_INFO;
-    const char* cp = *buf;
-    if (len && (*cp == '<')) {
+    const char* cp = buf;
+    if ((len > 0) && (*cp == '<')) {
         pri = 0;
         while (--len && isdigit(*++cp)) {
             pri = (pri * 10) + *cp - '0';
         }
-        if (len && (*cp == '>')) {
+        if ((len > 0) && (*cp == '>')) {
             ++cp;
         } else {
-            cp = *buf;
+            cp = buf;
             pri = LOG_USER | LOG_INFO;
         }
-        *buf = cp;
+        buf = cp;
     }
     return pri;
 }
 
 // Passed the entire SYSLOG_ACTION_READ_ALL buffer and interpret a
 // compensated start time.
-void LogKlog::synchronize(const char* buf, size_t len) {
+void LogKlog::synchronize(const char* buf, ssize_t len) {
     const char* cp = android::strnstr(buf, len, suspendStr);
     if (!cp) {
         cp = android::strnstr(buf, len, resumeStr);
@@ -471,10 +449,10 @@
     if (*cp == '\n') {
         ++cp;
     }
-    parseKernelPrio(&cp, len - (cp - buf));
+    parseKernelPrio(cp, len - (cp - buf));
 
     log_time now;
-    sniffTime(now, &cp, len - (cp - buf), true);
+    sniffTime(now, cp, len - (cp - buf), true);
 
     const char* suspended = android::strnstr(buf, len, suspendedStr);
     if (!suspended || (suspended > cp)) {
@@ -488,9 +466,9 @@
     if (*cp == '\n') {
         ++cp;
     }
-    parseKernelPrio(&cp, len - (cp - buf));
+    parseKernelPrio(cp, len - (cp - buf));
 
-    sniffTime(now, &cp, len - (cp - buf), true);
+    sniffTime(now, cp, len - (cp - buf), true);
 }
 
 // Convert kernel log priority number into an Android Logger priority number
@@ -523,9 +501,9 @@
     return ANDROID_LOG_INFO;
 }
 
-static const char* strnrchr(const char* s, size_t len, char c) {
-    const char* save = NULL;
-    for (; len; ++s, len--) {
+static const char* strnrchr(const char* s, ssize_t len, char c) {
+    const char* save = nullptr;
+    for (; len > 0; ++s, len--) {
         if (*s == c) {
             save = s;
         }
@@ -566,22 +544,21 @@
 //  logd.klogd:
 // return -1 if message logd.klogd: <signature>
 //
-int LogKlog::log(const char* buf, size_t len) {
-    if (auditd && android::strnstr(buf, len, " audit(")) {
+int LogKlog::log(const char* buf, ssize_t len) {
+    if (auditd && android::strnstr(buf, len, auditStr)) {
         return 0;
     }
 
     const char* p = buf;
-    int pri = parseKernelPrio(&p, len);
+    int pri = parseKernelPrio(p, len);
 
     log_time now;
-    sniffTime(now, &p, len - (p - buf), false);
+    sniffTime(now, p, len - (p - buf), false);
 
     // sniff for start marker
-    const char klogd_message[] = "logd.klogd: ";
-    const char* start = android::strnstr(p, len - (p - buf), klogd_message);
+    const char* start = android::strnstr(p, len - (p - buf), klogdStr);
     if (start) {
-        uint64_t sig = strtoll(start + sizeof(klogd_message) - 1, NULL, 10);
+        uint64_t sig = strtoll(start + strlen(klogdStr), nullptr, 10);
         if (sig == signature.nsec()) {
             if (initialized) {
                 enableLogging = true;
@@ -598,11 +575,11 @@
     }
 
     // Parse pid, tid and uid
-    const pid_t pid = sniffPid(&p, len - (p - buf));
+    const pid_t pid = sniffPid(p, len - (p - buf));
     const pid_t tid = pid;
     uid_t uid = AID_ROOT;
     if (pid) {
-        logbuf->lock();
+        logbuf->wrlock();
         uid = logbuf->pidToUid(pid);
         logbuf->unlock();
     }
@@ -620,11 +597,11 @@
     start = p;
     const char* tag = "";
     const char* etag = tag;
-    size_t taglen = len - (p - buf);
+    ssize_t taglen = len - (p - buf);
     const char* bt = p;
 
     static const char infoBrace[] = "[INFO]";
-    static const size_t infoBraceLen = strlen(infoBrace);
+    static const ssize_t infoBraceLen = strlen(infoBrace);
     if ((taglen >= infoBraceLen) &&
         !fastcmp<strncmp>(p, infoBrace, infoBraceLen)) {
         // <PRI>[<TIME>] "[INFO]"<tag> ":" message
@@ -633,26 +610,26 @@
     }
 
     const char* et;
-    for (et = bt; taglen && *et && (*et != ':') && !isspace(*et);
+    for (et = bt; (taglen > 0) && *et && (*et != ':') && !isspace(*et);
          ++et, --taglen) {
         // skip ':' within [ ... ]
         if (*et == '[') {
-            while (taglen && *et && *et != ']') {
+            while ((taglen > 0) && *et && *et != ']') {
                 ++et;
                 --taglen;
             }
-            if (!taglen) {
+            if (taglen <= 0) {
                 break;
             }
         }
     }
     const char* cp;
-    for (cp = et; taglen && isspace(*cp); ++cp, --taglen) {
+    for (cp = et; (taglen > 0) && isspace(*cp); ++cp, --taglen) {
     }
 
     // Validate tag
-    size_t size = et - bt;
-    if (taglen && size) {
+    ssize_t size = et - bt;
+    if ((taglen > 0) && (size > 0)) {
         if (*cp == ':') {
             // ToDo: handle case insensitive colon separated logging stutter:
             //       <tag> : <tag>: ...
@@ -672,12 +649,12 @@
                 const char* b = cp;
                 cp += size;
                 taglen -= size;
-                while (--taglen && !isspace(*++cp) && (*cp != ':')) {
+                while ((--taglen > 0) && !isspace(*++cp) && (*cp != ':')) {
                 }
                 const char* e;
-                for (e = cp; taglen && isspace(*cp); ++cp, --taglen) {
+                for (e = cp; (taglen > 0) && isspace(*cp); ++cp, --taglen) {
                 }
-                if (taglen && (*cp == ':')) {
+                if ((taglen > 0) && (*cp == ':')) {
                     tag = b;
                     etag = e;
                     p = cp + 1;
@@ -685,7 +662,7 @@
             } else {
                 // what about <PRI>[<TIME>] <tag>_host '<tag><stuff>' : message
                 static const char host[] = "_host";
-                static const size_t hostlen = strlen(host);
+                static const ssize_t hostlen = strlen(host);
                 if ((size > hostlen) &&
                     !fastcmp<strncmp>(bt + size - hostlen, host, hostlen) &&
                     !fastcmp<strncmp>(bt + 1, cp + 1, size - hostlen - 1)) {
@@ -693,12 +670,14 @@
                     cp += size - hostlen;
                     taglen -= size - hostlen;
                     if (*cp == '.') {
-                        while (--taglen && !isspace(*++cp) && (*cp != ':')) {
+                        while ((--taglen > 0) && !isspace(*++cp) &&
+                               (*cp != ':')) {
                         }
                         const char* e;
-                        for (e = cp; taglen && isspace(*cp); ++cp, --taglen) {
+                        for (e = cp; (taglen > 0) && isspace(*cp);
+                             ++cp, --taglen) {
                         }
-                        if (taglen && (*cp == ':')) {
+                        if ((taglen > 0) && (*cp == ':')) {
                             tag = b;
                             etag = e;
                             p = cp + 1;
@@ -711,13 +690,13 @@
         } else {
         // <PRI>[<TIME>] <tag> <stuff>' : message
         twoWord:
-            while (--taglen && !isspace(*++cp) && (*cp != ':')) {
+            while ((--taglen > 0) && !isspace(*++cp) && (*cp != ':')) {
             }
             const char* e;
-            for (e = cp; taglen && isspace(*cp); ++cp, --taglen) {
+            for (e = cp; (taglen > 0) && isspace(*cp); ++cp, --taglen) {
             }
             // Two words
-            if (taglen && (*cp == ':')) {
+            if ((taglen > 0) && (*cp == ':')) {
                 tag = bt;
                 etag = e;
                 p = cp + 1;
@@ -726,13 +705,13 @@
     }  // else no tag
 
     static const char cpu[] = "CPU";
-    static const size_t cpuLen = strlen(cpu);
+    static const ssize_t cpuLen = strlen(cpu);
     static const char warning[] = "WARNING";
-    static const size_t warningLen = strlen(warning);
+    static const ssize_t warningLen = strlen(warning);
     static const char error[] = "ERROR";
-    static const size_t errorLen = strlen(error);
+    static const ssize_t errorLen = strlen(error);
     static const char info[] = "INFO";
-    static const size_t infoLen = strlen(info);
+    static const ssize_t infoLen = strlen(info);
 
     size = etag - tag;
     if ((size <= 1) ||
@@ -756,13 +735,13 @@
     // Mediatek-special printk induced stutter
     const char* mp = strnrchr(tag, taglen, ']');
     if (mp && (++mp < etag)) {
-        size_t s = etag - mp;
+        ssize_t s = etag - mp;
         if (((s + s) < taglen) && !fastcmp<memcmp>(mp, mp - 1 - s, s)) {
             taglen = mp - tag;
         }
     }
     // Deal with sloppy and simplistic harmless p = cp + 1 etc above.
-    if (len < (size_t)(p - buf)) {
+    if (len < (p - buf)) {
         p = &buf[len];
     }
     // skip leading space
@@ -770,12 +749,12 @@
         ++p;
     }
     // truncate trailing space or nuls
-    size_t b = len - (p - buf);
-    while (b && (isspace(p[b - 1]) || !p[b - 1])) {
+    ssize_t b = len - (p - buf);
+    while ((b > 0) && (isspace(p[b - 1]) || !p[b - 1])) {
         --b;
     }
     // trick ... allow tag with empty content to be logged. log() drops empty
-    if (!b && taglen) {
+    if ((b <= 0) && (taglen > 0)) {
         p = " ";
         b = 1;
     }
@@ -787,9 +766,9 @@
         taglen = LOGGER_ENTRY_MAX_PAYLOAD;
     }
     // calculate buffer copy requirements
-    size_t n = 1 + taglen + 1 + b + 1;
+    ssize_t n = 1 + taglen + 1 + b + 1;
     // paranoid sanity check, first two just can not happen ...
-    if ((taglen > n) || (b > n) || (n > USHRT_MAX)) {
+    if ((taglen > n) || (b > n) || (n > (ssize_t)USHRT_MAX) || (n <= 0)) {
         return -EINVAL;
     }
 
diff --git a/logd/LogKlog.h b/logd/LogKlog.h
index 976afc8..bb92dd2 100644
--- a/logd/LogKlog.h
+++ b/logd/LogKlog.h
@@ -20,8 +20,6 @@
 #include <private/android_logger.h>
 #include <sysutils/SocketListener.h>
 
-char* log_strntok_r(char* s, size_t* len, char** saveptr, size_t* sublen);
-
 class LogBuffer;
 class LogReader;
 
@@ -43,8 +41,8 @@
    public:
     LogKlog(LogBuffer* buf, LogReader* reader, int fdWrite, int fdRead,
             bool auditd);
-    int log(const char* buf, size_t len);
-    void synchronize(const char* buf, size_t len);
+    int log(const char* buf, ssize_t len);
+    void synchronize(const char* buf, ssize_t len);
 
     bool isMonotonic() {
         return logbuf->isMonotonic();
@@ -57,10 +55,10 @@
     }
 
    protected:
-    void sniffTime(log_time& now, const char** buf, size_t len, bool reverse);
-    pid_t sniffPid(const char** buf, size_t len);
+    void sniffTime(log_time& now, const char*& buf, ssize_t len, bool reverse);
+    pid_t sniffPid(const char*& buf, ssize_t len);
     void calculateCorrection(const log_time& monotonic, const char* real_string,
-                             size_t len);
+                             ssize_t len);
     virtual bool onDataAvailable(SocketClient* cli);
 };
 
diff --git a/logd/LogListener.cpp b/logd/LogListener.cpp
index dadc75f..709646e 100644
--- a/logd/LogListener.cpp
+++ b/logd/LogListener.cpp
@@ -30,7 +30,7 @@
 #include "LogListener.h"
 #include "LogUtils.h"
 
-LogListener::LogListener(LogBuffer* buf, LogReader* reader)
+LogListener::LogListener(LogBufferInterface* buf, LogReader* reader)
     : SocketListener(getLogSocket(), false), logbuf(buf), reader(reader) {
 }
 
@@ -102,11 +102,14 @@
     // NB: hdr.msg_flags & MSG_TRUNC is not tested, silently passing a
     // truncated message to the logs.
 
-    if (logbuf->log((log_id_t)header->id, header->realtime, cred->uid,
-                    cred->pid, header->tid, msg,
-                    ((size_t)n <= USHRT_MAX) ? (unsigned short)n : USHRT_MAX) >=
-        0) {
-        reader->notifyNewLog();
+    if (logbuf != nullptr) {
+        int res = logbuf->log(
+            (log_id_t)header->id, header->realtime, cred->uid, cred->pid,
+            header->tid, msg,
+            ((size_t)n <= USHRT_MAX) ? (unsigned short)n : USHRT_MAX);
+        if (res > 0 && reader != nullptr) {
+            reader->notifyNewLog();
+        }
     }
 
     return true;
diff --git a/logd/LogListener.h b/logd/LogListener.h
index 2973b8b..e16c5fb 100644
--- a/logd/LogListener.h
+++ b/logd/LogListener.h
@@ -21,11 +21,11 @@
 #include "LogReader.h"
 
 class LogListener : public SocketListener {
-    LogBuffer* logbuf;
+    LogBufferInterface* logbuf;
     LogReader* reader;
 
    public:
-    LogListener(LogBuffer* buf, LogReader* reader);
+    LogListener(LogBufferInterface* buf, LogReader* reader /* nullable */);
 
    protected:
     virtual bool onDataAvailable(SocketClient* cli);
diff --git a/logd/LogReader.cpp b/logd/LogReader.cpp
index 620d4d0..6d69316 100644
--- a/logd/LogReader.cpp
+++ b/logd/LogReader.cpp
@@ -15,6 +15,7 @@
  */
 
 #include <ctype.h>
+#include <inttypes.h>
 #include <poll.h>
 #include <sys/prctl.h>
 #include <sys/socket.h>
@@ -110,7 +111,7 @@
     if (!fastcmp<strncmp>(buffer, "dumpAndClose", 12)) {
         // Allow writer to get some cycles, and wait for pending notifications
         sched_yield();
-        LogTimeEntry::lock();
+        LogTimeEntry::wrlock();
         LogTimeEntry::unlock();
         sched_yield();
         nonBlock = true;
@@ -182,7 +183,7 @@
         } logFindStart(pid, logMask, sequence,
                        logbuf().isMonotonic() && android::isMonotonic(start));
 
-        logbuf().flushTo(cli, sequence, FlushCommand::hasReadLogs(cli),
+        logbuf().flushTo(cli, sequence, nullptr, FlushCommand::hasReadLogs(cli),
                          FlushCommand::hasSecurityLogs(cli),
                          logFindStart.callback, &logFindStart);
 
@@ -192,6 +193,12 @@
         }
     }
 
+    android::prdebug(
+        "logdr: UID=%d GID=%d PID=%d %c tail=%lu logMask=%x pid=%d "
+        "start=%" PRIu64 "ns timeout=%" PRIu64 "ns\n",
+        cli->getUid(), cli->getGid(), cli->getPid(), nonBlock ? 'n' : 'b', tail,
+        logMask, (int)pid, sequence.nsec(), timeout);
+
     FlushCommand command(*this, nonBlock, tail, logMask, pid, sequence, timeout);
 
     // Set acceptable upper limit to wait for slow reader processing b/27242723
@@ -205,7 +212,7 @@
 
 void LogReader::doSocketDelete(SocketClient* cli) {
     LastLogTimes& times = mLogbuf.mTimes;
-    LogTimeEntry::lock();
+    LogTimeEntry::wrlock();
     LastLogTimes::iterator it = times.begin();
     while (it != times.end()) {
         LogTimeEntry* entry = (*it);
diff --git a/logd/LogStatistics.cpp b/logd/LogStatistics.cpp
index cc30f77..d20d90e 100644
--- a/logd/LogStatistics.cpp
+++ b/logd/LogStatistics.cpp
@@ -15,6 +15,7 @@
  */
 
 #include <fcntl.h>
+#include <inttypes.h>
 #include <pwd.h>
 #include <stdio.h>
 #include <string.h>
@@ -23,19 +24,26 @@
 
 #include <list>
 
-#include <android/log.h>
+#include <private/android_logger.h>
 
 #include "LogStatistics.h"
 
+static const uint64_t hourSec = 60 * 60;
+static const uint64_t monthSec = 31 * 24 * hourSec;
+
 size_t LogStatistics::SizesTotal;
 
 LogStatistics::LogStatistics() : enable(false) {
+    log_time now(CLOCK_REALTIME);
     log_id_for_each(id) {
         mSizes[id] = 0;
         mElements[id] = 0;
         mDroppedElements[id] = 0;
         mSizesTotal[id] = 0;
         mElementsTotal[id] = 0;
+        mOldest[id] = now;
+        mNewest[id] = now;
+        mNewestDropped[id] = now;
     }
 }
 
@@ -70,25 +78,56 @@
 }
 }
 
+void LogStatistics::addTotal(LogBufferElement* element) {
+    if (element->getDropped()) return;
+
+    log_id_t log_id = element->getLogId();
+    unsigned short size = element->getMsgLen();
+    mSizesTotal[log_id] += size;
+    SizesTotal += size;
+    ++mElementsTotal[log_id];
+}
+
 void LogStatistics::add(LogBufferElement* element) {
     log_id_t log_id = element->getLogId();
     unsigned short size = element->getMsgLen();
     mSizes[log_id] += size;
     ++mElements[log_id];
 
+    // When caller adding a chatty entry, they will have already
+    // called add() and subtract() for each entry as they are
+    // evaluated and trimmed, thus recording size and number of
+    // elements, but we must recognize the manufactured dropped
+    // entry as not contributing to the lifetime totals.
     if (element->getDropped()) {
         ++mDroppedElements[log_id];
     } else {
-        // When caller adding a chatty entry, they will have already
-        // called add() and subtract() for each entry as they are
-        // evaluated and trimmed, thus recording size and number of
-        // elements, but we must recognize the manufactured dropped
-        // entry as not contributing to the lifetime totals.
         mSizesTotal[log_id] += size;
         SizesTotal += size;
         ++mElementsTotal[log_id];
     }
 
+    log_time stamp(element->getRealTime());
+    if (mNewest[log_id] < stamp) {
+        // A major time update invalidates the statistics :-(
+        log_time diff = stamp - mNewest[log_id];
+        mNewest[log_id] = stamp;
+
+        if (diff.tv_sec > hourSec) {
+            // approximate Do-Your-Best fixup
+            diff += mOldest[log_id];
+            if ((diff > stamp) && ((diff - stamp).tv_sec < hourSec)) {
+                diff = stamp;
+            }
+            if (diff <= stamp) {
+                mOldest[log_id] = diff;
+                if (mNewestDropped[log_id] < diff) {
+                    mNewestDropped[log_id] = diff;
+                }
+            }
+        }
+    }
+
     if (log_id == LOG_ID_KERNEL) {
         return;
     }
@@ -113,6 +152,10 @@
             tagTable.add(tag, element);
         }
     }
+
+    if (!element->getDropped()) {
+        tagNameTable.add(TagNameKey(element), element);
+    }
 }
 
 void LogStatistics::subtract(LogBufferElement* element) {
@@ -124,6 +167,10 @@
         --mDroppedElements[log_id];
     }
 
+    if (mOldest[log_id] < element->getRealTime()) {
+        mOldest[log_id] = element->getRealTime();
+    }
+
     if (log_id == LOG_ID_KERNEL) {
         return;
     }
@@ -148,6 +195,10 @@
             tagTable.subtract(tag, element);
         }
     }
+
+    if (!element->getDropped()) {
+        tagNameTable.subtract(TagNameKey(element), element);
+    }
 }
 
 // Atomically set an entry to drop
@@ -158,6 +209,10 @@
     mSizes[log_id] -= size;
     ++mDroppedElements[log_id];
 
+    if (mNewestDropped[log_id] < element->getRealTime()) {
+        mNewestDropped[log_id] = element->getRealTime();
+    }
+
     uidTable[log_id].drop(element->getUid(), element);
     if (element->getUid() == AID_SYSTEM) {
         pidSystemTable[log_id].drop(element->getPid(), element);
@@ -178,9 +233,12 @@
             tagTable.drop(tag, element);
         }
     }
+
+    tagNameTable.subtract(TagNameKey(element), element);
 }
 
 // caller must own and free character string
+// Requires parent LogBuffer::wrlock() to be held
 const char* LogStatistics::uidToName(uid_t uid) const {
     // Local hard coded favourites
     if (uid == AID_LOGD) {
@@ -248,18 +306,38 @@
                       std::string(isprune ? "NUM" : ""));
 }
 
+// Helper to truncate name, if too long, and add name dressings
+static void formatTmp(const LogStatistics& stat, const char* nameTmp, uid_t uid,
+                      std::string& name, std::string& size, size_t nameLen) {
+    const char* allocNameTmp = nullptr;
+    if (!nameTmp) nameTmp = allocNameTmp = stat.uidToName(uid);
+    if (nameTmp) {
+        size_t lenSpace = std::max(nameLen - name.length(), (size_t)1);
+        size_t len = EntryBaseConstants::total_len -
+                     EntryBaseConstants::pruned_len - size.length() -
+                     name.length() - lenSpace - 2;
+        size_t lenNameTmp = strlen(nameTmp);
+        while ((len < lenNameTmp) && (lenSpace > 1)) {
+            ++len;
+            --lenSpace;
+        }
+        name += android::base::StringPrintf("%*s", (int)lenSpace, "");
+        if (len < lenNameTmp) {
+            name += "...";
+            nameTmp += lenNameTmp - std::max(len - 3, (size_t)1);
+        }
+        name += nameTmp;
+        free(const_cast<char*>(allocNameTmp));
+    }
+}
+
 std::string UidEntry::format(const LogStatistics& stat, log_id_t id) const {
     uid_t uid = getUid();
     std::string name = android::base::StringPrintf("%u", uid);
-    const char* nameTmp = stat.uidToName(uid);
-    if (nameTmp) {
-        name += android::base::StringPrintf(
-            "%*s%s", (int)std::max(6 - name.length(), (size_t)1), "", nameTmp);
-        free(const_cast<char*>(nameTmp));
-    }
-
     std::string size = android::base::StringPrintf("%zu", getSizes());
 
+    formatTmp(stat, nullptr, uid, name, size, 6);
+
     std::string pruned = "";
     if (worstUidEnabledForLogid(id)) {
         size_t totalDropped = 0;
@@ -366,18 +444,10 @@
     uid_t uid = getUid();
     pid_t pid = getPid();
     std::string name = android::base::StringPrintf("%5u/%u", pid, uid);
-    const char* nameTmp = getName();
-    if (nameTmp) {
-        name += android::base::StringPrintf(
-            "%*s%s", (int)std::max(12 - name.length(), (size_t)1), "", nameTmp);
-    } else if ((nameTmp = stat.uidToName(uid))) {
-        name += android::base::StringPrintf(
-            "%*s%s", (int)std::max(12 - name.length(), (size_t)1), "", nameTmp);
-        free(const_cast<char*>(nameTmp));
-    }
-
     std::string size = android::base::StringPrintf("%zu", getSizes());
 
+    formatTmp(stat, getName(), uid, name, size, 12);
+
     std::string pruned = "";
     size_t dropped = getDropped();
     if (dropped) {
@@ -398,21 +468,10 @@
                              log_id_t /* id */) const {
     uid_t uid = getUid();
     std::string name = android::base::StringPrintf("%5u/%u", getTid(), uid);
-    const char* nameTmp = getName();
-    if (nameTmp) {
-        name += android::base::StringPrintf(
-            "%*s%s", (int)std::max(12 - name.length(), (size_t)1), "", nameTmp);
-    } else if ((nameTmp = stat.uidToName(uid))) {
-        // if we do not have a PID name, lets punt to try UID name?
-        name += android::base::StringPrintf(
-            "%*s%s", (int)std::max(12 - name.length(), (size_t)1), "", nameTmp);
-        free(const_cast<char*>(nameTmp));
-        // We tried, better to not have a name at all, we still
-        // have TID/UID by number to report in any case.
-    }
-
     std::string size = android::base::StringPrintf("%zu", getSizes());
 
+    formatTmp(stat, getName(), uid, name, size, 12);
+
     std::string pruned = "";
     size_t dropped = getDropped();
     if (dropped) {
@@ -456,6 +515,101 @@
     return formatLine(name, size, pruned);
 }
 
+std::string TagNameEntry::formatHeader(const std::string& name,
+                                       log_id_t /* id */) const {
+    return formatLine(name, std::string("Size"), std::string("")) +
+           formatLine(std::string("  TID/PID/UID   LOG_TAG NAME"),
+                      std::string("BYTES"), std::string(""));
+}
+
+std::string TagNameEntry::format(const LogStatistics& /* stat */,
+                                 log_id_t /* id */) const {
+    std::string name;
+    pid_t tid = getTid();
+    pid_t pid = getPid();
+    std::string pidstr;
+    if (pid != (pid_t)-1) {
+        pidstr = android::base::StringPrintf("%u", pid);
+        if ((tid != (pid_t)-1) && (tid != pid)) pidstr = "/" + pidstr;
+    }
+    int len = 9 - pidstr.length();
+    if (len < 0) len = 0;
+    if ((tid == (pid_t)-1) || (tid == pid)) {
+        name = android::base::StringPrintf("%*s", len, "");
+    } else {
+        name = android::base::StringPrintf("%*u", len, tid);
+    }
+    name += pidstr;
+    uid_t uid = getUid();
+    if (uid != (uid_t)-1) {
+        name += android::base::StringPrintf("/%u", uid);
+    }
+
+    std::string size = android::base::StringPrintf("%zu", getSizes());
+
+    const char* nameTmp = getName();
+    if (nameTmp) {
+        size_t lenSpace = std::max(16 - name.length(), (size_t)1);
+        size_t len = EntryBaseConstants::total_len -
+                     EntryBaseConstants::pruned_len - size.length() -
+                     name.length() - lenSpace - 2;
+        size_t lenNameTmp = strlen(nameTmp);
+        while ((len < lenNameTmp) && (lenSpace > 1)) {
+            ++len;
+            --lenSpace;
+        }
+        name += android::base::StringPrintf("%*s", (int)lenSpace, "");
+        if (len < lenNameTmp) {
+            name += "...";
+            nameTmp += lenNameTmp - std::max(len - 3, (size_t)1);
+        }
+        name += nameTmp;
+    }
+
+    std::string pruned = "";
+
+    return formatLine(name, size, pruned);
+}
+
+static std::string formatMsec(uint64_t val) {
+    static const unsigned subsecDigits = 3;
+    static const uint64_t sec = MS_PER_SEC;
+
+    static const uint64_t minute = 60 * sec;
+    static const uint64_t hour = 60 * minute;
+    static const uint64_t day = 24 * hour;
+
+    std::string output;
+    if (val < sec) return output;
+
+    if (val >= day) {
+        output = android::base::StringPrintf("%" PRIu64 "d ", val / day);
+        val = (val % day) + day;
+    }
+    if (val >= minute) {
+        if (val >= hour) {
+            output += android::base::StringPrintf("%" PRIu64 ":",
+                                                  (val / hour) % (day / hour));
+        }
+        output += android::base::StringPrintf(
+            (val >= hour) ? "%02" PRIu64 ":" : "%" PRIu64 ":",
+            (val / minute) % (hour / minute));
+    }
+    output +=
+        android::base::StringPrintf((val >= minute) ? "%02" PRIu64 : "%" PRIu64,
+                                    (val / sec) % (minute / sec));
+    val %= sec;
+    unsigned digits = subsecDigits;
+    while (digits && ((val % 10) == 0)) {
+        val /= 10;
+        --digits;
+    }
+    if (digits) {
+        output += android::base::StringPrintf(".%0*" PRIu64, digits, val);
+    }
+    return output;
+}
+
 std::string LogStatistics::format(uid_t uid, pid_t pid,
                                   unsigned int logMask) const {
     static const unsigned short spaces_total = 19;
@@ -525,6 +679,67 @@
     output += android::base::StringPrintf("%*s%zu/%zu", spaces, "", totalSize,
                                           totalEls);
 
+    static const char SpanStr[] = "\nLogspan";
+    spaces = 10 - strlen(SpanStr);
+    output += SpanStr;
+
+    // Total reports the greater of the individual maximum time span, or the
+    // validated minimum start and maximum end time span if it makes sense.
+    uint64_t minTime = UINT64_MAX;
+    uint64_t maxTime = 0;
+    uint64_t maxSpan = 0;
+    totalSize = 0;
+
+    log_id_for_each(id) {
+        if (!(logMask & (1 << id))) continue;
+
+        // validity checking
+        uint64_t oldest = mOldest[id].msec();
+        uint64_t newest = mNewest[id].msec();
+        if (newest <= oldest) {
+            spaces += spaces_total;
+            continue;
+        }
+
+        uint64_t span = newest - oldest;
+        if (span > (monthSec * MS_PER_SEC)) {
+            spaces += spaces_total;
+            continue;
+        }
+
+        // total span
+        if (minTime > oldest) minTime = oldest;
+        if (maxTime < newest) maxTime = newest;
+        if (span > maxSpan) maxSpan = span;
+        totalSize += span;
+
+        uint64_t dropped = mNewestDropped[id].msec();
+        if (dropped < oldest) dropped = oldest;
+        if (dropped > newest) dropped = newest;
+
+        oldLength = output.length();
+        output += android::base::StringPrintf("%*s%s", spaces, "",
+                                              formatMsec(span).c_str());
+        unsigned permille = ((newest - dropped) * 1000 + (span / 2)) / span;
+        if ((permille > 1) && (permille < 999)) {
+            output += android::base::StringPrintf("(%u", permille / 10);
+            permille %= 10;
+            if (permille) {
+                output += android::base::StringPrintf(".%u", permille);
+            }
+            output += android::base::StringPrintf("%%)");
+        }
+        spaces -= output.length() - oldLength;
+        spaces += spaces_total;
+    }
+    if ((maxTime > minTime) && ((maxTime -= minTime) < totalSize) &&
+        (maxTime > maxSpan)) {
+        maxSpan = maxTime;
+    }
+    if (spaces < 0) spaces = 0;
+    output += android::base::StringPrintf("%*s%s", spaces, "",
+                                          formatMsec(maxSpan).c_str());
+
     static const char OverheadStr[] = "\nOverhead";
     spaces = 10 - strlen(OverheadStr);
     output += OverheadStr;
@@ -591,6 +806,13 @@
             securityTagTable.format(*this, uid, pid, name, LOG_ID_SECURITY);
     }
 
+    if (enable) {
+        name = "Chattiest TAGs";
+        if (pid) name += android::base::StringPrintf(" for PID %d", pid);
+        name += ":";
+        output += tagNameTable.format(*this, uid, pid, name);
+    }
+
     return output;
 }
 
diff --git a/logd/LogStatistics.h b/logd/LogStatistics.h
index 066b7de..945fc0a 100644
--- a/logd/LogStatistics.h
+++ b/logd/LogStatistics.h
@@ -18,17 +18,23 @@
 #define _LOGD_LOG_STATISTICS_H__
 
 #include <ctype.h>
+#include <inttypes.h>
+#include <stdint.h>
 #include <stdlib.h>
+#include <string.h>
 #include <sys/types.h>
 
 #include <algorithm>  // std::max
+#include <experimental/string_view>
 #include <memory>
 #include <string>  // std::string
 #include <unordered_map>
 
 #include <android-base/stringprintf.h>
 #include <android/log.h>
+#include <log/log_time.h>
 #include <private/android_filesystem_config.h>
+#include <utils/FastStrcmp.h>
 
 #include "LogBufferElement.h"
 #include "LogUtils.h"
@@ -76,7 +82,7 @@
     std::unique_ptr<const TEntry* []> sort(uid_t uid, pid_t pid,
                                            size_t len) const {
         if (!len) {
-            std::unique_ptr<const TEntry* []> sorted(NULL);
+            std::unique_ptr<const TEntry* []> sorted(nullptr);
             return sorted;
         }
 
@@ -111,7 +117,7 @@
         return sorted;
     }
 
-    inline iterator add(TKey key, LogBufferElement* element) {
+    inline iterator add(const TKey& key, const LogBufferElement* element) {
         iterator it = map.find(key);
         if (it == map.end()) {
             it = map.insert(std::make_pair(key, TEntry(element))).first;
@@ -131,14 +137,21 @@
         return it;
     }
 
-    void subtract(TKey key, LogBufferElement* element) {
+    void subtract(TKey&& key, const LogBufferElement* element) {
+        iterator it = map.find(std::move(key));
+        if ((it != map.end()) && it->second.subtract(element)) {
+            map.erase(it);
+        }
+    }
+
+    void subtract(const TKey& key, const LogBufferElement* element) {
         iterator it = map.find(key);
         if ((it != map.end()) && it->second.subtract(element)) {
             map.erase(it);
         }
     }
 
-    inline void drop(TKey key, LogBufferElement* element) {
+    inline void drop(TKey key, const LogBufferElement* element) {
         iterator it = map.find(key);
         if (it != map.end()) {
             it->second.drop(element);
@@ -198,17 +211,18 @@
 
     EntryBase() : size(0) {
     }
-    explicit EntryBase(LogBufferElement* element) : size(element->getMsgLen()) {
+    explicit EntryBase(const LogBufferElement* element)
+        : size(element->getMsgLen()) {
     }
 
     size_t getSizes() const {
         return size;
     }
 
-    inline void add(LogBufferElement* element) {
+    inline void add(const LogBufferElement* element) {
         size += element->getMsgLen();
     }
-    inline bool subtract(LogBufferElement* element) {
+    inline bool subtract(const LogBufferElement* element) {
         size -= element->getMsgLen();
         return !size;
     }
@@ -239,7 +253,7 @@
 
     EntryBaseDropped() : dropped(0) {
     }
-    explicit EntryBaseDropped(LogBufferElement* element)
+    explicit EntryBaseDropped(const LogBufferElement* element)
         : EntryBase(element), dropped(element->getDropped()) {
     }
 
@@ -247,15 +261,15 @@
         return dropped;
     }
 
-    inline void add(LogBufferElement* element) {
+    inline void add(const LogBufferElement* element) {
         dropped += element->getDropped();
         EntryBase::add(element);
     }
-    inline bool subtract(LogBufferElement* element) {
+    inline bool subtract(const LogBufferElement* element) {
         dropped -= element->getDropped();
         return EntryBase::subtract(element) && !dropped;
     }
-    inline void drop(LogBufferElement* element) {
+    inline void drop(const LogBufferElement* element) {
         dropped += 1;
         EntryBase::subtract(element);
     }
@@ -265,7 +279,7 @@
     const uid_t uid;
     pid_t pid;
 
-    explicit UidEntry(LogBufferElement* element)
+    explicit UidEntry(const LogBufferElement* element)
         : EntryBaseDropped(element),
           uid(element->getUid()),
           pid(element->getPid()) {
@@ -281,7 +295,7 @@
         return pid;
     }
 
-    inline void add(LogBufferElement* element) {
+    inline void add(const LogBufferElement* element) {
         if (pid != element->getPid()) {
             pid = -1;
         }
@@ -307,7 +321,7 @@
           uid(android::pidToUid(pid)),
           name(android::pidToName(pid)) {
     }
-    explicit PidEntry(LogBufferElement* element)
+    explicit PidEntry(const LogBufferElement* element)
         : EntryBaseDropped(element),
           pid(element->getPid()),
           uid(element->getUid()),
@@ -317,7 +331,7 @@
         : EntryBaseDropped(element),
           pid(element.pid),
           uid(element.uid),
-          name(element.name ? strdup(element.name) : NULL) {
+          name(element.name ? strdup(element.name) : nullptr) {
     }
     ~PidEntry() {
         free(name);
@@ -339,14 +353,14 @@
     inline void add(pid_t newPid) {
         if (name && !fastcmp<strncmp>(name, "zygote", 6)) {
             free(name);
-            name = NULL;
+            name = nullptr;
         }
         if (!name) {
             name = android::pidToName(newPid);
         }
     }
 
-    inline void add(LogBufferElement* element) {
+    inline void add(const LogBufferElement* element) {
         uid_t incomingUid = element->getUid();
         if (getUid() != incomingUid) {
             uid = incomingUid;
@@ -375,7 +389,7 @@
           uid(android::pidToUid(tid)),
           name(android::tidToName(tid)) {
     }
-    explicit TidEntry(LogBufferElement* element)
+    explicit TidEntry(const LogBufferElement* element)
         : EntryBaseDropped(element),
           tid(element->getTid()),
           pid(element->getPid()),
@@ -387,7 +401,7 @@
           tid(element.tid),
           pid(element.pid),
           uid(element.uid),
-          name(element.name ? strdup(element.name) : NULL) {
+          name(element.name ? strdup(element.name) : nullptr) {
     }
     ~TidEntry() {
         free(name);
@@ -412,14 +426,14 @@
     inline void add(pid_t incomingTid) {
         if (name && !fastcmp<strncmp>(name, "zygote", 6)) {
             free(name);
-            name = NULL;
+            name = nullptr;
         }
         if (!name) {
             name = android::tidToName(incomingTid);
         }
     }
 
-    inline void add(LogBufferElement* element) {
+    inline void add(const LogBufferElement* element) {
         uid_t incomingUid = element->getUid();
         pid_t incomingPid = element->getPid();
         if ((getUid() != incomingUid) || (getPid() != incomingPid)) {
@@ -442,7 +456,7 @@
     pid_t pid;
     uid_t uid;
 
-    explicit TagEntry(LogBufferElement* element)
+    explicit TagEntry(const LogBufferElement* element)
         : EntryBaseDropped(element),
           tag(element->getTag()),
           pid(element->getPid()),
@@ -462,7 +476,7 @@
         return android::tagToName(tag);
     }
 
-    inline void add(LogBufferElement* element) {
+    inline void add(const LogBufferElement* element) {
         if (uid != element->getUid()) {
             uid = -1;
         }
@@ -476,6 +490,144 @@
     std::string format(const LogStatistics& stat, log_id_t id) const;
 };
 
+struct TagNameKey {
+    std::string* alloc;
+    std::experimental::string_view name;  // Saves space if const char*
+
+    explicit TagNameKey(const LogBufferElement* element)
+        : alloc(nullptr), name("", strlen("")) {
+        if (element->isBinary()) {
+            uint32_t tag = element->getTag();
+            if (tag) {
+                const char* cp = android::tagToName(tag);
+                if (cp) {
+                    name = std::experimental::string_view(cp, strlen(cp));
+                    return;
+                }
+            }
+            alloc = new std::string(
+                android::base::StringPrintf("[%" PRIu32 "]", tag));
+            if (!alloc) return;
+            name = std::experimental::string_view(alloc->c_str(), alloc->size());
+            return;
+        }
+        const char* msg = element->getMsg();
+        if (!msg) {
+            name = std::experimental::string_view("chatty", strlen("chatty"));
+            return;
+        }
+        ++msg;
+        unsigned short len = element->getMsgLen();
+        len = (len <= 1) ? 0 : strnlen(msg, len - 1);
+        if (!len) {
+            name = std::experimental::string_view("<NULL>", strlen("<NULL>"));
+            return;
+        }
+        alloc = new std::string(msg, len);
+        if (!alloc) return;
+        name = std::experimental::string_view(alloc->c_str(), alloc->size());
+    }
+
+    explicit TagNameKey(TagNameKey&& rval)
+        : alloc(rval.alloc), name(rval.name.data(), rval.name.length()) {
+        rval.alloc = nullptr;
+    }
+
+    explicit TagNameKey(const TagNameKey& rval)
+        : alloc(rval.alloc ? new std::string(*rval.alloc) : nullptr),
+          name(alloc ? alloc->data() : rval.name.data(), rval.name.length()) {
+    }
+
+    ~TagNameKey() {
+        if (alloc) delete alloc;
+    }
+
+    operator const std::experimental::string_view() const {
+        return name;
+    }
+
+    const char* data() const {
+        return name.data();
+    }
+    size_t length() const {
+        return name.length();
+    }
+
+    bool operator==(const TagNameKey& rval) const {
+        if (length() != rval.length()) return false;
+        if (length() == 0) return true;
+        return fastcmp<strncmp>(data(), rval.data(), length()) == 0;
+    }
+    bool operator!=(const TagNameKey& rval) const {
+        return !(*this == rval);
+    }
+
+    size_t getAllocLength() const {
+        return alloc ? alloc->length() + 1 + sizeof(std::string) : 0;
+    }
+};
+
+// Hash for TagNameKey
+template <>
+struct std::hash<TagNameKey>
+    : public std::unary_function<const TagNameKey&, size_t> {
+    size_t operator()(const TagNameKey& __t) const noexcept {
+        if (!__t.length()) return 0;
+        return std::hash<std::experimental::string_view>()(
+            std::experimental::string_view(__t));
+    }
+};
+
+struct TagNameEntry : public EntryBase {
+    pid_t tid;
+    pid_t pid;
+    uid_t uid;
+    TagNameKey name;
+
+    explicit TagNameEntry(const LogBufferElement* element)
+        : EntryBase(element),
+          tid(element->getTid()),
+          pid(element->getPid()),
+          uid(element->getUid()),
+          name(element) {
+    }
+
+    const TagNameKey& getKey() const {
+        return name;
+    }
+    const pid_t& getTid() const {
+        return tid;
+    }
+    const pid_t& getPid() const {
+        return pid;
+    }
+    const uid_t& getUid() const {
+        return uid;
+    }
+    const char* getName() const {
+        return name.data();
+    }
+    size_t getNameAllocLength() const {
+        return name.getAllocLength();
+    }
+
+    inline void add(const LogBufferElement* element) {
+        if (uid != element->getUid()) {
+            uid = -1;
+        }
+        if (pid != element->getPid()) {
+            pid = -1;
+        }
+        if (tid != element->getTid()) {
+            tid = -1;
+        }
+        EntryBase::add(element);
+    }
+
+    std::string formatHeader(const std::string& name, log_id_t id) const;
+    std::string format(const LogStatistics& stat, log_id_t id) const;
+};
+
 template <typename TEntry>
 class LogFindWorst {
     std::unique_ptr<const TEntry* []> sorted;
@@ -520,6 +672,9 @@
     size_t mDroppedElements[LOG_ID_MAX];
     size_t mSizesTotal[LOG_ID_MAX];
     size_t mElementsTotal[LOG_ID_MAX];
+    log_time mOldest[LOG_ID_MAX];
+    log_time mNewest[LOG_ID_MAX];
+    log_time mNewestDropped[LOG_ID_MAX];
     static size_t SizesTotal;
     bool enable;
 
@@ -546,9 +701,14 @@
     // security tag list
     tagTable_t securityTagTable;
 
+    // global tag list
+    typedef LogHashtable<TagNameKey, TagNameEntry> tagNameTable_t;
+    tagNameTable_t tagNameTable;
+
     size_t sizeOf() const {
         size_t size = sizeof(*this) + pidTable.sizeOf() + tidTable.sizeOf() +
                       tagTable.sizeOf() + securityTagTable.sizeOf() +
+                      tagNameTable.sizeOf() +
                       (pidTable.size() * sizeof(pidTable_t::iterator)) +
                       (tagTable.size() * sizeof(tagTable_t::iterator));
         for (auto it : pidTable) {
@@ -559,6 +719,7 @@
             const char* name = it.second.getName();
             if (name) size += strlen(name) + 1;
         }
+        for (auto it : tagNameTable) size += it.second.getNameAllocLength();
         log_id_for_each(id) {
             size += uidTable[id].sizeOf();
             size += uidTable[id].size() * sizeof(uidTable_t::iterator);
@@ -576,6 +737,7 @@
         enable = true;
     }
 
+    void addTotal(LogBufferElement* entry);
     void add(LogBufferElement* entry);
     void subtract(LogBufferElement* entry);
     // entry->setDropped(1) must follow this call
diff --git a/logd/LogTags.cpp b/logd/LogTags.cpp
index 67649b1..fcd45bd 100644
--- a/logd/LogTags.cpp
+++ b/logd/LogTags.cpp
@@ -32,8 +32,8 @@
 #include <android-base/macros.h>
 #include <android-base/stringprintf.h>
 #include <log/log_event_list.h>
+#include <log/log_properties.h>
 #include <private/android_filesystem_config.h>
-#include <private/android_logger.h>
 
 #include "LogTags.h"
 #include "LogUtils.h"
diff --git a/logd/LogTimes.cpp b/logd/LogTimes.cpp
index 04e531f..25c2ad2 100644
--- a/logd/LogTimes.cpp
+++ b/logd/LogTimes.cpp
@@ -15,6 +15,7 @@
  */
 
 #include <errno.h>
+#include <string.h>
 #include <sys/prctl.h>
 
 #include <private/android_logger.h>
@@ -47,7 +48,8 @@
       mEnd(log_time(android_log_clockid())) {
     mTimeout.tv_sec = timeout / NS_PER_SEC;
     mTimeout.tv_nsec = timeout % NS_PER_SEC;
-    pthread_cond_init(&threadTriggeredCondition, NULL);
+    memset(mLastTid, 0, sizeof(mLastTid));
+    pthread_cond_init(&threadTriggeredCondition, nullptr);
     cleanSkip_Locked();
 }
 
@@ -76,7 +78,7 @@
 void LogTimeEntry::threadStop(void* obj) {
     LogTimeEntry* me = reinterpret_cast<LogTimeEntry*>(obj);
 
-    lock();
+    wrlock();
 
     if (me->mNonBlock) {
         me->error_Locked();
@@ -98,7 +100,7 @@
             it++;
         }
 
-        me->mClient = NULL;
+        me->mClient = nullptr;
         reader.release(client);
     }
 
@@ -122,7 +124,7 @@
     SocketClient* client = me->mClient;
     if (!client) {
         me->error();
-        return NULL;
+        return nullptr;
     }
 
     LogBuffer& logbuf = me->mReader.logbuf();
@@ -132,7 +134,7 @@
 
     me->leadingDropped = true;
 
-    lock();
+    wrlock();
 
     log_time start = me->mStart;
 
@@ -151,14 +153,14 @@
         unlock();
 
         if (me->mTail) {
-            logbuf.flushTo(client, start, privileged, security, FilterFirstPass,
-                           me);
+            logbuf.flushTo(client, start, nullptr, privileged, security,
+                           FilterFirstPass, me);
             me->leadingDropped = true;
         }
-        start = logbuf.flushTo(client, start, privileged, security,
-                               FilterSecondPass, me);
+        start = logbuf.flushTo(client, start, me->mLastTid, privileged,
+                               security, FilterSecondPass, me);
 
-        lock();
+        wrlock();
 
         if (start == LogBufferElement::FLUSH_ERROR) {
             me->error_Locked();
@@ -182,14 +184,14 @@
 
     pthread_cleanup_pop(true);
 
-    return NULL;
+    return nullptr;
 }
 
 // A first pass to count the number of elements
 int LogTimeEntry::FilterFirstPass(const LogBufferElement* element, void* obj) {
     LogTimeEntry* me = reinterpret_cast<LogTimeEntry*>(obj);
 
-    LogTimeEntry::lock();
+    LogTimeEntry::wrlock();
 
     if (me->leadingDropped) {
         if (element->getDropped()) {
@@ -217,7 +219,7 @@
 int LogTimeEntry::FilterSecondPass(const LogBufferElement* element, void* obj) {
     LogTimeEntry* me = reinterpret_cast<LogTimeEntry*>(obj);
 
-    LogTimeEntry::lock();
+    LogTimeEntry::wrlock();
 
     me->mStart = element->getRealTime();
 
@@ -281,7 +283,5 @@
 }
 
 void LogTimeEntry::cleanSkip_Locked(void) {
-    for (log_id_t i = LOG_ID_MIN; i < LOG_ID_MAX; i = (log_id_t)(i + 1)) {
-        skipAhead[i] = 0;
-    }
+    memset(skipAhead, 0, sizeof(skipAhead));
 }
diff --git a/logd/LogTimes.h b/logd/LogTimes.h
index 9a3ddab..9ca2aea 100644
--- a/logd/LogTimes.h
+++ b/logd/LogTimes.h
@@ -44,6 +44,7 @@
     const unsigned int mLogMask;
     const pid_t mPid;
     unsigned int skipAhead[LOG_ID_MAX];
+    pid_t mLastTid[LOG_ID_MAX];
     unsigned long mCount;
     unsigned long mTail;
     unsigned long mIndex;
@@ -60,7 +61,10 @@
     const log_time mEnd;  // only relevant if mNonBlock
 
     // Protect List manipulations
-    static void lock(void) {
+    static void wrlock(void) {
+        pthread_mutex_lock(&timesLock);
+    }
+    static void rdlock(void) {
         pthread_mutex_lock(&timesLock);
     }
     static void unlock(void) {
@@ -103,7 +107,7 @@
         mError = true;
     }
     void error(void) {
-        lock();
+        wrlock();
         error_Locked();
         unlock();
     }
diff --git a/logd/LogUtils.h b/logd/LogUtils.h
index 93d2a79..fa9f398 100644
--- a/logd/LogUtils.h
+++ b/logd/LogUtils.h
@@ -43,8 +43,25 @@
 const char* tagToName(uint32_t tag);
 void ReReadEventLogTags();
 
-// Furnished by LogKlog.cpp.
-const char* strnstr(const char* s, size_t len, const char* needle);
+// Furnished by LogKlog.cpp
+char* log_strntok_r(char* s, ssize_t& len, char*& saveptr, ssize_t& sublen);
+
+// needle should reference a string longer than 1 character
+static inline const char* strnstr(const char* s, ssize_t len,
+                                  const char* needle) {
+    if (len <= 0) return nullptr;
+
+    const char c = *needle++;
+    const size_t needleLen = strlen(needle);
+    do {
+        do {
+            if (len <= (ssize_t)needleLen) return nullptr;
+            --len;
+        } while (*s++ != c);
+    } while (fastcmp<memcmp>(s, needle, needleLen));
+    s--;
+    return s;
+}
 }
 
 // Furnished in LogCommand.cpp
diff --git a/logd/event.logtags b/logd/event.logtags
index 39063a9..fa13a62 100644
--- a/logd/event.logtags
+++ b/logd/event.logtags
@@ -29,6 +29,7 @@
 # 4: Number of allocations
 # 5: Id
 # 6: Percent
+# s: Number of seconds (monotonic time)
 # Default value for data of type int/long is 2 (bytes).
 #
 # TODO: generate ".java" and ".h" files with integer constants from this file.
diff --git a/logd/main.cpp b/logd/main.cpp
index 3334506..18029eb 100644
--- a/logd/main.cpp
+++ b/logd/main.cpp
@@ -221,7 +221,7 @@
 
 static sem_t reinit;
 static bool reinit_running = false;
-static LogBuffer* logBuf = NULL;
+static LogBuffer* logBuf = nullptr;
 
 static bool package_list_parser_cb(pkg_info* info, void* /* userdata */) {
     bool rc = true;
@@ -254,9 +254,9 @@
     while (reinit_running && !sem_wait(&reinit) && reinit_running) {
         // uidToName Privileged Worker
         if (uid) {
-            name = NULL;
+            name = nullptr;
 
-            packagelist_parse(package_list_parser_cb, NULL);
+            packagelist_parse(package_list_parser_cb, nullptr);
 
             uid = 0;
             sem_post(&uidName);
@@ -291,19 +291,19 @@
         // Anything that reads persist.<property>
         if (logBuf) {
             logBuf->init();
-            logBuf->initPrune(NULL);
+            logBuf->initPrune(nullptr);
         }
         android::ReReadEventLogTags();
     }
 
-    return NULL;
+    return nullptr;
 }
 
 static sem_t sem_name;
 
 char* android::uidToName(uid_t u) {
     if (!u || !reinit_running) {
-        return NULL;
+        return nullptr;
     }
 
     sem_wait(&sem_name);
@@ -311,7 +311,7 @@
     // Not multi-thread safe, we use sem_name to protect
     uid = u;
 
-    name = NULL;
+    name = nullptr;
     sem_post(&reinit);
     sem_wait(&uidName);
     char* ret = name;
@@ -332,12 +332,13 @@
         return;
     }
 
-    int rc = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
+    int rc = klogctl(KLOG_SIZE_BUFFER, nullptr, 0);
     if (rc <= 0) {
         return;
     }
 
-    size_t len = rc + 1024;  // Margin for additional input race or trailing nul
+    // Margin for additional input race or trailing nul
+    ssize_t len = rc + 1024;
     std::unique_ptr<char[]> buf(new char[len]);
 
     rc = klogctl(KLOG_READ_ALL, buf.get(), len);
@@ -345,7 +346,7 @@
         return;
     }
 
-    if ((size_t)rc < len) {
+    if (rc < len) {
         len = rc + 1;
     }
     buf[--len] = '\0';
@@ -354,10 +355,11 @@
         kl->synchronize(buf.get(), len);
     }
 
-    size_t sublen;
-    for (char *ptr = NULL, *tok = buf.get();
-         (rc >= 0) && ((tok = log_strntok_r(tok, &len, &ptr, &sublen)));
-         tok = NULL) {
+    ssize_t sublen;
+    for (char *ptr = nullptr, *tok = buf.get();
+         (rc >= 0) && !!(tok = android::log_strntok_r(tok, len, ptr, sublen));
+         tok = nullptr) {
+        if ((sublen <= 0) || !*tok) continue;
         if (al) {
             rc = al->log(tok, sublen);
         }
@@ -405,6 +407,11 @@
 // logging plugins like auditd and restart control. Additional
 // transitory per-client threads are created for each reader.
 int main(int argc, char* argv[]) {
+    // logd is written under the assumption that the timezone is UTC.
+    // If TZ is not set, persist.sys.timezone is looked up in some time utility
+    // libc functions, including mktime. It confuses the logd time handling,
+    // so here explicitly set TZ to UTC, which overrides the property.
+    setenv("TZ", "UTC", 1);
     // issue reinit command. KISS argument parsing.
     if ((argc > 1) && argv[1] && !strcmp(argv[1], "--reinit")) {
         return issueReinit();
@@ -444,7 +451,7 @@
         if (!pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)) {
             pthread_t thread;
             reinit_running = true;
-            if (pthread_create(&thread, &attr, reinit_thread_start, NULL)) {
+            if (pthread_create(&thread, &attr, reinit_thread_start, nullptr)) {
                 reinit_running = false;
             }
         }
@@ -507,7 +514,7 @@
     // initiated log messages. New log entries are added to LogBuffer
     // and LogReader is notified to send updates to connected clients.
 
-    LogAudit* al = NULL;
+    LogAudit* al = nullptr;
     if (auditd) {
         al = new LogAudit(logBuf, reader,
                           __android_logger_property_get_bool(
@@ -516,9 +523,9 @@
                               : -1);
     }
 
-    LogKlog* kl = NULL;
+    LogKlog* kl = nullptr;
     if (klogd) {
-        kl = new LogKlog(logBuf, reader, fdDmesg, fdPmesg, al != NULL);
+        kl = new LogKlog(logBuf, reader, fdDmesg, fdPmesg, al != nullptr);
     }
 
     readDmesg(al, kl);
diff --git a/logd/tests/Android.mk b/logd/tests/Android.mk
index c053993..1915677 100644
--- a/logd/tests/Android.mk
+++ b/logd/tests/Android.mk
@@ -49,3 +49,38 @@
 LOCAL_SHARED_LIBRARIES := libbase libcutils liblog libselinux
 LOCAL_SRC_FILES := $(test_src_files)
 include $(BUILD_NATIVE_TEST)
+
+cts_executable := CtsLogdTestCases
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := $(cts_executable)
+LOCAL_MODULE_TAGS := tests
+LOCAL_CFLAGS += $(test_c_flags)
+LOCAL_SRC_FILES := $(test_src_files)
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA)/nativetest
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+LOCAL_SHARED_LIBRARIES := libbase libcutils liblog libselinux
+LOCAL_STATIC_LIBRARIES := libgtest libgtest_main
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_CTS_TEST_PACKAGE := android.core.logd
+include $(BUILD_CTS_EXECUTABLE)
+
+ifeq ($(HOST_OS)-$(HOST_ARCH),$(filter $(HOST_OS)-$(HOST_ARCH),linux-x86 linux-x86_64))
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := $(cts_executable)_list
+LOCAL_MODULE_TAGS := optional
+LOCAL_CFLAGS := $(test_c_flags) -DHOST
+LOCAL_C_INCLUDES := external/gtest/include
+LOCAL_SRC_FILES := $(test_src_files)
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+LOCAL_CXX_STL := libc++
+LOCAL_SHARED_LIBRARIES := libbase libcutils liblog
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
+include $(BUILD_HOST_NATIVE_TEST)
+
+endif  # ifeq ($(HOST_OS)-$(HOST_ARCH),$(filter $(HOST_OS)-$(HOST_ARCH),linux-x86 linux-x86_64))
diff --git a/logd/tests/AndroidTest.xml b/logd/tests/AndroidTest.xml
new file mode 100644
index 0000000..b16bdfd
--- /dev/null
+++ b/logd/tests/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 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.
+-->
+<configuration description="Config for CTS Logging Daemon test cases">
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
+        <option name="cleanup" value="true" />
+        <option name="push" value="CtsLogdTestCases->/data/local/tmp/CtsLogdTestCases" />
+        <option name="append-bitness" value="true" />
+    </target_preparer>
+    <test class="com.android.tradefed.testtype.GTest" >
+        <option name="native-test-device-path" value="/data/local/tmp" />
+        <option name="module-name" value="CtsLogdTestCases" />
+        <option name="runtime-hint" value="65s" />
+    </test>
+</configuration>
diff --git a/logd/tests/logd_test.cpp b/logd/tests/logd_test.cpp
index ddff393..bd9fa93 100644
--- a/logd/tests/logd_test.cpp
+++ b/logd/tests/logd_test.cpp
@@ -39,6 +39,7 @@
 #include "../LogReader.h"  // pickup LOGD_SNDTIMEO
 #include "../libaudit.h"   // pickup AUDIT_RATE_LIMIT_*
 
+#ifdef __ANDROID__
 static void send_to_control(char* buf, size_t len) {
     int sock = socket_local_client("logd", ANDROID_SOCKET_NAMESPACE_RESERVED,
                                    SOCK_STREAM);
@@ -157,8 +158,10 @@
     } while (*cp);
     return benchmark;
 }
+#endif
 
 TEST(logd, statistics) {
+#ifdef __ANDROID__
     size_t len;
     char* buf;
 
@@ -204,8 +207,12 @@
     EXPECT_TRUE(NULL != events_logs);
 
     delete[] buf;
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
+#ifdef __ANDROID__
 static void caught_signal(int /* signum */) {
 }
 
@@ -315,8 +322,10 @@
     fprintf(stderr, "}\n");
     fflush(stderr);
 }
+#endif
 
 TEST(logd, both) {
+#ifdef __ANDROID__
     log_msg msg;
 
     // check if we can read any logs from logd
@@ -390,8 +399,12 @@
     EXPECT_EQ(0, !user_logger_available && !kernel_logger_available);
     EXPECT_EQ(0, user_logger_content && kernel_logger_content);
     EXPECT_EQ(0, !user_logger_content && !kernel_logger_content);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
+#ifdef __ANDROID__
 // BAD ROBOT
 //   Benchmark threshold are generally considered bad form unless there is
 //   is some human love applied to the continued maintenance and whether the
@@ -426,7 +439,7 @@
                     " BM_log_maximum_retry"
                     " BM_log_maximum"
                     " BM_clock_overhead"
-                    " BM_log_overhead"
+                    " BM_log_print_overhead"
                     " BM_log_latency"
                     " BM_log_delay",
                     "r")));
@@ -434,13 +447,13 @@
     char buffer[5120];
 
     static const char* benchmarks[] = {
-        "BM_log_maximum_retry ", "BM_log_maximum ", "BM_clock_overhead ",
-        "BM_log_overhead ",      "BM_log_latency ", "BM_log_delay "
+        "BM_log_maximum_retry ",  "BM_log_maximum ", "BM_clock_overhead ",
+        "BM_log_print_overhead ", "BM_log_latency ", "BM_log_delay "
     };
     static const unsigned int log_maximum_retry = 0;
     static const unsigned int log_maximum = 1;
     static const unsigned int clock_overhead = 2;
-    static const unsigned int log_overhead = 3;
+    static const unsigned int log_print_overhead = 3;
     static const unsigned int log_latency = 4;
     static const unsigned int log_delay = 5;
 
@@ -469,21 +482,23 @@
     }
 
     EXPECT_GE(200000UL, ns[log_maximum_retry]);  // 104734 user
+    EXPECT_NE(0UL, ns[log_maximum_retry]);       // failure to parse
 
     EXPECT_GE(90000UL, ns[log_maximum]);  // 46913 user
+    EXPECT_NE(0UL, ns[log_maximum]);      // failure to parse
 
     EXPECT_GE(4096UL, ns[clock_overhead]);  // 4095
+    EXPECT_NE(0UL, ns[clock_overhead]);     // failure to parse
 
-    EXPECT_GE(250000UL, ns[log_overhead]);  // 126886 user
+    EXPECT_GE(250000UL, ns[log_print_overhead]);  // 126886 user
+    EXPECT_NE(0UL, ns[log_print_overhead]);       // failure to parse
 
     EXPECT_GE(10000000UL,
               ns[log_latency]);  // 1453559 user space (background cgroup)
+    EXPECT_NE(0UL, ns[log_latency]);  // failure to parse
 
     EXPECT_GE(20000000UL, ns[log_delay]);  // 10500289 user
-
-    for (unsigned i = 0; i < arraysize(ns); ++i) {
-        EXPECT_NE(0UL, ns[i]);
-    }
+    EXPECT_NE(0UL, ns[log_delay]);         // failure to parse
 
     alloc_statistics(&buf, &len);
 
@@ -558,9 +573,11 @@
     // 50% threshold for SPAM filter (<20% typical, lots of engineering margin)
     ASSERT_GT(totalSize, nowSpamSize * 2);
 }
+#endif
 
 // b/26447386 confirm fixed
 void timeout_negative(const char* command) {
+#ifdef __ANDROID__
     log_msg msg_wrap, msg_timeout;
     bool content_wrap = false, content_timeout = false, written = false;
     unsigned int alarm_wrap = 0, alarm_timeout = 0;
@@ -630,6 +647,10 @@
     EXPECT_NE(0U, alarm_wrap);
     EXPECT_TRUE(content_timeout);
     EXPECT_NE(0U, alarm_timeout);
+#else
+    command = NULL;
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(logd, timeout_no_start) {
@@ -643,6 +664,7 @@
 
 // b/26447386 refined behavior
 TEST(logd, timeout) {
+#ifdef __ANDROID__
     // b/33962045 This test interferes with other log reader tests that
     // follow because of file descriptor socket persistence in the same
     // process.  So let's fork it to isolate it from giving us pain.
@@ -668,8 +690,12 @@
     while (--i) {
         int fd = socket_local_client("logdr", ANDROID_SOCKET_NAMESPACE_RESERVED,
                                      SOCK_SEQPACKET);
-        EXPECT_LT(0, fd);
-        if (fd < 0) _exit(fd);
+        int save_errno = errno;
+        if (fd < 0) {
+            fprintf(stderr, "failed to open /dev/socket/logdr %s\n",
+                    strerror(save_errno));
+            _exit(fd);
+        }
 
         std::string ask = android::base::StringPrintf(
             "dumpAndClose lids=0,1,2,3,4,5 timeout=6 start=%" PRIu32
@@ -721,8 +747,12 @@
         // active _or_ inactive during the test.
         if (content_timeout) {
             log_time msg(msg_timeout.entry.sec, msg_timeout.entry.nsec);
-            EXPECT_FALSE(msg < now);
-            if (msg < now) _exit(-1);
+            if (msg < now) {
+                fprintf(stderr, "%u.%09u < %u.%09u\n", msg_timeout.entry.sec,
+                        msg_timeout.entry.nsec, (unsigned)now.tv_sec,
+                        (unsigned)now.tv_nsec);
+                _exit(-1);
+            }
             if (msg > now) {
                 now = msg;
                 now.tv_sec += 30;
@@ -758,10 +788,14 @@
 
     _exit(!written + content_wrap + alarm_wrap + !content_timeout +
           !alarm_timeout);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 // b/27242723 confirmed fixed
 TEST(logd, SNDTIMEO) {
+#ifdef __ANDROID__
     static const unsigned sndtimeo =
         LOGD_SNDTIMEO;  // <sigh> it has to be done!
     static const unsigned sleep_time = sndtimeo + 3;
@@ -812,6 +846,9 @@
     EXPECT_EQ(0, save_errno);
 
     close(fd);
+#else
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(logd, getEventTag_list) {
@@ -869,11 +906,14 @@
 #endif
 }
 
+#ifdef __ANDROID__
 static inline int32_t get4LE(const char* src) {
     return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
 }
+#endif
 
 void __android_log_btwrite_multiple__helper(int count) {
+#ifdef __ANDROID__
     log_time ts(CLOCK_MONOTONIC);
 
     log_time ts1(CLOCK_MONOTONIC);
@@ -966,6 +1006,10 @@
     EXPECT_EQ(expected_chatty_count, chatty_count);
     EXPECT_EQ(expected_identical_count, identical_count);
     EXPECT_EQ(expected_expire_count, expire_count);
+#else
+    count = 0;
+    GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
 }
 
 TEST(logd, multiple_test_1) {
@@ -997,16 +1041,18 @@
     }
 
     // We may have DAC, but let's not have MAC
-    if (setcon("u:object_r:shell:s0") < 0) {
+    if ((setcon("u:object_r:shell:s0") < 0) && (setcon("u:r:shell:s0") < 0)) {
         int save_errno = errno;
         security_context_t context;
         getcon(&context);
-        fprintf(stderr, "setcon(\"u:r:shell:s0\") failed @\"%s\" %s\n", context,
-                strerror(save_errno));
-        freecon(context);
-        _exit(-1);
-        // NOTREACHED
-        return 0;
+        if (strcmp(context, "u:r:shell:s0")) {
+            fprintf(stderr, "setcon(\"u:r:shell:s0\") failed @\"%s\" %s\n",
+                    context, strerror(save_errno));
+            freecon(context);
+            _exit(-1);
+            // NOTREACHED
+            return 0;
+        }
     }
 
     // The key here is we are root, but we are in u:r:shell:s0,
diff --git a/logwrapper/Android.bp b/logwrapper/Android.bp
index 7ee0464..ccb1aa6 100644
--- a/logwrapper/Android.bp
+++ b/logwrapper/Android.bp
@@ -32,3 +32,22 @@
         "-Werror",
     ],
 }
+
+// ========================================================
+// Benchmark
+// ========================================================
+cc_benchmark {
+    name: "android_fork_execvp_ext_benchmark",
+    srcs: [
+        "android_fork_execvp_ext_benchmark.cpp",
+    ],
+    shared_libs: [
+        "libbase",
+        "libcutils",
+        "liblog",
+        "liblogwrap",
+    ],
+    cflags: [
+        "-Werror",
+    ]
+}
diff --git a/logwrapper/android_fork_execvp_ext_benchmark.cpp b/logwrapper/android_fork_execvp_ext_benchmark.cpp
new file mode 100644
index 0000000..1abd932
--- /dev/null
+++ b/logwrapper/android_fork_execvp_ext_benchmark.cpp
@@ -0,0 +1,34 @@
+/*
+ * 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 "logwrap/logwrap.h"
+
+#include <android-base/logging.h>
+#include <benchmark/benchmark.h>
+
+static void BM_android_fork_execvp_ext(benchmark::State& state) {
+    const char* argv[] = {"/system/bin/echo", "hello", "world"};
+    const int argc = 3;
+    while (state.KeepRunning()) {
+        int rc = android_fork_execvp_ext(
+            argc, (char**)argv, NULL /* status */, false /* ignore_int_quit */, LOG_NONE,
+            false /* abbreviated */, NULL /* file_path */, NULL /* opts */, 0 /* opts_len */);
+        CHECK_EQ(0, rc);
+    }
+}
+BENCHMARK(BM_android_fork_execvp_ext);
+
+BENCHMARK_MAIN();
diff --git a/logwrapper/include/logwrap/logwrap.h b/logwrapper/include/logwrap/logwrap.h
index 89a8fdd..d3538b3 100644
--- a/logwrapper/include/logwrap/logwrap.h
+++ b/logwrapper/include/logwrap/logwrap.h
@@ -54,9 +54,8 @@
  *           the specified log until the child has exited.
  *   file_path: if log_target has the LOG_FILE bit set, then this parameter
  *           must be set to the pathname of the file to log to.
- *   opts: set to non-NULL if you want to use one or more of the
- *           FORK_EXECVP_OPTION_* features.
- *   opts_len: the length of the opts array. When opts is NULL, pass 0.
+ *   unused_opts: currently unused.
+ *   unused_opts_len: currently unused.
  *
  * Return value:
  *   0 when logwrap successfully run the child process and captured its status
@@ -72,30 +71,10 @@
 #define LOG_KLOG        2
 #define LOG_FILE        4
 
-/* Write data to child's stdin. */
-#define FORK_EXECVP_OPTION_INPUT             0
-/* Capture data from child's stdout and stderr. */
-#define FORK_EXECVP_OPTION_CAPTURE_OUTPUT    1
-
-struct AndroidForkExecvpOption {
-    int opt_type;
-    union {
-        struct {
-            const uint8_t* input;
-            size_t input_len;
-        } opt_input;
-        struct {
-            void (*on_output)(const uint8_t* /*output*/,
-                              size_t /*output_len*/,
-                              void* /* user_pointer */);
-            void* user_pointer;
-        } opt_capture_output;
-    };
-};
-
+// TODO: Remove unused_opts / unused_opts_len in a followup change.
 int android_fork_execvp_ext(int argc, char* argv[], int *status, bool ignore_int_quit,
-        int log_target, bool abbreviated, char *file_path,
-        const struct AndroidForkExecvpOption* opts, size_t opts_len);
+        int log_target, bool abbreviated, char *file_path, void* unused_opts,
+        int unused_opts_len);
 
 /* Similar to above, except abbreviated logging is not available, and if logwrap
  * is true, logging is to the Android system log, and if false, there is no
diff --git a/logwrapper/logwrap.c b/logwrapper/logwrap.c
index 3ad0983..7076078 100644
--- a/logwrapper/logwrap.c
+++ b/logwrapper/logwrap.c
@@ -291,8 +291,7 @@
 }
 
 static int parent(const char *tag, int parent_read, pid_t pid,
-        int *chld_sts, int log_target, bool abbreviated, char *file_path,
-        const struct AndroidForkExecvpOption* opts, size_t opts_len) {
+        int *chld_sts, int log_target, bool abbreviated, char *file_path) {
     int status = 0;
     char buffer[4096];
     struct pollfd poll_fds[] = {
@@ -359,13 +358,6 @@
             sz = TEMP_FAILURE_RETRY(
                 read(parent_read, &buffer[b], sizeof(buffer) - 1 - b));
 
-            for (size_t i = 0; sz > 0 && i < opts_len; ++i) {
-                if (opts[i].opt_type == FORK_EXECVP_OPTION_CAPTURE_OUTPUT) {
-                  opts[i].opt_capture_output.on_output(
-                      (uint8_t*)&buffer[b], sz, opts[i].opt_capture_output.user_pointer);
-                }
-            }
-
             sz += b;
             // Log one line at a time
             for (b = 0; b < sz; b++) {
@@ -483,7 +475,7 @@
 
 int android_fork_execvp_ext(int argc, char* argv[], int *status, bool ignore_int_quit,
         int log_target, bool abbreviated, char *file_path,
-        const struct AndroidForkExecvpOption* opts, size_t opts_len) {
+        void *unused_opts, int unused_opts_len) {
     pid_t pid;
     int parent_ptty;
     int child_ptty;
@@ -493,6 +485,9 @@
     sigset_t oldset;
     int rc = 0;
 
+    LOG_ALWAYS_FATAL_IF(unused_opts != NULL);
+    LOG_ALWAYS_FATAL_IF(unused_opts_len != 0);
+
     rc = pthread_mutex_lock(&fd_mutex);
     if (rc) {
         ERROR("failed to lock signal_fd mutex\n");
@@ -538,13 +533,6 @@
         pthread_sigmask(SIG_SETMASK, &oldset, NULL);
         close(parent_ptty);
 
-        // redirect stdin, stdout and stderr
-        for (size_t i = 0; i < opts_len; ++i) {
-            if (opts[i].opt_type == FORK_EXECVP_OPTION_INPUT) {
-                dup2(child_ptty, 0);
-                break;
-            }
-        }
         dup2(child_ptty, 1);
         dup2(child_ptty, 2);
         close(child_ptty);
@@ -561,24 +549,8 @@
             sigaction(SIGQUIT, &ignact, &quitact);
         }
 
-        for (size_t i = 0; i < opts_len; ++i) {
-            if (opts[i].opt_type == FORK_EXECVP_OPTION_INPUT) {
-                size_t left = opts[i].opt_input.input_len;
-                const uint8_t* input = opts[i].opt_input.input;
-                while (left > 0) {
-                    ssize_t res =
-                        TEMP_FAILURE_RETRY(write(parent_ptty, input, left));
-                    if (res < 0) {
-                        break;
-                    }
-                    left -= res;
-                    input += res;
-                }
-            }
-        }
-
         rc = parent(argv[0], parent_ptty, pid, status, log_target,
-                    abbreviated, file_path, opts, opts_len);
+                    abbreviated, file_path);
     }
 
     if (ignore_int_quit) {
diff --git a/qemu_pipe/Android.mk b/qemu_pipe/Android.mk
deleted file mode 100644
index 6e0144c..0000000
--- a/qemu_pipe/Android.mk
+++ /dev/null
@@ -1,19 +0,0 @@
-# Copyright 2011 The Android Open Source Project
-
-LOCAL_PATH:= $(call my-dir)
-
-common_static_libraries := \
-    libbase
-include $(CLEAR_VARS)
-LOCAL_CLANG := true
-LOCAL_SANITIZE := integer
-LOCAL_SRC_FILES:= \
-    qemu_pipe.cpp
-LOCAL_C_INCLUDES := \
-    $(LOCAL_PATH)/include \
-    system/base/include
-LOCAL_MODULE:= libqemu_pipe
-LOCAL_STATIC_LIBRARIES := $(common_static_libraries)
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_CFLAGS := -Werror
-include $(BUILD_STATIC_LIBRARY)
diff --git a/qemu_pipe/include/qemu_pipe.h b/qemu_pipe/include/qemu_pipe.h
deleted file mode 100644
index 0987498..0000000
--- a/qemu_pipe/include/qemu_pipe.h
+++ /dev/null
@@ -1,64 +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 ANDROID_CORE_INCLUDE_QEMU_PIPE_H
-#define ANDROID_CORE_INCLUDE_QEMU_PIPE_H
-
-#include <stddef.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-// Try to open a new Qemu fast-pipe. This function returns a file descriptor
-// that can be used to communicate with a named service managed by the
-// emulator.
-//
-// This file descriptor can be used as a standard pipe/socket descriptor.
-//
-// 'pipeName' is the name of the emulator service you want to connect to,
-// and should begin with 'pipe:' (e.g. 'pipe:camera' or 'pipe:opengles').
-// For backward compatibility, the 'pipe:' prefix can be omitted, and in
-// that case, qemu_pipe_open will add it for you.
-
-// On success, return a valid file descriptor, or -1/errno on failure. E.g.:
-//
-// EINVAL  -> unknown/unsupported pipeName
-// ENOSYS  -> fast pipes not available in this system.
-//
-// ENOSYS should never happen, except if you're trying to run within a
-// misconfigured emulator.
-//
-// You should be able to open several pipes to the same pipe service,
-// except for a few special cases (e.g. GSM modem), where EBUSY will be
-// returned if more than one client tries to connect to it.
-int qemu_pipe_open(const char* pipeName);
-
-// Send a framed message |buff| of |len| bytes through the |fd| descriptor.
-// This really adds a 4-hexchar prefix describing the payload size.
-// Returns 0 on success, and -1 on error.
-int qemu_pipe_frame_send(int fd, const void* buff, size_t len);
-
-// Read a frame message from |fd|, and store it into |buff| of |len| bytes.
-// If the framed message is larger than |len|, then this returns -1 and the
-// content is lost. Otherwise, this returns the size of the message. NOTE:
-// empty messages are possible in a framed wire protocol and do not mean
-// end-of-stream.
-int qemu_pipe_frame_recv(int fd, void* buff, size_t len);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* ANDROID_CORE_INCLUDE_QEMU_PIPE_H */
diff --git a/qemu_pipe/qemu_pipe.cpp b/qemu_pipe/qemu_pipe.cpp
deleted file mode 100644
index beeccb0..0000000
--- a/qemu_pipe/qemu_pipe.cpp
+++ /dev/null
@@ -1,108 +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.
- */
-
-#include "qemu_pipe.h"
-
-#include <unistd.h>
-#include <fcntl.h>
-#include <string.h>
-#include <errno.h>
-#include <stdio.h>
-
-#include <android-base/file.h>
-
-using android::base::ReadFully;
-using android::base::WriteFully;
-
-// Define QEMU_PIPE_DEBUG if you want to print error messages when an error
-// occurs during pipe operations. The macro should simply take a printf-style
-// formatting string followed by optional arguments.
-#ifndef QEMU_PIPE_DEBUG
-#  define  QEMU_PIPE_DEBUG(...)   (void)0
-#endif
-
-int qemu_pipe_open(const char* pipeName) {
-    // Sanity check.
-    if (!pipeName) {
-        errno = EINVAL;
-        return -1;
-    }
-
-    int fd = TEMP_FAILURE_RETRY(open("/dev/qemu_pipe", O_RDWR));
-    if (fd < 0) {
-        QEMU_PIPE_DEBUG("%s: Could not open /dev/qemu_pipe: %s", __FUNCTION__,
-                        strerror(errno));
-        return -1;
-    }
-
-    // Write the pipe name, *including* the trailing zero which is necessary.
-    size_t pipeNameLen = strlen(pipeName);
-    if (WriteFully(fd, pipeName, pipeNameLen + 1U)) {
-        return fd;
-    }
-
-    // now, add 'pipe:' prefix and try again
-    // Note: host side will wait for the trailing '\0' to start
-    // service lookup.
-    const char pipe_prefix[] = "pipe:";
-    if (WriteFully(fd, pipe_prefix, strlen(pipe_prefix)) &&
-            WriteFully(fd, pipeName, pipeNameLen + 1U)) {
-        return fd;
-    }
-    QEMU_PIPE_DEBUG("%s: Could not write to %s pipe service: %s",
-            __FUNCTION__, pipeName, strerror(errno));
-    close(fd);
-    return -1;
-}
-
-int qemu_pipe_frame_send(int fd, const void* buff, size_t len) {
-    char header[5];
-    snprintf(header, sizeof(header), "%04zx", len);
-    if (!WriteFully(fd, header, 4)) {
-        QEMU_PIPE_DEBUG("Can't write qemud frame header: %s", strerror(errno));
-        return -1;
-    }
-    if (!WriteFully(fd, buff, len)) {
-        QEMU_PIPE_DEBUG("Can't write qemud frame payload: %s", strerror(errno));
-        return -1;
-    }
-    return 0;
-}
-
-int qemu_pipe_frame_recv(int fd, void* buff, size_t len) {
-    char header[5];
-    if (!ReadFully(fd, header, 4)) {
-        QEMU_PIPE_DEBUG("Can't read qemud frame header: %s", strerror(errno));
-        return -1;
-    }
-    header[4] = '\0';
-    size_t size;
-    if (sscanf(header, "%04zx", &size) != 1) {
-        QEMU_PIPE_DEBUG("Malformed qemud frame header: [%.*s]", 4, header);
-        return -1;
-    }
-    if (size > len) {
-        QEMU_PIPE_DEBUG("Oversized qemud frame (% bytes, expected <= %)", size,
-                        len);
-        return -1;
-    }
-    if (!ReadFully(fd, buff, size)) {
-        QEMU_PIPE_DEBUG("Could not read qemud frame payload: %s",
-                        strerror(errno));
-        return -1;
-    }
-    return size;
-}
diff --git a/rootdir/etc/ld.config.txt b/rootdir/etc/ld.config.txt
new file mode 100644
index 0000000..e3468ca
--- /dev/null
+++ b/rootdir/etc/ld.config.txt
@@ -0,0 +1,47 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Bionic loader config file.
+#
+
+#dir.vendor=/vendor/bin/
+#dir.system=/system/bin/
+
+[vendor]
+
+# When this flag is set to true linker will
+# set target_sdk_version for this binary to
+# the version specified in <dirname>/.version
+# file, where <dirname> = dirname(executable_path)
+#
+# default value is false
+enable.target.sdk.version = true
+
+# There is always the default namespace no
+# need to mention it in this list
+additional.namespaces=system
+
+# Is the namespace isolated
+namespace.default.isolated = true
+namespace.default.search.paths = /vendor/${LIB}
+
+# TODO: property for asan search path?
+namespace.default.permitted.paths = /vendor/${LIB}
+namespace.default.asan.permitted.paths = /data/vendor/${LIB}
+namespace.default.links = system
+
+# Todo complete this list
+namespace.default.link.system.shared_libs = libc.so:libm.so:libdl.so:libstdc++.so
+
+namespace.system.isolated = true
+namespace.system.search.paths = /system/${LIB}:/system/${LIB}/framework
+namespace.system.permitted.paths = /system/${LIB}
+
+[system]
+namespace.default.isolated = true
+namespace.default.search.paths = /system/${LIB}
+namespace.default.permitted.paths = /system/${LIB}
+
+# app_process will setup additional vendor namespace manually.
+# Note that zygote will need vendor namespace to setup list of public
+# libraries provided by vendors to apps.
+
diff --git a/rootdir/init.rc b/rootdir/init.rc
index 25cea7f..540e976 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -150,15 +150,6 @@
     write /dev/cpuctl/cpu.rt_period_us 1000000
     write /dev/cpuctl/cpu.rt_runtime_us 950000
 
-    mkdir /dev/cpuctl/bg_non_interactive
-    chown system system /dev/cpuctl/bg_non_interactive/tasks
-    chmod 0666 /dev/cpuctl/bg_non_interactive/tasks
-    # 5.0 %
-    write /dev/cpuctl/bg_non_interactive/cpu.shares 52
-    write /dev/cpuctl/bg_non_interactive/cpu.rt_period_us 1000000
-    # active FIFO threads will never be in BG
-    write /dev/cpuctl/bg_non_interactive/cpu.rt_runtime_us 10000
-
     # sets up initial cpusets for ActivityManager
     mkdir /dev/cpuset
     mount cpuset none /dev/cpuset
@@ -166,25 +157,25 @@
     # this ensures that the cpusets are present and usable, but the device's
     # init.rc must actually set the correct cpus
     mkdir /dev/cpuset/foreground
-    write /dev/cpuset/foreground/cpus 0
-    write /dev/cpuset/foreground/mems 0
+    copy /dev/cpuset/cpus /dev/cpuset/foreground/cpus
+    copy /dev/cpuset/mems /dev/cpuset/foreground/mems
     mkdir /dev/cpuset/foreground/boost
-    write /dev/cpuset/foreground/boost/cpus 0
-    write /dev/cpuset/foreground/boost/mems 0
+    copy /dev/cpuset/cpus /dev/cpuset/foreground/boost/cpus
+    copy /dev/cpuset/mems /dev/cpuset/foreground/boost/mems
     mkdir /dev/cpuset/background
-    write /dev/cpuset/background/cpus 0
-    write /dev/cpuset/background/mems 0
+    copy /dev/cpuset/cpus /dev/cpuset/background/cpus
+    copy /dev/cpuset/mems /dev/cpuset/background/mems
 
     # system-background is for system tasks that should only run on
     # little cores, not on bigs
     # to be used only by init, so don't change system-bg permissions
     mkdir /dev/cpuset/system-background
-    write /dev/cpuset/system-background/cpus 0
-    write /dev/cpuset/system-background/mems 0
+    copy /dev/cpuset/cpus /dev/cpuset/system-background/cpus
+    copy /dev/cpuset/mems /dev/cpuset/system-background/mems
 
     mkdir /dev/cpuset/top-app
-    write /dev/cpuset/top-app/cpus 0
-    write /dev/cpuset/top-app/mems 0
+    copy /dev/cpuset/cpus /dev/cpuset/top-app/cpus
+    copy /dev/cpuset/mems /dev/cpuset/top-app/mems
 
     # change permissions for all cpusets we'll touch at runtime
     chown system system /dev/cpuset
@@ -254,10 +245,6 @@
     class_stop charger
     trigger late-init
 
-# Load properties from /system/ + /factory after fs mount.
-on load_system_props_action
-    load_system_props
-
 on load_persist_props_action
     load_persist_props
     start logd
@@ -278,11 +265,6 @@
     trigger fs
     trigger post-fs
 
-    # Load properties from /system/ + /factory after fs mount. Place
-    # this in another action so that the load will be scheduled after the prior
-    # issued fs triggers have completed.
-    trigger load_system_props_action
-
     # Mount fstab in init.{$device}.rc by mount_all with '--late' parameter
     # to only mount entries with 'latemount'. This is needed if '--early' is
     # specified in the previous mount_all command on the fs stage.
@@ -307,7 +289,16 @@
     trigger boot
 
 on post-fs
+    # Load properties from
+    #     /system/build.prop,
+    #     /odm/build.prop,
+    #     /vendor/build.prop and
+    #     /factory/factory.prop
+    load_system_props
+    # start essential services
     start logd
+    start hwservicemanager
+
     # once everything is setup, no need to modify /
     mount rootfs rootfs / ro remount
     # Mount shared so changes propagate into child namespaces
@@ -355,6 +346,10 @@
     # create the lost+found directories, so as to enforce our permissions
     mkdir /cache/lost+found 0770 root root
 
+on late-fs
+    # HALs required before storage encryption can get unlocked (FBE/FDE)
+    class_start early_hal
+
 on post-fs-data
     # We chown/chmod /data again so because mount is run as root + defaults
     chown system system /data
@@ -389,6 +384,7 @@
     mkdir /data/misc/radio 0770 system radio
     mkdir /data/misc/sms 0770 system radio
     mkdir /data/misc/zoneinfo 0775 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
     mkdir /data/misc/systemkeys 0700 system system
@@ -409,7 +405,7 @@
     mkdir /data/misc/boottrace 0771 system shell
     mkdir /data/misc/update_engine 0700 root root
     mkdir /data/misc/trace 0700 root root
-    mkdir /data/misc/reboot 0700 root root
+    mkdir /data/misc/reboot 0700 system system
     # profile file layout
     mkdir /data/misc/profiles 0771 system system
     mkdir /data/misc/profiles/cur 0771 system system
@@ -417,6 +413,9 @@
     mkdir /data/misc/profman 0770 system shell
     mkdir /data/misc/gcov 0770 root root
 
+    mkdir /data/vendor 0771 root root
+    mkdir /data/vendor/hardware 0771 root root
+
     # For security reasons, /data/local/tmp should always be empty.
     # Do not place files or directories in /data/local/tmp
     mkdir /data/local/tmp 0771 shell shell
@@ -497,12 +496,28 @@
     # Set indication (checked by vold) that we have finished this action
     #setprop vold.post_fs_data_done 1
 
-# This trigger will be triggered before 'zygote-start' since there is no zygote-start defined in
-# current init.rc. It is recommended to put unnecessary data/ initialization from post-fs-data
-# to start-zygote to unblock zygote start.
+# It is recommended to put unnecessary data/ initialization from post-fs-data
+# to start-zygote in device's init.rc to unblock zygote start.
+on zygote-start && property:ro.crypto.state=unencrypted
+    # A/B update verifier that marks a successful boot.
+    exec_start update_verifier_nonencrypted
+    start netd
+    start zygote
+    start zygote_secondary
+
+on zygote-start && property:ro.crypto.state=unsupported
+    # A/B update verifier that marks a successful boot.
+    exec_start update_verifier_nonencrypted
+    start netd
+    start zygote
+    start zygote_secondary
+
 on zygote-start && property:ro.crypto.state=encrypted && property:ro.crypto.type=file
-   start netd
-   start zygote
+    # A/B update verifier that marks a successful boot.
+    exec_start update_verifier_nonencrypted
+    start netd
+    start zygote
+    start zygote_secondary
 
 on boot
     # basic network init
@@ -595,13 +610,12 @@
     # Define default initial receive window size in segments.
     setprop net.tcp.default_init_rwnd 60
 
-    # Start all binderized HAL daemons
-    start hwservicemanager
+    # Start standard binderized HAL daemons
+    class_start hal
+
     class_start core
 
 on nonencrypted
-    # A/B update verifier that marks a successful boot.
-    exec - root cache -- /system/bin/update_verifier nonencrypted
     class_start main
     class_start late_start
 
@@ -624,12 +638,12 @@
 
 on property:vold.decrypt=trigger_restart_min_framework
     # A/B update verifier that marks a successful boot.
-    exec - root cache -- /system/bin/update_verifier trigger_restart_min_framework
+    exec_start update_verifier
     class_start main
 
 on property:vold.decrypt=trigger_restart_framework
     # A/B update verifier that marks a successful boot.
-    exec - root cache -- /system/bin/update_verifier trigger_restart_framework
+    exec_start update_verifier
     class_start main
     class_start late_start
 
@@ -637,12 +651,15 @@
     class_reset late_start
     class_reset main
 
-on property:sys.powerctl=*
-    powerctl ${sys.powerctl}
-
 on property:sys.boot_completed=1
     bootchart stop
 
+on property:sys.boot_completed=1 && property:ro.build.type=user
+    write /proc/sys/kernel/modules_disabled 1
+
+on property:sys.boot_completed=1 && property:ro.build.type=userdebug
+    write /proc/sys/kernel/modules_disabled 1
+
 # system server cannot write to /proc/sys files,
 # and chown/chmod does not work for /proc/sys/ entries.
 # So proxy writes through init.
diff --git a/rootdir/init.usb.configfs.rc b/rootdir/init.usb.configfs.rc
index 32f0198..de1aab3 100644
--- a/rootdir/init.usb.configfs.rc
+++ b/rootdir/init.usb.configfs.rc
@@ -2,6 +2,7 @@
     write /config/usb_gadget/g1/UDC "none"
     stop adbd
     setprop sys.usb.ffs.ready 0
+    setprop sys.usb.ffs.mtp.ready 0
     write /config/usb_gadget/g1/bDeviceClass 0
     write /config/usb_gadget/g1/bDeviceSubClass 0
     write /config/usb_gadget/g1/bDeviceProtocol 0
@@ -11,6 +12,9 @@
     rmdir /config/usb_gadget/g1/functions/rndis.gs4
     setprop sys.usb.state ${sys.usb.config}
 
+on property:init.svc.adbd=stopped
+    setprop sys.usb.ffs.ready 0
+
 on property:sys.usb.config=adb && property:sys.usb.configfs=1
     start adbd
 
@@ -20,7 +24,7 @@
     write /config/usb_gadget/g1/UDC ${sys.usb.controller}
     setprop sys.usb.state ${sys.usb.config}
 
-on property:sys.usb.config=mtp && property:sys.usb.configfs=1
+on property:sys.usb.ffs.mtp.ready=1 && property:sys.usb.config=mtp && property:sys.usb.configfs=1
     write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "mtp"
     symlink /config/usb_gadget/g1/functions/mtp.gs0 /config/usb_gadget/g1/configs/b.1/f1
     write /config/usb_gadget/g1/UDC ${sys.usb.controller}
@@ -29,14 +33,15 @@
 on property:sys.usb.config=mtp,adb && property:sys.usb.configfs=1
     start adbd
 
-on property:sys.usb.ffs.ready=1 && property:sys.usb.config=mtp,adb && property:sys.usb.configfs=1
+on property:sys.usb.ffs.ready=1 && property:sys.usb.ffs.mtp.ready=1 && \
+property:sys.usb.config=mtp,adb && property:sys.usb.configfs=1
     write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "mtp_adb"
     symlink /config/usb_gadget/g1/functions/mtp.gs0 /config/usb_gadget/g1/configs/b.1/f1
     symlink /config/usb_gadget/g1/functions/ffs.adb /config/usb_gadget/g1/configs/b.1/f2
     write /config/usb_gadget/g1/UDC ${sys.usb.controller}
     setprop sys.usb.state ${sys.usb.config}
 
-on property:sys.usb.config=ptp && property:sys.usb.configfs=1
+on property:sys.usb.ffs.mtp.ready=1 && property:sys.usb.config=ptp && property:sys.usb.configfs=1
     write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "ptp"
     symlink /config/usb_gadget/g1/functions/ptp.gs1 /config/usb_gadget/g1/configs/b.1/f1
     write /config/usb_gadget/g1/UDC ${sys.usb.controller}
@@ -45,7 +50,8 @@
 on property:sys.usb.config=ptp,adb && property:sys.usb.configfs=1
     start adbd
 
-on property:sys.usb.ffs.ready=1 && property:sys.usb.config=ptp,adb && property:sys.usb.configfs=1
+on property:sys.usb.ffs.ready=1 && property:sys.usb.ffs.mtp.ready=1 && \
+property:sys.usb.config=ptp,adb && property:sys.usb.configfs=1
     write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "ptp_adb"
     symlink /config/usb_gadget/g1/functions/ptp.gs1 /config/usb_gadget/g1/configs/b.1/f1
     symlink /config/usb_gadget/g1/functions/ffs.adb /config/usb_gadget/g1/configs/b.1/f2
diff --git a/rootdir/ueventd.rc b/rootdir/ueventd.rc
index 0633a68..1609ef2 100644
--- a/rootdir/ueventd.rc
+++ b/rootdir/ueventd.rc
@@ -1,5 +1,37 @@
 subsystem adf
-	devname uevent_devname
+    devname uevent_devname
+
+subsystem graphics
+    devname uevent_devpath
+    dirname /dev/graphics
+
+subsystem drm
+    devname uevent_devpath
+    dirname /dev/dri
+
+subsystem oncrpc
+    devname uevent_devpath
+    dirname /dev/oncrpc
+
+subsystem adsp
+    devname uevent_devpath
+    dirname /dev/adsp
+
+subsystem msm_camera
+    devname uevent_devpath
+    dirname /dev/msm_camera
+
+subsystem input
+    devname uevent_devpath
+    dirname /dev/input
+
+subsystem mtd
+    devname uevent_devpath
+    dirname /dev/mtd
+
+subsystem sound
+    devname uevent_devpath
+    dirname /dev/snd
 
 # ueventd can only set permissions on device nodes and their associated
 # sysfs attributes, not on arbitrary paths.
@@ -21,9 +53,6 @@
 /dev/binder               0666   root       root
 /dev/hwbinder             0666   root       root
 
-# Anyone can read the logs, but if they're not in the "logs"
-# group, then they'll only see log entries for their UID.
-/dev/log/*                0666   root       log
 /dev/pmsg0                0222   root       log
 
 # the msm hw3d client device node is world writable/readable.
diff --git a/shell_and_utilities/Android.bp b/shell_and_utilities/Android.bp
new file mode 100644
index 0000000..81cf315
--- /dev/null
+++ b/shell_and_utilities/Android.bp
@@ -0,0 +1,13 @@
+phony {
+    name: "shell_and_utilities",
+    required: [
+        "bzip2",
+        "grep",
+        "gzip",
+        "mkshrc",
+        "reboot",
+        "sh",
+        "toolbox",
+        "toybox",
+    ],
+}
diff --git a/shell_and_utilities/README.md b/shell_and_utilities/README.md
new file mode 100644
index 0000000..5d10c18
--- /dev/null
+++ b/shell_and_utilities/README.md
@@ -0,0 +1,157 @@
+Android's shell and utilities
+=============================
+
+Since IceCreamSandwich Android has used
+[mksh](https://www.mirbsd.org/mksh.htm) as its shell. Before then it used
+[ash](https://en.wikipedia.org/wiki/Almquist_shell) (which actually
+remained in the tree up to and including KitKat).
+
+Initially Android had a very limited command-line provided by its
+own "toolbox" binary. These days almost everything is supplied by
+[toybox](http://landley.net/toybox/) instead.
+
+We started moving a few of the more important tools to full
+BSD implementations in JellyBean before we started in earnest in
+Lollipop. Lollipop was a major break with the past in many ways (LP64
+support and the switch to ART both having lots of knock-on effects around
+the system), so although this was the beginning of the end of toolbox it
+(a) didn't stand out given all the other systems-level changes and (b)
+in Marshmallow we changed direction and started the move to toybox.
+
+The lists below show what tools were provided and where they came from in
+each release starting with Gingerbread. This doesn't tell the full story,
+because the toolbox implementations did have bugs fixed and options added
+over the years. Gingerbread's rm, for example, supported `-r`/`-R` but not
+`-f`. But this gives you an idea of what was available in any given release,
+and how usable it was likely to be.
+
+
+Android 2.3 (Gingerbread)
+-------------------------
+
+BSD: cat dd newfs\_msdos
+
+toolbox: chmod chown cmp date df dmesg getevent getprop hd id ifconfig
+iftop insmod ioctl ionice kill ln log ls lsmod lsof mkdir mount mv
+nandread netstat notify printenv ps reboot renice rm rmdir rmmod route
+schedtop sendevent setconsole setprop sleep smd start stop sync top
+umount uptime vmstat watchprops wipe
+
+
+Android 4.0 (IceCreamSandwich)
+------------------------------
+
+BSD: cat dd newfs\_msdos
+
+toolbox: chmod chown cmp date df dmesg getevent getprop hd id ifconfig
+iftop insmod ioctl ionice kill ln log ls lsmod lsof mkdir mount mv
+nandread netstat notify printenv ps reboot renice rm rmdir rmmod route
+schedtop sendevent setconsole setprop sleep smd start stop sync top
+touch umount uptime vmstat watchprops wipe
+
+
+Android 4.1-4.3 (JellyBean)
+---------------------------
+
+BSD: cat cp dd du grep newfs\_msdos
+
+toolbox: chcon chmod chown clear cmp date df dmesg getenforce getevent
+getprop getsebool hd id ifconfig iftop insmod ioctl ionice kill ln
+load\_policy log ls lsmod lsof md5 mkdir mount mv nandread netstat notify
+printenv ps reboot renice restorecon rm rmdir rmmod route runcon schedtop
+sendevent setconsole setenforce setprop setsebool sleep smd start stop
+sync top touch umount uptime vmstat watchprops wipe
+
+
+Android 4.4 (KitKat)
+--------------------
+
+BSD: cat cp dd du grep newfs\_msdos
+
+toolbox: chcon chmod chown clear cmp date df dmesg getenforce getevent
+getprop getsebool hd id ifconfig iftop insmod ioctl ionice kill ln
+load\_policy log ls lsmod lsof md5 mkdir mkswap mount mv nandread netstat
+notify printenv ps readlink renice restorecon rm rmdir rmmod route runcon
+schedtop sendevent setconsole setenforce setprop setsebool sleep smd start
+stop swapoff swapon sync top touch umount uptime vmstat watchprops wipe
+
+
+Android 5.0 (Lollipop)
+----------------------
+
+BSD: cat chown cp dd du grep kill ln mv printenv rm rmdir sleep sync
+
+toolbox: chcon chmod clear cmp date df dmesg getenforce getevent getprop
+getsebool hd id ifconfig iftop insmod ioctl ionice load\_policy log ls
+lsmod lsof md5 mkdir mknod mkswap mount nandread netstat newfs\_msdos
+nohup notify ps readlink renice restorecon rmmod route runcon schedtop
+sendevent setenforce setprop setsebool smd start stop swapoff swapon
+top touch umount uptime vmstat watchprops wipe
+
+
+Android 6.0 (Marshmallow)
+-------------------------
+
+BSD: dd du grep
+
+toolbox: df getevent iftop ioctl ionice log ls lsof mount nandread
+newfs\_msdos ps prlimit renice sendevent start stop top uptime watchprops
+
+toybox: acpi basename blockdev bzcat cal cat chcon chgrp chmod chown
+chroot cksum clear comm cmp cp cpio cut date dirname dmesg dos2unix echo
+env expand expr fallocate false find free getenforce getprop groups
+head hostname hwclock id ifconfig inotifyd insmod kill load\_policy ln
+logname losetup lsmod lsusb md5sum mkdir mknod mkswap mktemp modinfo
+more mountpoint mv netstat nice nl nohup od paste patch pgrep pidof
+pkill pmap printenv printf pwd readlink realpath restorecon rm rmdir
+rmmod route runcon sed seq setenforce setprop setsid sha1sum sleep sort
+split stat strings swapoff swapon sync sysctl tac tail tar taskset tee
+time timeout touch tr true truncate umount uname uniq unix2dos usleep
+vmstat wc which whoami xargs yes
+
+
+Android 7.0 (Nougat)
+--------------------
+
+BSD: dd grep
+
+toolbox: getevent iftop ioctl log nandread newfs\_msdos ps prlimit
+sendevent start stop top
+
+toybox: acpi base64 basename blockdev bzcat cal cat chcon chgrp chmod
+chown chroot cksum clear comm cmp cp cpio cut date df dirname dmesg
+dos2unix du echo env expand expr fallocate false find flock free
+getenforce getprop groups head hostname hwclock id ifconfig inotifyd
+insmod ionice iorenice kill killall load\_policy ln logname losetup ls
+lsmod lsof lsusb md5sum mkdir mknod mkswap mktemp modinfo more mount
+mountpoint mv netstat nice nl nohup od paste patch pgrep pidof pkill
+pmap printenv printf pwd readlink realpath renice restorecon rm rmdir
+rmmod route runcon sed seq setenforce setprop setsid sha1sum sleep sort
+split stat strings swapoff swapon sync sysctl tac tail tar taskset tee
+time timeout touch tr true truncate tty ulimit umount uname uniq unix2dos
+uptime usleep vmstat wc which whoami xargs xxd yes
+
+
+Current AOSP
+------------
+
+BSD: dd grep
+
+bzip2: bzcat bzip2 bunzip2
+
+toolbox: getevent gzip newfs\_msdos gunzip zcat
+
+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 head hostname hwclock id ifconfig inotifyd
+insmod ionice iorenice kill killall ln load\_policy log logname losetup
+ls lsmod lsof lsusb md5sum microcom mkdir 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 vmstat wc which whoami xargs
+xxd yes
diff --git a/toolbox/Android.mk b/toolbox/Android.mk
index d6ead1a..aa755ed 100644
--- a/toolbox/Android.mk
+++ b/toolbox/Android.mk
@@ -95,3 +95,13 @@
 LOCAL_MODULE := grep
 LOCAL_POST_INSTALL_CMD := $(hide) $(foreach t,egrep fgrep,ln -sf grep $(TARGET_OUT)/bin/$(t);)
 include $(BUILD_EXECUTABLE)
+
+
+# We build gzip separately, so it can provide gunzip and zcat too.
+include $(CLEAR_VARS)
+LOCAL_MODULE := gzip
+LOCAL_SRC_FILES := gzip.c
+LOCAL_CFLAGS += -Wall -Werror
+LOCAL_SHARED_LIBRARIES += libz
+LOCAL_POST_INSTALL_CMD := $(hide) $(foreach t,gunzip zcat,ln -sf gzip $(TARGET_OUT)/bin/$(t);)
+include $(BUILD_EXECUTABLE)
diff --git a/toolbox/gzip.c b/toolbox/gzip.c
new file mode 100644
index 0000000..62c4518
--- /dev/null
+++ b/toolbox/gzip.c
@@ -0,0 +1,261 @@
+/* gzip.c - gzip/gunzip/zcat tools for gzip data
+ *
+ * Copyright 2017 The Android Open Source Project
+ *
+ * GZIP RFC: http://www.ietf.org/rfc/rfc1952.txt
+
+TODO: port to toybox.
+
+*/
+
+#define _GNU_SOURCE
+
+#include <errno.h>
+#include <error.h>
+#include <fcntl.h>
+#include <getopt.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+
+#include <zlib.h>
+
+// toybox-style flags/globals.
+#define FLAG_c 1
+#define FLAG_d 2
+#define FLAG_f 4
+#define FLAG_k 8
+static struct {
+  int optflags;
+} toys;
+static struct {
+  int level;
+} TT;
+
+static void xstat(const char *path, struct stat *sb)
+{
+  if (stat(path, sb)) error(1, errno, "stat %s", path);
+}
+
+static void fix_time(const char *path, struct stat *sb)
+{
+  struct timespec times[] = { sb->st_atim, sb->st_mtim };
+
+  if (utimensat(AT_FDCWD, path, times, 0)) error(1, errno, "utimes");
+}
+
+static FILE *xfdopen(const char *name, int flags, mode_t open_mode,
+    const char *mode)
+{
+  FILE *fp;
+  int fd;
+
+  if (!strcmp(name, "-")) fd = dup((*mode == 'r') ? 0 : 1);
+  else fd = open(name, flags, open_mode);
+
+  if (fd == -1) error(1, errno, "open %s (%s)", name, mode);
+  fp = fdopen(fd, mode);
+  if (fp == NULL) error(1, errno, "fopen %s (%s)", name, mode);
+  return fp;
+}
+
+static gzFile xgzopen(const char *name, int flags, mode_t open_mode,
+    const char *mode)
+{
+  gzFile f;
+  int fd;
+
+  if (!strcmp(name, "-")) fd = dup((*mode == 'r') ? 0 : 1);
+  else fd = open(name, flags, open_mode);
+
+  if (fd == -1) error(1, errno, "open %s (%s)", name, mode);
+  f = gzdopen(fd, mode);
+  if (f == NULL) error(1, errno, "gzdopen %s (%s)", name, mode);
+  return f;
+}
+
+static void gzfatal(gzFile f, char *what)
+{
+  int err;
+  const char *msg = gzerror(f, &err);
+
+  error(1, (err == Z_ERRNO) ? errno : 0, "%s: %s", what, msg);
+}
+
+static void gunzip(char *arg)
+{
+  struct stat sb;
+  char buf[BUFSIZ];
+  int len, both_files;
+  char *in_name, *out_name;
+  gzFile in;
+  FILE *out;
+
+  // "gunzip x.gz" will decompress "x.gz" to "x".
+  len = strlen(arg);
+  if (len > 3 && !strcmp(arg+len-3, ".gz")) {
+    in_name = strdup(arg);
+    out_name = strdup(arg);
+    out_name[len-3] = '\0';
+  } else if (!strcmp(arg, "-")) {
+    // "-" means stdin; assume output to stdout.
+    // TODO: require -f to read compressed data from tty?
+    in_name = strdup("-");
+    out_name = strdup("-");
+  } else error(1, 0, "unknown suffix");
+
+  if (toys.optflags&FLAG_c) {
+    free(out_name);
+    out_name = strdup("-");
+  }
+
+  both_files = strcmp(in_name, "-") && strcmp(out_name, "-");
+  if (both_files) xstat(in_name, &sb);
+
+  in = xgzopen(in_name, O_RDONLY, 0, "r");
+  out = xfdopen(out_name, O_CREAT|O_WRONLY|((toys.optflags&FLAG_f)?0:O_EXCL),
+      both_files?sb.st_mode:0666, "w");
+
+  while ((len = gzread(in, buf, sizeof(buf))) > 0) {
+    if (fwrite(buf, 1, len, out) != (size_t) len) error(1, errno, "fwrite");
+  }
+  if (len < 0) gzfatal(in, "gzread");
+  if (fclose(out)) error(1, errno, "fclose");
+  if (gzclose(in) != Z_OK) error(1, 0, "gzclose");
+
+  if (both_files) fix_time(out_name, &sb);
+  if (!(toys.optflags&(FLAG_c|FLAG_k))) unlink(in_name);
+  free(in_name);
+  free(out_name);
+}
+
+static void gzip(char *in_name)
+{
+  char buf[BUFSIZ];
+  size_t len;
+  char *out_name;
+  FILE *in;
+  gzFile out;
+  struct stat sb;
+  int both_files;
+
+  if (toys.optflags&FLAG_c) {
+    out_name = strdup("-");
+  } else {
+    if (asprintf(&out_name, "%s.gz", in_name) == -1) {
+      error(1, errno, "asprintf");
+    }
+  }
+
+  both_files = strcmp(in_name, "-") && strcmp(out_name, "-");
+  if (both_files) xstat(in_name, &sb);
+
+  snprintf(buf, sizeof(buf), "w%d", TT.level);
+  in = xfdopen(in_name, O_RDONLY, 0, "r");
+  out = xgzopen(out_name, O_CREAT|O_WRONLY|((toys.optflags&FLAG_f)?0:O_EXCL),
+      both_files?sb.st_mode:0, buf);
+
+  while ((len = fread(buf, 1, sizeof(buf), in)) > 0) {
+    if (gzwrite(out, buf, len) != (int) len) gzfatal(out, "gzwrite");
+  }
+  if (ferror(in)) error(1, errno, "fread");
+  if (fclose(in)) error(1, errno, "fclose");
+  if (gzclose(out) != Z_OK) error(1, 0, "gzclose");
+
+  if (both_files) fix_time(out_name, &sb);
+  if (!(toys.optflags&(FLAG_c|FLAG_k))) unlink(in_name);
+  free(out_name);
+}
+
+static void do_file(char *arg)
+{
+  if (toys.optflags&FLAG_d) gunzip(arg);
+  else gzip(arg);
+}
+
+static void usage()
+{
+  char *cmd = basename(getprogname());
+
+  printf("usage: %s [-c] [-d] [-f] [-#] [FILE...]\n", cmd);
+  printf("\n");
+  if (!strcmp(cmd, "zcat")) {
+    printf("Decompress files to stdout. Like `gzip -dc`.\n");
+    printf("\n");
+    printf("-c\tOutput to stdout\n");
+    printf("-f\tForce: allow read from tty\n");
+  } else if (!strcmp(cmd, "gunzip")) {
+    printf("Decompress files. With no files, decompresses stdin to stdout.\n");
+    printf("On success, the input files are removed and replaced by new\n");
+    printf("files without the .gz suffix.\n");
+    printf("\n");
+    printf("-c\tOutput to stdout\n");
+    printf("-f\tForce: allow read from tty\n");
+    printf("-k\tKeep input files (don't remove)\n");
+  } else { // gzip
+    printf("Compress files. With no files, compresses stdin to stdout.\n");
+    printf("On success, the input files are removed and replaced by new\n");
+    printf("files with the .gz suffix.\n");
+    printf("\n");
+    printf("-c\tOutput to stdout\n");
+    printf("-d\tDecompress (act as gunzip)\n");
+    printf("-f\tForce: allow overwrite of output file\n");
+    printf("-k\tKeep input files (don't remove)\n");
+    printf("-#\tCompression level 1-9 (1:fastest, 6:default, 9:best)\n");
+  }
+  printf("\n");
+}
+
+int main(int argc, char *argv[])
+{
+  char *cmd = basename(argv[0]);
+  int opt_ch;
+
+  toys.optflags = 0;
+  TT.level = 6;
+
+  if (!strcmp(cmd, "gunzip")) {
+    // gunzip == gzip -d
+    toys.optflags = FLAG_d;
+  } else if (!strcmp(cmd, "zcat")) {
+    // zcat == gzip -dc
+    toys.optflags = (FLAG_c|FLAG_d);
+  }
+
+  while ((opt_ch = getopt(argc, argv, "cdfhk123456789")) != -1) {
+    switch (opt_ch) {
+    case 'c': toys.optflags |= FLAG_c; break;
+    case 'd': toys.optflags |= FLAG_d; break;
+    case 'f': toys.optflags |= FLAG_f; break;
+    case 'k': toys.optflags |= FLAG_k; break;
+
+    case '1':
+    case '2':
+    case '3':
+    case '4':
+    case '5':
+    case '6':
+    case '7':
+    case '8':
+    case '9':
+      TT.level = opt_ch - '0';
+      break;
+
+    default:
+      usage();
+      return 1;
+    }
+  }
+
+  if (optind == argc) {
+    // With no arguments, we go from stdin to stdout.
+    toys.optflags |= FLAG_c;
+    do_file("-");
+    return 0;
+  }
+
+  // Otherwise process each file in turn.
+  while (optind < argc) do_file(argv[optind++]);
+  return 0;
+}
diff --git a/trusty/Android.bp b/trusty/Android.bp
new file mode 100644
index 0000000..1b2e2c7
--- /dev/null
+++ b/trusty/Android.bp
@@ -0,0 +1,3 @@
+subdirs = [
+    "libtrusty",
+]
diff --git a/trusty/keymaster/Android.mk b/trusty/keymaster/Android.mk
index 0ebf52d..2d614ae 100644
--- a/trusty/keymaster/Android.mk
+++ b/trusty/keymaster/Android.mk
@@ -32,7 +32,7 @@
 LOCAL_MODULE := trusty_keymaster_tipc
 LOCAL_SRC_FILES := \
 	trusty_keymaster_device.cpp \
-	trusty_keymaster_ipc.c \
+	trusty_keymaster_ipc.cpp \
 	trusty_keymaster_main.cpp
 LOCAL_SHARED_LIBRARIES := \
 	libcrypto \
@@ -40,6 +40,7 @@
 	libkeymaster1 \
 	libtrusty \
 	libkeymaster_messages \
+	libsoftkeymasterdevice \
 	liblog
 
 include $(BUILD_EXECUTABLE)
@@ -53,7 +54,7 @@
 LOCAL_MODULE := keystore.trusty
 LOCAL_MODULE_RELATIVE_PATH := hw
 LOCAL_SRC_FILES := module.cpp \
-	trusty_keymaster_ipc.c \
+	trusty_keymaster_ipc.cpp \
 	trusty_keymaster_device.cpp
 LOCAL_CLFAGS = -fvisibility=hidden -Wall -Werror
 LOCAL_SHARED_LIBRARIES := \
diff --git a/trusty/keymaster/keymaster_ipc.h b/trusty/keymaster/keymaster_ipc.h
index 48fa53d..b38eb05 100644
--- a/trusty/keymaster/keymaster_ipc.h
+++ b/trusty/keymaster/keymaster_ipc.h
@@ -16,13 +16,15 @@
 
 #pragma once
 
+// clang-format off
+
 #define KEYMASTER_PORT "com.android.trusty.keymaster"
 #define KEYMASTER_MAX_BUFFER_LENGTH 4096
 
 // Commands
-enum keymaster_command {
-	KEYMASTER_RESP_BIT              = 1,
-	KEYMASTER_REQ_SHIFT             = 1,
+enum keymaster_command : uint32_t {
+    KEYMASTER_RESP_BIT              = 1,
+    KEYMASTER_REQ_SHIFT             = 1,
 
     KM_GENERATE_KEY                 = (0 << KEYMASTER_REQ_SHIFT),
     KM_BEGIN_OPERATION              = (1 << KEYMASTER_REQ_SHIFT),
@@ -40,6 +42,9 @@
     KM_GET_SUPPORTED_IMPORT_FORMATS = (13 << KEYMASTER_REQ_SHIFT),
     KM_GET_SUPPORTED_EXPORT_FORMATS = (14 << KEYMASTER_REQ_SHIFT),
     KM_GET_KEY_CHARACTERISTICS      = (15 << KEYMASTER_REQ_SHIFT),
+    KM_ATTEST_KEY                   = (16 << KEYMASTER_REQ_SHIFT),
+    KM_UPGRADE_KEY                  = (17 << KEYMASTER_REQ_SHIFT),
+    KM_CONFIGURE                    = (18 << KEYMASTER_REQ_SHIFT),
 };
 
 #ifdef __ANDROID__
@@ -50,8 +55,8 @@
  * @payload: start of the serialized command specific payload
  */
 struct keymaster_message {
-	uint32_t cmd;
-	uint8_t payload[0];
+    uint32_t cmd;
+    uint8_t payload[0];
 };
 
 #endif
diff --git a/trusty/keymaster/module.cpp b/trusty/keymaster/module.cpp
index 81597d9..b472680 100644
--- a/trusty/keymaster/module.cpp
+++ b/trusty/keymaster/module.cpp
@@ -26,14 +26,15 @@
 /*
  * Generic device handling
  */
-static int trusty_keymaster_open(const hw_module_t* module, const char* name,
-                                 hw_device_t** device) {
-    if (strcmp(name, KEYSTORE_KEYMASTER) != 0)
+static int trusty_keymaster_open(const hw_module_t* module, const char* name, hw_device_t** device) {
+    if (strcmp(name, KEYSTORE_KEYMASTER) != 0) {
         return -EINVAL;
+    }
 
     TrustyKeymasterDevice* dev = new TrustyKeymasterDevice(module);
-    if (dev == NULL)
+    if (dev == NULL) {
         return -ENOMEM;
+    }
     *device = dev->hw_device();
     // Do not delete dev; it will get cleaned up when the caller calls device->close(), and must
     // exist until then.
@@ -47,14 +48,14 @@
 struct keystore_module HAL_MODULE_INFO_SYM __attribute__((visibility("default"))) = {
     .common =
         {
-         .tag = HARDWARE_MODULE_TAG,
-         .module_api_version = KEYMASTER_MODULE_API_VERSION_0_3,
-         .hal_api_version = HARDWARE_HAL_API_VERSION,
-         .id = KEYSTORE_HARDWARE_MODULE_ID,
-         .name = "Trusty Keymaster HAL",
-         .author = "The Android Open Source Project",
-         .methods = &keystore_module_methods,
-         .dso = 0,
-         .reserved = {},
+            .tag = HARDWARE_MODULE_TAG,
+            .module_api_version = KEYMASTER_MODULE_API_VERSION_2_0,
+            .hal_api_version = HARDWARE_HAL_API_VERSION,
+            .id = KEYSTORE_HARDWARE_MODULE_ID,
+            .name = "Trusty Keymaster HAL",
+            .author = "The Android Open Source Project",
+            .methods = &keystore_module_methods,
+            .dso = 0,
+            .reserved = {},
         },
 };
diff --git a/trusty/keymaster/trusty_keymaster_device.cpp b/trusty/keymaster/trusty_keymaster_device.cpp
index 1368f88..5f16fd0 100644
--- a/trusty/keymaster/trusty_keymaster_device.cpp
+++ b/trusty/keymaster/trusty_keymaster_device.cpp
@@ -25,49 +25,53 @@
 #include <string.h>
 #include <time.h>
 
+#include <algorithm>
 #include <type_traits>
 
-#include <hardware/keymaster0.h>
+#include <hardware/keymaster2.h>
 #include <keymaster/authorization_set.h>
 #include <log/log.h>
 
+#include "keymaster_ipc.h"
 #include "trusty_keymaster_device.h"
 #include "trusty_keymaster_ipc.h"
-#include "keymaster_ipc.h"
 
-const uint32_t SEND_BUF_SIZE = 8192;
-const uint32_t RECV_BUF_SIZE = 8192;
+const uint32_t RECV_BUF_SIZE = PAGE_SIZE;
+const uint32_t SEND_BUF_SIZE = (PAGE_SIZE - sizeof(struct keymaster_message) - 16 /* tipc header */);
+
+const size_t kMaximumAttestationChallengeLength = 128;
+const size_t kMaximumFinishInputLength = 2048;
 
 namespace keymaster {
 
 static keymaster_error_t translate_error(int err) {
     switch (err) {
-    case 0:
-        return KM_ERROR_OK;
-    case -EPERM:
-    case -EACCES:
-        return KM_ERROR_SECURE_HW_ACCESS_DENIED;
+        case 0:
+            return KM_ERROR_OK;
+        case -EPERM:
+        case -EACCES:
+            return KM_ERROR_SECURE_HW_ACCESS_DENIED;
 
-    case -ECANCELED:
-        return KM_ERROR_OPERATION_CANCELLED;
+        case -ECANCELED:
+            return KM_ERROR_OPERATION_CANCELLED;
 
-    case -ENODEV:
-        return KM_ERROR_UNIMPLEMENTED;
+        case -ENODEV:
+            return KM_ERROR_UNIMPLEMENTED;
 
-    case -ENOMEM:
-        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
+        case -ENOMEM:
+            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
 
-    case -EBUSY:
-        return KM_ERROR_SECURE_HW_BUSY;
+        case -EBUSY:
+            return KM_ERROR_SECURE_HW_BUSY;
 
-    case -EIO:
-        return KM_ERROR_SECURE_HW_COMMUNICATION_FAILED;
+        case -EIO:
+            return KM_ERROR_SECURE_HW_COMMUNICATION_FAILED;
 
-    case -EOVERFLOW:
-        return KM_ERROR_INVALID_INPUT_LENGTH;
+        case -EOVERFLOW:
+            return KM_ERROR_INVALID_INPUT_LENGTH;
 
-    default:
-        return KM_ERROR_UNKNOWN_ERROR;
+        default:
+            return KM_ERROR_UNKNOWN_ERROR;
     }
 }
 
@@ -75,31 +79,36 @@
     static_assert(std::is_standard_layout<TrustyKeymasterDevice>::value,
                   "TrustyKeymasterDevice must be standard layout");
     static_assert(offsetof(TrustyKeymasterDevice, device_) == 0,
-                  "device_ must be the first member of KeymasterOpenSsl");
+                  "device_ must be the first member of TrustyKeymasterDevice");
     static_assert(offsetof(TrustyKeymasterDevice, device_.common) == 0,
-                  "common must be the first member of keymaster_device");
+                  "common must be the first member of keymaster2_device");
 
     ALOGI("Creating device");
     ALOGD("Device address: %p", this);
 
-    memset(&device_, 0, sizeof(device_));
+    device_ = {};
 
     device_.common.tag = HARDWARE_DEVICE_TAG;
     device_.common.version = 1;
     device_.common.module = const_cast<hw_module_t*>(module);
     device_.common.close = close_device;
 
-    device_.flags = KEYMASTER_BLOBS_ARE_STANDALONE | KEYMASTER_SUPPORTS_EC;
+    device_.flags = KEYMASTER_SUPPORTS_EC;
 
-    device_.generate_keypair = generate_keypair;
-    device_.import_keypair = import_keypair;
-    device_.get_keypair_public = get_keypair_public;
-    device_.delete_keypair = NULL;
-    device_.delete_all = NULL;
-    device_.sign_data = sign_data;
-    device_.verify_data = verify_data;
-
-    device_.context = NULL;
+    device_.configure = configure;
+    device_.add_rng_entropy = add_rng_entropy;
+    device_.generate_key = generate_key;
+    device_.get_key_characteristics = get_key_characteristics;
+    device_.import_key = import_key;
+    device_.export_key = export_key;
+    device_.attest_key = attest_key;
+    device_.upgrade_key = upgrade_key;
+    device_.delete_key = nullptr;
+    device_.delete_all_keys = nullptr;
+    device_.begin = begin;
+    device_.update = update;
+    device_.finish = finish;
+    device_.abort = abort;
 
     int rc = trusty_keymaster_connect();
     error_ = translate_error(rc);
@@ -110,11 +119,11 @@
 
     GetVersionRequest version_request;
     GetVersionResponse version_response;
-    error_ = Send(version_request, &version_response);
+    error_ = Send(KM_GET_VERSION, version_request, &version_response);
     if (error_ == KM_ERROR_INVALID_ARGUMENT || error_ == KM_ERROR_UNIMPLEMENTED) {
-        ALOGI("\"Bad parameters\" error on GetVersion call.  Assuming version 0.");
-        message_version_ = 0;
-        error_ = KM_ERROR_OK;
+        ALOGE("\"Bad parameters\" error on GetVersion call.  Version 0 is not supported.");
+        error_ = KM_ERROR_VERSION_MISMATCH;
+        return;
     }
     message_version_ = MessageVersion(version_response.major_ver, version_response.minor_ver,
                                       version_response.subminor_ver);
@@ -130,261 +139,510 @@
     trusty_keymaster_disconnect();
 }
 
-const uint64_t HUNDRED_YEARS = 1000LL * 60 * 60 * 24 * 365 * 100;
+namespace {
 
-int TrustyKeymasterDevice::generate_keypair(const keymaster_keypair_t key_type,
-                                            const void* key_params, uint8_t** key_blob,
-                                            size_t* key_blob_length) {
-    ALOGD("Device received generate_keypair");
+// Allocates a new buffer with malloc and copies the contents of |buffer| to it. Caller takes
+// ownership of the returned buffer.
+uint8_t* DuplicateBuffer(const uint8_t* buffer, size_t size) {
+    uint8_t* tmp = reinterpret_cast<uint8_t*>(malloc(size));
+    if (tmp) {
+        memcpy(tmp, buffer, size);
+    }
+    return tmp;
+}
 
-    if (error_ != KM_ERROR_OK)
+template <typename RequestType>
+void AddClientAndAppData(const keymaster_blob_t* client_id, const keymaster_blob_t* app_data,
+                         RequestType* request) {
+    request->additional_params.Clear();
+    if (client_id) {
+        request->additional_params.push_back(TAG_APPLICATION_ID, *client_id);
+    }
+    if (app_data) {
+        request->additional_params.push_back(TAG_APPLICATION_DATA, *app_data);
+    }
+}
+
+}  //  unnamed namespace
+
+keymaster_error_t TrustyKeymasterDevice::configure(const keymaster_key_param_set_t* params) {
+    ALOGD("Device received configure\n");
+
+    if (error_ != KM_ERROR_OK) {
         return error_;
-
-    GenerateKeyRequest req(message_version_);
-    StoreNewKeyParams(&req.key_description);
-
-    switch (key_type) {
-    case TYPE_RSA: {
-        req.key_description.push_back(TAG_ALGORITHM, KM_ALGORITHM_RSA);
-        const keymaster_rsa_keygen_params_t* rsa_params =
-            static_cast<const keymaster_rsa_keygen_params_t*>(key_params);
-        ALOGD("Generating RSA pair, modulus size: %u, public exponent: %lu",
-              rsa_params->modulus_size, rsa_params->public_exponent);
-        req.key_description.push_back(TAG_KEY_SIZE, rsa_params->modulus_size);
-        req.key_description.push_back(TAG_RSA_PUBLIC_EXPONENT, rsa_params->public_exponent);
-        break;
+    }
+    if (!params) {
+        return KM_ERROR_UNEXPECTED_NULL_POINTER;
     }
 
-    case TYPE_EC: {
-        req.key_description.push_back(TAG_ALGORITHM, KM_ALGORITHM_EC);
-        const keymaster_ec_keygen_params_t* ec_params =
-            static_cast<const keymaster_ec_keygen_params_t*>(key_params);
-        ALOGD("Generating ECDSA pair, key size: %u", ec_params->field_size);
-        req.key_description.push_back(TAG_KEY_SIZE, ec_params->field_size);
-        break;
-    }
-    default:
-        ALOGD("Received request for unsuported key type %d", key_type);
-        return KM_ERROR_UNSUPPORTED_ALGORITHM;
+    AuthorizationSet params_copy(*params);
+    ConfigureRequest request;
+    if (!params_copy.GetTagValue(TAG_OS_VERSION, &request.os_version) ||
+        !params_copy.GetTagValue(TAG_OS_PATCHLEVEL, &request.os_patchlevel)) {
+        ALOGD("Configuration parameters must contain OS version and patch level");
+        return KM_ERROR_INVALID_ARGUMENT;
     }
 
-    GenerateKeyResponse rsp(message_version_);
-    ALOGD("Sending generate request");
-    keymaster_error_t err = Send(req, &rsp);
+    ConfigureResponse response;
+    keymaster_error_t err = Send(KM_CONFIGURE, request, &response);
     if (err != KM_ERROR_OK) {
-        ALOGE("Got error %d from send", err);
         return err;
     }
 
-    *key_blob_length = rsp.key_blob.key_material_size;
-    *key_blob = static_cast<uint8_t*>(malloc(*key_blob_length));
-    memcpy(*key_blob, rsp.key_blob.key_material, *key_blob_length);
-    ALOGD("Returning %d bytes in key blob\n", (int)*key_blob_length);
-
     return KM_ERROR_OK;
 }
 
-struct EVP_PKEY_Delete {
-    void operator()(EVP_PKEY* p) const { EVP_PKEY_free(p); }
-};
+keymaster_error_t TrustyKeymasterDevice::add_rng_entropy(const uint8_t* data, size_t data_length) {
+    ALOGD("Device received add_rng_entropy");
 
-struct PKCS8_PRIV_KEY_INFO_Delete {
-    void operator()(PKCS8_PRIV_KEY_INFO* p) const { PKCS8_PRIV_KEY_INFO_free(p); }
-};
-
-int TrustyKeymasterDevice::import_keypair(const uint8_t* key, const size_t key_length,
-                                          uint8_t** key_blob, size_t* key_blob_length) {
-    ALOGD("Device received import_keypair");
-    if (error_ != KM_ERROR_OK)
+    if (error_ != KM_ERROR_OK) {
         return error_;
+    }
 
-    if (!key)
+    AddEntropyRequest request;
+    request.random_data.Reinitialize(data, data_length);
+    AddEntropyResponse response;
+    return Send(KM_ADD_RNG_ENTROPY, request, &response);
+}
+
+keymaster_error_t TrustyKeymasterDevice::generate_key(
+    const keymaster_key_param_set_t* params, keymaster_key_blob_t* key_blob,
+    keymaster_key_characteristics_t* characteristics) {
+    ALOGD("Device received generate_key");
+
+    if (error_ != KM_ERROR_OK) {
+        return error_;
+    }
+    if (!params) {
         return KM_ERROR_UNEXPECTED_NULL_POINTER;
-
-    if (!key_blob || !key_blob_length)
+    }
+    if (!key_blob) {
         return KM_ERROR_OUTPUT_PARAMETER_NULL;
+    }
+
+    GenerateKeyRequest request(message_version_);
+    request.key_description.Reinitialize(*params);
+    request.key_description.push_back(TAG_CREATION_DATETIME, java_time(time(NULL)));
+
+    GenerateKeyResponse response(message_version_);
+    keymaster_error_t err = Send(KM_GENERATE_KEY, request, &response);
+    if (err != KM_ERROR_OK) {
+        return err;
+    }
+
+    key_blob->key_material_size = response.key_blob.key_material_size;
+    key_blob->key_material =
+        DuplicateBuffer(response.key_blob.key_material, response.key_blob.key_material_size);
+    if (!key_blob->key_material) {
+        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
+    }
+
+    if (characteristics) {
+        response.enforced.CopyToParamSet(&characteristics->hw_enforced);
+        response.unenforced.CopyToParamSet(&characteristics->sw_enforced);
+    }
+
+    return KM_ERROR_OK;
+}
+
+keymaster_error_t TrustyKeymasterDevice::get_key_characteristics(
+    const keymaster_key_blob_t* key_blob, const keymaster_blob_t* client_id,
+    const keymaster_blob_t* app_data, keymaster_key_characteristics_t* characteristics) {
+    ALOGD("Device received get_key_characteristics");
+
+    if (error_ != KM_ERROR_OK) {
+        return error_;
+    }
+    if (!key_blob || !key_blob->key_material) {
+        return KM_ERROR_UNEXPECTED_NULL_POINTER;
+    }
+    if (!characteristics) {
+        return KM_ERROR_OUTPUT_PARAMETER_NULL;
+    }
+
+    GetKeyCharacteristicsRequest request;
+    request.SetKeyMaterial(*key_blob);
+    AddClientAndAppData(client_id, app_data, &request);
+
+    GetKeyCharacteristicsResponse response;
+    keymaster_error_t err = Send(KM_GET_KEY_CHARACTERISTICS, request, &response);
+    if (err != KM_ERROR_OK) {
+        return err;
+    }
+
+    response.enforced.CopyToParamSet(&characteristics->hw_enforced);
+    response.unenforced.CopyToParamSet(&characteristics->sw_enforced);
+
+    return KM_ERROR_OK;
+}
+
+keymaster_error_t TrustyKeymasterDevice::import_key(
+    const keymaster_key_param_set_t* params, keymaster_key_format_t key_format,
+    const keymaster_blob_t* key_data, keymaster_key_blob_t* key_blob,
+    keymaster_key_characteristics_t* characteristics) {
+    ALOGD("Device received import_key");
+
+    if (error_ != KM_ERROR_OK) {
+        return error_;
+    }
+    if (!params || !key_data) {
+        return KM_ERROR_UNEXPECTED_NULL_POINTER;
+    }
+    if (!key_blob) {
+        return KM_ERROR_OUTPUT_PARAMETER_NULL;
+    }
 
     ImportKeyRequest request(message_version_);
-    StoreNewKeyParams(&request.key_description);
-    keymaster_algorithm_t algorithm;
-    keymaster_error_t err = GetPkcs8KeyAlgorithm(key, key_length, &algorithm);
-    if (err != KM_ERROR_OK)
-        return err;
-    request.key_description.push_back(TAG_ALGORITHM, algorithm);
+    request.key_description.Reinitialize(*params);
+    request.key_description.push_back(TAG_CREATION_DATETIME, java_time(time(NULL)));
 
-    request.SetKeyMaterial(key, key_length);
-    request.key_format = KM_KEY_FORMAT_PKCS8;
+    request.key_format = key_format;
+    request.SetKeyMaterial(key_data->data, key_data->data_length);
+
     ImportKeyResponse response(message_version_);
-    err = Send(request, &response);
-    if (err != KM_ERROR_OK)
+    keymaster_error_t err = Send(KM_IMPORT_KEY, request, &response);
+    if (err != KM_ERROR_OK) {
         return err;
+    }
 
-    *key_blob_length = response.key_blob.key_material_size;
-    *key_blob = static_cast<uint8_t*>(malloc(*key_blob_length));
-    memcpy(*key_blob, response.key_blob.key_material, *key_blob_length);
-    printf("Returning %d bytes in key blob\n", (int)*key_blob_length);
+    key_blob->key_material_size = response.key_blob.key_material_size;
+    key_blob->key_material =
+        DuplicateBuffer(response.key_blob.key_material, response.key_blob.key_material_size);
+    if (!key_blob->key_material) {
+        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
+    }
+
+    if (characteristics) {
+        response.enforced.CopyToParamSet(&characteristics->hw_enforced);
+        response.unenforced.CopyToParamSet(&characteristics->sw_enforced);
+    }
 
     return KM_ERROR_OK;
 }
 
-keymaster_error_t TrustyKeymasterDevice::GetPkcs8KeyAlgorithm(const uint8_t* key, size_t key_length,
-                                                              keymaster_algorithm_t* algorithm) {
-    if (key == NULL) {
-        ALOGE("No key specified for import");
+keymaster_error_t TrustyKeymasterDevice::export_key(keymaster_key_format_t export_format,
+                                                    const keymaster_key_blob_t* key_to_export,
+                                                    const keymaster_blob_t* client_id,
+                                                    const keymaster_blob_t* app_data,
+                                                    keymaster_blob_t* export_data) {
+    ALOGD("Device received export_key");
+
+    if (error_ != KM_ERROR_OK) {
+        return error_;
+    }
+    if (!key_to_export || !key_to_export->key_material) {
         return KM_ERROR_UNEXPECTED_NULL_POINTER;
     }
-
-    UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> pkcs8(
-        d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, key_length));
-    if (pkcs8.get() == NULL) {
-        ALOGE("Could not parse PKCS8 key blob");
-        return KM_ERROR_INVALID_KEY_BLOB;
+    if (!export_data) {
+        return KM_ERROR_OUTPUT_PARAMETER_NULL;
     }
 
-    UniquePtr<EVP_PKEY, EVP_PKEY_Delete> pkey(EVP_PKCS82PKEY(pkcs8.get()));
-    if (pkey.get() == NULL) {
-        ALOGE("Could not extract key from PKCS8 key blob");
-        return KM_ERROR_INVALID_KEY_BLOB;
-    }
-
-    switch (EVP_PKEY_type(pkey->type)) {
-    case EVP_PKEY_RSA:
-        *algorithm = KM_ALGORITHM_RSA;
-        break;
-    case EVP_PKEY_EC:
-        *algorithm = KM_ALGORITHM_EC;
-        break;
-    default:
-        ALOGE("Unsupported algorithm %d", EVP_PKEY_type(pkey->type));
-        return KM_ERROR_UNSUPPORTED_ALGORITHM;
-    }
-
-    return KM_ERROR_OK;
-}
-
-int TrustyKeymasterDevice::get_keypair_public(const uint8_t* key_blob, const size_t key_blob_length,
-                                              uint8_t** x509_data, size_t* x509_data_length) {
-    ALOGD("Device received get_keypair_public");
-    if (error_ != KM_ERROR_OK)
-        return error_;
+    export_data->data = nullptr;
+    export_data->data_length = 0;
 
     ExportKeyRequest request(message_version_);
-    request.SetKeyMaterial(key_blob, key_blob_length);
-    request.key_format = KM_KEY_FORMAT_X509;
+    request.key_format = export_format;
+    request.SetKeyMaterial(*key_to_export);
+    AddClientAndAppData(client_id, app_data, &request);
+
     ExportKeyResponse response(message_version_);
-    keymaster_error_t err = Send(request, &response);
-    if (err != KM_ERROR_OK)
+    keymaster_error_t err = Send(KM_EXPORT_KEY, request, &response);
+    if (err != KM_ERROR_OK) {
         return err;
+    }
 
-    *x509_data_length = response.key_data_length;
-    *x509_data = static_cast<uint8_t*>(malloc(*x509_data_length));
-    memcpy(*x509_data, response.key_data, *x509_data_length);
-    printf("Returning %d bytes in x509 key\n", (int)*x509_data_length);
+    export_data->data_length = response.key_data_length;
+    export_data->data = DuplicateBuffer(response.key_data, response.key_data_length);
+    if (!export_data->data) {
+        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
+    }
 
     return KM_ERROR_OK;
 }
 
-int TrustyKeymasterDevice::sign_data(const void* signing_params, const uint8_t* key_blob,
-                                     const size_t key_blob_length, const uint8_t* data,
-                                     const size_t data_length, uint8_t** signed_data,
-                                     size_t* signed_data_length) {
-    ALOGD("Device received sign_data, %d", error_);
-    if (error_ != KM_ERROR_OK)
+keymaster_error_t TrustyKeymasterDevice::attest_key(const keymaster_key_blob_t* key_to_attest,
+                                                    const keymaster_key_param_set_t* attest_params,
+                                                    keymaster_cert_chain_t* cert_chain) {
+    ALOGD("Device received attest_key");
+
+    if (error_ != KM_ERROR_OK) {
         return error_;
+    }
+    if (!key_to_attest || !attest_params) {
+        return KM_ERROR_UNEXPECTED_NULL_POINTER;
+    }
+    if (!cert_chain) {
+        return KM_ERROR_OUTPUT_PARAMETER_NULL;
+    }
 
-    BeginOperationRequest begin_request(message_version_);
-    begin_request.purpose = KM_PURPOSE_SIGN;
-    begin_request.SetKeyMaterial(key_blob, key_blob_length);
-    keymaster_error_t err = StoreSigningParams(signing_params, key_blob, key_blob_length,
-                                               &begin_request.additional_params);
+    cert_chain->entry_count = 0;
+    cert_chain->entries = nullptr;
+
+    AttestKeyRequest request;
+    request.SetKeyMaterial(*key_to_attest);
+    request.attest_params.Reinitialize(*attest_params);
+
+    keymaster_blob_t attestation_challenge = {};
+    request.attest_params.GetTagValue(TAG_ATTESTATION_CHALLENGE, &attestation_challenge);
+    if (attestation_challenge.data_length > kMaximumAttestationChallengeLength) {
+        ALOGE("%zu-byte attestation challenge; only %zu bytes allowed",
+              attestation_challenge.data_length, kMaximumAttestationChallengeLength);
+        return KM_ERROR_INVALID_INPUT_LENGTH;
+    }
+
+    AttestKeyResponse response;
+    keymaster_error_t err = Send(KM_ATTEST_KEY, request, &response);
     if (err != KM_ERROR_OK) {
-        ALOGE("Error extracting signing params: %d", err);
         return err;
     }
 
-    BeginOperationResponse begin_response(message_version_);
-    ALOGD("Sending signing request begin");
-    err = Send(begin_request, &begin_response);
-    if (err != KM_ERROR_OK) {
-        ALOGE("Error sending sign begin: %d", err);
-        return err;
+    // Allocate and clear storage for cert_chain.
+    keymaster_cert_chain_t& rsp_chain = response.certificate_chain;
+    cert_chain->entries = reinterpret_cast<keymaster_blob_t*>(
+        malloc(rsp_chain.entry_count * sizeof(*cert_chain->entries)));
+    if (!cert_chain->entries) {
+        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
+    }
+    cert_chain->entry_count = rsp_chain.entry_count;
+    for (keymaster_blob_t& entry : array_range(cert_chain->entries, cert_chain->entry_count)) {
+        entry = {};
     }
 
-    UpdateOperationRequest update_request(message_version_);
-    update_request.op_handle = begin_response.op_handle;
-    update_request.input.Reinitialize(data, data_length);
-    UpdateOperationResponse update_response(message_version_);
-    ALOGD("Sending signing request update");
-    err = Send(update_request, &update_response);
-    if (err != KM_ERROR_OK) {
-        ALOGE("Error sending sign update: %d", err);
-        return err;
+    // Copy cert_chain contents
+    size_t i = 0;
+    for (keymaster_blob_t& entry : array_range(rsp_chain.entries, rsp_chain.entry_count)) {
+        cert_chain->entries[i].data = DuplicateBuffer(entry.data, entry.data_length);
+        if (!cert_chain->entries[i].data) {
+            keymaster_free_cert_chain(cert_chain);
+            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
+        }
+        cert_chain->entries[i].data_length = entry.data_length;
+        ++i;
     }
 
-    FinishOperationRequest finish_request(message_version_);
-    finish_request.op_handle = begin_response.op_handle;
-    FinishOperationResponse finish_response(message_version_);
-    ALOGD("Sending signing request finish");
-    err = Send(finish_request, &finish_response);
-    if (err != KM_ERROR_OK) {
-        ALOGE("Error sending sign finish: %d", err);
-        return err;
-    }
-
-    *signed_data_length = finish_response.output.available_read();
-    *signed_data = static_cast<uint8_t*>(malloc(*signed_data_length));
-    if (!finish_response.output.read(*signed_data, *signed_data_length)) {
-        ALOGE("Error reading response data: %d", err);
-        return KM_ERROR_UNKNOWN_ERROR;
-    }
     return KM_ERROR_OK;
 }
 
-int TrustyKeymasterDevice::verify_data(const void* signing_params, const uint8_t* key_blob,
-                                       const size_t key_blob_length, const uint8_t* signed_data,
-                                       const size_t signed_data_length, const uint8_t* signature,
-                                       const size_t signature_length) {
-    ALOGD("Device received verify_data");
-    if (error_ != KM_ERROR_OK)
+keymaster_error_t TrustyKeymasterDevice::upgrade_key(const keymaster_key_blob_t* key_to_upgrade,
+                                                     const keymaster_key_param_set_t* upgrade_params,
+                                                     keymaster_key_blob_t* upgraded_key) {
+    ALOGD("Device received upgrade_key");
+
+    if (error_ != KM_ERROR_OK) {
         return error_;
+    }
+    if (!key_to_upgrade || !upgrade_params) {
+        return KM_ERROR_UNEXPECTED_NULL_POINTER;
+    }
+    if (!upgraded_key) {
+        return KM_ERROR_OUTPUT_PARAMETER_NULL;
+    }
 
-    BeginOperationRequest begin_request(message_version_);
-    begin_request.purpose = KM_PURPOSE_VERIFY;
-    begin_request.SetKeyMaterial(key_blob, key_blob_length);
-    keymaster_error_t err = StoreSigningParams(signing_params, key_blob, key_blob_length,
-                                               &begin_request.additional_params);
-    if (err != KM_ERROR_OK)
-        return err;
+    UpgradeKeyRequest request;
+    request.SetKeyMaterial(*key_to_upgrade);
+    request.upgrade_params.Reinitialize(*upgrade_params);
 
-    BeginOperationResponse begin_response(message_version_);
-    err = Send(begin_request, &begin_response);
-    if (err != KM_ERROR_OK)
+    UpgradeKeyResponse response;
+    keymaster_error_t err = Send(KM_UPGRADE_KEY, request, &response);
+    if (err != KM_ERROR_OK) {
         return err;
+    }
 
-    UpdateOperationRequest update_request(message_version_);
-    update_request.op_handle = begin_response.op_handle;
-    update_request.input.Reinitialize(signed_data, signed_data_length);
-    UpdateOperationResponse update_response(message_version_);
-    err = Send(update_request, &update_response);
-    if (err != KM_ERROR_OK)
-        return err;
+    upgraded_key->key_material_size = response.upgraded_key.key_material_size;
+    upgraded_key->key_material = DuplicateBuffer(response.upgraded_key.key_material,
+                                                 response.upgraded_key.key_material_size);
+    if (!upgraded_key->key_material) {
+        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
+    }
 
-    FinishOperationRequest finish_request(message_version_);
-    finish_request.op_handle = begin_response.op_handle;
-    finish_request.signature.Reinitialize(signature, signature_length);
-    FinishOperationResponse finish_response(message_version_);
-    err = Send(finish_request, &finish_response);
-    if (err != KM_ERROR_OK)
-        return err;
     return KM_ERROR_OK;
 }
 
+keymaster_error_t TrustyKeymasterDevice::begin(keymaster_purpose_t purpose,
+                                               const keymaster_key_blob_t* key,
+                                               const keymaster_key_param_set_t* in_params,
+                                               keymaster_key_param_set_t* out_params,
+                                               keymaster_operation_handle_t* operation_handle) {
+    ALOGD("Device received begin");
+
+    if (error_ != KM_ERROR_OK) {
+        return error_;
+    }
+    if (!key || !key->key_material) {
+        return KM_ERROR_UNEXPECTED_NULL_POINTER;
+    }
+    if (!operation_handle) {
+        return KM_ERROR_OUTPUT_PARAMETER_NULL;
+    }
+
+    if (out_params) {
+        *out_params = {};
+    }
+
+    BeginOperationRequest request;
+    request.purpose = purpose;
+    request.SetKeyMaterial(*key);
+    request.additional_params.Reinitialize(*in_params);
+
+    BeginOperationResponse response;
+    keymaster_error_t err = Send(KM_BEGIN_OPERATION, request, &response);
+    if (err != KM_ERROR_OK) {
+        return err;
+    }
+
+    if (response.output_params.size() > 0) {
+        if (out_params) {
+            response.output_params.CopyToParamSet(out_params);
+        } else {
+            return KM_ERROR_OUTPUT_PARAMETER_NULL;
+        }
+    }
+    *operation_handle = response.op_handle;
+
+    return KM_ERROR_OK;
+}
+
+keymaster_error_t TrustyKeymasterDevice::update(keymaster_operation_handle_t operation_handle,
+                                                const keymaster_key_param_set_t* in_params,
+                                                const keymaster_blob_t* input,
+                                                size_t* input_consumed,
+                                                keymaster_key_param_set_t* out_params,
+                                                keymaster_blob_t* output) {
+    ALOGD("Device received update");
+
+    if (error_ != KM_ERROR_OK) {
+        return error_;
+    }
+    if (!input) {
+        return KM_ERROR_UNEXPECTED_NULL_POINTER;
+    }
+    if (!input_consumed) {
+        return KM_ERROR_OUTPUT_PARAMETER_NULL;
+    }
+
+    if (out_params) {
+        *out_params = {};
+    }
+    if (output) {
+        *output = {};
+    }
+
+    UpdateOperationRequest request;
+    request.op_handle = operation_handle;
+    if (in_params) {
+        request.additional_params.Reinitialize(*in_params);
+    }
+    if (input && input->data_length > 0) {
+        size_t max_input_size = SEND_BUF_SIZE - request.SerializedSize();
+        request.input.Reinitialize(input->data, std::min(input->data_length, max_input_size));
+    }
+
+    UpdateOperationResponse response;
+    keymaster_error_t err = Send(KM_UPDATE_OPERATION, request, &response);
+    if (err != KM_ERROR_OK) {
+        return err;
+    }
+
+    if (response.output_params.size() > 0) {
+        if (out_params) {
+            response.output_params.CopyToParamSet(out_params);
+        } else {
+            return KM_ERROR_OUTPUT_PARAMETER_NULL;
+        }
+    }
+    *input_consumed = response.input_consumed;
+    if (output) {
+        output->data_length = response.output.available_read();
+        output->data = DuplicateBuffer(response.output.peek_read(), output->data_length);
+        if (!output->data) {
+            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
+        }
+    } else if (response.output.available_read() > 0) {
+        return KM_ERROR_OUTPUT_PARAMETER_NULL;
+    }
+
+    return KM_ERROR_OK;
+}
+
+keymaster_error_t TrustyKeymasterDevice::finish(keymaster_operation_handle_t operation_handle,
+                                                const keymaster_key_param_set_t* in_params,
+                                                const keymaster_blob_t* input,
+                                                const keymaster_blob_t* signature,
+                                                keymaster_key_param_set_t* out_params,
+                                                keymaster_blob_t* output) {
+    ALOGD("Device received finish");
+
+    if (error_ != KM_ERROR_OK) {
+        return error_;
+    }
+    if (input && input->data_length > kMaximumFinishInputLength) {
+        return KM_ERROR_INVALID_ARGUMENT;
+    }
+
+    if (out_params) {
+        *out_params = {};
+    }
+    if (output) {
+        *output = {};
+    }
+
+    FinishOperationRequest request;
+    request.op_handle = operation_handle;
+    if (signature && signature->data && signature->data_length > 0) {
+        request.signature.Reinitialize(signature->data, signature->data_length);
+    }
+    if (input && input->data && input->data_length) {
+        request.input.Reinitialize(input->data, input->data_length);
+    }
+    if (in_params) {
+        request.additional_params.Reinitialize(*in_params);
+    }
+
+    FinishOperationResponse response;
+    keymaster_error_t err = Send(KM_FINISH_OPERATION, request, &response);
+    if (err != KM_ERROR_OK) {
+        return err;
+    }
+
+    if (response.output_params.size() > 0) {
+        if (out_params) {
+            response.output_params.CopyToParamSet(out_params);
+        } else {
+            return KM_ERROR_OUTPUT_PARAMETER_NULL;
+        }
+    }
+    if (output) {
+        output->data_length = response.output.available_read();
+        output->data = DuplicateBuffer(response.output.peek_read(), output->data_length);
+        if (!output->data) {
+            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
+        }
+    } else if (response.output.available_read() > 0) {
+        return KM_ERROR_OUTPUT_PARAMETER_NULL;
+    }
+
+    return KM_ERROR_OK;
+}
+
+keymaster_error_t TrustyKeymasterDevice::abort(keymaster_operation_handle_t operation_handle) {
+    ALOGD("Device received abort");
+
+    if (error_ != KM_ERROR_OK) {
+        return error_;
+    }
+
+    AbortOperationRequest request;
+    request.op_handle = operation_handle;
+    AbortOperationResponse response;
+    return Send(KM_ABORT_OPERATION, request, &response);
+}
+
 hw_device_t* TrustyKeymasterDevice::hw_device() {
     return &device_.common;
 }
 
-static inline TrustyKeymasterDevice* convert_device(const keymaster0_device_t* dev) {
-    return reinterpret_cast<TrustyKeymasterDevice*>(const_cast<keymaster0_device_t*>(dev));
+static inline TrustyKeymasterDevice* convert_device(const keymaster2_device_t* dev) {
+    return reinterpret_cast<TrustyKeymasterDevice*>(const_cast<keymaster2_device_t*>(dev));
 }
 
 /* static */
@@ -394,52 +652,111 @@
 }
 
 /* static */
-int TrustyKeymasterDevice::generate_keypair(const keymaster0_device_t* dev,
-                                            const keymaster_keypair_t key_type,
-                                            const void* key_params, uint8_t** keyBlob,
-                                            size_t* keyBlobLength) {
-    ALOGD("Generate keypair, sending to device: %p", convert_device(dev));
-    return convert_device(dev)->generate_keypair(key_type, key_params, keyBlob, keyBlobLength);
+keymaster_error_t TrustyKeymasterDevice::configure(const keymaster2_device_t* dev,
+                                                   const keymaster_key_param_set_t* params) {
+    return convert_device(dev)->configure(params);
 }
 
 /* static */
-int TrustyKeymasterDevice::import_keypair(const keymaster0_device_t* dev, const uint8_t* key,
-                                          const size_t key_length, uint8_t** key_blob,
-                                          size_t* key_blob_length) {
-    return convert_device(dev)->import_keypair(key, key_length, key_blob, key_blob_length);
+keymaster_error_t TrustyKeymasterDevice::add_rng_entropy(const keymaster2_device_t* dev,
+                                                         const uint8_t* data, size_t data_length) {
+    return convert_device(dev)->add_rng_entropy(data, data_length);
 }
 
 /* static */
-int TrustyKeymasterDevice::get_keypair_public(const keymaster0_device_t* dev,
-                                              const uint8_t* key_blob, const size_t key_blob_length,
-                                              uint8_t** x509_data, size_t* x509_data_length) {
-    return convert_device(dev)
-        ->get_keypair_public(key_blob, key_blob_length, x509_data, x509_data_length);
+keymaster_error_t TrustyKeymasterDevice::generate_key(
+    const keymaster2_device_t* dev, const keymaster_key_param_set_t* params,
+    keymaster_key_blob_t* key_blob, keymaster_key_characteristics_t* characteristics) {
+    return convert_device(dev)->generate_key(params, key_blob, characteristics);
 }
 
 /* static */
-int TrustyKeymasterDevice::sign_data(const keymaster0_device_t* dev, const void* params,
-                                     const uint8_t* keyBlob, const size_t keyBlobLength,
-                                     const uint8_t* data, const size_t dataLength,
-                                     uint8_t** signedData, size_t* signedDataLength) {
-    return convert_device(dev)
-        ->sign_data(params, keyBlob, keyBlobLength, data, dataLength, signedData, signedDataLength);
+keymaster_error_t TrustyKeymasterDevice::get_key_characteristics(
+    const keymaster2_device_t* dev, const keymaster_key_blob_t* key_blob,
+    const keymaster_blob_t* client_id, const keymaster_blob_t* app_data,
+    keymaster_key_characteristics_t* characteristics) {
+    return convert_device(dev)->get_key_characteristics(key_blob, client_id, app_data,
+                                                        characteristics);
 }
 
 /* static */
-int TrustyKeymasterDevice::verify_data(const keymaster0_device_t* dev, const void* params,
-                                       const uint8_t* keyBlob, const size_t keyBlobLength,
-                                       const uint8_t* signedData, const size_t signedDataLength,
-                                       const uint8_t* signature, const size_t signatureLength) {
-    return convert_device(dev)->verify_data(params, keyBlob, keyBlobLength, signedData,
-                                            signedDataLength, signature, signatureLength);
+keymaster_error_t TrustyKeymasterDevice::import_key(
+    const keymaster2_device_t* dev, const keymaster_key_param_set_t* params,
+    keymaster_key_format_t key_format, const keymaster_blob_t* key_data,
+    keymaster_key_blob_t* key_blob, keymaster_key_characteristics_t* characteristics) {
+    return convert_device(dev)->import_key(params, key_format, key_data, key_blob, characteristics);
+}
+
+/* static */
+keymaster_error_t TrustyKeymasterDevice::export_key(const keymaster2_device_t* dev,
+                                                    keymaster_key_format_t export_format,
+                                                    const keymaster_key_blob_t* key_to_export,
+                                                    const keymaster_blob_t* client_id,
+                                                    const keymaster_blob_t* app_data,
+                                                    keymaster_blob_t* export_data) {
+    return convert_device(dev)->export_key(export_format, key_to_export, client_id, app_data,
+                                           export_data);
+}
+
+/* static */
+keymaster_error_t TrustyKeymasterDevice::attest_key(const keymaster2_device_t* dev,
+                                                    const keymaster_key_blob_t* key_to_attest,
+                                                    const keymaster_key_param_set_t* attest_params,
+                                                    keymaster_cert_chain_t* cert_chain) {
+    return convert_device(dev)->attest_key(key_to_attest, attest_params, cert_chain);
+}
+
+/* static */
+keymaster_error_t TrustyKeymasterDevice::upgrade_key(const keymaster2_device_t* dev,
+                                                     const keymaster_key_blob_t* key_to_upgrade,
+                                                     const keymaster_key_param_set_t* upgrade_params,
+                                                     keymaster_key_blob_t* upgraded_key) {
+    return convert_device(dev)->upgrade_key(key_to_upgrade, upgrade_params, upgraded_key);
+}
+
+/* static */
+keymaster_error_t TrustyKeymasterDevice::begin(const keymaster2_device_t* dev,
+                                               keymaster_purpose_t purpose,
+                                               const keymaster_key_blob_t* key,
+                                               const keymaster_key_param_set_t* in_params,
+                                               keymaster_key_param_set_t* out_params,
+                                               keymaster_operation_handle_t* operation_handle) {
+    return convert_device(dev)->begin(purpose, key, in_params, out_params, operation_handle);
+}
+
+/* static */
+keymaster_error_t TrustyKeymasterDevice::update(
+    const keymaster2_device_t* dev, keymaster_operation_handle_t operation_handle,
+    const keymaster_key_param_set_t* in_params, const keymaster_blob_t* input,
+    size_t* input_consumed, keymaster_key_param_set_t* out_params, keymaster_blob_t* output) {
+    return convert_device(dev)->update(operation_handle, in_params, input, input_consumed,
+                                       out_params, output);
+}
+
+/* static */
+keymaster_error_t TrustyKeymasterDevice::finish(const keymaster2_device_t* dev,
+                                                keymaster_operation_handle_t operation_handle,
+                                                const keymaster_key_param_set_t* in_params,
+                                                const keymaster_blob_t* input,
+                                                const keymaster_blob_t* signature,
+                                                keymaster_key_param_set_t* out_params,
+                                                keymaster_blob_t* output) {
+    return convert_device(dev)->finish(operation_handle, in_params, input, signature, out_params,
+                                       output);
+}
+
+/* static */
+keymaster_error_t TrustyKeymasterDevice::abort(const keymaster2_device_t* dev,
+                                               keymaster_operation_handle_t operation_handle) {
+    return convert_device(dev)->abort(operation_handle);
 }
 
 keymaster_error_t TrustyKeymasterDevice::Send(uint32_t command, const Serializable& req,
                                               KeymasterResponse* rsp) {
     uint32_t req_size = req.SerializedSize();
-    if (req_size > SEND_BUF_SIZE)
+    if (req_size > SEND_BUF_SIZE) {
         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
+    }
     uint8_t send_buf[SEND_BUF_SIZE];
     Eraser send_buf_eraser(send_buf, SEND_BUF_SIZE);
     req.Serialize(send_buf, send_buf + req_size);
@@ -448,7 +765,7 @@
     uint8_t recv_buf[RECV_BUF_SIZE];
     Eraser recv_buf_eraser(recv_buf, RECV_BUF_SIZE);
     uint32_t rsp_size = RECV_BUF_SIZE;
-    printf("Sending %d byte request\n", (int)req.SerializedSize());
+    ALOGV("Sending %d byte request\n", (int)req.SerializedSize());
     int rc = trusty_keymaster_call(command, send_buf, req_size, recv_buf, &rsp_size);
     if (rc < 0) {
         ALOGE("tipc error: %d\n", rc);
@@ -458,8 +775,8 @@
         ALOGV("Received %d byte response\n", rsp_size);
     }
 
-    const keymaster_message* msg = (keymaster_message *) recv_buf;
-    const uint8_t *p = msg->payload;
+    const keymaster_message* msg = (keymaster_message*)recv_buf;
+    const uint8_t* p = msg->payload;
     if (!rsp->Deserialize(&p, p + rsp_size)) {
         ALOGE("Error deserializing response of size %d\n", (int)rsp_size);
         return KM_ERROR_UNKNOWN_ERROR;
@@ -470,65 +787,4 @@
     return rsp->error;
 }
 
-keymaster_error_t TrustyKeymasterDevice::StoreSigningParams(const void* signing_params,
-                                                            const uint8_t* key_blob,
-                                                            size_t key_blob_length,
-                                                            AuthorizationSet* auth_set) {
-    uint8_t* pub_key_data;
-    size_t pub_key_data_length;
-    int err = get_keypair_public(&device_, key_blob, key_blob_length, &pub_key_data,
-                                 &pub_key_data_length);
-    if (err < 0) {
-        ALOGE("Error %d extracting public key to determine algorithm", err);
-        return KM_ERROR_INVALID_KEY_BLOB;
-    }
-    UniquePtr<uint8_t, Malloc_Delete> pub_key(pub_key_data);
-
-    const uint8_t* p = pub_key_data;
-    UniquePtr<EVP_PKEY, EVP_PKEY_Delete> pkey(
-        d2i_PUBKEY(nullptr /* allocate new struct */, &p, pub_key_data_length));
-
-    switch (EVP_PKEY_type(pkey->type)) {
-    case EVP_PKEY_RSA: {
-        const keymaster_rsa_sign_params_t* rsa_params =
-            reinterpret_cast<const keymaster_rsa_sign_params_t*>(signing_params);
-        if (rsa_params->digest_type != DIGEST_NONE)
-            return KM_ERROR_UNSUPPORTED_DIGEST;
-        if (rsa_params->padding_type != PADDING_NONE)
-            return KM_ERROR_UNSUPPORTED_PADDING_MODE;
-        if (!auth_set->push_back(TAG_DIGEST, KM_DIGEST_NONE) ||
-            !auth_set->push_back(TAG_PADDING, KM_PAD_NONE))
-            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
-    } break;
-    case EVP_PKEY_EC: {
-        const keymaster_ec_sign_params_t* ecdsa_params =
-            reinterpret_cast<const keymaster_ec_sign_params_t*>(signing_params);
-        if (ecdsa_params->digest_type != DIGEST_NONE)
-            return KM_ERROR_UNSUPPORTED_DIGEST;
-        if (!auth_set->push_back(TAG_DIGEST, KM_DIGEST_NONE))
-            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
-    } break;
-    default:
-        return KM_ERROR_UNSUPPORTED_ALGORITHM;
-    }
-    return KM_ERROR_OK;
-}
-
-void TrustyKeymasterDevice::StoreNewKeyParams(AuthorizationSet* auth_set) {
-    auth_set->push_back(TAG_PURPOSE, KM_PURPOSE_SIGN);
-    auth_set->push_back(TAG_PURPOSE, KM_PURPOSE_VERIFY);
-    auth_set->push_back(TAG_ALL_USERS);
-    auth_set->push_back(TAG_NO_AUTH_REQUIRED);
-    uint64_t now = java_time(time(NULL));
-    auth_set->push_back(TAG_CREATION_DATETIME, now);
-    auth_set->push_back(TAG_ORIGINATION_EXPIRE_DATETIME, now + HUNDRED_YEARS);
-    if (message_version_ == 0) {
-        auth_set->push_back(TAG_DIGEST_OLD, KM_DIGEST_NONE);
-        auth_set->push_back(TAG_PADDING_OLD, KM_PAD_NONE);
-    } else {
-        auth_set->push_back(TAG_DIGEST, KM_DIGEST_NONE);
-        auth_set->push_back(TAG_PADDING, KM_PAD_NONE);
-    }
-}
-
 }  // namespace keymaster
diff --git a/trusty/keymaster/trusty_keymaster_device.h b/trusty/keymaster/trusty_keymaster_device.h
index 68cf40c..cfada1b 100644
--- a/trusty/keymaster/trusty_keymaster_device.h
+++ b/trusty/keymaster/trusty_keymaster_device.h
@@ -14,19 +14,16 @@
  * limitations under the License.
  */
 
-#ifndef EXTERNAL_KEYMASTER_TRUSTY_KEYMASTER_DEVICE_H_
-#define EXTERNAL_KEYMASTER_TRUSTY_KEYMASTER_DEVICE_H_
+#ifndef TRUSTY_KEYMASTER_TRUSTY_KEYMASTER_DEVICE_H_
+#define TRUSTY_KEYMASTER_TRUSTY_KEYMASTER_DEVICE_H_
 
-#include <hardware/keymaster0.h>
-
+#include <hardware/keymaster2.h>
 #include <keymaster/android_keymaster_messages.h>
 
-#include "keymaster_ipc.h"
-
 namespace keymaster {
 
 /**
- * Software OpenSSL-based Keymaster device.
+ * Trusty Keymaster device.
  *
  * IMPORTANT MAINTAINER NOTE: Pointers to instances of this class must be castable to hw_device_t
  * and keymaster_device. This means it must remain a standard layout class (no virtual functions and
@@ -46,79 +43,111 @@
 
     keymaster_error_t session_error() { return error_; }
 
-    int generate_keypair(const keymaster_keypair_t key_type, const void* key_params,
-                         uint8_t** key_blob, size_t* key_blob_length);
-    int import_keypair(const uint8_t* key, const size_t key_length, uint8_t** key_blob,
-                       size_t* key_blob_length);
-    int get_keypair_public(const uint8_t* key_blob, const size_t key_blob_length,
-                           uint8_t** x509_data, size_t* x509_data_length);
-    int sign_data(const void* signing_params, const uint8_t* key_blob, const size_t key_blob_length,
-                  const uint8_t* data, const size_t data_length, uint8_t** signed_data,
-                  size_t* signed_data_length);
-    int verify_data(const void* signing_params, const uint8_t* key_blob,
-                    const size_t key_blob_length, const uint8_t* signed_data,
-                    const size_t signed_data_length, const uint8_t* signature,
-                    const size_t signature_length);
+    keymaster_error_t configure(const keymaster_key_param_set_t* params);
+    keymaster_error_t add_rng_entropy(const uint8_t* data, size_t data_length);
+    keymaster_error_t generate_key(const keymaster_key_param_set_t* params,
+                                   keymaster_key_blob_t* key_blob,
+                                   keymaster_key_characteristics_t* characteristics);
+    keymaster_error_t get_key_characteristics(const keymaster_key_blob_t* key_blob,
+                                              const keymaster_blob_t* client_id,
+                                              const keymaster_blob_t* app_data,
+                                              keymaster_key_characteristics_t* character);
+    keymaster_error_t import_key(const keymaster_key_param_set_t* params,
+                                 keymaster_key_format_t key_format,
+                                 const keymaster_blob_t* key_data, keymaster_key_blob_t* key_blob,
+                                 keymaster_key_characteristics_t* characteristics);
+    keymaster_error_t export_key(keymaster_key_format_t export_format,
+                                 const keymaster_key_blob_t* key_to_export,
+                                 const keymaster_blob_t* client_id,
+                                 const keymaster_blob_t* app_data, keymaster_blob_t* export_data);
+    keymaster_error_t attest_key(const keymaster_key_blob_t* key_to_attest,
+                                 const keymaster_key_param_set_t* attest_params,
+                                 keymaster_cert_chain_t* cert_chain);
+    keymaster_error_t upgrade_key(const keymaster_key_blob_t* key_to_upgrade,
+                                  const keymaster_key_param_set_t* upgrade_params,
+                                  keymaster_key_blob_t* upgraded_key);
+    keymaster_error_t begin(keymaster_purpose_t purpose, const keymaster_key_blob_t* key,
+                            const keymaster_key_param_set_t* in_params,
+                            keymaster_key_param_set_t* out_params,
+                            keymaster_operation_handle_t* operation_handle);
+    keymaster_error_t update(keymaster_operation_handle_t operation_handle,
+                             const keymaster_key_param_set_t* in_params,
+                             const keymaster_blob_t* input, size_t* input_consumed,
+                             keymaster_key_param_set_t* out_params, keymaster_blob_t* output);
+    keymaster_error_t finish(keymaster_operation_handle_t operation_handle,
+                             const keymaster_key_param_set_t* in_params,
+                             const keymaster_blob_t* input, const keymaster_blob_t* signature,
+                             keymaster_key_param_set_t* out_params, keymaster_blob_t* output);
+    keymaster_error_t abort(keymaster_operation_handle_t operation_handle);
 
   private:
     keymaster_error_t Send(uint32_t command, const Serializable& request,
                            KeymasterResponse* response);
-    keymaster_error_t Send(const GenerateKeyRequest& request, GenerateKeyResponse* response) {
-        return Send(KM_GENERATE_KEY, request, response);
-    }
-    keymaster_error_t Send(const BeginOperationRequest& request, BeginOperationResponse* response) {
-        return Send(KM_BEGIN_OPERATION, request, response);
-    }
-    keymaster_error_t Send(const UpdateOperationRequest& request,
-                           UpdateOperationResponse* response) {
-        return Send(KM_UPDATE_OPERATION, request, response);
-    }
-    keymaster_error_t Send(const FinishOperationRequest& request,
-                           FinishOperationResponse* response) {
-        return Send(KM_FINISH_OPERATION, request, response);
-    }
-    keymaster_error_t Send(const ImportKeyRequest& request, ImportKeyResponse* response) {
-        return Send(KM_IMPORT_KEY, request, response);
-    }
-    keymaster_error_t Send(const ExportKeyRequest& request, ExportKeyResponse* response) {
-        return Send(KM_EXPORT_KEY, request, response);
-    }
-    keymaster_error_t Send(const GetVersionRequest& request, GetVersionResponse* response) {
-        return Send(KM_GET_VERSION, request, response);
-    }
-
-    keymaster_error_t StoreSigningParams(const void* signing_params, const uint8_t* key_blob,
-                                         size_t key_blob_length, AuthorizationSet* auth_set);
-    void StoreNewKeyParams(AuthorizationSet* auth_set);
-    keymaster_error_t GetPkcs8KeyAlgorithm(const uint8_t* key, size_t key_length,
-                                           keymaster_algorithm_t* algorithm);
 
     /*
      * These static methods are the functions referenced through the function pointers in
      * keymaster_device.  They're all trivial wrappers.
      */
     static int close_device(hw_device_t* dev);
-    static int generate_keypair(const keymaster0_device_t* dev, const keymaster_keypair_t key_type,
-                                const void* key_params, uint8_t** keyBlob, size_t* keyBlobLength);
-    static int import_keypair(const keymaster0_device_t* dev, const uint8_t* key,
-                              const size_t key_length, uint8_t** key_blob, size_t* key_blob_length);
-    static int get_keypair_public(const keymaster0_device_t* dev, const uint8_t* key_blob,
-                                  const size_t key_blob_length, uint8_t** x509_data,
-                                  size_t* x509_data_length);
-    static int sign_data(const keymaster0_device_t* dev, const void* signing_params,
-                         const uint8_t* key_blob, const size_t key_blob_length, const uint8_t* data,
-                         const size_t data_length, uint8_t** signed_data,
-                         size_t* signed_data_length);
-    static int verify_data(const keymaster0_device_t* dev, const void* signing_params,
-                           const uint8_t* key_blob, const size_t key_blob_length,
-                           const uint8_t* signed_data, const size_t signed_data_length,
-                           const uint8_t* signature, const size_t signature_length);
+    static keymaster_error_t configure(const keymaster2_device_t* dev,
+                                       const keymaster_key_param_set_t* params);
+    static keymaster_error_t add_rng_entropy(const keymaster2_device_t* dev, const uint8_t* data,
+                                             size_t data_length);
+    static keymaster_error_t generate_key(const keymaster2_device_t* dev,
+                                          const keymaster_key_param_set_t* params,
+                                          keymaster_key_blob_t* key_blob,
+                                          keymaster_key_characteristics_t* characteristics);
+    static keymaster_error_t get_key_characteristics(const keymaster2_device_t* dev,
+                                                     const keymaster_key_blob_t* key_blob,
+                                                     const keymaster_blob_t* client_id,
+                                                     const keymaster_blob_t* app_data,
+                                                     keymaster_key_characteristics_t* character);
+    static keymaster_error_t import_key(const keymaster2_device_t* dev,
+                                        const keymaster_key_param_set_t* params,
+                                        keymaster_key_format_t key_format,
+                                        const keymaster_blob_t* key_data,
+                                        keymaster_key_blob_t* key_blob,
+                                        keymaster_key_characteristics_t* characteristics);
+    static keymaster_error_t export_key(const keymaster2_device_t* dev,
+                                        keymaster_key_format_t export_format,
+                                        const keymaster_key_blob_t* key_to_export,
+                                        const keymaster_blob_t* client_id,
+                                        const keymaster_blob_t* app_data,
+                                        keymaster_blob_t* export_data);
+    static keymaster_error_t attest_key(const keymaster2_device_t* dev,
+                                        const keymaster_key_blob_t* key_to_attest,
+                                        const keymaster_key_param_set_t* attest_params,
+                                        keymaster_cert_chain_t* cert_chain);
+    static keymaster_error_t upgrade_key(const keymaster2_device_t* dev,
+                                         const keymaster_key_blob_t* key_to_upgrade,
+                                         const keymaster_key_param_set_t* upgrade_params,
+                                         keymaster_key_blob_t* upgraded_key);
+    static keymaster_error_t delete_key(const keymaster2_device_t* dev,
+                                        const keymaster_key_blob_t* key);
+    static keymaster_error_t delete_all_keys(const keymaster2_device_t* dev);
+    static keymaster_error_t begin(const keymaster2_device_t* dev, keymaster_purpose_t purpose,
+                                   const keymaster_key_blob_t* key,
+                                   const keymaster_key_param_set_t* in_params,
+                                   keymaster_key_param_set_t* out_params,
+                                   keymaster_operation_handle_t* operation_handle);
+    static keymaster_error_t update(const keymaster2_device_t* dev,
+                                    keymaster_operation_handle_t operation_handle,
+                                    const keymaster_key_param_set_t* in_params,
+                                    const keymaster_blob_t* input, size_t* input_consumed,
+                                    keymaster_key_param_set_t* out_params, keymaster_blob_t* output);
+    static keymaster_error_t finish(const keymaster2_device_t* dev,
+                                    keymaster_operation_handle_t operation_handle,
+                                    const keymaster_key_param_set_t* in_params,
+                                    const keymaster_blob_t* input, const keymaster_blob_t* signature,
+                                    keymaster_key_param_set_t* out_params, keymaster_blob_t* output);
+    static keymaster_error_t abort(const keymaster2_device_t* dev,
+                                   keymaster_operation_handle_t operation_handle);
 
-    keymaster0_device_t device_;
+    keymaster2_device_t device_;
     keymaster_error_t error_;
     int32_t message_version_;
 };
 
 }  // namespace keymaster
 
-#endif  // EXTERNAL_KEYMASTER_TRUSTY_KEYMASTER_DEVICE_H_
+#endif  // TRUSTY_KEYMASTER_TRUSTY_KEYMASTER_DEVICE_H_
diff --git a/trusty/keymaster/trusty_keymaster_ipc.c b/trusty/keymaster/trusty_keymaster_ipc.cpp
similarity index 75%
rename from trusty/keymaster/trusty_keymaster_ipc.c
rename to trusty/keymaster/trusty_keymaster_ipc.cpp
index 88546af..cdc2778 100644
--- a/trusty/keymaster/trusty_keymaster_ipc.c
+++ b/trusty/keymaster/trusty_keymaster_ipc.cpp
@@ -26,8 +26,8 @@
 #include <log/log.h>
 #include <trusty/tipc.h>
 
-#include "trusty_keymaster_ipc.h"
 #include "keymaster_ipc.h"
+#include "trusty_keymaster_ipc.h"
 
 #define TRUSTY_DEVICE_NAME "/dev/trusty-ipc-dev0"
 
@@ -43,15 +43,15 @@
     return 0;
 }
 
-int trusty_keymaster_call(uint32_t cmd, void *in, uint32_t in_size, uint8_t *out,
-                          uint32_t *out_size)  {
+int trusty_keymaster_call(uint32_t cmd, void* in, uint32_t in_size, uint8_t* out,
+                          uint32_t* out_size) {
     if (handle_ == 0) {
         ALOGE("not connected\n");
         return -EINVAL;
     }
 
     size_t msg_size = in_size + sizeof(struct keymaster_message);
-    struct keymaster_message *msg = malloc(msg_size);
+    struct keymaster_message* msg = reinterpret_cast<struct keymaster_message*>(malloc(msg_size));
     msg->cmd = cmd;
     memcpy(msg->payload, in, in_size);
 
@@ -59,31 +59,30 @@
     free(msg);
 
     if (rc < 0) {
-        ALOGE("failed to send cmd (%d) to %s: %s\n", cmd,
-                KEYMASTER_PORT, strerror(errno));
+        ALOGE("failed to send cmd (%d) to %s: %s\n", cmd, KEYMASTER_PORT, strerror(errno));
         return -errno;
     }
 
     rc = read(handle_, out, *out_size);
     if (rc < 0) {
-        ALOGE("failed to retrieve response for cmd (%d) to %s: %s\n",
-                cmd, KEYMASTER_PORT, strerror(errno));
+        ALOGE("failed to retrieve response for cmd (%d) to %s: %s\n", cmd, KEYMASTER_PORT,
+              strerror(errno));
         return -errno;
     }
 
-    if ((size_t) rc < sizeof(struct keymaster_message)) {
-        ALOGE("invalid response size (%d)\n", (int) rc);
+    if ((size_t)rc < sizeof(struct keymaster_message)) {
+        ALOGE("invalid response size (%d)\n", (int)rc);
         return -EINVAL;
     }
 
-    msg = (struct keymaster_message *) out;
+    msg = (struct keymaster_message*)out;
 
     if ((cmd | KEYMASTER_RESP_BIT) != msg->cmd) {
         ALOGE("invalid command (%d)", msg->cmd);
         return -EINVAL;
     }
 
-    *out_size = ((size_t) rc) - sizeof(struct keymaster_message);
+    *out_size = ((size_t)rc) - sizeof(struct keymaster_message);
     return rc;
 }
 
@@ -92,4 +91,3 @@
         tipc_close(handle_);
     }
 }
-
diff --git a/trusty/keymaster/trusty_keymaster_ipc.h b/trusty/keymaster/trusty_keymaster_ipc.h
index 9785247..c15f7c1 100644
--- a/trusty/keymaster/trusty_keymaster_ipc.h
+++ b/trusty/keymaster/trusty_keymaster_ipc.h
@@ -14,11 +14,16 @@
  * limitations under the License.
  */
 
+#ifndef TRUSTY_KEYMASTER_TRUSTY_KEYMASTER_IPC_H_
+#define TRUSTY_KEYMASTER_TRUSTY_KEYMASTER_IPC_H_
+
 __BEGIN_DECLS
 
 int trusty_keymaster_connect(void);
-int trusty_keymaster_call(uint32_t cmd, void *in, uint32_t in_size, uint8_t *out,
-         uint32_t *out_size);
+int trusty_keymaster_call(uint32_t cmd, void* in, uint32_t in_size, uint8_t* out,
+                          uint32_t* out_size);
 void trusty_keymaster_disconnect(void);
 
 __END_DECLS
+
+#endif  // TRUSTY_KEYMASTER_TRUSTY_KEYMASTER_IPC_H_
diff --git a/trusty/keymaster/trusty_keymaster_main.cpp b/trusty/keymaster/trusty_keymaster_main.cpp
index 7ed880e..9c2ae2d 100644
--- a/trusty/keymaster/trusty_keymaster_main.cpp
+++ b/trusty/keymaster/trusty_keymaster_main.cpp
@@ -14,7 +14,10 @@
  * limitations under the License.
  */
 
+#include <keymaster/keymaster_configuration.h>
+
 #include <stdio.h>
+#include <memory>
 
 #include <openssl/evp.h>
 #include <openssl/x509.h>
@@ -102,6 +105,28 @@
     0xd1, 0x1f, 0xd4, 0x49, 0x49, 0xe0, 0xb2, 0x18, 0x3b, 0xfe};
 unsigned int ec_privkey_pk8_der_len = 138;
 
+keymaster_key_param_t ec_params[] = {
+    keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC),
+    keymaster_param_long(KM_TAG_EC_CURVE, KM_EC_CURVE_P_521),
+    keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_SIGN),
+    keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_VERIFY),
+    keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
+    keymaster_param_bool(KM_TAG_NO_AUTH_REQUIRED),
+};
+keymaster_key_param_set_t ec_param_set = {ec_params, sizeof(ec_params) / sizeof(*ec_params)};
+
+keymaster_key_param_t rsa_params[] = {
+    keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA),
+    keymaster_param_int(KM_TAG_KEY_SIZE, 1024),
+    keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT, 65537),
+    keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_SIGN),
+    keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_VERIFY),
+    keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
+    keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
+    keymaster_param_bool(KM_TAG_NO_AUTH_REQUIRED),
+};
+keymaster_key_param_set_t rsa_param_set = {rsa_params, sizeof(rsa_params) / sizeof(*rsa_params)};
+
 struct EVP_PKEY_Delete {
     void operator()(EVP_PKEY* p) const { EVP_PKEY_free(p); }
 };
@@ -110,41 +135,70 @@
     void operator()(EVP_PKEY_CTX* p) { EVP_PKEY_CTX_free(p); }
 };
 
+static bool do_operation(TrustyKeymasterDevice* device, keymaster_purpose_t purpose,
+                         keymaster_key_blob_t* key, keymaster_blob_t* input,
+                         keymaster_blob_t* signature, keymaster_blob_t* output) {
+    keymaster_key_param_t params[] = {
+        keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
+        keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
+    };
+    keymaster_key_param_set_t param_set = {params, sizeof(params) / sizeof(*params)};
+    keymaster_operation_handle_t op_handle;
+    keymaster_error_t error = device->begin(purpose, key, &param_set, nullptr, &op_handle);
+    if (error != KM_ERROR_OK) {
+        printf("Keymaster begin() failed: %d\n", error);
+        return false;
+    }
+    size_t input_consumed;
+    error = device->update(op_handle, nullptr, input, &input_consumed, nullptr, nullptr);
+    if (error != KM_ERROR_OK) {
+        printf("Keymaster update() failed: %d\n", error);
+        return false;
+    }
+    if (input_consumed != input->data_length) {
+        // This should never happen. If it does, it's a bug in the keymaster implementation.
+        printf("Keymaster update() did not consume all data.\n");
+        device->abort(op_handle);
+        return false;
+    }
+    error = device->finish(op_handle, nullptr, nullptr, signature, nullptr, output);
+    if (error != KM_ERROR_OK) {
+        printf("Keymaster finish() failed: %d\n", error);
+        return false;
+    }
+    return true;
+}
+
 static bool test_import_rsa(TrustyKeymasterDevice* device) {
     printf("===================\n");
     printf("= RSA Import Test =\n");
     printf("===================\n\n");
 
     printf("=== Importing RSA keypair === \n");
-    uint8_t* key;
-    size_t size;
-    int error = device->import_keypair(rsa_privkey_pk8_der, rsa_privkey_pk8_der_len, &key, &size);
+    keymaster_key_blob_t key;
+    keymaster_blob_t private_key = {rsa_privkey_pk8_der, rsa_privkey_pk8_der_len};
+    int error = device->import_key(&rsa_param_set, KM_KEY_FORMAT_PKCS8, &private_key, &key, nullptr);
     if (error != KM_ERROR_OK) {
-        printf("Error importing key pair: %d\n\n", error);
+        printf("Error importing RSA key: %d\n\n", error);
         return false;
     }
-    UniquePtr<uint8_t[]> key_deleter(key);
+    std::unique_ptr<const uint8_t[]> key_deleter(key.key_material);
 
     printf("=== Signing with imported RSA key ===\n");
-    keymaster_rsa_sign_params_t sign_params = {DIGEST_NONE, PADDING_NONE};
     size_t message_len = 1024 / 8;
-    UniquePtr<uint8_t[]> message(new uint8_t[message_len]);
+    std::unique_ptr<uint8_t[]> message(new uint8_t[message_len]);
     memset(message.get(), 'a', message_len);
-    uint8_t* signature;
-    size_t signature_len;
-    error = device->sign_data(&sign_params, key, size, message.get(), message_len, &signature,
-                              &signature_len);
-    if (error != KM_ERROR_OK) {
-        printf("Error signing data with imported RSA key: %d\n\n", error);
+    keymaster_blob_t input = {message.get(), message_len}, signature;
+
+    if (!do_operation(device, KM_PURPOSE_SIGN, &key, &input, nullptr, &signature)) {
+        printf("Error signing data with imported RSA key\n\n");
         return false;
     }
-    UniquePtr<uint8_t[]> signature_deleter(signature);
+    std::unique_ptr<const uint8_t[]> signature_deleter(signature.data);
 
     printf("=== Verifying with imported RSA key === \n");
-    error = device->verify_data(&sign_params, key, size, message.get(), message_len, signature,
-                                signature_len);
-    if (error != KM_ERROR_OK) {
-        printf("Error verifying data with imported RSA key: %d\n\n", error);
+    if (!do_operation(device, KM_PURPOSE_VERIFY, &key, &input, &signature, nullptr)) {
+        printf("Error verifying data with imported RSA key\n\n");
         return false;
     }
 
@@ -158,67 +212,58 @@
     printf("============\n\n");
 
     printf("=== Generating RSA key pair ===\n");
-    keymaster_rsa_keygen_params_t params;
-    params.public_exponent = 65537;
-    params.modulus_size = 2048;
-
-    uint8_t* key;
-    size_t size;
-    int error = device->generate_keypair(TYPE_RSA, &params, &key, &size);
+    keymaster_key_blob_t key;
+    int error = device->generate_key(&rsa_param_set, &key, nullptr);
     if (error != KM_ERROR_OK) {
         printf("Error generating RSA key pair: %d\n\n", error);
         return false;
     }
-    UniquePtr<uint8_t[]> deleter(key);
+    std::unique_ptr<const uint8_t[]> key_deleter(key.key_material);
 
     printf("=== Signing with RSA key === \n");
-    keymaster_rsa_sign_params_t sign_params = {DIGEST_NONE, PADDING_NONE};
-    size_t message_len = params.modulus_size / 8;
-    UniquePtr<uint8_t[]> message(new uint8_t[message_len]);
+    size_t message_len = 1024 / 8;
+    std::unique_ptr<uint8_t[]> message(new uint8_t[message_len]);
     memset(message.get(), 'a', message_len);
-    uint8_t* signature;
-    size_t signature_len;
-    error = device->sign_data(&sign_params, key, size, message.get(), message_len, &signature,
-                              &signature_len);
-    if (error != KM_ERROR_OK) {
-        printf("Error signing data with RSA key: %d\n\n", error);
+    keymaster_blob_t input = {message.get(), message_len}, signature;
+
+    if (!do_operation(device, KM_PURPOSE_SIGN, &key, &input, nullptr, &signature)) {
+        printf("Error signing data with RSA key\n\n");
         return false;
     }
-    UniquePtr<uint8_t[]> signature_deleter(signature);
+    std::unique_ptr<const uint8_t[]> signature_deleter(signature.data);
 
     printf("=== Verifying with RSA key === \n");
-    error = device->verify_data(&sign_params, key, size, message.get(), message_len, signature,
-                                signature_len);
-    if (error != KM_ERROR_OK) {
-        printf("Error verifying data with RSA key: %d\n\n", error);
+    if (!do_operation(device, KM_PURPOSE_VERIFY, &key, &input, &signature, nullptr)) {
+        printf("Error verifying data with RSA key\n\n");
         return false;
     }
 
     printf("=== Exporting RSA public key ===\n");
-    uint8_t* exported_key;
-    size_t exported_size;
-    error = device->get_keypair_public(key, size, &exported_key, &exported_size);
+    keymaster_blob_t exported_key;
+    error = device->export_key(KM_KEY_FORMAT_X509, &key, nullptr, nullptr, &exported_key);
     if (error != KM_ERROR_OK) {
         printf("Error exporting RSA public key: %d\n\n", error);
         return false;
     }
 
     printf("=== Verifying with exported key ===\n");
-    const uint8_t* tmp = exported_key;
-    UniquePtr<EVP_PKEY, EVP_PKEY_Delete> pkey(d2i_PUBKEY(NULL, &tmp, exported_size));
-    UniquePtr<EVP_PKEY_CTX, EVP_PKEY_CTX_Delete> ctx(EVP_PKEY_CTX_new(pkey.get(), NULL));
+    const uint8_t* tmp = exported_key.data;
+    std::unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(
+        d2i_PUBKEY(NULL, &tmp, exported_key.data_length));
+    std::unique_ptr<EVP_PKEY_CTX, EVP_PKEY_CTX_Delete> ctx(EVP_PKEY_CTX_new(pkey.get(), NULL));
     if (EVP_PKEY_verify_init(ctx.get()) != 1) {
-        printf("Error initializing openss EVP context\n");
+        printf("Error initializing openss EVP context\n\n");
         return false;
     }
     if (EVP_PKEY_type(pkey->type) != EVP_PKEY_RSA) {
-        printf("Exported key was the wrong type?!?\n");
+        printf("Exported key was the wrong type?!?\n\n");
         return false;
     }
 
     EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING);
-    if (EVP_PKEY_verify(ctx.get(), signature, signature_len, message.get(), message_len) != 1) {
-        printf("Verification with exported pubkey failed.\n");
+    if (EVP_PKEY_verify(ctx.get(), signature.data, signature.data_length, message.get(),
+                        message_len) != 1) {
+        printf("Verification with exported pubkey failed.\n\n");
         return false;
     } else {
         printf("Verification succeeded\n");
@@ -234,35 +279,31 @@
     printf("=====================\n\n");
 
     printf("=== Importing ECDSA keypair === \n");
-    uint8_t* key;
-    size_t size;
-    int error = device->import_keypair(ec_privkey_pk8_der, ec_privkey_pk8_der_len, &key, &size);
+    keymaster_key_blob_t key;
+    keymaster_blob_t private_key = {ec_privkey_pk8_der, ec_privkey_pk8_der_len};
+    int error = device->import_key(&ec_param_set, KM_KEY_FORMAT_PKCS8, &private_key, &key, nullptr);
     if (error != KM_ERROR_OK) {
-        printf("Error importing key pair: %d\n\n", error);
+        printf("Error importing ECDSA key: %d\n\n", error);
         return false;
     }
-    UniquePtr<uint8_t[]> deleter(key);
+    std::unique_ptr<const uint8_t[]> deleter(key.key_material);
 
     printf("=== Signing with imported ECDSA key ===\n");
     keymaster_ec_sign_params_t sign_params = {DIGEST_NONE};
     size_t message_len = 30 /* arbitrary */;
-    UniquePtr<uint8_t[]> message(new uint8_t[message_len]);
+    std::unique_ptr<uint8_t[]> message(new uint8_t[message_len]);
     memset(message.get(), 'a', message_len);
-    uint8_t* signature;
-    size_t signature_len;
-    error = device->sign_data(&sign_params, key, size, message.get(), message_len, &signature,
-                              &signature_len);
-    if (error != KM_ERROR_OK) {
-        printf("Error signing data with imported ECDSA key: %d\n\n", error);
+    keymaster_blob_t input = {message.get(), message_len}, signature;
+
+    if (!do_operation(device, KM_PURPOSE_SIGN, &key, &input, nullptr, &signature)) {
+        printf("Error signing data with imported ECDSA key\n\n");
         return false;
     }
-    UniquePtr<uint8_t[]> signature_deleter(signature);
+    std::unique_ptr<const uint8_t[]> signature_deleter(signature.data);
 
     printf("=== Verifying with imported ECDSA key === \n");
-    error = device->verify_data(&sign_params, key, size, message.get(), message_len, signature,
-                                signature_len);
-    if (error != KM_ERROR_OK) {
-        printf("Error verifying data with imported ECDSA key: %d\n\n", error);
+    if (!do_operation(device, KM_PURPOSE_VERIFY, &key, &input, &signature, nullptr)) {
+        printf("Error verifying data with imported ECDSA key\n\n");
         return false;
     }
 
@@ -276,64 +317,57 @@
     printf("==============\n\n");
 
     printf("=== Generating ECDSA key pair ===\n");
-    keymaster_ec_keygen_params_t params;
-    params.field_size = 521;
-    uint8_t* key;
-    size_t size;
-    int error = device->generate_keypair(TYPE_EC, &params, &key, &size);
-    if (error != 0) {
+    keymaster_key_blob_t key;
+    int error = device->generate_key(&ec_param_set, &key, nullptr);
+    if (error != KM_ERROR_OK) {
         printf("Error generating ECDSA key pair: %d\n\n", error);
         return false;
     }
-    UniquePtr<uint8_t[]> deleter(key);
+    std::unique_ptr<const uint8_t[]> key_deleter(key.key_material);
 
     printf("=== Signing with ECDSA key === \n");
-    keymaster_ec_sign_params_t sign_params = {DIGEST_NONE};
     size_t message_len = 30 /* arbitrary */;
-    UniquePtr<uint8_t[]> message(new uint8_t[message_len]);
+    std::unique_ptr<uint8_t[]> message(new uint8_t[message_len]);
     memset(message.get(), 'a', message_len);
-    uint8_t* signature;
-    size_t signature_len;
-    error = device->sign_data(&sign_params, key, size, message.get(), message_len, &signature,
-                              &signature_len);
-    if (error != KM_ERROR_OK) {
-        printf("Error signing data with ECDSA key: %d\n\n", error);
+    keymaster_blob_t input = {message.get(), message_len}, signature;
+
+    if (!do_operation(device, KM_PURPOSE_SIGN, &key, &input, nullptr, &signature)) {
+        printf("Error signing data with ECDSA key\n\n");
         return false;
     }
-    UniquePtr<uint8_t[]> signature_deleter(signature);
+    std::unique_ptr<const uint8_t[]> signature_deleter(signature.data);
 
     printf("=== Verifying with ECDSA key === \n");
-    error = device->verify_data(&sign_params, key, size, message.get(), message_len, signature,
-                                signature_len);
-    if (error != KM_ERROR_OK) {
-        printf("Error verifying data with ECDSA key: %d\n\n", error);
+    if (!do_operation(device, KM_PURPOSE_VERIFY, &key, &input, &signature, nullptr)) {
+        printf("Error verifying data with ECDSA key\n\n");
         return false;
     }
 
     printf("=== Exporting ECDSA public key ===\n");
-    uint8_t* exported_key;
-    size_t exported_size;
-    error = device->get_keypair_public(key, size, &exported_key, &exported_size);
+    keymaster_blob_t exported_key;
+    error = device->export_key(KM_KEY_FORMAT_X509, &key, nullptr, nullptr, &exported_key);
     if (error != KM_ERROR_OK) {
         printf("Error exporting ECDSA public key: %d\n\n", error);
         return false;
     }
 
     printf("=== Verifying with exported key ===\n");
-    const uint8_t* tmp = exported_key;
-    UniquePtr<EVP_PKEY, EVP_PKEY_Delete> pkey(d2i_PUBKEY(NULL, &tmp, exported_size));
-    UniquePtr<EVP_PKEY_CTX, EVP_PKEY_CTX_Delete> ctx(EVP_PKEY_CTX_new(pkey.get(), NULL));
+    const uint8_t* tmp = exported_key.data;
+    std::unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(
+        d2i_PUBKEY(NULL, &tmp, exported_key.data_length));
+    std::unique_ptr<EVP_PKEY_CTX, EVP_PKEY_CTX_Delete> ctx(EVP_PKEY_CTX_new(pkey.get(), NULL));
     if (EVP_PKEY_verify_init(ctx.get()) != 1) {
-        printf("Error initializing openss EVP context\n");
+        printf("Error initializing openssl EVP context\n\n");
         return false;
     }
     if (EVP_PKEY_type(pkey->type) != EVP_PKEY_EC) {
-        printf("Exported key was the wrong type?!?\n");
+        printf("Exported key was the wrong type?!?\n\n");
         return false;
     }
 
-    if (EVP_PKEY_verify(ctx.get(), signature, signature_len, message.get(), message_len) != 1) {
-        printf("Verification with exported pubkey failed.\n");
+    if (EVP_PKEY_verify(ctx.get(), signature.data, signature.data_length, message.get(),
+                        message_len) != 1) {
+        printf("Verification with exported pubkey failed.\n\n");
         return false;
     } else {
         printf("Verification succeeded\n");
@@ -344,8 +378,8 @@
 }
 
 int main(void) {
-
     TrustyKeymasterDevice device(NULL);
+    keymaster::ConfigureDevice(reinterpret_cast<keymaster2_device_t*>(&device));
     if (device.session_error() != KM_ERROR_OK) {
         printf("Failed to initialize Trusty session: %d\n", device.session_error());
         return 1;
diff --git a/trusty/libtrusty/Android.bp b/trusty/libtrusty/Android.bp
new file mode 100644
index 0000000..f316da2
--- /dev/null
+++ b/trusty/libtrusty/Android.bp
@@ -0,0 +1,26 @@
+// 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.
+
+subdirs = [
+    "tipc-test",
+]
+
+cc_library {
+    name: "libtrusty",
+
+    srcs: ["trusty.c"],
+    export_include_dirs: ["include"],
+
+    shared_libs: ["liblog"],
+}
diff --git a/trusty/libtrusty/Android.mk b/trusty/libtrusty/Android.mk
deleted file mode 100644
index 45fc079..0000000
--- a/trusty/libtrusty/Android.mk
+++ /dev/null
@@ -1,36 +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.
-
-LOCAL_PATH := $(call my-dir)
-
-# == libtrusty Static library ==
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := libtrusty
-LOCAL_MODULE_TAGS := optional
-LOCAL_SRC_FILES := trusty.c
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-
-include $(BUILD_STATIC_LIBRARY)
-
-# ==  libtrusty shared library ==
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := libtrusty
-LOCAL_MODULE_TAGS := optional
-LOCAL_SRC_FILES := trusty.c
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-LOCAL_SHARED_LIBRARIES := liblog
-
-include $(BUILD_SHARED_LIBRARY)
diff --git a/trusty/libtrusty/tipc-test/Android.bp b/trusty/libtrusty/tipc-test/Android.bp
new file mode 100644
index 0000000..cb00fe7
--- /dev/null
+++ b/trusty/libtrusty/tipc-test/Android.bp
@@ -0,0 +1,26 @@
+// 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.
+
+cc_test {
+    name: "tipc-test",
+    static_executable: true,
+
+    srcs: ["tipc_test.c"],
+    static_libs: [
+        "libc",
+        "libtrusty",
+        "liblog",
+    ],
+    gtest: false,
+}
diff --git a/trusty/libtrusty/tipc-test/Android.mk b/trusty/libtrusty/tipc-test/Android.mk
deleted file mode 100644
index 80030fe..0000000
--- a/trusty/libtrusty/tipc-test/Android.mk
+++ /dev/null
@@ -1,29 +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.
-
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := tipc-test
-LOCAL_FORCE_STATIC_EXECUTABLE := true
-LOCAL_MODULE_PATH := $(TARGET_OUT_OPTIONAL_EXECUTABLES)
-LOCAL_MODULE_TAGS := optional
-LOCAL_SRC_FILES := tipc_test.c
-LOCAL_STATIC_LIBRARIES := libc libtrusty liblog
-LOCAL_MULTILIB := both
-LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
-LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
-
-include $(BUILD_EXECUTABLE)
diff --git a/tzdatacheck/tzdatacheck.cpp b/tzdatacheck/tzdatacheck.cpp
index 381df5a..8fcd17f 100644
--- a/tzdatacheck/tzdatacheck.cpp
+++ b/tzdatacheck/tzdatacheck.cpp
@@ -30,6 +30,19 @@
 
 #include "android-base/logging.h"
 
+// The name of the directory that holds a staged time zone update distro. If this exists it should
+// replace the one in CURRENT_DIR_NAME.
+// See also libcore.tzdata.update2.TimeZoneDistroInstaller.
+static const char* STAGED_DIR_NAME = "/staged";
+
+// The name of the directory that holds the (optional) installed time zone update distro.
+// See also libcore.tzdata.update2.TimeZoneDistroInstaller.
+static const char* CURRENT_DIR_NAME = "/current";
+
+// The name of a file in the staged dir that indicates the staged operation is an "uninstall".
+// See also libcore.tzdata.update2.TimeZoneDistroInstaller.
+static const char* UNINSTALL_TOMBSTONE_FILE_NAME = "/STAGED_UNINSTALL_TOMBSTONE";
+
 // The name of the file containing the distro version information.
 // See also libcore.tzdata.shared2.TimeZoneDistro / libcore.tzdata.shared2.DistroVersion.
 static const char* DISTRO_VERSION_FILENAME = "/distro_version";
@@ -75,7 +88,6 @@
 static const char TZ_DATA_HEADER_PREFIX[] = "tzdata";
 static const size_t TZ_DATA_HEADER_PREFIX_LEN = sizeof(TZ_DATA_HEADER_PREFIX) - 1; // exclude \0
 
-
 static void usage() {
     std::cerr << "Usage: tzdatacheck SYSTEM_TZ_DIR DATA_TZ_DIR\n"
             "\n"
@@ -184,7 +196,7 @@
     return 0;
 }
 
-enum PathStatus { ERR, NONE, IS_DIR, NOT_DIR };
+enum PathStatus { ERR, NONE, IS_DIR, IS_REG, UNKNOWN };
 
 static PathStatus checkPath(const std::string& path) {
     struct stat buf;
@@ -195,7 +207,31 @@
         }
         return NONE;
     }
-    return S_ISDIR(buf.st_mode) ? IS_DIR : NOT_DIR;
+    return S_ISDIR(buf.st_mode) ? IS_DIR : S_ISREG(buf.st_mode) ? IS_REG : UNKNOWN;
+}
+
+/*
+ * Deletes fileToDelete and returns true if it is successful. If fileToDelete is not a file or
+ * cannot be accessed this method returns false.
+ */
+static bool deleteFile(const std::string& fileToDelete) {
+    // Check whether the file exists.
+    PathStatus pathStatus = checkPath(fileToDelete);
+    if (pathStatus == NONE) {
+        LOG(INFO) << "Path " << fileToDelete << " does not exist";
+        return true;
+    }
+    if (pathStatus != IS_REG) {
+        LOG(WARNING) << "Path " << fileToDelete << " failed to stat() or is not a file.";
+        return false;
+    }
+
+    // Attempt the deletion.
+    int rc = unlink(fileToDelete.c_str());
+    if (rc != 0) {
+        PLOG(WARNING) << "unlink() failed for " << fileToDelete;
+    }
+    return rc == 0;
 }
 
 /*
@@ -260,8 +296,7 @@
     std::string dataUpdatesDirName(dataZoneInfoDir);
     dataUpdatesDirName += "/updates";
     LOG(INFO) << "Removing: " << dataUpdatesDirName;
-    bool deleted = deleteDir(dataUpdatesDirName);
-    if (!deleted) {
+    if (!deleteDir(dataUpdatesDirName)) {
         LOG(WARNING) << "Deletion of install metadata " << dataUpdatesDirName
                 << " was not successful";
     }
@@ -270,14 +305,151 @@
 /*
  * Deletes the timezone update distro directory.
  */
-static void deleteUpdateDistroDir(std::string& distroDirName) {
+static void deleteUpdateDistroDir(const std::string& distroDirName) {
     LOG(INFO) << "Removing: " << distroDirName;
-    bool deleted = deleteDir(distroDirName);
-    if (!deleted) {
+    if (!deleteDir(distroDirName)) {
         LOG(WARNING) << "Deletion of distro dir " << distroDirName << " was not successful";
     }
 }
 
+static void handleStagedUninstall(const std::string& dataStagedDirName,
+                                  const std::string& dataCurrentDirName,
+                                  const PathStatus dataCurrentDirStatus) {
+    LOG(INFO) << "Staged operation is an uninstall.";
+
+    // Delete the current install directory.
+    switch (dataCurrentDirStatus) {
+        case NONE:
+            // This is unexpected: No uninstall should be staged if there is nothing to
+            // uninstall. Carry on anyway.
+            LOG(WARNING) << "No current install to delete.";
+            break;
+        case IS_DIR:
+            // This is normal. Delete the current install dir.
+            if (!deleteDir(dataCurrentDirName)) {
+                LOG(WARNING) << "Deletion of current distro " << dataCurrentDirName
+                             << " was not successful";
+                // If this happens we don't know whether we were able to delete or not. We don't
+                // delete the staged operation so it will be retried next boot unless overridden.
+                return;
+            }
+            break;
+        case IS_REG:
+        default:
+            // This is unexpected: We can try to delete the unexpected file and carry on.
+            LOG(WARNING) << "Current distro dir " << dataCurrentDirName
+                         << " is not actually a directory. Attempting deletion.";
+            if (!deleteFile(dataCurrentDirName)) {
+                LOG(WARNING) << "Could not delete " << dataCurrentDirName;
+                return;
+            }
+            break;
+    }
+
+    // Delete the staged uninstall dir.
+    if (!deleteDir(dataStagedDirName)) {
+        LOG(WARNING) << "Deletion of current distro " << dataCurrentDirName
+                     << " was not successful";
+        // If this happens we don't know whether we were able to delete the staged operation
+        // or not.
+        return;
+    }
+    LOG(INFO) << "Staged uninstall complete.";
+}
+
+static void handleStagedInstall(const std::string& dataStagedDirName,
+                                const std::string& dataCurrentDirName,
+                                const PathStatus dataCurrentDirStatus) {
+    LOG(INFO) << "Staged operation is an install.";
+
+    switch (dataCurrentDirStatus) {
+        case NONE:
+            // This is expected: This is the first install.
+            LOG(INFO) << "No current install to replace.";
+            break;
+        case IS_DIR:
+            // This is expected: We are replacing an existing install.
+            // Delete the current dir so we can replace it.
+            if (!deleteDir(dataCurrentDirName)) {
+                LOG(WARNING) << "Deletion of current distro " << dataCurrentDirName
+                             << " was not successful";
+                // If this happens, we cannot proceed.
+                return;
+            }
+            break;
+        case IS_REG:
+        default:
+            // This is unexpected: We can try to delete the unexpected file and carry on.
+            LOG(WARNING) << "Current distro dir " << dataCurrentDirName
+                         << " is not actually a directory. Attempting deletion.";
+            if (!deleteFile(dataCurrentDirName)) {
+                LOG(WARNING) << "Could not delete " << dataCurrentDirName;
+                return;
+            }
+            break;
+    }
+
+    // Move the staged dir so it is the new current dir, completing the install.
+    LOG(INFO) << "Moving " << dataStagedDirName << " to " << dataCurrentDirName;
+    int rc = rename(dataStagedDirName.c_str(), dataCurrentDirName.c_str());
+    if (rc == -1) {
+        PLOG(WARNING) << "Unable to rename directory from " << dataStagedDirName << " to "
+                      << &dataCurrentDirName[0];
+        return;
+    }
+
+    LOG(INFO) << "Staged install complete.";
+}
+/*
+ * Process a staged operation if there is one.
+ */
+static void processStagedOperation(const std::string& dataStagedDirName,
+                                   const std::string& dataCurrentDirName) {
+    PathStatus dataStagedDirStatus = checkPath(dataStagedDirName);
+
+    // Exit early for the common case.
+    if (dataStagedDirStatus == NONE) {
+        LOG(DEBUG) << "No staged time zone operation.";
+        return;
+    }
+
+    // Check known directory names are in a good starting state.
+    if (dataStagedDirStatus != IS_DIR) {
+        LOG(WARNING) << "Staged distro dir " << dataStagedDirName
+                     << " could not be accessed or is not a directory."
+                     << " stagedDirStatus=" << dataStagedDirStatus;
+        return;
+    }
+
+    // dataStagedDirStatus == IS_DIR.
+
+    // Work out whether there is anything currently installed.
+    PathStatus dataCurrentDirStatus = checkPath(dataCurrentDirName);
+    if (dataCurrentDirStatus == ERR) {
+        LOG(WARNING) << "Current install dir " << dataCurrentDirName << " could not be accessed"
+                     << " dataCurrentDirStatus=" << dataCurrentDirStatus;
+        return;
+    }
+
+    // We must perform the staged operation.
+
+    // Check to see if the staged directory contains an uninstall or an install operation.
+    std::string uninstallTombStoneFile(dataStagedDirName);
+    uninstallTombStoneFile += UNINSTALL_TOMBSTONE_FILE_NAME;
+    int uninstallTombStoneFileStatus = checkPath(uninstallTombStoneFile);
+    if (uninstallTombStoneFileStatus != IS_REG && uninstallTombStoneFileStatus != NONE) {
+        // Error case.
+        LOG(WARNING) << "Unable to determine if the staged operation is an uninstall.";
+        return;
+    }
+    if (uninstallTombStoneFileStatus == IS_REG) {
+        handleStagedUninstall(dataStagedDirName, dataCurrentDirName, dataCurrentDirStatus);
+    } else {
+        // uninstallTombStoneFileStatus == NONE meaning this is a staged install.
+        handleStagedInstall(dataStagedDirName, dataCurrentDirName, dataCurrentDirStatus);
+    }
+}
+
 /*
  * After a platform update it is likely that timezone data found on the system partition will be
  * newer than the version found in the data partition. This tool detects this case and removes the
@@ -300,15 +472,25 @@
     const char* systemZoneInfoDir = argv[1];
     const char* dataZoneInfoDir = argv[2];
 
-    // Check the distro directory exists. If it does not, exit quickly: nothing to do.
+    std::string dataStagedDirName(dataZoneInfoDir);
+    dataStagedDirName += STAGED_DIR_NAME;
+
     std::string dataCurrentDirName(dataZoneInfoDir);
-    dataCurrentDirName += "/current";
-    int dataCurrentDirStatus = checkPath(dataCurrentDirName);
+    dataCurrentDirName += CURRENT_DIR_NAME;
+
+    // Check for an process any staged operation.
+    // If the staged operation could not be handled we still have to validate the current installed
+    // directory so we do not check for errors and do not quit early.
+    processStagedOperation(dataStagedDirName, dataCurrentDirName);
+
+    // Check the distro directory exists. If it does not, exit quickly: nothing to do.
+    PathStatus dataCurrentDirStatus = checkPath(dataCurrentDirName);
     if (dataCurrentDirStatus == NONE) {
         LOG(INFO) << "timezone distro dir " << dataCurrentDirName
                 << " does not exist. No action required.";
         return 0;
     }
+
     // If the distro directory path is not a directory or we can't stat() the path, exit with a
     // warning: either there's a problem accessing storage or the world is not as it should be;
     // nothing to do.